Merge branch 'MDL-47480-28' of git://github.com/ankitagarwal/moodle into MOODLE_28_STABLE
[moodle.git] / lib / adminlib.php
blobb0e24df58f5c8e58d94fd1a2f6457cfd6a5fa4b3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // Delete Inbound Message datakeys.
206 $DB->delete_records_select('messageinbound_datakeys',
207 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($pluginname));
209 // Delete Inbound Message handlers.
210 $DB->delete_records('messageinbound_handlers', array('component' => $pluginname));
212 // delete all the logs
213 $DB->delete_records('log', array('module' => $pluginname));
215 // delete log_display information
216 $DB->delete_records('log_display', array('component' => $component));
218 // delete the module configuration records
219 unset_all_config_for_plugin($component);
220 if ($type === 'mod') {
221 unset_all_config_for_plugin($pluginname);
224 // delete message provider
225 message_provider_uninstall($component);
227 // delete the plugin tables
228 $xmldbfilepath = $plugindirectory . '/db/install.xml';
229 drop_plugin_tables($component, $xmldbfilepath, false);
230 if ($type === 'mod' or $type === 'block') {
231 // non-frankenstyle table prefixes
232 drop_plugin_tables($name, $xmldbfilepath, false);
235 // delete the capabilities that were defined by this module
236 capabilities_cleanup($component);
238 // remove event handlers and dequeue pending events
239 events_uninstall($component);
241 // Delete all remaining files in the filepool owned by the component.
242 $fs = get_file_storage();
243 $fs->delete_component_files($component);
245 // Finally purge all caches.
246 purge_all_caches();
248 // Invalidate the hash used for upgrade detections.
249 set_config('allversionshash', '');
251 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
255 * Returns the version of installed component
257 * @param string $component component name
258 * @param string $source either 'disk' or 'installed' - where to get the version information from
259 * @return string|bool version number or false if the component is not found
261 function get_component_version($component, $source='installed') {
262 global $CFG, $DB;
264 list($type, $name) = core_component::normalize_component($component);
266 // moodle core or a core subsystem
267 if ($type === 'core') {
268 if ($source === 'installed') {
269 if (empty($CFG->version)) {
270 return false;
271 } else {
272 return $CFG->version;
274 } else {
275 if (!is_readable($CFG->dirroot.'/version.php')) {
276 return false;
277 } else {
278 $version = null; //initialize variable for IDEs
279 include($CFG->dirroot.'/version.php');
280 return $version;
285 // activity module
286 if ($type === 'mod') {
287 if ($source === 'installed') {
288 if ($CFG->version < 2013092001.02) {
289 return $DB->get_field('modules', 'version', array('name'=>$name));
290 } else {
291 return get_config('mod_'.$name, 'version');
294 } else {
295 $mods = core_component::get_plugin_list('mod');
296 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
297 return false;
298 } else {
299 $plugin = new stdClass();
300 $plugin->version = null;
301 $module = $plugin;
302 include($mods[$name].'/version.php');
303 return $plugin->version;
308 // block
309 if ($type === 'block') {
310 if ($source === 'installed') {
311 if ($CFG->version < 2013092001.02) {
312 return $DB->get_field('block', 'version', array('name'=>$name));
313 } else {
314 return get_config('block_'.$name, 'version');
316 } else {
317 $blocks = core_component::get_plugin_list('block');
318 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
319 return false;
320 } else {
321 $plugin = new stdclass();
322 include($blocks[$name].'/version.php');
323 return $plugin->version;
328 // all other plugin types
329 if ($source === 'installed') {
330 return get_config($type.'_'.$name, 'version');
331 } else {
332 $plugins = core_component::get_plugin_list($type);
333 if (empty($plugins[$name])) {
334 return false;
335 } else {
336 $plugin = new stdclass();
337 include($plugins[$name].'/version.php');
338 return $plugin->version;
344 * Delete all plugin tables
346 * @param string $name Name of plugin, used as table prefix
347 * @param string $file Path to install.xml file
348 * @param bool $feedback defaults to true
349 * @return bool Always returns true
351 function drop_plugin_tables($name, $file, $feedback=true) {
352 global $CFG, $DB;
354 // first try normal delete
355 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
356 return true;
359 // then try to find all tables that start with name and are not in any xml file
360 $used_tables = get_used_table_names();
362 $tables = $DB->get_tables();
364 /// Iterate over, fixing id fields as necessary
365 foreach ($tables as $table) {
366 if (in_array($table, $used_tables)) {
367 continue;
370 if (strpos($table, $name) !== 0) {
371 continue;
374 // found orphan table --> delete it
375 if ($DB->get_manager()->table_exists($table)) {
376 $xmldb_table = new xmldb_table($table);
377 $DB->get_manager()->drop_table($xmldb_table);
381 return true;
385 * Returns names of all known tables == tables that moodle knows about.
387 * @return array Array of lowercase table names
389 function get_used_table_names() {
390 $table_names = array();
391 $dbdirs = get_db_directories();
393 foreach ($dbdirs as $dbdir) {
394 $file = $dbdir.'/install.xml';
396 $xmldb_file = new xmldb_file($file);
398 if (!$xmldb_file->fileExists()) {
399 continue;
402 $loaded = $xmldb_file->loadXMLStructure();
403 $structure = $xmldb_file->getStructure();
405 if ($loaded and $tables = $structure->getTables()) {
406 foreach($tables as $table) {
407 $table_names[] = strtolower($table->getName());
412 return $table_names;
416 * Returns list of all directories where we expect install.xml files
417 * @return array Array of paths
419 function get_db_directories() {
420 global $CFG;
422 $dbdirs = array();
424 /// First, the main one (lib/db)
425 $dbdirs[] = $CFG->libdir.'/db';
427 /// Then, all the ones defined by core_component::get_plugin_types()
428 $plugintypes = core_component::get_plugin_types();
429 foreach ($plugintypes as $plugintype => $pluginbasedir) {
430 if ($plugins = core_component::get_plugin_list($plugintype)) {
431 foreach ($plugins as $plugin => $plugindir) {
432 $dbdirs[] = $plugindir.'/db';
437 return $dbdirs;
441 * Try to obtain or release the cron lock.
442 * @param string $name name of lock
443 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
444 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
445 * @return bool true if lock obtained
447 function set_cron_lock($name, $until, $ignorecurrent=false) {
448 global $DB;
449 if (empty($name)) {
450 debugging("Tried to get a cron lock for a null fieldname");
451 return false;
454 // remove lock by force == remove from config table
455 if (is_null($until)) {
456 set_config($name, null);
457 return true;
460 if (!$ignorecurrent) {
461 // read value from db - other processes might have changed it
462 $value = $DB->get_field('config', 'value', array('name'=>$name));
464 if ($value and $value > time()) {
465 //lock active
466 return false;
470 set_config($name, $until);
471 return true;
475 * Test if and critical warnings are present
476 * @return bool
478 function admin_critical_warnings_present() {
479 global $SESSION;
481 if (!has_capability('moodle/site:config', context_system::instance())) {
482 return 0;
485 if (!isset($SESSION->admin_critical_warning)) {
486 $SESSION->admin_critical_warning = 0;
487 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
488 $SESSION->admin_critical_warning = 1;
492 return $SESSION->admin_critical_warning;
496 * Detects if float supports at least 10 decimal digits
498 * Detects if float supports at least 10 decimal digits
499 * and also if float-->string conversion works as expected.
501 * @return bool true if problem found
503 function is_float_problem() {
504 $num1 = 2009010200.01;
505 $num2 = 2009010200.02;
507 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
511 * Try to verify that dataroot is not accessible from web.
513 * Try to verify that dataroot is not accessible from web.
514 * It is not 100% correct but might help to reduce number of vulnerable sites.
515 * Protection from httpd.conf and .htaccess is not detected properly.
517 * @uses INSECURE_DATAROOT_WARNING
518 * @uses INSECURE_DATAROOT_ERROR
519 * @param bool $fetchtest try to test public access by fetching file, default false
520 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
522 function is_dataroot_insecure($fetchtest=false) {
523 global $CFG;
525 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
527 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
528 $rp = strrev(trim($rp, '/'));
529 $rp = explode('/', $rp);
530 foreach($rp as $r) {
531 if (strpos($siteroot, '/'.$r.'/') === 0) {
532 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
533 } else {
534 break; // probably alias root
538 $siteroot = strrev($siteroot);
539 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
541 if (strpos($dataroot, $siteroot) !== 0) {
542 return false;
545 if (!$fetchtest) {
546 return INSECURE_DATAROOT_WARNING;
549 // now try all methods to fetch a test file using http protocol
551 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
552 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
553 $httpdocroot = $matches[1];
554 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
555 make_upload_directory('diag');
556 $testfile = $CFG->dataroot.'/diag/public.txt';
557 if (!file_exists($testfile)) {
558 file_put_contents($testfile, 'test file, do not delete');
559 @chmod($testfile, $CFG->filepermissions);
561 $teststr = trim(file_get_contents($testfile));
562 if (empty($teststr)) {
563 // hmm, strange
564 return INSECURE_DATAROOT_WARNING;
567 $testurl = $datarooturl.'/diag/public.txt';
568 if (extension_loaded('curl') and
569 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
570 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
571 ($ch = @curl_init($testurl)) !== false) {
572 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
573 curl_setopt($ch, CURLOPT_HEADER, false);
574 $data = curl_exec($ch);
575 if (!curl_errno($ch)) {
576 $data = trim($data);
577 if ($data === $teststr) {
578 curl_close($ch);
579 return INSECURE_DATAROOT_ERROR;
582 curl_close($ch);
585 if ($data = @file_get_contents($testurl)) {
586 $data = trim($data);
587 if ($data === $teststr) {
588 return INSECURE_DATAROOT_ERROR;
592 preg_match('|https?://([^/]+)|i', $testurl, $matches);
593 $sitename = $matches[1];
594 $error = 0;
595 if ($fp = @fsockopen($sitename, 80, $error)) {
596 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
597 $localurl = $matches[1];
598 $out = "GET $localurl HTTP/1.1\r\n";
599 $out .= "Host: $sitename\r\n";
600 $out .= "Connection: Close\r\n\r\n";
601 fwrite($fp, $out);
602 $data = '';
603 $incoming = false;
604 while (!feof($fp)) {
605 if ($incoming) {
606 $data .= fgets($fp, 1024);
607 } else if (@fgets($fp, 1024) === "\r\n") {
608 $incoming = true;
611 fclose($fp);
612 $data = trim($data);
613 if ($data === $teststr) {
614 return INSECURE_DATAROOT_ERROR;
618 return INSECURE_DATAROOT_WARNING;
622 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
624 function enable_cli_maintenance_mode() {
625 global $CFG;
627 if (file_exists("$CFG->dataroot/climaintenance.html")) {
628 unlink("$CFG->dataroot/climaintenance.html");
631 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
632 $data = $CFG->maintenance_message;
633 $data = bootstrap_renderer::early_error_content($data, null, null, null);
634 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
636 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
637 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
639 } else {
640 $data = get_string('sitemaintenance', 'admin');
641 $data = bootstrap_renderer::early_error_content($data, null, null, null);
642 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
645 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
646 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
649 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
653 * Interface for anything appearing in the admin tree
655 * The interface that is implemented by anything that appears in the admin tree
656 * block. It forces inheriting classes to define a method for checking user permissions
657 * and methods for finding something in the admin tree.
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
661 interface part_of_admin_tree {
664 * Finds a named part_of_admin_tree.
666 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
667 * and not parentable_part_of_admin_tree, then this function should only check if
668 * $this->name matches $name. If it does, it should return a reference to $this,
669 * otherwise, it should return a reference to NULL.
671 * If a class inherits parentable_part_of_admin_tree, this method should be called
672 * recursively on all child objects (assuming, of course, the parent object's name
673 * doesn't match the search criterion).
675 * @param string $name The internal name of the part_of_admin_tree we're searching for.
676 * @return mixed An object reference or a NULL reference.
678 public function locate($name);
681 * Removes named part_of_admin_tree.
683 * @param string $name The internal name of the part_of_admin_tree we want to remove.
684 * @return bool success.
686 public function prune($name);
689 * Search using query
690 * @param string $query
691 * @return mixed array-object structure of found settings and pages
693 public function search($query);
696 * Verifies current user's access to this part_of_admin_tree.
698 * Used to check if the current user has access to this part of the admin tree or
699 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
700 * then this method is usually just a call to has_capability() in the site context.
702 * If a class inherits parentable_part_of_admin_tree, this method should return the
703 * logical OR of the return of check_access() on all child objects.
705 * @return bool True if the user has access, false if she doesn't.
707 public function check_access();
710 * Mostly useful for removing of some parts of the tree in admin tree block.
712 * @return True is hidden from normal list view
714 public function is_hidden();
717 * Show we display Save button at the page bottom?
718 * @return bool
720 public function show_save();
725 * Interface implemented by any part_of_admin_tree that has children.
727 * The interface implemented by any part_of_admin_tree that can be a parent
728 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
729 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
730 * include an add method for adding other part_of_admin_tree objects as children.
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 interface parentable_part_of_admin_tree extends part_of_admin_tree {
737 * Adds a part_of_admin_tree object to the admin tree.
739 * Used to add a part_of_admin_tree object to this object or a child of this
740 * object. $something should only be added if $destinationname matches
741 * $this->name. If it doesn't, add should be called on child objects that are
742 * also parentable_part_of_admin_tree's.
744 * $something should be appended as the last child in the $destinationname. If the
745 * $beforesibling is specified, $something should be prepended to it. If the given
746 * sibling is not found, $something should be appended to the end of $destinationname
747 * and a developer debugging message should be displayed.
749 * @param string $destinationname The internal name of the new parent for $something.
750 * @param part_of_admin_tree $something The object to be added.
751 * @return bool True on success, false on failure.
753 public function add($destinationname, $something, $beforesibling = null);
759 * The object used to represent folders (a.k.a. categories) in the admin tree block.
761 * Each admin_category object contains a number of part_of_admin_tree objects.
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class admin_category implements parentable_part_of_admin_tree {
767 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
768 protected $children;
769 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
770 public $name;
771 /** @var string The displayed name for this category. Usually obtained through get_string() */
772 public $visiblename;
773 /** @var bool Should this category be hidden in admin tree block? */
774 public $hidden;
775 /** @var mixed Either a string or an array or strings */
776 public $path;
777 /** @var mixed Either a string or an array or strings */
778 public $visiblepath;
780 /** @var array fast lookup category cache, all categories of one tree point to one cache */
781 protected $category_cache;
783 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
784 protected $sort = false;
785 /** @var bool If set to true children will be sorted in ascending order. */
786 protected $sortasc = true;
787 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
788 protected $sortsplit = true;
789 /** @var bool $sorted True if the children have been sorted and don't need resorting */
790 protected $sorted = false;
793 * Constructor for an empty admin category
795 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
796 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
797 * @param bool $hidden hide category in admin tree block, defaults to false
799 public function __construct($name, $visiblename, $hidden=false) {
800 $this->children = array();
801 $this->name = $name;
802 $this->visiblename = $visiblename;
803 $this->hidden = $hidden;
807 * Returns a reference to the part_of_admin_tree object with internal name $name.
809 * @param string $name The internal name of the object we want.
810 * @param bool $findpath initialize path and visiblepath arrays
811 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
812 * defaults to false
814 public function locate($name, $findpath=false) {
815 if (!isset($this->category_cache[$this->name])) {
816 // somebody much have purged the cache
817 $this->category_cache[$this->name] = $this;
820 if ($this->name == $name) {
821 if ($findpath) {
822 $this->visiblepath[] = $this->visiblename;
823 $this->path[] = $this->name;
825 return $this;
828 // quick category lookup
829 if (!$findpath and isset($this->category_cache[$name])) {
830 return $this->category_cache[$name];
833 $return = NULL;
834 foreach($this->children as $childid=>$unused) {
835 if ($return = $this->children[$childid]->locate($name, $findpath)) {
836 break;
840 if (!is_null($return) and $findpath) {
841 $return->visiblepath[] = $this->visiblename;
842 $return->path[] = $this->name;
845 return $return;
849 * Search using query
851 * @param string query
852 * @return mixed array-object structure of found settings and pages
854 public function search($query) {
855 $result = array();
856 foreach ($this->get_children() as $child) {
857 $subsearch = $child->search($query);
858 if (!is_array($subsearch)) {
859 debugging('Incorrect search result from '.$child->name);
860 continue;
862 $result = array_merge($result, $subsearch);
864 return $result;
868 * Removes part_of_admin_tree object with internal name $name.
870 * @param string $name The internal name of the object we want to remove.
871 * @return bool success
873 public function prune($name) {
875 if ($this->name == $name) {
876 return false; //can not remove itself
879 foreach($this->children as $precedence => $child) {
880 if ($child->name == $name) {
881 // clear cache and delete self
882 while($this->category_cache) {
883 // delete the cache, but keep the original array address
884 array_pop($this->category_cache);
886 unset($this->children[$precedence]);
887 return true;
888 } else if ($this->children[$precedence]->prune($name)) {
889 return true;
892 return false;
896 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
898 * By default the new part of the tree is appended as the last child of the parent. You
899 * can specify a sibling node that the new part should be prepended to. If the given
900 * sibling is not found, the part is appended to the end (as it would be by default) and
901 * a developer debugging message is displayed.
903 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
904 * @param string $destinationame The internal name of the immediate parent that we want for $something.
905 * @param mixed $something A part_of_admin_tree or setting instance to be added.
906 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something, $beforesibling = null) {
910 global $CFG;
912 $parent = $this->locate($parentname);
913 if (is_null($parent)) {
914 debugging('parent does not exist!');
915 return false;
918 if ($something instanceof part_of_admin_tree) {
919 if (!($parent instanceof parentable_part_of_admin_tree)) {
920 debugging('error - parts of tree can be inserted only into parentable parts');
921 return false;
923 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
924 // The name of the node is already used, simply warn the developer that this should not happen.
925 // It is intentional to check for the debug level before performing the check.
926 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
928 if (is_null($beforesibling)) {
929 // Append $something as the parent's last child.
930 $parent->children[] = $something;
931 } else {
932 if (!is_string($beforesibling) or trim($beforesibling) === '') {
933 throw new coding_exception('Unexpected value of the beforesibling parameter');
935 // Try to find the position of the sibling.
936 $siblingposition = null;
937 foreach ($parent->children as $childposition => $child) {
938 if ($child->name === $beforesibling) {
939 $siblingposition = $childposition;
940 break;
943 if (is_null($siblingposition)) {
944 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
945 $parent->children[] = $something;
946 } else {
947 $parent->children = array_merge(
948 array_slice($parent->children, 0, $siblingposition),
949 array($something),
950 array_slice($parent->children, $siblingposition)
954 if ($something instanceof admin_category) {
955 if (isset($this->category_cache[$something->name])) {
956 debugging('Duplicate admin category name: '.$something->name);
957 } else {
958 $this->category_cache[$something->name] = $something;
959 $something->category_cache =& $this->category_cache;
960 foreach ($something->children as $child) {
961 // just in case somebody already added subcategories
962 if ($child instanceof admin_category) {
963 if (isset($this->category_cache[$child->name])) {
964 debugging('Duplicate admin category name: '.$child->name);
965 } else {
966 $this->category_cache[$child->name] = $child;
967 $child->category_cache =& $this->category_cache;
973 return true;
975 } else {
976 debugging('error - can not add this element');
977 return false;
983 * Checks if the user has access to anything in this category.
985 * @return bool True if the user has access to at least one child in this category, false otherwise.
987 public function check_access() {
988 foreach ($this->children as $child) {
989 if ($child->check_access()) {
990 return true;
993 return false;
997 * Is this category hidden in admin tree block?
999 * @return bool True if hidden
1001 public function is_hidden() {
1002 return $this->hidden;
1006 * Show we display Save button at the page bottom?
1007 * @return bool
1009 public function show_save() {
1010 foreach ($this->children as $child) {
1011 if ($child->show_save()) {
1012 return true;
1015 return false;
1019 * Sets sorting on this category.
1021 * Please note this function doesn't actually do the sorting.
1022 * It can be called anytime.
1023 * Sorting occurs when the user calls get_children.
1024 * Code using the children array directly won't see the sorted results.
1026 * @param bool $sort If set to true children will be sorted, if false they won't be.
1027 * @param bool $asc If true sorting will be ascending, otherwise descending.
1028 * @param bool $split If true we sort pages and sub categories separately.
1030 public function set_sorting($sort, $asc = true, $split = true) {
1031 $this->sort = (bool)$sort;
1032 $this->sortasc = (bool)$asc;
1033 $this->sortsplit = (bool)$split;
1037 * Returns the children associated with this category.
1039 * @return part_of_admin_tree[]
1041 public function get_children() {
1042 // If we should sort and it hasn't already been sorted.
1043 if ($this->sort && !$this->sorted) {
1044 if ($this->sortsplit) {
1045 $categories = array();
1046 $pages = array();
1047 foreach ($this->children as $child) {
1048 if ($child instanceof admin_category) {
1049 $categories[] = $child;
1050 } else {
1051 $pages[] = $child;
1054 core_collator::asort_objects_by_property($categories, 'visiblename');
1055 core_collator::asort_objects_by_property($pages, 'visiblename');
1056 if (!$this->sortasc) {
1057 $categories = array_reverse($categories);
1058 $pages = array_reverse($pages);
1060 $this->children = array_merge($pages, $categories);
1061 } else {
1062 core_collator::asort_objects_by_property($this->children, 'visiblename');
1063 if (!$this->sortasc) {
1064 $this->children = array_reverse($this->children);
1067 $this->sorted = true;
1069 return $this->children;
1073 * Magically gets a property from this object.
1075 * @param $property
1076 * @return part_of_admin_tree[]
1077 * @throws coding_exception
1079 public function __get($property) {
1080 if ($property === 'children') {
1081 return $this->get_children();
1083 throw new coding_exception('Invalid property requested.');
1087 * Magically sets a property against this object.
1089 * @param string $property
1090 * @param mixed $value
1091 * @throws coding_exception
1093 public function __set($property, $value) {
1094 if ($property === 'children') {
1095 $this->sorted = false;
1096 $this->children = $value;
1097 } else {
1098 throw new coding_exception('Invalid property requested.');
1103 * Checks if an inaccessible property is set.
1105 * @param string $property
1106 * @return bool
1107 * @throws coding_exception
1109 public function __isset($property) {
1110 if ($property === 'children') {
1111 return isset($this->children);
1113 throw new coding_exception('Invalid property requested.');
1119 * Root of admin settings tree, does not have any parent.
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class admin_root extends admin_category {
1124 /** @var array List of errors */
1125 public $errors;
1126 /** @var string search query */
1127 public $search;
1128 /** @var bool full tree flag - true means all settings required, false only pages required */
1129 public $fulltree;
1130 /** @var bool flag indicating loaded tree */
1131 public $loaded;
1132 /** @var mixed site custom defaults overriding defaults in settings files*/
1133 public $custom_defaults;
1136 * @param bool $fulltree true means all settings required,
1137 * false only pages required
1139 public function __construct($fulltree) {
1140 global $CFG;
1142 parent::__construct('root', get_string('administration'), false);
1143 $this->errors = array();
1144 $this->search = '';
1145 $this->fulltree = $fulltree;
1146 $this->loaded = false;
1148 $this->category_cache = array();
1150 // load custom defaults if found
1151 $this->custom_defaults = null;
1152 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1153 if (is_readable($defaultsfile)) {
1154 $defaults = array();
1155 include($defaultsfile);
1156 if (is_array($defaults) and count($defaults)) {
1157 $this->custom_defaults = $defaults;
1163 * Empties children array, and sets loaded to false
1165 * @param bool $requirefulltree
1167 public function purge_children($requirefulltree) {
1168 $this->children = array();
1169 $this->fulltree = ($requirefulltree || $this->fulltree);
1170 $this->loaded = false;
1171 //break circular dependencies - this helps PHP 5.2
1172 while($this->category_cache) {
1173 array_pop($this->category_cache);
1175 $this->category_cache = array();
1181 * Links external PHP pages into the admin tree.
1183 * See detailed usage example at the top of this document (adminlib.php)
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1187 class admin_externalpage implements part_of_admin_tree {
1189 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1190 public $name;
1192 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1193 public $visiblename;
1195 /** @var string The external URL that we should link to when someone requests this external page. */
1196 public $url;
1198 /** @var string The role capability/permission a user must have to access this external page. */
1199 public $req_capability;
1201 /** @var object The context in which capability/permission should be checked, default is site context. */
1202 public $context;
1204 /** @var bool hidden in admin tree block. */
1205 public $hidden;
1207 /** @var mixed either string or array of string */
1208 public $path;
1210 /** @var array list of visible names of page parents */
1211 public $visiblepath;
1214 * Constructor for adding an external page into the admin tree.
1216 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1217 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1218 * @param string $url The external URL that we should link to when someone requests this external page.
1219 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1220 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1221 * @param stdClass $context The context the page relates to. Not sure what happens
1222 * if you specify something other than system or front page. Defaults to system.
1224 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1225 $this->name = $name;
1226 $this->visiblename = $visiblename;
1227 $this->url = $url;
1228 if (is_array($req_capability)) {
1229 $this->req_capability = $req_capability;
1230 } else {
1231 $this->req_capability = array($req_capability);
1233 $this->hidden = $hidden;
1234 $this->context = $context;
1238 * Returns a reference to the part_of_admin_tree object with internal name $name.
1240 * @param string $name The internal name of the object we want.
1241 * @param bool $findpath defaults to false
1242 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1244 public function locate($name, $findpath=false) {
1245 if ($this->name == $name) {
1246 if ($findpath) {
1247 $this->visiblepath = array($this->visiblename);
1248 $this->path = array($this->name);
1250 return $this;
1251 } else {
1252 $return = NULL;
1253 return $return;
1258 * This function always returns false, required function by interface
1260 * @param string $name
1261 * @return false
1263 public function prune($name) {
1264 return false;
1268 * Search using query
1270 * @param string $query
1271 * @return mixed array-object structure of found settings and pages
1273 public function search($query) {
1274 $found = false;
1275 if (strpos(strtolower($this->name), $query) !== false) {
1276 $found = true;
1277 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1278 $found = true;
1280 if ($found) {
1281 $result = new stdClass();
1282 $result->page = $this;
1283 $result->settings = array();
1284 return array($this->name => $result);
1285 } else {
1286 return array();
1291 * Determines if the current user has access to this external page based on $this->req_capability.
1293 * @return bool True if user has access, false otherwise.
1295 public function check_access() {
1296 global $CFG;
1297 $context = empty($this->context) ? context_system::instance() : $this->context;
1298 foreach($this->req_capability as $cap) {
1299 if (has_capability($cap, $context)) {
1300 return true;
1303 return false;
1307 * Is this external page hidden in admin tree block?
1309 * @return bool True if hidden
1311 public function is_hidden() {
1312 return $this->hidden;
1316 * Show we display Save button at the page bottom?
1317 * @return bool
1319 public function show_save() {
1320 return false;
1326 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 class admin_settingpage implements part_of_admin_tree {
1332 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1333 public $name;
1335 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1336 public $visiblename;
1338 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1339 public $settings;
1341 /** @var string The role capability/permission a user must have to access this external page. */
1342 public $req_capability;
1344 /** @var object The context in which capability/permission should be checked, default is site context. */
1345 public $context;
1347 /** @var bool hidden in admin tree block. */
1348 public $hidden;
1350 /** @var mixed string of paths or array of strings of paths */
1351 public $path;
1353 /** @var array list of visible names of page parents */
1354 public $visiblepath;
1357 * see admin_settingpage for details of this function
1359 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1360 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1361 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1362 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1363 * @param stdClass $context The context the page relates to. Not sure what happens
1364 * if you specify something other than system or front page. Defaults to system.
1366 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1367 $this->settings = new stdClass();
1368 $this->name = $name;
1369 $this->visiblename = $visiblename;
1370 if (is_array($req_capability)) {
1371 $this->req_capability = $req_capability;
1372 } else {
1373 $this->req_capability = array($req_capability);
1375 $this->hidden = $hidden;
1376 $this->context = $context;
1380 * see admin_category
1382 * @param string $name
1383 * @param bool $findpath
1384 * @return mixed Object (this) if name == this->name, else returns null
1386 public function locate($name, $findpath=false) {
1387 if ($this->name == $name) {
1388 if ($findpath) {
1389 $this->visiblepath = array($this->visiblename);
1390 $this->path = array($this->name);
1392 return $this;
1393 } else {
1394 $return = NULL;
1395 return $return;
1400 * Search string in settings page.
1402 * @param string $query
1403 * @return array
1405 public function search($query) {
1406 $found = array();
1408 foreach ($this->settings as $setting) {
1409 if ($setting->is_related($query)) {
1410 $found[] = $setting;
1414 if ($found) {
1415 $result = new stdClass();
1416 $result->page = $this;
1417 $result->settings = $found;
1418 return array($this->name => $result);
1421 $found = false;
1422 if (strpos(strtolower($this->name), $query) !== false) {
1423 $found = true;
1424 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1425 $found = true;
1427 if ($found) {
1428 $result = new stdClass();
1429 $result->page = $this;
1430 $result->settings = array();
1431 return array($this->name => $result);
1432 } else {
1433 return array();
1438 * This function always returns false, required by interface
1440 * @param string $name
1441 * @return bool Always false
1443 public function prune($name) {
1444 return false;
1448 * adds an admin_setting to this admin_settingpage
1450 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1451 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1453 * @param object $setting is the admin_setting object you want to add
1454 * @return bool true if successful, false if not
1456 public function add($setting) {
1457 if (!($setting instanceof admin_setting)) {
1458 debugging('error - not a setting instance');
1459 return false;
1462 $this->settings->{$setting->name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1554 * Constructor
1555 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1556 * or 'myplugin/mysetting' for ones in config_plugins.
1557 * @param string $visiblename localised name
1558 * @param string $description localised long description
1559 * @param mixed $defaultsetting string or array depending on implementation
1561 public function __construct($name, $visiblename, $description, $defaultsetting) {
1562 $this->parse_setting_name($name);
1563 $this->visiblename = $visiblename;
1564 $this->description = $description;
1565 $this->defaultsetting = $defaultsetting;
1569 * Generic function to add a flag to this admin setting.
1571 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1572 * @param bool $default - The default for the flag
1573 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1574 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1576 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1577 if (empty($this->flags[$shortname])) {
1578 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1579 } else {
1580 $this->flags[$shortname]->set_options($enabled, $default);
1585 * Set the enabled options flag on this admin setting.
1587 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1588 * @param bool $default - The default for the flag
1590 public function set_enabled_flag_options($enabled, $default) {
1591 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1595 * Set the advanced options flag on this admin setting.
1597 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1598 * @param bool $default - The default for the flag
1600 public function set_advanced_flag_options($enabled, $default) {
1601 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1606 * Set the locked options flag on this admin setting.
1608 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1609 * @param bool $default - The default for the flag
1611 public function set_locked_flag_options($enabled, $default) {
1612 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1616 * Get the currently saved value for a setting flag
1618 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1619 * @return bool
1621 public function get_setting_flag_value(admin_setting_flag $flag) {
1622 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1623 if (!isset($value)) {
1624 $value = $flag->get_default();
1627 return !empty($value);
1631 * Get the list of defaults for the flags on this setting.
1633 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1635 public function get_setting_flag_defaults(& $defaults) {
1636 foreach ($this->flags as $flag) {
1637 if ($flag->is_enabled() && $flag->get_default()) {
1638 $defaults[] = $flag->get_displayname();
1644 * Output the input fields for the advanced and locked flags on this setting.
1646 * @param bool $adv - The current value of the advanced flag.
1647 * @param bool $locked - The current value of the locked flag.
1648 * @return string $output - The html for the flags.
1650 public function output_setting_flags() {
1651 $output = '';
1653 foreach ($this->flags as $flag) {
1654 if ($flag->is_enabled()) {
1655 $output .= $flag->output_setting_flag($this);
1659 if (!empty($output)) {
1660 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1662 return $output;
1666 * Write the values of the flags for this admin setting.
1668 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1669 * @return bool - true if successful.
1671 public function write_setting_flags($data) {
1672 $result = true;
1673 foreach ($this->flags as $flag) {
1674 $result = $result && $flag->write_setting_flag($this, $data);
1676 return $result;
1680 * Set up $this->name and potentially $this->plugin
1682 * Set up $this->name and possibly $this->plugin based on whether $name looks
1683 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1684 * on the names, that is, output a developer debug warning if the name
1685 * contains anything other than [a-zA-Z0-9_]+.
1687 * @param string $name the setting name passed in to the constructor.
1689 private function parse_setting_name($name) {
1690 $bits = explode('/', $name);
1691 if (count($bits) > 2) {
1692 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1694 $this->name = array_pop($bits);
1695 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1698 if (!empty($bits)) {
1699 $this->plugin = array_pop($bits);
1700 if ($this->plugin === 'moodle') {
1701 $this->plugin = null;
1702 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1703 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1709 * Returns the fullname prefixed by the plugin
1710 * @return string
1712 public function get_full_name() {
1713 return 's_'.$this->plugin.'_'.$this->name;
1717 * Returns the ID string based on plugin and name
1718 * @return string
1720 public function get_id() {
1721 return 'id_s_'.$this->plugin.'_'.$this->name;
1725 * @param bool $affectsmodinfo If true, changes to this setting will
1726 * cause the course cache to be rebuilt
1728 public function set_affects_modinfo($affectsmodinfo) {
1729 $this->affectsmodinfo = $affectsmodinfo;
1733 * Returns the config if possible
1735 * @return mixed returns config if successful else null
1737 public function config_read($name) {
1738 global $CFG;
1739 if (!empty($this->plugin)) {
1740 $value = get_config($this->plugin, $name);
1741 return $value === false ? NULL : $value;
1743 } else {
1744 if (isset($CFG->$name)) {
1745 return $CFG->$name;
1746 } else {
1747 return NULL;
1753 * Used to set a config pair and log change
1755 * @param string $name
1756 * @param mixed $value Gets converted to string if not null
1757 * @return bool Write setting to config table
1759 public function config_write($name, $value) {
1760 global $DB, $USER, $CFG;
1762 if ($this->nosave) {
1763 return true;
1766 // make sure it is a real change
1767 $oldvalue = get_config($this->plugin, $name);
1768 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1769 $value = is_null($value) ? null : (string)$value;
1771 if ($oldvalue === $value) {
1772 return true;
1775 // store change
1776 set_config($name, $value, $this->plugin);
1778 // Some admin settings affect course modinfo
1779 if ($this->affectsmodinfo) {
1780 // Clear course cache for all courses
1781 rebuild_course_cache(0, true);
1784 $this->add_to_config_log($name, $oldvalue, $value);
1786 return true; // BC only
1790 * Log config changes if necessary.
1791 * @param string $name
1792 * @param string $oldvalue
1793 * @param string $value
1795 protected function add_to_config_log($name, $oldvalue, $value) {
1796 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1800 * Returns current value of this setting
1801 * @return mixed array or string depending on instance, NULL means not set yet
1803 public abstract function get_setting();
1806 * Returns default setting if exists
1807 * @return mixed array or string depending on instance; NULL means no default, user must supply
1809 public function get_defaultsetting() {
1810 $adminroot = admin_get_root(false, false);
1811 if (!empty($adminroot->custom_defaults)) {
1812 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1813 if (isset($adminroot->custom_defaults[$plugin])) {
1814 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1815 return $adminroot->custom_defaults[$plugin][$this->name];
1819 return $this->defaultsetting;
1823 * Store new setting
1825 * @param mixed $data string or array, must not be NULL
1826 * @return string empty string if ok, string error message otherwise
1828 public abstract function write_setting($data);
1831 * Return part of form with setting
1832 * This function should always be overwritten
1834 * @param mixed $data array or string depending on setting
1835 * @param string $query
1836 * @return string
1838 public function output_html($data, $query='') {
1839 // should be overridden
1840 return;
1844 * Function called if setting updated - cleanup, cache reset, etc.
1845 * @param string $functionname Sets the function name
1846 * @return void
1848 public function set_updatedcallback($functionname) {
1849 $this->updatedcallback = $functionname;
1853 * Execute postupdatecallback if necessary.
1854 * @param mixed $original original value before write_setting()
1855 * @return bool true if changed, false if not.
1857 public function post_write_settings($original) {
1858 // Comparison must work for arrays too.
1859 if (serialize($original) === serialize($this->get_setting())) {
1860 return false;
1863 $callbackfunction = $this->updatedcallback;
1864 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1865 $callbackfunction($this->get_full_name());
1867 return true;
1871 * Is setting related to query text - used when searching
1872 * @param string $query
1873 * @return bool
1875 public function is_related($query) {
1876 if (strpos(strtolower($this->name), $query) !== false) {
1877 return true;
1879 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1883 return true;
1885 $current = $this->get_setting();
1886 if (!is_null($current)) {
1887 if (is_string($current)) {
1888 if (strpos(core_text::strtolower($current), $query) !== false) {
1889 return true;
1893 $default = $this->get_defaultsetting();
1894 if (!is_null($default)) {
1895 if (is_string($default)) {
1896 if (strpos(core_text::strtolower($default), $query) !== false) {
1897 return true;
1901 return false;
1906 * An additional option that can be applied to an admin setting.
1907 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class admin_setting_flag {
1912 /** @var bool Flag to indicate if this option can be toggled for this setting */
1913 private $enabled = false;
1914 /** @var bool Flag to indicate if this option defaults to true or false */
1915 private $default = false;
1916 /** @var string Short string used to create setting name - e.g. 'adv' */
1917 private $shortname = '';
1918 /** @var string String used as the label for this flag */
1919 private $displayname = '';
1920 /** @const Checkbox for this flag is displayed in admin page */
1921 const ENABLED = true;
1922 /** @const Checkbox for this flag is not displayed in admin page */
1923 const DISABLED = false;
1926 * Constructor
1928 * @param bool $enabled Can this option can be toggled.
1929 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1930 * @param bool $default The default checked state for this setting option.
1931 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1932 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1934 public function __construct($enabled, $default, $shortname, $displayname) {
1935 $this->shortname = $shortname;
1936 $this->displayname = $displayname;
1937 $this->set_options($enabled, $default);
1941 * Update the values of this setting options class
1943 * @param bool $enabled Can this option can be toggled.
1944 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1945 * @param bool $default The default checked state for this setting option.
1947 public function set_options($enabled, $default) {
1948 $this->enabled = $enabled;
1949 $this->default = $default;
1953 * Should this option appear in the interface and be toggleable?
1955 * @return bool Is it enabled?
1957 public function is_enabled() {
1958 return $this->enabled;
1962 * Should this option be checked by default?
1964 * @return bool Is it on by default?
1966 public function get_default() {
1967 return $this->default;
1971 * Return the short name for this flag. e.g. 'adv' or 'locked'
1973 * @return string
1975 public function get_shortname() {
1976 return $this->shortname;
1980 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1982 * @return string
1984 public function get_displayname() {
1985 return $this->displayname;
1989 * Save the submitted data for this flag - or set it to the default if $data is null.
1991 * @param admin_setting $setting - The admin setting for this flag
1992 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1993 * @return bool
1995 public function write_setting_flag(admin_setting $setting, $data) {
1996 $result = true;
1997 if ($this->is_enabled()) {
1998 if (!isset($data)) {
1999 $value = $this->get_default();
2000 } else {
2001 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2003 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2006 return $result;
2011 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2013 * @param admin_setting $setting - The admin setting for this flag
2014 * @return string - The html for the checkbox.
2016 public function output_setting_flag(admin_setting $setting) {
2017 $value = $setting->get_setting_flag_value($this);
2018 $output = ' <input type="checkbox" class="form-checkbox" ' .
2019 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2020 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2021 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2022 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2023 $this->get_displayname() .
2024 ' </label> ';
2025 return $output;
2031 * No setting - just heading and text.
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class admin_setting_heading extends admin_setting {
2038 * not a setting, just text
2039 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2040 * @param string $heading heading
2041 * @param string $information text in box
2043 public function __construct($name, $heading, $information) {
2044 $this->nosave = true;
2045 parent::__construct($name, $heading, $information, '');
2049 * Always returns true
2050 * @return bool Always returns true
2052 public function get_setting() {
2053 return true;
2057 * Always returns true
2058 * @return bool Always returns true
2060 public function get_defaultsetting() {
2061 return true;
2065 * Never write settings
2066 * @return string Always returns an empty string
2068 public function write_setting($data) {
2069 // do not write any setting
2070 return '';
2074 * Returns an HTML string
2075 * @return string Returns an HTML string
2077 public function output_html($data, $query='') {
2078 global $OUTPUT;
2079 $return = '';
2080 if ($this->visiblename != '') {
2081 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2083 if ($this->description != '') {
2084 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2086 return $return;
2092 * The most flexibly setting, user is typing text
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configtext extends admin_setting {
2098 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2099 public $paramtype;
2100 /** @var int default field size */
2101 public $size;
2104 * Config text constructor
2106 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2107 * @param string $visiblename localised
2108 * @param string $description long localised info
2109 * @param string $defaultsetting
2110 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2111 * @param int $size default field size
2113 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2114 $this->paramtype = $paramtype;
2115 if (!is_null($size)) {
2116 $this->size = $size;
2117 } else {
2118 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2120 parent::__construct($name, $visiblename, $description, $defaultsetting);
2124 * Return the setting
2126 * @return mixed returns config if successful else null
2128 public function get_setting() {
2129 return $this->config_read($this->name);
2132 public function write_setting($data) {
2133 if ($this->paramtype === PARAM_INT and $data === '') {
2134 // do not complain if '' used instead of 0
2135 $data = 0;
2137 // $data is a string
2138 $validated = $this->validate($data);
2139 if ($validated !== true) {
2140 return $validated;
2142 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2146 * Validate data before storage
2147 * @param string data
2148 * @return mixed true if ok string if error found
2150 public function validate($data) {
2151 // allow paramtype to be a custom regex if it is the form of /pattern/
2152 if (preg_match('#^/.*/$#', $this->paramtype)) {
2153 if (preg_match($this->paramtype, $data)) {
2154 return true;
2155 } else {
2156 return get_string('validateerror', 'admin');
2159 } else if ($this->paramtype === PARAM_RAW) {
2160 return true;
2162 } else {
2163 $cleaned = clean_param($data, $this->paramtype);
2164 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2165 return true;
2166 } else {
2167 return get_string('validateerror', 'admin');
2173 * Return an XHTML string for the setting
2174 * @return string Returns an XHTML string
2176 public function output_html($data, $query='') {
2177 $default = $this->get_defaultsetting();
2179 return format_admin_setting($this, $this->visiblename,
2180 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2181 $this->description, true, '', $default, $query);
2186 * Text input with a maximum length constraint.
2188 * @copyright 2015 onwards Ankit Agarwal
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2193 /** @var int maximum number of chars allowed. */
2194 protected $maxlength;
2197 * Config text constructor
2199 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2200 * or 'myplugin/mysetting' for ones in config_plugins.
2201 * @param string $visiblename localised
2202 * @param string $description long localised info
2203 * @param string $defaultsetting
2204 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2205 * @param int $size default field size
2206 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2208 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2209 $size=null, $maxlength = 0) {
2210 $this->maxlength = $maxlength;
2211 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2215 * Validate data before storage
2217 * @param string $data data
2218 * @return mixed true if ok string if error found
2220 public function validate($data) {
2221 $parentvalidation = parent::validate($data);
2222 if ($parentvalidation === true) {
2223 if ($this->maxlength > 0) {
2224 // Max length check.
2225 $length = core_text::strlen($data);
2226 if ($length > $this->maxlength) {
2227 return get_string('maximumchars', 'moodle', $this->maxlength);
2229 return true;
2230 } else {
2231 return true; // No max length check needed.
2233 } else {
2234 return $parentvalidation;
2240 * General text area without html editor.
2242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2244 class admin_setting_configtextarea extends admin_setting_configtext {
2245 private $rows;
2246 private $cols;
2249 * @param string $name
2250 * @param string $visiblename
2251 * @param string $description
2252 * @param mixed $defaultsetting string or array
2253 * @param mixed $paramtype
2254 * @param string $cols The number of columns to make the editor
2255 * @param string $rows The number of rows to make the editor
2257 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2258 $this->rows = $rows;
2259 $this->cols = $cols;
2260 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2264 * Returns an XHTML string for the editor
2266 * @param string $data
2267 * @param string $query
2268 * @return string XHTML string for the editor
2270 public function output_html($data, $query='') {
2271 $default = $this->get_defaultsetting();
2273 $defaultinfo = $default;
2274 if (!is_null($default) and $default !== '') {
2275 $defaultinfo = "\n".$default;
2278 return format_admin_setting($this, $this->visiblename,
2279 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2280 $this->description, true, '', $defaultinfo, $query);
2286 * General text area with html editor.
2288 class admin_setting_confightmleditor extends admin_setting_configtext {
2289 private $rows;
2290 private $cols;
2293 * @param string $name
2294 * @param string $visiblename
2295 * @param string $description
2296 * @param mixed $defaultsetting string or array
2297 * @param mixed $paramtype
2299 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2300 $this->rows = $rows;
2301 $this->cols = $cols;
2302 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2303 editors_head_setup();
2307 * Returns an XHTML string for the editor
2309 * @param string $data
2310 * @param string $query
2311 * @return string XHTML string for the editor
2313 public function output_html($data, $query='') {
2314 $default = $this->get_defaultsetting();
2316 $defaultinfo = $default;
2317 if (!is_null($default) and $default !== '') {
2318 $defaultinfo = "\n".$default;
2321 $editor = editors_get_preferred_editor(FORMAT_HTML);
2322 $editor->use_editor($this->get_id(), array('noclean'=>true));
2324 return format_admin_setting($this, $this->visiblename,
2325 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2326 $this->description, true, '', $defaultinfo, $query);
2332 * Password field, allows unmasking of password
2334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2336 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2338 * Constructor
2339 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2340 * @param string $visiblename localised
2341 * @param string $description long localised info
2342 * @param string $defaultsetting default password
2344 public function __construct($name, $visiblename, $description, $defaultsetting) {
2345 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2349 * Log config changes if necessary.
2350 * @param string $name
2351 * @param string $oldvalue
2352 * @param string $value
2354 protected function add_to_config_log($name, $oldvalue, $value) {
2355 if ($value !== '') {
2356 $value = '********';
2358 if ($oldvalue !== '' and $oldvalue !== null) {
2359 $oldvalue = '********';
2361 parent::add_to_config_log($name, $oldvalue, $value);
2365 * Returns XHTML for the field
2366 * Writes Javascript into the HTML below right before the last div
2368 * @todo Make javascript available through newer methods if possible
2369 * @param string $data Value for the field
2370 * @param string $query Passed as final argument for format_admin_setting
2371 * @return string XHTML field
2373 public function output_html($data, $query='') {
2374 $id = $this->get_id();
2375 $unmask = get_string('unmaskpassword', 'form');
2376 $unmaskjs = '<script type="text/javascript">
2377 //<![CDATA[
2378 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2380 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2382 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2384 var unmaskchb = document.createElement("input");
2385 unmaskchb.setAttribute("type", "checkbox");
2386 unmaskchb.setAttribute("id", "'.$id.'unmask");
2387 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2388 unmaskdiv.appendChild(unmaskchb);
2390 var unmasklbl = document.createElement("label");
2391 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2392 if (is_ie) {
2393 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2394 } else {
2395 unmasklbl.setAttribute("for", "'.$id.'unmask");
2397 unmaskdiv.appendChild(unmasklbl);
2399 if (is_ie) {
2400 // ugly hack to work around the famous onchange IE bug
2401 unmaskchb.onclick = function() {this.blur();};
2402 unmaskdiv.onclick = function() {this.blur();};
2404 //]]>
2405 </script>';
2406 return format_admin_setting($this, $this->visiblename,
2407 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
2408 $this->description, true, '', NULL, $query);
2413 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2414 * Note: Only advanced makes sense right now - locked does not.
2416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2418 class admin_setting_configempty extends admin_setting_configtext {
2421 * @param string $name
2422 * @param string $visiblename
2423 * @param string $description
2425 public function __construct($name, $visiblename, $description) {
2426 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2430 * Returns an XHTML string for the hidden field
2432 * @param string $data
2433 * @param string $query
2434 * @return string XHTML string for the editor
2436 public function output_html($data, $query='') {
2437 return format_admin_setting($this,
2438 $this->visiblename,
2439 '<div class="form-empty" >' .
2440 '<input type="hidden"' .
2441 ' id="'. $this->get_id() .'"' .
2442 ' name="'. $this->get_full_name() .'"' .
2443 ' value=""/></div>',
2444 $this->description,
2445 true,
2447 get_string('none'),
2448 $query);
2454 * Path to directory
2456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2458 class admin_setting_configfile extends admin_setting_configtext {
2460 * Constructor
2461 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2462 * @param string $visiblename localised
2463 * @param string $description long localised info
2464 * @param string $defaultdirectory default directory location
2466 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2467 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2471 * Returns XHTML for the field
2473 * Returns XHTML for the field and also checks whether the file
2474 * specified in $data exists using file_exists()
2476 * @param string $data File name and path to use in value attr
2477 * @param string $query
2478 * @return string XHTML field
2480 public function output_html($data, $query='') {
2481 global $CFG;
2482 $default = $this->get_defaultsetting();
2484 if ($data) {
2485 if (file_exists($data)) {
2486 $executable = '<span class="pathok">&#x2714;</span>';
2487 } else {
2488 $executable = '<span class="patherror">&#x2718;</span>';
2490 } else {
2491 $executable = '';
2493 $readonly = '';
2494 if (!empty($CFG->preventexecpath)) {
2495 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2496 $readonly = 'readonly="readonly"';
2499 return format_admin_setting($this, $this->visiblename,
2500 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2501 $this->description, true, '', $default, $query);
2505 * Checks if execpatch has been disabled in config.php
2507 public function write_setting($data) {
2508 global $CFG;
2509 if (!empty($CFG->preventexecpath)) {
2510 if ($this->get_setting() === null) {
2511 // Use default during installation.
2512 $data = $this->get_defaultsetting();
2513 if ($data === null) {
2514 $data = '';
2516 } else {
2517 return '';
2520 return parent::write_setting($data);
2526 * Path to executable file
2528 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2530 class admin_setting_configexecutable extends admin_setting_configfile {
2533 * Returns an XHTML field
2535 * @param string $data This is the value for the field
2536 * @param string $query
2537 * @return string XHTML field
2539 public function output_html($data, $query='') {
2540 global $CFG;
2541 $default = $this->get_defaultsetting();
2543 if ($data) {
2544 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2545 $executable = '<span class="pathok">&#x2714;</span>';
2546 } else {
2547 $executable = '<span class="patherror">&#x2718;</span>';
2549 } else {
2550 $executable = '';
2552 $readonly = '';
2553 if (!empty($CFG->preventexecpath)) {
2554 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2555 $readonly = 'readonly="readonly"';
2558 return format_admin_setting($this, $this->visiblename,
2559 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2560 $this->description, true, '', $default, $query);
2566 * Path to directory
2568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2570 class admin_setting_configdirectory extends admin_setting_configfile {
2573 * Returns an XHTML field
2575 * @param string $data This is the value for the field
2576 * @param string $query
2577 * @return string XHTML
2579 public function output_html($data, $query='') {
2580 global $CFG;
2581 $default = $this->get_defaultsetting();
2583 if ($data) {
2584 if (file_exists($data) and is_dir($data)) {
2585 $executable = '<span class="pathok">&#x2714;</span>';
2586 } else {
2587 $executable = '<span class="patherror">&#x2718;</span>';
2589 } else {
2590 $executable = '';
2592 $readonly = '';
2593 if (!empty($CFG->preventexecpath)) {
2594 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2595 $readonly = 'readonly="readonly"';
2598 return format_admin_setting($this, $this->visiblename,
2599 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2600 $this->description, true, '', $default, $query);
2606 * Checkbox
2608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2610 class admin_setting_configcheckbox extends admin_setting {
2611 /** @var string Value used when checked */
2612 public $yes;
2613 /** @var string Value used when not checked */
2614 public $no;
2617 * Constructor
2618 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2619 * @param string $visiblename localised
2620 * @param string $description long localised info
2621 * @param string $defaultsetting
2622 * @param string $yes value used when checked
2623 * @param string $no value used when not checked
2625 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2626 parent::__construct($name, $visiblename, $description, $defaultsetting);
2627 $this->yes = (string)$yes;
2628 $this->no = (string)$no;
2632 * Retrieves the current setting using the objects name
2634 * @return string
2636 public function get_setting() {
2637 return $this->config_read($this->name);
2641 * Sets the value for the setting
2643 * Sets the value for the setting to either the yes or no values
2644 * of the object by comparing $data to yes
2646 * @param mixed $data Gets converted to str for comparison against yes value
2647 * @return string empty string or error
2649 public function write_setting($data) {
2650 if ((string)$data === $this->yes) { // convert to strings before comparison
2651 $data = $this->yes;
2652 } else {
2653 $data = $this->no;
2655 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2659 * Returns an XHTML checkbox field
2661 * @param string $data If $data matches yes then checkbox is checked
2662 * @param string $query
2663 * @return string XHTML field
2665 public function output_html($data, $query='') {
2666 $default = $this->get_defaultsetting();
2668 if (!is_null($default)) {
2669 if ((string)$default === $this->yes) {
2670 $defaultinfo = get_string('checkboxyes', 'admin');
2671 } else {
2672 $defaultinfo = get_string('checkboxno', 'admin');
2674 } else {
2675 $defaultinfo = NULL;
2678 if ((string)$data === $this->yes) { // convert to strings before comparison
2679 $checked = 'checked="checked"';
2680 } else {
2681 $checked = '';
2684 return format_admin_setting($this, $this->visiblename,
2685 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2686 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2687 $this->description, true, '', $defaultinfo, $query);
2693 * Multiple checkboxes, each represents different value, stored in csv format
2695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2697 class admin_setting_configmulticheckbox extends admin_setting {
2698 /** @var array Array of choices value=>label */
2699 public $choices;
2702 * Constructor: uses parent::__construct
2704 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2705 * @param string $visiblename localised
2706 * @param string $description long localised info
2707 * @param array $defaultsetting array of selected
2708 * @param array $choices array of $value=>$label for each checkbox
2710 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2711 $this->choices = $choices;
2712 parent::__construct($name, $visiblename, $description, $defaultsetting);
2716 * This public function may be used in ancestors for lazy loading of choices
2718 * @todo Check if this function is still required content commented out only returns true
2719 * @return bool true if loaded, false if error
2721 public function load_choices() {
2723 if (is_array($this->choices)) {
2724 return true;
2726 .... load choices here
2728 return true;
2732 * Is setting related to query text - used when searching
2734 * @param string $query
2735 * @return bool true on related, false on not or failure
2737 public function is_related($query) {
2738 if (!$this->load_choices() or empty($this->choices)) {
2739 return false;
2741 if (parent::is_related($query)) {
2742 return true;
2745 foreach ($this->choices as $desc) {
2746 if (strpos(core_text::strtolower($desc), $query) !== false) {
2747 return true;
2750 return false;
2754 * Returns the current setting if it is set
2756 * @return mixed null if null, else an array
2758 public function get_setting() {
2759 $result = $this->config_read($this->name);
2761 if (is_null($result)) {
2762 return NULL;
2764 if ($result === '') {
2765 return array();
2767 $enabled = explode(',', $result);
2768 $setting = array();
2769 foreach ($enabled as $option) {
2770 $setting[$option] = 1;
2772 return $setting;
2776 * Saves the setting(s) provided in $data
2778 * @param array $data An array of data, if not array returns empty str
2779 * @return mixed empty string on useless data or bool true=success, false=failed
2781 public function write_setting($data) {
2782 if (!is_array($data)) {
2783 return ''; // ignore it
2785 if (!$this->load_choices() or empty($this->choices)) {
2786 return '';
2788 unset($data['xxxxx']);
2789 $result = array();
2790 foreach ($data as $key => $value) {
2791 if ($value and array_key_exists($key, $this->choices)) {
2792 $result[] = $key;
2795 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2799 * Returns XHTML field(s) as required by choices
2801 * Relies on data being an array should data ever be another valid vartype with
2802 * acceptable value this may cause a warning/error
2803 * if (!is_array($data)) would fix the problem
2805 * @todo Add vartype handling to ensure $data is an array
2807 * @param array $data An array of checked values
2808 * @param string $query
2809 * @return string XHTML field
2811 public function output_html($data, $query='') {
2812 if (!$this->load_choices() or empty($this->choices)) {
2813 return '';
2815 $default = $this->get_defaultsetting();
2816 if (is_null($default)) {
2817 $default = array();
2819 if (is_null($data)) {
2820 $data = array();
2822 $options = array();
2823 $defaults = array();
2824 foreach ($this->choices as $key=>$description) {
2825 if (!empty($data[$key])) {
2826 $checked = 'checked="checked"';
2827 } else {
2828 $checked = '';
2830 if (!empty($default[$key])) {
2831 $defaults[] = $description;
2834 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2835 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2838 if (is_null($default)) {
2839 $defaultinfo = NULL;
2840 } else if (!empty($defaults)) {
2841 $defaultinfo = implode(', ', $defaults);
2842 } else {
2843 $defaultinfo = get_string('none');
2846 $return = '<div class="form-multicheckbox">';
2847 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2848 if ($options) {
2849 $return .= '<ul>';
2850 foreach ($options as $option) {
2851 $return .= '<li>'.$option.'</li>';
2853 $return .= '</ul>';
2855 $return .= '</div>';
2857 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2864 * Multiple checkboxes 2, value stored as string 00101011
2866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2868 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2871 * Returns the setting if set
2873 * @return mixed null if not set, else an array of set settings
2875 public function get_setting() {
2876 $result = $this->config_read($this->name);
2877 if (is_null($result)) {
2878 return NULL;
2880 if (!$this->load_choices()) {
2881 return NULL;
2883 $result = str_pad($result, count($this->choices), '0');
2884 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2885 $setting = array();
2886 foreach ($this->choices as $key=>$unused) {
2887 $value = array_shift($result);
2888 if ($value) {
2889 $setting[$key] = 1;
2892 return $setting;
2896 * Save setting(s) provided in $data param
2898 * @param array $data An array of settings to save
2899 * @return mixed empty string for bad data or bool true=>success, false=>error
2901 public function write_setting($data) {
2902 if (!is_array($data)) {
2903 return ''; // ignore it
2905 if (!$this->load_choices() or empty($this->choices)) {
2906 return '';
2908 $result = '';
2909 foreach ($this->choices as $key=>$unused) {
2910 if (!empty($data[$key])) {
2911 $result .= '1';
2912 } else {
2913 $result .= '0';
2916 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2922 * Select one value from list
2924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2926 class admin_setting_configselect extends admin_setting {
2927 /** @var array Array of choices value=>label */
2928 public $choices;
2931 * Constructor
2932 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2933 * @param string $visiblename localised
2934 * @param string $description long localised info
2935 * @param string|int $defaultsetting
2936 * @param array $choices array of $value=>$label for each selection
2938 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2939 $this->choices = $choices;
2940 parent::__construct($name, $visiblename, $description, $defaultsetting);
2944 * This function may be used in ancestors for lazy loading of choices
2946 * Override this method if loading of choices is expensive, such
2947 * as when it requires multiple db requests.
2949 * @return bool true if loaded, false if error
2951 public function load_choices() {
2953 if (is_array($this->choices)) {
2954 return true;
2956 .... load choices here
2958 return true;
2962 * Check if this is $query is related to a choice
2964 * @param string $query
2965 * @return bool true if related, false if not
2967 public function is_related($query) {
2968 if (parent::is_related($query)) {
2969 return true;
2971 if (!$this->load_choices()) {
2972 return false;
2974 foreach ($this->choices as $key=>$value) {
2975 if (strpos(core_text::strtolower($key), $query) !== false) {
2976 return true;
2978 if (strpos(core_text::strtolower($value), $query) !== false) {
2979 return true;
2982 return false;
2986 * Return the setting
2988 * @return mixed returns config if successful else null
2990 public function get_setting() {
2991 return $this->config_read($this->name);
2995 * Save a setting
2997 * @param string $data
2998 * @return string empty of error string
3000 public function write_setting($data) {
3001 if (!$this->load_choices() or empty($this->choices)) {
3002 return '';
3004 if (!array_key_exists($data, $this->choices)) {
3005 return ''; // ignore it
3008 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3012 * Returns XHTML select field
3014 * Ensure the options are loaded, and generate the XHTML for the select
3015 * element and any warning message. Separating this out from output_html
3016 * makes it easier to subclass this class.
3018 * @param string $data the option to show as selected.
3019 * @param string $current the currently selected option in the database, null if none.
3020 * @param string $default the default selected option.
3021 * @return array the HTML for the select element, and a warning message.
3023 public function output_select_html($data, $current, $default, $extraname = '') {
3024 if (!$this->load_choices() or empty($this->choices)) {
3025 return array('', '');
3028 $warning = '';
3029 if (is_null($current)) {
3030 // first run
3031 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
3032 // no warning
3033 } else if (!array_key_exists($current, $this->choices)) {
3034 $warning = get_string('warningcurrentsetting', 'admin', s($current));
3035 if (!is_null($default) and $data == $current) {
3036 $data = $default; // use default instead of first value when showing the form
3040 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
3041 foreach ($this->choices as $key => $value) {
3042 // the string cast is needed because key may be integer - 0 is equal to most strings!
3043 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
3045 $selecthtml .= '</select>';
3046 return array($selecthtml, $warning);
3050 * Returns XHTML select field and wrapping div(s)
3052 * @see output_select_html()
3054 * @param string $data the option to show as selected
3055 * @param string $query
3056 * @return string XHTML field and wrapping div
3058 public function output_html($data, $query='') {
3059 $default = $this->get_defaultsetting();
3060 $current = $this->get_setting();
3062 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3063 if (!$selecthtml) {
3064 return '';
3067 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3068 $defaultinfo = $this->choices[$default];
3069 } else {
3070 $defaultinfo = NULL;
3073 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3075 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3081 * Select multiple items from list
3083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3085 class admin_setting_configmultiselect extends admin_setting_configselect {
3087 * Constructor
3088 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3089 * @param string $visiblename localised
3090 * @param string $description long localised info
3091 * @param array $defaultsetting array of selected items
3092 * @param array $choices array of $value=>$label for each list item
3094 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3095 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3099 * Returns the select setting(s)
3101 * @return mixed null or array. Null if no settings else array of setting(s)
3103 public function get_setting() {
3104 $result = $this->config_read($this->name);
3105 if (is_null($result)) {
3106 return NULL;
3108 if ($result === '') {
3109 return array();
3111 return explode(',', $result);
3115 * Saves setting(s) provided through $data
3117 * Potential bug in the works should anyone call with this function
3118 * using a vartype that is not an array
3120 * @param array $data
3122 public function write_setting($data) {
3123 if (!is_array($data)) {
3124 return ''; //ignore it
3126 if (!$this->load_choices() or empty($this->choices)) {
3127 return '';
3130 unset($data['xxxxx']);
3132 $save = array();
3133 foreach ($data as $value) {
3134 if (!array_key_exists($value, $this->choices)) {
3135 continue; // ignore it
3137 $save[] = $value;
3140 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3144 * Is setting related to query text - used when searching
3146 * @param string $query
3147 * @return bool true if related, false if not
3149 public function is_related($query) {
3150 if (!$this->load_choices() or empty($this->choices)) {
3151 return false;
3153 if (parent::is_related($query)) {
3154 return true;
3157 foreach ($this->choices as $desc) {
3158 if (strpos(core_text::strtolower($desc), $query) !== false) {
3159 return true;
3162 return false;
3166 * Returns XHTML multi-select field
3168 * @todo Add vartype handling to ensure $data is an array
3169 * @param array $data Array of values to select by default
3170 * @param string $query
3171 * @return string XHTML multi-select field
3173 public function output_html($data, $query='') {
3174 if (!$this->load_choices() or empty($this->choices)) {
3175 return '';
3177 $choices = $this->choices;
3178 $default = $this->get_defaultsetting();
3179 if (is_null($default)) {
3180 $default = array();
3182 if (is_null($data)) {
3183 $data = array();
3186 $defaults = array();
3187 $size = min(10, count($this->choices));
3188 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3189 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3190 foreach ($this->choices as $key => $description) {
3191 if (in_array($key, $data)) {
3192 $selected = 'selected="selected"';
3193 } else {
3194 $selected = '';
3196 if (in_array($key, $default)) {
3197 $defaults[] = $description;
3200 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3203 if (is_null($default)) {
3204 $defaultinfo = NULL;
3205 } if (!empty($defaults)) {
3206 $defaultinfo = implode(', ', $defaults);
3207 } else {
3208 $defaultinfo = get_string('none');
3211 $return .= '</select></div>';
3212 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3217 * Time selector
3219 * This is a liiitle bit messy. we're using two selects, but we're returning
3220 * them as an array named after $name (so we only use $name2 internally for the setting)
3222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3224 class admin_setting_configtime extends admin_setting {
3225 /** @var string Used for setting second select (minutes) */
3226 public $name2;
3229 * Constructor
3230 * @param string $hoursname setting for hours
3231 * @param string $minutesname setting for hours
3232 * @param string $visiblename localised
3233 * @param string $description long localised info
3234 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3236 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3237 $this->name2 = $minutesname;
3238 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3242 * Get the selected time
3244 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3246 public function get_setting() {
3247 $result1 = $this->config_read($this->name);
3248 $result2 = $this->config_read($this->name2);
3249 if (is_null($result1) or is_null($result2)) {
3250 return NULL;
3253 return array('h' => $result1, 'm' => $result2);
3257 * Store the time (hours and minutes)
3259 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3260 * @return bool true if success, false if not
3262 public function write_setting($data) {
3263 if (!is_array($data)) {
3264 return '';
3267 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3268 return ($result ? '' : get_string('errorsetting', 'admin'));
3272 * Returns XHTML time select fields
3274 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3275 * @param string $query
3276 * @return string XHTML time select fields and wrapping div(s)
3278 public function output_html($data, $query='') {
3279 $default = $this->get_defaultsetting();
3281 if (is_array($default)) {
3282 $defaultinfo = $default['h'].':'.$default['m'];
3283 } else {
3284 $defaultinfo = NULL;
3287 $return = '<div class="form-time defaultsnext">';
3288 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3289 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3290 for ($i = 0; $i < 24; $i++) {
3291 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3293 $return .= '</select>:';
3294 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3295 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3296 for ($i = 0; $i < 60; $i += 5) {
3297 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3299 $return .= '</select>';
3300 $return .= '</div>';
3301 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3308 * Seconds duration setting.
3310 * @copyright 2012 Petr Skoda (http://skodak.org)
3311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3313 class admin_setting_configduration extends admin_setting {
3315 /** @var int default duration unit */
3316 protected $defaultunit;
3319 * Constructor
3320 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3321 * or 'myplugin/mysetting' for ones in config_plugins.
3322 * @param string $visiblename localised name
3323 * @param string $description localised long description
3324 * @param mixed $defaultsetting string or array depending on implementation
3325 * @param int $defaultunit - day, week, etc. (in seconds)
3327 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3328 if (is_number($defaultsetting)) {
3329 $defaultsetting = self::parse_seconds($defaultsetting);
3331 $units = self::get_units();
3332 if (isset($units[$defaultunit])) {
3333 $this->defaultunit = $defaultunit;
3334 } else {
3335 $this->defaultunit = 86400;
3337 parent::__construct($name, $visiblename, $description, $defaultsetting);
3341 * Returns selectable units.
3342 * @static
3343 * @return array
3345 protected static function get_units() {
3346 return array(
3347 604800 => get_string('weeks'),
3348 86400 => get_string('days'),
3349 3600 => get_string('hours'),
3350 60 => get_string('minutes'),
3351 1 => get_string('seconds'),
3356 * Converts seconds to some more user friendly string.
3357 * @static
3358 * @param int $seconds
3359 * @return string
3361 protected static function get_duration_text($seconds) {
3362 if (empty($seconds)) {
3363 return get_string('none');
3365 $data = self::parse_seconds($seconds);
3366 switch ($data['u']) {
3367 case (60*60*24*7):
3368 return get_string('numweeks', '', $data['v']);
3369 case (60*60*24):
3370 return get_string('numdays', '', $data['v']);
3371 case (60*60):
3372 return get_string('numhours', '', $data['v']);
3373 case (60):
3374 return get_string('numminutes', '', $data['v']);
3375 default:
3376 return get_string('numseconds', '', $data['v']*$data['u']);
3381 * Finds suitable units for given duration.
3382 * @static
3383 * @param int $seconds
3384 * @return array
3386 protected static function parse_seconds($seconds) {
3387 foreach (self::get_units() as $unit => $unused) {
3388 if ($seconds % $unit === 0) {
3389 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3392 return array('v'=>(int)$seconds, 'u'=>1);
3396 * Get the selected duration as array.
3398 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3400 public function get_setting() {
3401 $seconds = $this->config_read($this->name);
3402 if (is_null($seconds)) {
3403 return null;
3406 return self::parse_seconds($seconds);
3410 * Store the duration as seconds.
3412 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3413 * @return bool true if success, false if not
3415 public function write_setting($data) {
3416 if (!is_array($data)) {
3417 return '';
3420 $seconds = (int)($data['v']*$data['u']);
3421 if ($seconds < 0) {
3422 return get_string('errorsetting', 'admin');
3425 $result = $this->config_write($this->name, $seconds);
3426 return ($result ? '' : get_string('errorsetting', 'admin'));
3430 * Returns duration text+select fields.
3432 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3433 * @param string $query
3434 * @return string duration text+select fields and wrapping div(s)
3436 public function output_html($data, $query='') {
3437 $default = $this->get_defaultsetting();
3439 if (is_number($default)) {
3440 $defaultinfo = self::get_duration_text($default);
3441 } else if (is_array($default)) {
3442 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3443 } else {
3444 $defaultinfo = null;
3447 $units = self::get_units();
3449 $return = '<div class="form-duration defaultsnext">';
3450 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3451 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3452 foreach ($units as $val => $text) {
3453 $selected = '';
3454 if ($data['v'] == 0) {
3455 if ($val == $this->defaultunit) {
3456 $selected = ' selected="selected"';
3458 } else if ($val == $data['u']) {
3459 $selected = ' selected="selected"';
3461 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3463 $return .= '</select></div>';
3464 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3470 * Used to validate a textarea used for ip addresses
3472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3474 class admin_setting_configiplist extends admin_setting_configtextarea {
3477 * Validate the contents of the textarea as IP addresses
3479 * Used to validate a new line separated list of IP addresses collected from
3480 * a textarea control
3482 * @param string $data A list of IP Addresses separated by new lines
3483 * @return mixed bool true for success or string:error on failure
3485 public function validate($data) {
3486 if(!empty($data)) {
3487 $ips = explode("\n", $data);
3488 } else {
3489 return true;
3491 $result = true;
3492 foreach($ips as $ip) {
3493 $ip = trim($ip);
3494 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3495 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3496 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3497 $result = true;
3498 } else {
3499 $result = false;
3500 break;
3503 if($result) {
3504 return true;
3505 } else {
3506 return get_string('validateerror', 'admin');
3513 * An admin setting for selecting one or more users who have a capability
3514 * in the system context
3516 * An admin setting for selecting one or more users, who have a particular capability
3517 * in the system context. Warning, make sure the list will never be too long. There is
3518 * no paging or searching of this list.
3520 * To correctly get a list of users from this config setting, you need to call the
3521 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3525 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3526 /** @var string The capabilities name */
3527 protected $capability;
3528 /** @var int include admin users too */
3529 protected $includeadmins;
3532 * Constructor.
3534 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3535 * @param string $visiblename localised name
3536 * @param string $description localised long description
3537 * @param array $defaultsetting array of usernames
3538 * @param string $capability string capability name.
3539 * @param bool $includeadmins include administrators
3541 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3542 $this->capability = $capability;
3543 $this->includeadmins = $includeadmins;
3544 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3548 * Load all of the uses who have the capability into choice array
3550 * @return bool Always returns true
3552 function load_choices() {
3553 if (is_array($this->choices)) {
3554 return true;
3556 list($sort, $sortparams) = users_order_by_sql('u');
3557 if (!empty($sortparams)) {
3558 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3559 'This is unexpected, and a problem because there is no way to pass these ' .
3560 'parameters to get_users_by_capability. See MDL-34657.');
3562 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3563 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3564 $this->choices = array(
3565 '$@NONE@$' => get_string('nobody'),
3566 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3568 if ($this->includeadmins) {
3569 $admins = get_admins();
3570 foreach ($admins as $user) {
3571 $this->choices[$user->id] = fullname($user);
3574 if (is_array($users)) {
3575 foreach ($users as $user) {
3576 $this->choices[$user->id] = fullname($user);
3579 return true;
3583 * Returns the default setting for class
3585 * @return mixed Array, or string. Empty string if no default
3587 public function get_defaultsetting() {
3588 $this->load_choices();
3589 $defaultsetting = parent::get_defaultsetting();
3590 if (empty($defaultsetting)) {
3591 return array('$@NONE@$');
3592 } else if (array_key_exists($defaultsetting, $this->choices)) {
3593 return $defaultsetting;
3594 } else {
3595 return '';
3600 * Returns the current setting
3602 * @return mixed array or string
3604 public function get_setting() {
3605 $result = parent::get_setting();
3606 if ($result === null) {
3607 // this is necessary for settings upgrade
3608 return null;
3610 if (empty($result)) {
3611 $result = array('$@NONE@$');
3613 return $result;
3617 * Save the chosen setting provided as $data
3619 * @param array $data
3620 * @return mixed string or array
3622 public function write_setting($data) {
3623 // If all is selected, remove any explicit options.
3624 if (in_array('$@ALL@$', $data)) {
3625 $data = array('$@ALL@$');
3627 // None never needs to be written to the DB.
3628 if (in_array('$@NONE@$', $data)) {
3629 unset($data[array_search('$@NONE@$', $data)]);
3631 return parent::write_setting($data);
3637 * Special checkbox for calendar - resets SESSION vars.
3639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3641 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3643 * Calls the parent::__construct with default values
3645 * name => calendar_adminseesall
3646 * visiblename => get_string('adminseesall', 'admin')
3647 * description => get_string('helpadminseesall', 'admin')
3648 * defaultsetting => 0
3650 public function __construct() {
3651 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3652 get_string('helpadminseesall', 'admin'), '0');
3656 * Stores the setting passed in $data
3658 * @param mixed gets converted to string for comparison
3659 * @return string empty string or error message
3661 public function write_setting($data) {
3662 global $SESSION;
3663 return parent::write_setting($data);
3668 * Special select for settings that are altered in setup.php and can not be altered on the fly
3670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3672 class admin_setting_special_selectsetup extends admin_setting_configselect {
3674 * Reads the setting directly from the database
3676 * @return mixed
3678 public function get_setting() {
3679 // read directly from db!
3680 return get_config(NULL, $this->name);
3684 * Save the setting passed in $data
3686 * @param string $data The setting to save
3687 * @return string empty or error message
3689 public function write_setting($data) {
3690 global $CFG;
3691 // do not change active CFG setting!
3692 $current = $CFG->{$this->name};
3693 $result = parent::write_setting($data);
3694 $CFG->{$this->name} = $current;
3695 return $result;
3701 * Special select for frontpage - stores data in course table
3703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3705 class admin_setting_sitesetselect extends admin_setting_configselect {
3707 * Returns the site name for the selected site
3709 * @see get_site()
3710 * @return string The site name of the selected site
3712 public function get_setting() {
3713 $site = course_get_format(get_site())->get_course();
3714 return $site->{$this->name};
3718 * Updates the database and save the setting
3720 * @param string data
3721 * @return string empty or error message
3723 public function write_setting($data) {
3724 global $DB, $SITE, $COURSE;
3725 if (!in_array($data, array_keys($this->choices))) {
3726 return get_string('errorsetting', 'admin');
3728 $record = new stdClass();
3729 $record->id = SITEID;
3730 $temp = $this->name;
3731 $record->$temp = $data;
3732 $record->timemodified = time();
3734 course_get_format($SITE)->update_course_format_options($record);
3735 $DB->update_record('course', $record);
3737 // Reset caches.
3738 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3739 if ($SITE->id == $COURSE->id) {
3740 $COURSE = $SITE;
3742 format_base::reset_course_cache($SITE->id);
3744 return '';
3751 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3752 * block to hidden.
3754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3756 class admin_setting_bloglevel extends admin_setting_configselect {
3758 * Updates the database and save the setting
3760 * @param string data
3761 * @return string empty or error message
3763 public function write_setting($data) {
3764 global $DB, $CFG;
3765 if ($data == 0) {
3766 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3767 foreach ($blogblocks as $block) {
3768 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3770 } else {
3771 // reenable all blocks only when switching from disabled blogs
3772 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3773 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3774 foreach ($blogblocks as $block) {
3775 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3779 return parent::write_setting($data);
3785 * Special select - lists on the frontpage - hacky
3787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3789 class admin_setting_courselist_frontpage extends admin_setting {
3790 /** @var array Array of choices value=>label */
3791 public $choices;
3794 * Construct override, requires one param
3796 * @param bool $loggedin Is the user logged in
3798 public function __construct($loggedin) {
3799 global $CFG;
3800 require_once($CFG->dirroot.'/course/lib.php');
3801 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3802 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3803 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3804 $defaults = array(FRONTPAGEALLCOURSELIST);
3805 parent::__construct($name, $visiblename, $description, $defaults);
3809 * Loads the choices available
3811 * @return bool always returns true
3813 public function load_choices() {
3814 if (is_array($this->choices)) {
3815 return true;
3817 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3818 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3819 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3820 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3821 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3822 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3823 'none' => get_string('none'));
3824 if ($this->name === 'frontpage') {
3825 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3827 return true;
3831 * Returns the selected settings
3833 * @param mixed array or setting or null
3835 public function get_setting() {
3836 $result = $this->config_read($this->name);
3837 if (is_null($result)) {
3838 return NULL;
3840 if ($result === '') {
3841 return array();
3843 return explode(',', $result);
3847 * Save the selected options
3849 * @param array $data
3850 * @return mixed empty string (data is not an array) or bool true=success false=failure
3852 public function write_setting($data) {
3853 if (!is_array($data)) {
3854 return '';
3856 $this->load_choices();
3857 $save = array();
3858 foreach($data as $datum) {
3859 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3860 continue;
3862 $save[$datum] = $datum; // no duplicates
3864 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3868 * Return XHTML select field and wrapping div
3870 * @todo Add vartype handling to make sure $data is an array
3871 * @param array $data Array of elements to select by default
3872 * @return string XHTML select field and wrapping div
3874 public function output_html($data, $query='') {
3875 $this->load_choices();
3876 $currentsetting = array();
3877 foreach ($data as $key) {
3878 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3879 $currentsetting[] = $key; // already selected first
3883 $return = '<div class="form-group">';
3884 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3885 if (!array_key_exists($i, $currentsetting)) {
3886 $currentsetting[$i] = 'none'; //none
3888 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3889 foreach ($this->choices as $key => $value) {
3890 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3892 $return .= '</select>';
3893 if ($i !== count($this->choices) - 2) {
3894 $return .= '<br />';
3897 $return .= '</div>';
3899 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3905 * Special checkbox for frontpage - stores data in course table
3907 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3909 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3911 * Returns the current sites name
3913 * @return string
3915 public function get_setting() {
3916 $site = course_get_format(get_site())->get_course();
3917 return $site->{$this->name};
3921 * Save the selected setting
3923 * @param string $data The selected site
3924 * @return string empty string or error message
3926 public function write_setting($data) {
3927 global $DB, $SITE, $COURSE;
3928 $record = new stdClass();
3929 $record->id = $SITE->id;
3930 $record->{$this->name} = ($data == '1' ? 1 : 0);
3931 $record->timemodified = time();
3933 course_get_format($SITE)->update_course_format_options($record);
3934 $DB->update_record('course', $record);
3936 // Reset caches.
3937 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3938 if ($SITE->id == $COURSE->id) {
3939 $COURSE = $SITE;
3941 format_base::reset_course_cache($SITE->id);
3943 return '';
3948 * Special text for frontpage - stores data in course table.
3949 * Empty string means not set here. Manual setting is required.
3951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3953 class admin_setting_sitesettext extends admin_setting_configtext {
3955 * Return the current setting
3957 * @return mixed string or null
3959 public function get_setting() {
3960 $site = course_get_format(get_site())->get_course();
3961 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3965 * Validate the selected data
3967 * @param string $data The selected value to validate
3968 * @return mixed true or message string
3970 public function validate($data) {
3971 $cleaned = clean_param($data, PARAM_TEXT);
3972 if ($cleaned === '') {
3973 return get_string('required');
3975 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3976 return true;
3977 } else {
3978 return get_string('validateerror', 'admin');
3983 * Save the selected setting
3985 * @param string $data The selected value
3986 * @return string empty or error message
3988 public function write_setting($data) {
3989 global $DB, $SITE, $COURSE;
3990 $data = trim($data);
3991 $validated = $this->validate($data);
3992 if ($validated !== true) {
3993 return $validated;
3996 $record = new stdClass();
3997 $record->id = $SITE->id;
3998 $record->{$this->name} = $data;
3999 $record->timemodified = time();
4001 course_get_format($SITE)->update_course_format_options($record);
4002 $DB->update_record('course', $record);
4004 // Reset caches.
4005 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4006 if ($SITE->id == $COURSE->id) {
4007 $COURSE = $SITE;
4009 format_base::reset_course_cache($SITE->id);
4011 return '';
4017 * Special text editor for site description.
4019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4021 class admin_setting_special_frontpagedesc extends admin_setting {
4023 * Calls parent::__construct with specific arguments
4025 public function __construct() {
4026 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
4027 editors_head_setup();
4031 * Return the current setting
4032 * @return string The current setting
4034 public function get_setting() {
4035 $site = course_get_format(get_site())->get_course();
4036 return $site->{$this->name};
4040 * Save the new setting
4042 * @param string $data The new value to save
4043 * @return string empty or error message
4045 public function write_setting($data) {
4046 global $DB, $SITE, $COURSE;
4047 $record = new stdClass();
4048 $record->id = $SITE->id;
4049 $record->{$this->name} = $data;
4050 $record->timemodified = time();
4052 course_get_format($SITE)->update_course_format_options($record);
4053 $DB->update_record('course', $record);
4055 // Reset caches.
4056 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4057 if ($SITE->id == $COURSE->id) {
4058 $COURSE = $SITE;
4060 format_base::reset_course_cache($SITE->id);
4062 return '';
4066 * Returns XHTML for the field plus wrapping div
4068 * @param string $data The current value
4069 * @param string $query
4070 * @return string The XHTML output
4072 public function output_html($data, $query='') {
4073 global $CFG;
4075 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4077 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4083 * Administration interface for emoticon_manager settings.
4085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4087 class admin_setting_emoticons extends admin_setting {
4090 * Calls parent::__construct with specific args
4092 public function __construct() {
4093 global $CFG;
4095 $manager = get_emoticon_manager();
4096 $defaults = $this->prepare_form_data($manager->default_emoticons());
4097 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4101 * Return the current setting(s)
4103 * @return array Current settings array
4105 public function get_setting() {
4106 global $CFG;
4108 $manager = get_emoticon_manager();
4110 $config = $this->config_read($this->name);
4111 if (is_null($config)) {
4112 return null;
4115 $config = $manager->decode_stored_config($config);
4116 if (is_null($config)) {
4117 return null;
4120 return $this->prepare_form_data($config);
4124 * Save selected settings
4126 * @param array $data Array of settings to save
4127 * @return bool
4129 public function write_setting($data) {
4131 $manager = get_emoticon_manager();
4132 $emoticons = $this->process_form_data($data);
4134 if ($emoticons === false) {
4135 return false;
4138 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4139 return ''; // success
4140 } else {
4141 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4146 * Return XHTML field(s) for options
4148 * @param array $data Array of options to set in HTML
4149 * @return string XHTML string for the fields and wrapping div(s)
4151 public function output_html($data, $query='') {
4152 global $OUTPUT;
4154 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4155 $out .= html_writer::start_tag('thead');
4156 $out .= html_writer::start_tag('tr');
4157 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4158 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4159 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4160 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4161 $out .= html_writer::tag('th', '');
4162 $out .= html_writer::end_tag('tr');
4163 $out .= html_writer::end_tag('thead');
4164 $out .= html_writer::start_tag('tbody');
4165 $i = 0;
4166 foreach($data as $field => $value) {
4167 switch ($i) {
4168 case 0:
4169 $out .= html_writer::start_tag('tr');
4170 $current_text = $value;
4171 $current_filename = '';
4172 $current_imagecomponent = '';
4173 $current_altidentifier = '';
4174 $current_altcomponent = '';
4175 case 1:
4176 $current_filename = $value;
4177 case 2:
4178 $current_imagecomponent = $value;
4179 case 3:
4180 $current_altidentifier = $value;
4181 case 4:
4182 $current_altcomponent = $value;
4185 $out .= html_writer::tag('td',
4186 html_writer::empty_tag('input',
4187 array(
4188 'type' => 'text',
4189 'class' => 'form-text',
4190 'name' => $this->get_full_name().'['.$field.']',
4191 'value' => $value,
4193 ), array('class' => 'c'.$i)
4196 if ($i == 4) {
4197 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4198 $alt = get_string($current_altidentifier, $current_altcomponent);
4199 } else {
4200 $alt = $current_text;
4202 if ($current_filename) {
4203 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4204 } else {
4205 $out .= html_writer::tag('td', '');
4207 $out .= html_writer::end_tag('tr');
4208 $i = 0;
4209 } else {
4210 $i++;
4214 $out .= html_writer::end_tag('tbody');
4215 $out .= html_writer::end_tag('table');
4216 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4217 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4219 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4223 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4225 * @see self::process_form_data()
4226 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4227 * @return array of form fields and their values
4229 protected function prepare_form_data(array $emoticons) {
4231 $form = array();
4232 $i = 0;
4233 foreach ($emoticons as $emoticon) {
4234 $form['text'.$i] = $emoticon->text;
4235 $form['imagename'.$i] = $emoticon->imagename;
4236 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4237 $form['altidentifier'.$i] = $emoticon->altidentifier;
4238 $form['altcomponent'.$i] = $emoticon->altcomponent;
4239 $i++;
4241 // add one more blank field set for new object
4242 $form['text'.$i] = '';
4243 $form['imagename'.$i] = '';
4244 $form['imagecomponent'.$i] = '';
4245 $form['altidentifier'.$i] = '';
4246 $form['altcomponent'.$i] = '';
4248 return $form;
4252 * Converts the data from admin settings form into an array of emoticon objects
4254 * @see self::prepare_form_data()
4255 * @param array $data array of admin form fields and values
4256 * @return false|array of emoticon objects
4258 protected function process_form_data(array $form) {
4260 $count = count($form); // number of form field values
4262 if ($count % 5) {
4263 // we must get five fields per emoticon object
4264 return false;
4267 $emoticons = array();
4268 for ($i = 0; $i < $count / 5; $i++) {
4269 $emoticon = new stdClass();
4270 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4271 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4272 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4273 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4274 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4276 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4277 // prevent from breaking http://url.addresses by accident
4278 $emoticon->text = '';
4281 if (strlen($emoticon->text) < 2) {
4282 // do not allow single character emoticons
4283 $emoticon->text = '';
4286 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4287 // emoticon text must contain some non-alphanumeric character to prevent
4288 // breaking HTML tags
4289 $emoticon->text = '';
4292 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4293 $emoticons[] = $emoticon;
4296 return $emoticons;
4302 * Special setting for limiting of the list of available languages.
4304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4306 class admin_setting_langlist extends admin_setting_configtext {
4308 * Calls parent::__construct with specific arguments
4310 public function __construct() {
4311 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4315 * Save the new setting
4317 * @param string $data The new setting
4318 * @return bool
4320 public function write_setting($data) {
4321 $return = parent::write_setting($data);
4322 get_string_manager()->reset_caches();
4323 return $return;
4329 * Selection of one of the recognised countries using the list
4330 * returned by {@link get_list_of_countries()}.
4332 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4334 class admin_settings_country_select extends admin_setting_configselect {
4335 protected $includeall;
4336 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4337 $this->includeall = $includeall;
4338 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4342 * Lazy-load the available choices for the select box
4344 public function load_choices() {
4345 global $CFG;
4346 if (is_array($this->choices)) {
4347 return true;
4349 $this->choices = array_merge(
4350 array('0' => get_string('choosedots')),
4351 get_string_manager()->get_list_of_countries($this->includeall));
4352 return true;
4358 * admin_setting_configselect for the default number of sections in a course,
4359 * simply so we can lazy-load the choices.
4361 * @copyright 2011 The Open University
4362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4364 class admin_settings_num_course_sections extends admin_setting_configselect {
4365 public function __construct($name, $visiblename, $description, $defaultsetting) {
4366 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4369 /** Lazy-load the available choices for the select box */
4370 public function load_choices() {
4371 $max = get_config('moodlecourse', 'maxsections');
4372 if (!isset($max) || !is_numeric($max)) {
4373 $max = 52;
4375 for ($i = 0; $i <= $max; $i++) {
4376 $this->choices[$i] = "$i";
4378 return true;
4384 * Course category selection
4386 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4388 class admin_settings_coursecat_select extends admin_setting_configselect {
4390 * Calls parent::__construct with specific arguments
4392 public function __construct($name, $visiblename, $description, $defaultsetting) {
4393 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4397 * Load the available choices for the select box
4399 * @return bool
4401 public function load_choices() {
4402 global $CFG;
4403 require_once($CFG->dirroot.'/course/lib.php');
4404 if (is_array($this->choices)) {
4405 return true;
4407 $this->choices = make_categories_options();
4408 return true;
4414 * Special control for selecting days to backup
4416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4418 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4420 * Calls parent::__construct with specific arguments
4422 public function __construct() {
4423 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4424 $this->plugin = 'backup';
4428 * Load the available choices for the select box
4430 * @return bool Always returns true
4432 public function load_choices() {
4433 if (is_array($this->choices)) {
4434 return true;
4436 $this->choices = array();
4437 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4438 foreach ($days as $day) {
4439 $this->choices[$day] = get_string($day, 'calendar');
4441 return true;
4447 * Special debug setting
4449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4451 class admin_setting_special_debug extends admin_setting_configselect {
4453 * Calls parent::__construct with specific arguments
4455 public function __construct() {
4456 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4460 * Load the available choices for the select box
4462 * @return bool
4464 public function load_choices() {
4465 if (is_array($this->choices)) {
4466 return true;
4468 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4469 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4470 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4471 DEBUG_ALL => get_string('debugall', 'admin'),
4472 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4473 return true;
4479 * Special admin control
4481 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4483 class admin_setting_special_calendar_weekend extends admin_setting {
4485 * Calls parent::__construct with specific arguments
4487 public function __construct() {
4488 $name = 'calendar_weekend';
4489 $visiblename = get_string('calendar_weekend', 'admin');
4490 $description = get_string('helpweekenddays', 'admin');
4491 $default = array ('0', '6'); // Saturdays and Sundays
4492 parent::__construct($name, $visiblename, $description, $default);
4496 * Gets the current settings as an array
4498 * @return mixed Null if none, else array of settings
4500 public function get_setting() {
4501 $result = $this->config_read($this->name);
4502 if (is_null($result)) {
4503 return NULL;
4505 if ($result === '') {
4506 return array();
4508 $settings = array();
4509 for ($i=0; $i<7; $i++) {
4510 if ($result & (1 << $i)) {
4511 $settings[] = $i;
4514 return $settings;
4518 * Save the new settings
4520 * @param array $data Array of new settings
4521 * @return bool
4523 public function write_setting($data) {
4524 if (!is_array($data)) {
4525 return '';
4527 unset($data['xxxxx']);
4528 $result = 0;
4529 foreach($data as $index) {
4530 $result |= 1 << $index;
4532 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4536 * Return XHTML to display the control
4538 * @param array $data array of selected days
4539 * @param string $query
4540 * @return string XHTML for display (field + wrapping div(s)
4542 public function output_html($data, $query='') {
4543 // The order matters very much because of the implied numeric keys
4544 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4545 $return = '<table><thead><tr>';
4546 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4547 foreach($days as $index => $day) {
4548 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4550 $return .= '</tr></thead><tbody><tr>';
4551 foreach($days as $index => $day) {
4552 $return .= '<td><input type="checkbox" class="form-checkbox" id="'.$this->get_id().$index.'" name="'.$this->get_full_name().'[]" value="'.$index.'" '.(in_array("$index", $data) ? 'checked="checked"' : '').' /></td>';
4554 $return .= '</tr></tbody></table>';
4556 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4563 * Admin setting that allows a user to pick a behaviour.
4565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4567 class admin_setting_question_behaviour extends admin_setting_configselect {
4569 * @param string $name name of config variable
4570 * @param string $visiblename display name
4571 * @param string $description description
4572 * @param string $default default.
4574 public function __construct($name, $visiblename, $description, $default) {
4575 parent::__construct($name, $visiblename, $description, $default, NULL);
4579 * Load list of behaviours as choices
4580 * @return bool true => success, false => error.
4582 public function load_choices() {
4583 global $CFG;
4584 require_once($CFG->dirroot . '/question/engine/lib.php');
4585 $this->choices = question_engine::get_behaviour_options('');
4586 return true;
4592 * Admin setting that allows a user to pick appropriate roles for something.
4594 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4596 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4597 /** @var array Array of capabilities which identify roles */
4598 private $types;
4601 * @param string $name Name of config variable
4602 * @param string $visiblename Display name
4603 * @param string $description Description
4604 * @param array $types Array of archetypes which identify
4605 * roles that will be enabled by default.
4607 public function __construct($name, $visiblename, $description, $types) {
4608 parent::__construct($name, $visiblename, $description, NULL, NULL);
4609 $this->types = $types;
4613 * Load roles as choices
4615 * @return bool true=>success, false=>error
4617 public function load_choices() {
4618 global $CFG, $DB;
4619 if (during_initial_install()) {
4620 return false;
4622 if (is_array($this->choices)) {
4623 return true;
4625 if ($roles = get_all_roles()) {
4626 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4627 return true;
4628 } else {
4629 return false;
4634 * Return the default setting for this control
4636 * @return array Array of default settings
4638 public function get_defaultsetting() {
4639 global $CFG;
4641 if (during_initial_install()) {
4642 return null;
4644 $result = array();
4645 foreach($this->types as $archetype) {
4646 if ($caproles = get_archetype_roles($archetype)) {
4647 foreach ($caproles as $caprole) {
4648 $result[$caprole->id] = 1;
4652 return $result;
4658 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4662 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4664 * Constructor
4665 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4666 * @param string $visiblename localised
4667 * @param string $description long localised info
4668 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4669 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4670 * @param int $size default field size
4672 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4673 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4674 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4680 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4682 * @copyright 2009 Petr Skoda (http://skodak.org)
4683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4685 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4688 * Constructor
4689 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4690 * @param string $visiblename localised
4691 * @param string $description long localised info
4692 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4693 * @param string $yes value used when checked
4694 * @param string $no value used when not checked
4696 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4697 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4698 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4705 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4707 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4709 * @copyright 2010 Sam Hemelryk
4710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4712 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4714 * Constructor
4715 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4716 * @param string $visiblename localised
4717 * @param string $description long localised info
4718 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4719 * @param string $yes value used when checked
4720 * @param string $no value used when not checked
4722 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4723 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4724 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4731 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4735 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4737 * Calls parent::__construct with specific arguments
4739 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4740 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4741 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4748 * Graded roles in gradebook
4750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4752 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4754 * Calls parent::__construct with specific arguments
4756 public function __construct() {
4757 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4758 get_string('configgradebookroles', 'admin'),
4759 array('student'));
4766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4768 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4770 * Saves the new settings passed in $data
4772 * @param string $data
4773 * @return mixed string or Array
4775 public function write_setting($data) {
4776 global $CFG, $DB;
4778 $oldvalue = $this->config_read($this->name);
4779 $return = parent::write_setting($data);
4780 $newvalue = $this->config_read($this->name);
4782 if ($oldvalue !== $newvalue) {
4783 // force full regrading
4784 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4787 return $return;
4793 * Which roles to show on course description page
4795 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4797 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4799 * Calls parent::__construct with specific arguments
4801 public function __construct() {
4802 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4803 get_string('coursecontact_desc', 'admin'),
4804 array('editingteacher'));
4811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4813 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4815 * Calls parent::__construct with specific arguments
4817 function admin_setting_special_gradelimiting() {
4818 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4819 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4823 * Force site regrading
4825 function regrade_all() {
4826 global $CFG;
4827 require_once("$CFG->libdir/gradelib.php");
4828 grade_force_site_regrading();
4832 * Saves the new settings
4834 * @param mixed $data
4835 * @return string empty string or error message
4837 function write_setting($data) {
4838 $previous = $this->get_setting();
4840 if ($previous === null) {
4841 if ($data) {
4842 $this->regrade_all();
4844 } else {
4845 if ($data != $previous) {
4846 $this->regrade_all();
4849 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4856 * Primary grade export plugin - has state tracking.
4858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4860 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4862 * Calls parent::__construct with specific arguments
4864 public function __construct() {
4865 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4866 get_string('configgradeexport', 'admin'), array(), NULL);
4870 * Load the available choices for the multicheckbox
4872 * @return bool always returns true
4874 public function load_choices() {
4875 if (is_array($this->choices)) {
4876 return true;
4878 $this->choices = array();
4880 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4881 foreach($plugins as $plugin => $unused) {
4882 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4885 return true;
4891 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4895 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4897 * Config gradepointmax constructor
4899 * @param string $name Overidden by "gradepointmax"
4900 * @param string $visiblename Overridden by "gradepointmax" language string.
4901 * @param string $description Overridden by "gradepointmax_help" language string.
4902 * @param string $defaultsetting Not used, overridden by 100.
4903 * @param mixed $paramtype Overridden by PARAM_INT.
4904 * @param int $size Overridden by 5.
4906 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4907 $name = 'gradepointdefault';
4908 $visiblename = get_string('gradepointdefault', 'grades');
4909 $description = get_string('gradepointdefault_help', 'grades');
4910 $defaultsetting = 100;
4911 $paramtype = PARAM_INT;
4912 $size = 5;
4913 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4917 * Validate data before storage
4918 * @param string $data The submitted data
4919 * @return bool|string true if ok, string if error found
4921 public function validate($data) {
4922 global $CFG;
4923 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4924 return true;
4925 } else {
4926 return get_string('gradepointdefault_validateerror', 'grades');
4933 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4935 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4937 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4940 * Config gradepointmax constructor
4942 * @param string $name Overidden by "gradepointmax"
4943 * @param string $visiblename Overridden by "gradepointmax" language string.
4944 * @param string $description Overridden by "gradepointmax_help" language string.
4945 * @param string $defaultsetting Not used, overridden by 100.
4946 * @param mixed $paramtype Overridden by PARAM_INT.
4947 * @param int $size Overridden by 5.
4949 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4950 $name = 'gradepointmax';
4951 $visiblename = get_string('gradepointmax', 'grades');
4952 $description = get_string('gradepointmax_help', 'grades');
4953 $defaultsetting = 100;
4954 $paramtype = PARAM_INT;
4955 $size = 5;
4956 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4960 * Save the selected setting
4962 * @param string $data The selected site
4963 * @return string empty string or error message
4965 public function write_setting($data) {
4966 if ($data === '') {
4967 $data = (int)$this->defaultsetting;
4968 } else {
4969 $data = $data;
4971 return parent::write_setting($data);
4975 * Validate data before storage
4976 * @param string $data The submitted data
4977 * @return bool|string true if ok, string if error found
4979 public function validate($data) {
4980 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4981 return true;
4982 } else {
4983 return get_string('gradepointmax_validateerror', 'grades');
4988 * Return an XHTML string for the setting
4989 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4990 * @param string $query search query to be highlighted
4991 * @return string XHTML to display control
4993 public function output_html($data, $query = '') {
4994 $default = $this->get_defaultsetting();
4996 $attr = array(
4997 'type' => 'text',
4998 'size' => $this->size,
4999 'id' => $this->get_id(),
5000 'name' => $this->get_full_name(),
5001 'value' => s($data),
5002 'maxlength' => '5'
5004 $input = html_writer::empty_tag('input', $attr);
5006 $attr = array('class' => 'form-text defaultsnext');
5007 $div = html_writer::tag('div', $input, $attr);
5008 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
5014 * Grade category settings
5016 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5018 class admin_setting_gradecat_combo extends admin_setting {
5019 /** @var array Array of choices */
5020 public $choices;
5023 * Sets choices and calls parent::__construct with passed arguments
5024 * @param string $name
5025 * @param string $visiblename
5026 * @param string $description
5027 * @param mixed $defaultsetting string or array depending on implementation
5028 * @param array $choices An array of choices for the control
5030 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5031 $this->choices = $choices;
5032 parent::__construct($name, $visiblename, $description, $defaultsetting);
5036 * Return the current setting(s) array
5038 * @return array Array of value=>xx, forced=>xx, adv=>xx
5040 public function get_setting() {
5041 global $CFG;
5043 $value = $this->config_read($this->name);
5044 $flag = $this->config_read($this->name.'_flag');
5046 if (is_null($value) or is_null($flag)) {
5047 return NULL;
5050 $flag = (int)$flag;
5051 $forced = (boolean)(1 & $flag); // first bit
5052 $adv = (boolean)(2 & $flag); // second bit
5054 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5058 * Save the new settings passed in $data
5060 * @todo Add vartype handling to ensure $data is array
5061 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5062 * @return string empty or error message
5064 public function write_setting($data) {
5065 global $CFG;
5067 $value = $data['value'];
5068 $forced = empty($data['forced']) ? 0 : 1;
5069 $adv = empty($data['adv']) ? 0 : 2;
5070 $flag = ($forced | $adv); //bitwise or
5072 if (!in_array($value, array_keys($this->choices))) {
5073 return 'Error setting ';
5076 $oldvalue = $this->config_read($this->name);
5077 $oldflag = (int)$this->config_read($this->name.'_flag');
5078 $oldforced = (1 & $oldflag); // first bit
5080 $result1 = $this->config_write($this->name, $value);
5081 $result2 = $this->config_write($this->name.'_flag', $flag);
5083 // force regrade if needed
5084 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5085 require_once($CFG->libdir.'/gradelib.php');
5086 grade_category::updated_forced_settings();
5089 if ($result1 and $result2) {
5090 return '';
5091 } else {
5092 return get_string('errorsetting', 'admin');
5097 * Return XHTML to display the field and wrapping div
5099 * @todo Add vartype handling to ensure $data is array
5100 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5101 * @param string $query
5102 * @return string XHTML to display control
5104 public function output_html($data, $query='') {
5105 $value = $data['value'];
5106 $forced = !empty($data['forced']);
5107 $adv = !empty($data['adv']);
5109 $default = $this->get_defaultsetting();
5110 if (!is_null($default)) {
5111 $defaultinfo = array();
5112 if (isset($this->choices[$default['value']])) {
5113 $defaultinfo[] = $this->choices[$default['value']];
5115 if (!empty($default['forced'])) {
5116 $defaultinfo[] = get_string('force');
5118 if (!empty($default['adv'])) {
5119 $defaultinfo[] = get_string('advanced');
5121 $defaultinfo = implode(', ', $defaultinfo);
5123 } else {
5124 $defaultinfo = NULL;
5128 $return = '<div class="form-group">';
5129 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5130 foreach ($this->choices as $key => $val) {
5131 // the string cast is needed because key may be integer - 0 is equal to most strings!
5132 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5134 $return .= '</select>';
5135 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5136 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5137 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5138 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5139 $return .= '</div>';
5141 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5147 * Selection of grade report in user profiles
5149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5151 class admin_setting_grade_profilereport extends admin_setting_configselect {
5153 * Calls parent::__construct with specific arguments
5155 public function __construct() {
5156 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5160 * Loads an array of choices for the configselect control
5162 * @return bool always return true
5164 public function load_choices() {
5165 if (is_array($this->choices)) {
5166 return true;
5168 $this->choices = array();
5170 global $CFG;
5171 require_once($CFG->libdir.'/gradelib.php');
5173 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5174 if (file_exists($plugindir.'/lib.php')) {
5175 require_once($plugindir.'/lib.php');
5176 $functionname = 'grade_report_'.$plugin.'_profilereport';
5177 if (function_exists($functionname)) {
5178 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5182 return true;
5188 * Special class for register auth selection
5190 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5192 class admin_setting_special_registerauth extends admin_setting_configselect {
5194 * Calls parent::__construct with specific arguments
5196 public function __construct() {
5197 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5201 * Returns the default option
5203 * @return string empty or default option
5205 public function get_defaultsetting() {
5206 $this->load_choices();
5207 $defaultsetting = parent::get_defaultsetting();
5208 if (array_key_exists($defaultsetting, $this->choices)) {
5209 return $defaultsetting;
5210 } else {
5211 return '';
5216 * Loads the possible choices for the array
5218 * @return bool always returns true
5220 public function load_choices() {
5221 global $CFG;
5223 if (is_array($this->choices)) {
5224 return true;
5226 $this->choices = array();
5227 $this->choices[''] = get_string('disable');
5229 $authsenabled = get_enabled_auth_plugins(true);
5231 foreach ($authsenabled as $auth) {
5232 $authplugin = get_auth_plugin($auth);
5233 if (!$authplugin->can_signup()) {
5234 continue;
5236 // Get the auth title (from core or own auth lang files)
5237 $authtitle = $authplugin->get_title();
5238 $this->choices[$auth] = $authtitle;
5240 return true;
5246 * General plugins manager
5248 class admin_page_pluginsoverview extends admin_externalpage {
5251 * Sets basic information about the external page
5253 public function __construct() {
5254 global $CFG;
5255 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5256 "$CFG->wwwroot/$CFG->admin/plugins.php");
5261 * Module manage page
5263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5265 class admin_page_managemods extends admin_externalpage {
5267 * Calls parent::__construct with specific arguments
5269 public function __construct() {
5270 global $CFG;
5271 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5275 * Try to find the specified module
5277 * @param string $query The module to search for
5278 * @return array
5280 public function search($query) {
5281 global $CFG, $DB;
5282 if ($result = parent::search($query)) {
5283 return $result;
5286 $found = false;
5287 if ($modules = $DB->get_records('modules')) {
5288 foreach ($modules as $module) {
5289 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5290 continue;
5292 if (strpos($module->name, $query) !== false) {
5293 $found = true;
5294 break;
5296 $strmodulename = get_string('modulename', $module->name);
5297 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5298 $found = true;
5299 break;
5303 if ($found) {
5304 $result = new stdClass();
5305 $result->page = $this;
5306 $result->settings = array();
5307 return array($this->name => $result);
5308 } else {
5309 return array();
5316 * Special class for enrol plugins management.
5318 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5321 class admin_setting_manageenrols extends admin_setting {
5323 * Calls parent::__construct with specific arguments
5325 public function __construct() {
5326 $this->nosave = true;
5327 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5331 * Always returns true, does nothing
5333 * @return true
5335 public function get_setting() {
5336 return true;
5340 * Always returns true, does nothing
5342 * @return true
5344 public function get_defaultsetting() {
5345 return true;
5349 * Always returns '', does not write anything
5351 * @return string Always returns ''
5353 public function write_setting($data) {
5354 // do not write any setting
5355 return '';
5359 * Checks if $query is one of the available enrol plugins
5361 * @param string $query The string to search for
5362 * @return bool Returns true if found, false if not
5364 public function is_related($query) {
5365 if (parent::is_related($query)) {
5366 return true;
5369 $query = core_text::strtolower($query);
5370 $enrols = enrol_get_plugins(false);
5371 foreach ($enrols as $name=>$enrol) {
5372 $localised = get_string('pluginname', 'enrol_'.$name);
5373 if (strpos(core_text::strtolower($name), $query) !== false) {
5374 return true;
5376 if (strpos(core_text::strtolower($localised), $query) !== false) {
5377 return true;
5380 return false;
5384 * Builds the XHTML to display the control
5386 * @param string $data Unused
5387 * @param string $query
5388 * @return string
5390 public function output_html($data, $query='') {
5391 global $CFG, $OUTPUT, $DB, $PAGE;
5393 // Display strings.
5394 $strup = get_string('up');
5395 $strdown = get_string('down');
5396 $strsettings = get_string('settings');
5397 $strenable = get_string('enable');
5398 $strdisable = get_string('disable');
5399 $struninstall = get_string('uninstallplugin', 'core_admin');
5400 $strusage = get_string('enrolusage', 'enrol');
5401 $strversion = get_string('version');
5402 $strtest = get_string('testsettings', 'core_enrol');
5404 $pluginmanager = core_plugin_manager::instance();
5406 $enrols_available = enrol_get_plugins(false);
5407 $active_enrols = enrol_get_plugins(true);
5409 $allenrols = array();
5410 foreach ($active_enrols as $key=>$enrol) {
5411 $allenrols[$key] = true;
5413 foreach ($enrols_available as $key=>$enrol) {
5414 $allenrols[$key] = true;
5416 // Now find all borked plugins and at least allow then to uninstall.
5417 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5418 foreach ($condidates as $candidate) {
5419 if (empty($allenrols[$candidate])) {
5420 $allenrols[$candidate] = true;
5424 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5425 $return .= $OUTPUT->box_start('generalbox enrolsui');
5427 $table = new html_table();
5428 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5429 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5430 $table->id = 'courseenrolmentplugins';
5431 $table->attributes['class'] = 'admintable generaltable';
5432 $table->data = array();
5434 // Iterate through enrol plugins and add to the display table.
5435 $updowncount = 1;
5436 $enrolcount = count($active_enrols);
5437 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5438 $printed = array();
5439 foreach($allenrols as $enrol => $unused) {
5440 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5441 $version = get_config('enrol_'.$enrol, 'version');
5442 if ($version === false) {
5443 $version = '';
5446 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5447 $name = get_string('pluginname', 'enrol_'.$enrol);
5448 } else {
5449 $name = $enrol;
5451 // Usage.
5452 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5453 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5454 $usage = "$ci / $cp";
5456 // Hide/show links.
5457 $class = '';
5458 if (isset($active_enrols[$enrol])) {
5459 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5460 $hideshow = "<a href=\"$aurl\">";
5461 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5462 $enabled = true;
5463 $displayname = $name;
5464 } else if (isset($enrols_available[$enrol])) {
5465 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5466 $hideshow = "<a href=\"$aurl\">";
5467 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5468 $enabled = false;
5469 $displayname = $name;
5470 $class = 'dimmed_text';
5471 } else {
5472 $hideshow = '';
5473 $enabled = false;
5474 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5476 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5477 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5478 } else {
5479 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5482 // Up/down link (only if enrol is enabled).
5483 $updown = '';
5484 if ($enabled) {
5485 if ($updowncount > 1) {
5486 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5487 $updown .= "<a href=\"$aurl\">";
5488 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5489 } else {
5490 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5492 if ($updowncount < $enrolcount) {
5493 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5494 $updown .= "<a href=\"$aurl\">";
5495 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5496 } else {
5497 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5499 ++$updowncount;
5502 // Add settings link.
5503 if (!$version) {
5504 $settings = '';
5505 } else if ($surl = $plugininfo->get_settings_url()) {
5506 $settings = html_writer::link($surl, $strsettings);
5507 } else {
5508 $settings = '';
5511 // Add uninstall info.
5512 $uninstall = '';
5513 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5514 $uninstall = html_writer::link($uninstallurl, $struninstall);
5517 $test = '';
5518 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5519 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5520 $test = html_writer::link($testsettingsurl, $strtest);
5523 // Add a row to the table.
5524 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5525 if ($class) {
5526 $row->attributes['class'] = $class;
5528 $table->data[] = $row;
5530 $printed[$enrol] = true;
5533 $return .= html_writer::table($table);
5534 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5535 $return .= $OUTPUT->box_end();
5536 return highlight($query, $return);
5542 * Blocks manage page
5544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5546 class admin_page_manageblocks extends admin_externalpage {
5548 * Calls parent::__construct with specific arguments
5550 public function __construct() {
5551 global $CFG;
5552 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5556 * Search for a specific block
5558 * @param string $query The string to search for
5559 * @return array
5561 public function search($query) {
5562 global $CFG, $DB;
5563 if ($result = parent::search($query)) {
5564 return $result;
5567 $found = false;
5568 if ($blocks = $DB->get_records('block')) {
5569 foreach ($blocks as $block) {
5570 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5571 continue;
5573 if (strpos($block->name, $query) !== false) {
5574 $found = true;
5575 break;
5577 $strblockname = get_string('pluginname', 'block_'.$block->name);
5578 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5579 $found = true;
5580 break;
5584 if ($found) {
5585 $result = new stdClass();
5586 $result->page = $this;
5587 $result->settings = array();
5588 return array($this->name => $result);
5589 } else {
5590 return array();
5596 * Message outputs configuration
5598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5600 class admin_page_managemessageoutputs extends admin_externalpage {
5602 * Calls parent::__construct with specific arguments
5604 public function __construct() {
5605 global $CFG;
5606 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5610 * Search for a specific message processor
5612 * @param string $query The string to search for
5613 * @return array
5615 public function search($query) {
5616 global $CFG, $DB;
5617 if ($result = parent::search($query)) {
5618 return $result;
5621 $found = false;
5622 if ($processors = get_message_processors()) {
5623 foreach ($processors as $processor) {
5624 if (!$processor->available) {
5625 continue;
5627 if (strpos($processor->name, $query) !== false) {
5628 $found = true;
5629 break;
5631 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5632 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5633 $found = true;
5634 break;
5638 if ($found) {
5639 $result = new stdClass();
5640 $result->page = $this;
5641 $result->settings = array();
5642 return array($this->name => $result);
5643 } else {
5644 return array();
5650 * Default message outputs configuration
5652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5654 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5656 * Calls parent::__construct with specific arguments
5658 public function __construct() {
5659 global $CFG;
5660 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5666 * Manage question behaviours page
5668 * @copyright 2011 The Open University
5669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5671 class admin_page_manageqbehaviours extends admin_externalpage {
5673 * Constructor
5675 public function __construct() {
5676 global $CFG;
5677 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5678 new moodle_url('/admin/qbehaviours.php'));
5682 * Search question behaviours for the specified string
5684 * @param string $query The string to search for in question behaviours
5685 * @return array
5687 public function search($query) {
5688 global $CFG;
5689 if ($result = parent::search($query)) {
5690 return $result;
5693 $found = false;
5694 require_once($CFG->dirroot . '/question/engine/lib.php');
5695 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5696 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5697 $query) !== false) {
5698 $found = true;
5699 break;
5702 if ($found) {
5703 $result = new stdClass();
5704 $result->page = $this;
5705 $result->settings = array();
5706 return array($this->name => $result);
5707 } else {
5708 return array();
5715 * Question type manage page
5717 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5719 class admin_page_manageqtypes extends admin_externalpage {
5721 * Calls parent::__construct with specific arguments
5723 public function __construct() {
5724 global $CFG;
5725 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5726 new moodle_url('/admin/qtypes.php'));
5730 * Search question types for the specified string
5732 * @param string $query The string to search for in question types
5733 * @return array
5735 public function search($query) {
5736 global $CFG;
5737 if ($result = parent::search($query)) {
5738 return $result;
5741 $found = false;
5742 require_once($CFG->dirroot . '/question/engine/bank.php');
5743 foreach (question_bank::get_all_qtypes() as $qtype) {
5744 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5745 $found = true;
5746 break;
5749 if ($found) {
5750 $result = new stdClass();
5751 $result->page = $this;
5752 $result->settings = array();
5753 return array($this->name => $result);
5754 } else {
5755 return array();
5761 class admin_page_manageportfolios extends admin_externalpage {
5763 * Calls parent::__construct with specific arguments
5765 public function __construct() {
5766 global $CFG;
5767 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5768 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5772 * Searches page for the specified string.
5773 * @param string $query The string to search for
5774 * @return bool True if it is found on this page
5776 public function search($query) {
5777 global $CFG;
5778 if ($result = parent::search($query)) {
5779 return $result;
5782 $found = false;
5783 $portfolios = core_component::get_plugin_list('portfolio');
5784 foreach ($portfolios as $p => $dir) {
5785 if (strpos($p, $query) !== false) {
5786 $found = true;
5787 break;
5790 if (!$found) {
5791 foreach (portfolio_instances(false, false) as $instance) {
5792 $title = $instance->get('name');
5793 if (strpos(core_text::strtolower($title), $query) !== false) {
5794 $found = true;
5795 break;
5800 if ($found) {
5801 $result = new stdClass();
5802 $result->page = $this;
5803 $result->settings = array();
5804 return array($this->name => $result);
5805 } else {
5806 return array();
5812 class admin_page_managerepositories extends admin_externalpage {
5814 * Calls parent::__construct with specific arguments
5816 public function __construct() {
5817 global $CFG;
5818 parent::__construct('managerepositories', get_string('manage',
5819 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5823 * Searches page for the specified string.
5824 * @param string $query The string to search for
5825 * @return bool True if it is found on this page
5827 public function search($query) {
5828 global $CFG;
5829 if ($result = parent::search($query)) {
5830 return $result;
5833 $found = false;
5834 $repositories= core_component::get_plugin_list('repository');
5835 foreach ($repositories as $p => $dir) {
5836 if (strpos($p, $query) !== false) {
5837 $found = true;
5838 break;
5841 if (!$found) {
5842 foreach (repository::get_types() as $instance) {
5843 $title = $instance->get_typename();
5844 if (strpos(core_text::strtolower($title), $query) !== false) {
5845 $found = true;
5846 break;
5851 if ($found) {
5852 $result = new stdClass();
5853 $result->page = $this;
5854 $result->settings = array();
5855 return array($this->name => $result);
5856 } else {
5857 return array();
5864 * Special class for authentication administration.
5866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5868 class admin_setting_manageauths extends admin_setting {
5870 * Calls parent::__construct with specific arguments
5872 public function __construct() {
5873 $this->nosave = true;
5874 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5878 * Always returns true
5880 * @return true
5882 public function get_setting() {
5883 return true;
5887 * Always returns true
5889 * @return true
5891 public function get_defaultsetting() {
5892 return true;
5896 * Always returns '' and doesn't write anything
5898 * @return string Always returns ''
5900 public function write_setting($data) {
5901 // do not write any setting
5902 return '';
5906 * Search to find if Query is related to auth plugin
5908 * @param string $query The string to search for
5909 * @return bool true for related false for not
5911 public function is_related($query) {
5912 if (parent::is_related($query)) {
5913 return true;
5916 $authsavailable = core_component::get_plugin_list('auth');
5917 foreach ($authsavailable as $auth => $dir) {
5918 if (strpos($auth, $query) !== false) {
5919 return true;
5921 $authplugin = get_auth_plugin($auth);
5922 $authtitle = $authplugin->get_title();
5923 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5924 return true;
5927 return false;
5931 * Return XHTML to display control
5933 * @param mixed $data Unused
5934 * @param string $query
5935 * @return string highlight
5937 public function output_html($data, $query='') {
5938 global $CFG, $OUTPUT, $DB;
5940 // display strings
5941 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5942 'settings', 'edit', 'name', 'enable', 'disable',
5943 'up', 'down', 'none', 'users'));
5944 $txt->updown = "$txt->up/$txt->down";
5945 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5946 $txt->testsettings = get_string('testsettings', 'core_auth');
5948 $authsavailable = core_component::get_plugin_list('auth');
5949 get_enabled_auth_plugins(true); // fix the list of enabled auths
5950 if (empty($CFG->auth)) {
5951 $authsenabled = array();
5952 } else {
5953 $authsenabled = explode(',', $CFG->auth);
5956 // construct the display array, with enabled auth plugins at the top, in order
5957 $displayauths = array();
5958 $registrationauths = array();
5959 $registrationauths[''] = $txt->disable;
5960 $authplugins = array();
5961 foreach ($authsenabled as $auth) {
5962 $authplugin = get_auth_plugin($auth);
5963 $authplugins[$auth] = $authplugin;
5964 /// Get the auth title (from core or own auth lang files)
5965 $authtitle = $authplugin->get_title();
5966 /// Apply titles
5967 $displayauths[$auth] = $authtitle;
5968 if ($authplugin->can_signup()) {
5969 $registrationauths[$auth] = $authtitle;
5973 foreach ($authsavailable as $auth => $dir) {
5974 if (array_key_exists($auth, $displayauths)) {
5975 continue; //already in the list
5977 $authplugin = get_auth_plugin($auth);
5978 $authplugins[$auth] = $authplugin;
5979 /// Get the auth title (from core or own auth lang files)
5980 $authtitle = $authplugin->get_title();
5981 /// Apply titles
5982 $displayauths[$auth] = $authtitle;
5983 if ($authplugin->can_signup()) {
5984 $registrationauths[$auth] = $authtitle;
5988 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5989 $return .= $OUTPUT->box_start('generalbox authsui');
5991 $table = new html_table();
5992 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5993 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5994 $table->data = array();
5995 $table->attributes['class'] = 'admintable generaltable';
5996 $table->id = 'manageauthtable';
5998 //add always enabled plugins first
5999 $displayname = $displayauths['manual'];
6000 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6001 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6002 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6003 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6004 $displayname = $displayauths['nologin'];
6005 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6006 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6007 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6010 // iterate through auth plugins and add to the display table
6011 $updowncount = 1;
6012 $authcount = count($authsenabled);
6013 $url = "auth.php?sesskey=" . sesskey();
6014 foreach ($displayauths as $auth => $name) {
6015 if ($auth == 'manual' or $auth == 'nologin') {
6016 continue;
6018 $class = '';
6019 // hide/show link
6020 if (in_array($auth, $authsenabled)) {
6021 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6022 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6023 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6024 $enabled = true;
6025 $displayname = $name;
6027 else {
6028 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6029 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6030 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6031 $enabled = false;
6032 $displayname = $name;
6033 $class = 'dimmed_text';
6036 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6038 // up/down link (only if auth is enabled)
6039 $updown = '';
6040 if ($enabled) {
6041 if ($updowncount > 1) {
6042 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6043 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6045 else {
6046 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6048 if ($updowncount < $authcount) {
6049 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6050 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6052 else {
6053 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6055 ++ $updowncount;
6058 // settings link
6059 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6060 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6061 } else {
6062 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6065 // Uninstall link.
6066 $uninstall = '';
6067 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6068 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6071 $test = '';
6072 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6073 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6074 $test = html_writer::link($testurl, $txt->testsettings);
6077 // Add a row to the table.
6078 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6079 if ($class) {
6080 $row->attributes['class'] = $class;
6082 $table->data[] = $row;
6084 $return .= html_writer::table($table);
6085 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6086 $return .= $OUTPUT->box_end();
6087 return highlight($query, $return);
6093 * Special class for authentication administration.
6095 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6097 class admin_setting_manageeditors extends admin_setting {
6099 * Calls parent::__construct with specific arguments
6101 public function __construct() {
6102 $this->nosave = true;
6103 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6107 * Always returns true, does nothing
6109 * @return true
6111 public function get_setting() {
6112 return true;
6116 * Always returns true, does nothing
6118 * @return true
6120 public function get_defaultsetting() {
6121 return true;
6125 * Always returns '', does not write anything
6127 * @return string Always returns ''
6129 public function write_setting($data) {
6130 // do not write any setting
6131 return '';
6135 * Checks if $query is one of the available editors
6137 * @param string $query The string to search for
6138 * @return bool Returns true if found, false if not
6140 public function is_related($query) {
6141 if (parent::is_related($query)) {
6142 return true;
6145 $editors_available = editors_get_available();
6146 foreach ($editors_available as $editor=>$editorstr) {
6147 if (strpos($editor, $query) !== false) {
6148 return true;
6150 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6151 return true;
6154 return false;
6158 * Builds the XHTML to display the control
6160 * @param string $data Unused
6161 * @param string $query
6162 * @return string
6164 public function output_html($data, $query='') {
6165 global $CFG, $OUTPUT;
6167 // display strings
6168 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6169 'up', 'down', 'none'));
6170 $struninstall = get_string('uninstallplugin', 'core_admin');
6172 $txt->updown = "$txt->up/$txt->down";
6174 $editors_available = editors_get_available();
6175 $active_editors = explode(',', $CFG->texteditors);
6177 $active_editors = array_reverse($active_editors);
6178 foreach ($active_editors as $key=>$editor) {
6179 if (empty($editors_available[$editor])) {
6180 unset($active_editors[$key]);
6181 } else {
6182 $name = $editors_available[$editor];
6183 unset($editors_available[$editor]);
6184 $editors_available[$editor] = $name;
6187 if (empty($active_editors)) {
6188 //$active_editors = array('textarea');
6190 $editors_available = array_reverse($editors_available, true);
6191 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6192 $return .= $OUTPUT->box_start('generalbox editorsui');
6194 $table = new html_table();
6195 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6196 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6197 $table->id = 'editormanagement';
6198 $table->attributes['class'] = 'admintable generaltable';
6199 $table->data = array();
6201 // iterate through auth plugins and add to the display table
6202 $updowncount = 1;
6203 $editorcount = count($active_editors);
6204 $url = "editors.php?sesskey=" . sesskey();
6205 foreach ($editors_available as $editor => $name) {
6206 // hide/show link
6207 $class = '';
6208 if (in_array($editor, $active_editors)) {
6209 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6210 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6211 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6212 $enabled = true;
6213 $displayname = $name;
6215 else {
6216 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6217 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6218 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6219 $enabled = false;
6220 $displayname = $name;
6221 $class = 'dimmed_text';
6224 // up/down link (only if auth is enabled)
6225 $updown = '';
6226 if ($enabled) {
6227 if ($updowncount > 1) {
6228 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6229 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6231 else {
6232 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6234 if ($updowncount < $editorcount) {
6235 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6236 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6238 else {
6239 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6241 ++ $updowncount;
6244 // settings link
6245 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6246 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6247 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6248 } else {
6249 $settings = '';
6252 $uninstall = '';
6253 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6254 $uninstall = html_writer::link($uninstallurl, $struninstall);
6257 // Add a row to the table.
6258 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6259 if ($class) {
6260 $row->attributes['class'] = $class;
6262 $table->data[] = $row;
6264 $return .= html_writer::table($table);
6265 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6266 $return .= $OUTPUT->box_end();
6267 return highlight($query, $return);
6273 * Special class for license administration.
6275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6277 class admin_setting_managelicenses extends admin_setting {
6279 * Calls parent::__construct with specific arguments
6281 public function __construct() {
6282 $this->nosave = true;
6283 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6287 * Always returns true, does nothing
6289 * @return true
6291 public function get_setting() {
6292 return true;
6296 * Always returns true, does nothing
6298 * @return true
6300 public function get_defaultsetting() {
6301 return true;
6305 * Always returns '', does not write anything
6307 * @return string Always returns ''
6309 public function write_setting($data) {
6310 // do not write any setting
6311 return '';
6315 * Builds the XHTML to display the control
6317 * @param string $data Unused
6318 * @param string $query
6319 * @return string
6321 public function output_html($data, $query='') {
6322 global $CFG, $OUTPUT;
6323 require_once($CFG->libdir . '/licenselib.php');
6324 $url = "licenses.php?sesskey=" . sesskey();
6326 // display strings
6327 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6328 $licenses = license_manager::get_licenses();
6330 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6332 $return .= $OUTPUT->box_start('generalbox editorsui');
6334 $table = new html_table();
6335 $table->head = array($txt->name, $txt->enable);
6336 $table->colclasses = array('leftalign', 'centeralign');
6337 $table->id = 'availablelicenses';
6338 $table->attributes['class'] = 'admintable generaltable';
6339 $table->data = array();
6341 foreach ($licenses as $value) {
6342 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6344 if ($value->enabled == 1) {
6345 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6346 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6347 } else {
6348 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6349 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6352 if ($value->shortname == $CFG->sitedefaultlicense) {
6353 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6354 $hideshow = '';
6357 $enabled = true;
6359 $table->data[] =array($displayname, $hideshow);
6361 $return .= html_writer::table($table);
6362 $return .= $OUTPUT->box_end();
6363 return highlight($query, $return);
6368 * Course formats manager. Allows to enable/disable formats and jump to settings
6370 class admin_setting_manageformats extends admin_setting {
6373 * Calls parent::__construct with specific arguments
6375 public function __construct() {
6376 $this->nosave = true;
6377 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6381 * Always returns true
6383 * @return true
6385 public function get_setting() {
6386 return true;
6390 * Always returns true
6392 * @return true
6394 public function get_defaultsetting() {
6395 return true;
6399 * Always returns '' and doesn't write anything
6401 * @param mixed $data string or array, must not be NULL
6402 * @return string Always returns ''
6404 public function write_setting($data) {
6405 // do not write any setting
6406 return '';
6410 * Search to find if Query is related to format plugin
6412 * @param string $query The string to search for
6413 * @return bool true for related false for not
6415 public function is_related($query) {
6416 if (parent::is_related($query)) {
6417 return true;
6419 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6420 foreach ($formats as $format) {
6421 if (strpos($format->component, $query) !== false ||
6422 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6423 return true;
6426 return false;
6430 * Return XHTML to display control
6432 * @param mixed $data Unused
6433 * @param string $query
6434 * @return string highlight
6436 public function output_html($data, $query='') {
6437 global $CFG, $OUTPUT;
6438 $return = '';
6439 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6440 $return .= $OUTPUT->box_start('generalbox formatsui');
6442 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6444 // display strings
6445 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6446 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6447 $txt->updown = "$txt->up/$txt->down";
6449 $table = new html_table();
6450 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6451 $table->align = array('left', 'center', 'center', 'center', 'center');
6452 $table->attributes['class'] = 'manageformattable generaltable admintable';
6453 $table->data = array();
6455 $cnt = 0;
6456 $defaultformat = get_config('moodlecourse', 'format');
6457 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6458 foreach ($formats as $format) {
6459 $url = new moodle_url('/admin/courseformats.php',
6460 array('sesskey' => sesskey(), 'format' => $format->name));
6461 $isdefault = '';
6462 $class = '';
6463 if ($format->is_enabled()) {
6464 $strformatname = $format->displayname;
6465 if ($defaultformat === $format->name) {
6466 $hideshow = $txt->default;
6467 } else {
6468 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6469 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6471 } else {
6472 $strformatname = $format->displayname;
6473 $class = 'dimmed_text';
6474 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6475 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6477 $updown = '';
6478 if ($cnt) {
6479 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6480 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6481 } else {
6482 $updown .= $spacer;
6484 if ($cnt < count($formats) - 1) {
6485 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6486 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6487 } else {
6488 $updown .= $spacer;
6490 $cnt++;
6491 $settings = '';
6492 if ($format->get_settings_url()) {
6493 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6495 $uninstall = '';
6496 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6497 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6499 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6500 if ($class) {
6501 $row->attributes['class'] = $class;
6503 $table->data[] = $row;
6505 $return .= html_writer::table($table);
6506 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6507 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6508 $return .= $OUTPUT->box_end();
6509 return highlight($query, $return);
6514 * Special class for filter administration.
6516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6518 class admin_page_managefilters extends admin_externalpage {
6520 * Calls parent::__construct with specific arguments
6522 public function __construct() {
6523 global $CFG;
6524 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6528 * Searches all installed filters for specified filter
6530 * @param string $query The filter(string) to search for
6531 * @param string $query
6533 public function search($query) {
6534 global $CFG;
6535 if ($result = parent::search($query)) {
6536 return $result;
6539 $found = false;
6540 $filternames = filter_get_all_installed();
6541 foreach ($filternames as $path => $strfiltername) {
6542 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6543 $found = true;
6544 break;
6546 if (strpos($path, $query) !== false) {
6547 $found = true;
6548 break;
6552 if ($found) {
6553 $result = new stdClass;
6554 $result->page = $this;
6555 $result->settings = array();
6556 return array($this->name => $result);
6557 } else {
6558 return array();
6565 * Initialise admin page - this function does require login and permission
6566 * checks specified in page definition.
6568 * This function must be called on each admin page before other code.
6570 * @global moodle_page $PAGE
6572 * @param string $section name of page
6573 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6574 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6575 * added to the turn blocks editing on/off form, so this page reloads correctly.
6576 * @param string $actualurl if the actual page being viewed is not the normal one for this
6577 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6578 * @param array $options Additional options that can be specified for page setup.
6579 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6581 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6582 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6584 $PAGE->set_context(null); // hack - set context to something, by default to system context
6586 $site = get_site();
6587 require_login();
6589 if (!empty($options['pagelayout'])) {
6590 // A specific page layout has been requested.
6591 $PAGE->set_pagelayout($options['pagelayout']);
6592 } else if ($section === 'upgradesettings') {
6593 $PAGE->set_pagelayout('maintenance');
6594 } else {
6595 $PAGE->set_pagelayout('admin');
6598 $adminroot = admin_get_root(false, false); // settings not required for external pages
6599 $extpage = $adminroot->locate($section, true);
6601 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6602 // The requested section isn't in the admin tree
6603 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6604 if (!has_capability('moodle/site:config', context_system::instance())) {
6605 // The requested section could depend on a different capability
6606 // but most likely the user has inadequate capabilities
6607 print_error('accessdenied', 'admin');
6608 } else {
6609 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6613 // this eliminates our need to authenticate on the actual pages
6614 if (!$extpage->check_access()) {
6615 print_error('accessdenied', 'admin');
6616 die;
6619 navigation_node::require_admin_tree();
6621 // $PAGE->set_extra_button($extrabutton); TODO
6623 if (!$actualurl) {
6624 $actualurl = $extpage->url;
6627 $PAGE->set_url($actualurl, $extraurlparams);
6628 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6629 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6632 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6633 // During initial install.
6634 $strinstallation = get_string('installation', 'install');
6635 $strsettings = get_string('settings');
6636 $PAGE->navbar->add($strsettings);
6637 $PAGE->set_title($strinstallation);
6638 $PAGE->set_heading($strinstallation);
6639 $PAGE->set_cacheable(false);
6640 return;
6643 // Locate the current item on the navigation and make it active when found.
6644 $path = $extpage->path;
6645 $node = $PAGE->settingsnav;
6646 while ($node && count($path) > 0) {
6647 $node = $node->get(array_pop($path));
6649 if ($node) {
6650 $node->make_active();
6653 // Normal case.
6654 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6655 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6656 $USER->editing = $adminediting;
6659 $visiblepathtosection = array_reverse($extpage->visiblepath);
6661 if ($PAGE->user_allowed_editing()) {
6662 if ($PAGE->user_is_editing()) {
6663 $caption = get_string('blockseditoff');
6664 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6665 } else {
6666 $caption = get_string('blocksediton');
6667 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6669 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6672 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6673 $PAGE->set_heading($SITE->fullname);
6675 // prevent caching in nav block
6676 $PAGE->navigation->clear_cache();
6680 * Returns the reference to admin tree root
6682 * @return object admin_root object
6684 function admin_get_root($reload=false, $requirefulltree=true) {
6685 global $CFG, $DB, $OUTPUT;
6687 static $ADMIN = NULL;
6689 if (is_null($ADMIN)) {
6690 // create the admin tree!
6691 $ADMIN = new admin_root($requirefulltree);
6694 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6695 $ADMIN->purge_children($requirefulltree);
6698 if (!$ADMIN->loaded) {
6699 // we process this file first to create categories first and in correct order
6700 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6702 // now we process all other files in admin/settings to build the admin tree
6703 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6704 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6705 continue;
6707 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6708 // plugins are loaded last - they may insert pages anywhere
6709 continue;
6711 require($file);
6713 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6715 $ADMIN->loaded = true;
6718 return $ADMIN;
6721 /// settings utility functions
6724 * This function applies default settings.
6726 * @param object $node, NULL means complete tree, null by default
6727 * @param bool $unconditional if true overrides all values with defaults, null buy default
6729 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6730 global $CFG;
6732 if (is_null($node)) {
6733 core_plugin_manager::reset_caches();
6734 $node = admin_get_root(true, true);
6737 if ($node instanceof admin_category) {
6738 $entries = array_keys($node->children);
6739 foreach ($entries as $entry) {
6740 admin_apply_default_settings($node->children[$entry], $unconditional);
6743 } else if ($node instanceof admin_settingpage) {
6744 foreach ($node->settings as $setting) {
6745 if (!$unconditional and !is_null($setting->get_setting())) {
6746 //do not override existing defaults
6747 continue;
6749 $defaultsetting = $setting->get_defaultsetting();
6750 if (is_null($defaultsetting)) {
6751 // no value yet - default maybe applied after admin user creation or in upgradesettings
6752 continue;
6754 $setting->write_setting($defaultsetting);
6755 $setting->write_setting_flags(null);
6758 // Just in case somebody modifies the list of active plugins directly.
6759 core_plugin_manager::reset_caches();
6763 * Store changed settings, this function updates the errors variable in $ADMIN
6765 * @param object $formdata from form
6766 * @return int number of changed settings
6768 function admin_write_settings($formdata) {
6769 global $CFG, $SITE, $DB;
6771 $olddbsessions = !empty($CFG->dbsessions);
6772 $formdata = (array)$formdata;
6774 $data = array();
6775 foreach ($formdata as $fullname=>$value) {
6776 if (strpos($fullname, 's_') !== 0) {
6777 continue; // not a config value
6779 $data[$fullname] = $value;
6782 $adminroot = admin_get_root();
6783 $settings = admin_find_write_settings($adminroot, $data);
6785 $count = 0;
6786 foreach ($settings as $fullname=>$setting) {
6787 /** @var $setting admin_setting */
6788 $original = $setting->get_setting();
6789 $error = $setting->write_setting($data[$fullname]);
6790 if ($error !== '') {
6791 $adminroot->errors[$fullname] = new stdClass();
6792 $adminroot->errors[$fullname]->data = $data[$fullname];
6793 $adminroot->errors[$fullname]->id = $setting->get_id();
6794 $adminroot->errors[$fullname]->error = $error;
6795 } else {
6796 $setting->write_setting_flags($data);
6798 if ($setting->post_write_settings($original)) {
6799 $count++;
6803 if ($olddbsessions != !empty($CFG->dbsessions)) {
6804 require_logout();
6807 // Now update $SITE - just update the fields, in case other people have a
6808 // a reference to it (e.g. $PAGE, $COURSE).
6809 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6810 foreach (get_object_vars($newsite) as $field => $value) {
6811 $SITE->$field = $value;
6814 // now reload all settings - some of them might depend on the changed
6815 admin_get_root(true);
6816 return $count;
6820 * Internal recursive function - finds all settings from submitted form
6822 * @param object $node Instance of admin_category, or admin_settingpage
6823 * @param array $data
6824 * @return array
6826 function admin_find_write_settings($node, $data) {
6827 $return = array();
6829 if (empty($data)) {
6830 return $return;
6833 if ($node instanceof admin_category) {
6834 $entries = array_keys($node->children);
6835 foreach ($entries as $entry) {
6836 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6839 } else if ($node instanceof admin_settingpage) {
6840 foreach ($node->settings as $setting) {
6841 $fullname = $setting->get_full_name();
6842 if (array_key_exists($fullname, $data)) {
6843 $return[$fullname] = $setting;
6849 return $return;
6853 * Internal function - prints the search results
6855 * @param string $query String to search for
6856 * @return string empty or XHTML
6858 function admin_search_settings_html($query) {
6859 global $CFG, $OUTPUT;
6861 if (core_text::strlen($query) < 2) {
6862 return '';
6864 $query = core_text::strtolower($query);
6866 $adminroot = admin_get_root();
6867 $findings = $adminroot->search($query);
6868 $return = '';
6869 $savebutton = false;
6871 foreach ($findings as $found) {
6872 $page = $found->page;
6873 $settings = $found->settings;
6874 if ($page->is_hidden()) {
6875 // hidden pages are not displayed in search results
6876 continue;
6878 if ($page instanceof admin_externalpage) {
6879 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6880 } else if ($page instanceof admin_settingpage) {
6881 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/settings.php?section='.$page->name.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6882 } else {
6883 continue;
6885 if (!empty($settings)) {
6886 $return .= '<fieldset class="adminsettings">'."\n";
6887 foreach ($settings as $setting) {
6888 if (empty($setting->nosave)) {
6889 $savebutton = true;
6891 $return .= '<div class="clearer"><!-- --></div>'."\n";
6892 $fullname = $setting->get_full_name();
6893 if (array_key_exists($fullname, $adminroot->errors)) {
6894 $data = $adminroot->errors[$fullname]->data;
6895 } else {
6896 $data = $setting->get_setting();
6897 // do not use defaults if settings not available - upgradesettings handles the defaults!
6899 $return .= $setting->output_html($data, $query);
6901 $return .= '</fieldset>';
6905 if ($savebutton) {
6906 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6909 return $return;
6913 * Internal function - returns arrays of html pages with uninitialised settings
6915 * @param object $node Instance of admin_category or admin_settingpage
6916 * @return array
6918 function admin_output_new_settings_by_page($node) {
6919 global $OUTPUT;
6920 $return = array();
6922 if ($node instanceof admin_category) {
6923 $entries = array_keys($node->children);
6924 foreach ($entries as $entry) {
6925 $return += admin_output_new_settings_by_page($node->children[$entry]);
6928 } else if ($node instanceof admin_settingpage) {
6929 $newsettings = array();
6930 foreach ($node->settings as $setting) {
6931 if (is_null($setting->get_setting())) {
6932 $newsettings[] = $setting;
6935 if (count($newsettings) > 0) {
6936 $adminroot = admin_get_root();
6937 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6938 $page .= '<fieldset class="adminsettings">'."\n";
6939 foreach ($newsettings as $setting) {
6940 $fullname = $setting->get_full_name();
6941 if (array_key_exists($fullname, $adminroot->errors)) {
6942 $data = $adminroot->errors[$fullname]->data;
6943 } else {
6944 $data = $setting->get_setting();
6945 if (is_null($data)) {
6946 $data = $setting->get_defaultsetting();
6949 $page .= '<div class="clearer"><!-- --></div>'."\n";
6950 $page .= $setting->output_html($data);
6952 $page .= '</fieldset>';
6953 $return[$node->name] = $page;
6957 return $return;
6961 * Format admin settings
6963 * @param object $setting
6964 * @param string $title label element
6965 * @param string $form form fragment, html code - not highlighted automatically
6966 * @param string $description
6967 * @param bool $label link label to id, true by default
6968 * @param string $warning warning text
6969 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6970 * @param string $query search query to be highlighted
6971 * @return string XHTML
6973 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6974 global $CFG;
6976 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6977 $fullname = $setting->get_full_name();
6979 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6980 if ($label) {
6981 $labelfor = 'for = "'.$setting->get_id().'"';
6982 } else {
6983 $labelfor = '';
6985 $form .= $setting->output_setting_flags();
6987 $override = '';
6988 if (empty($setting->plugin)) {
6989 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6990 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6992 } else {
6993 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6994 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6998 if ($warning !== '') {
6999 $warning = '<div class="form-warning">'.$warning.'</div>';
7002 $defaults = array();
7003 if (!is_null($defaultinfo)) {
7004 if ($defaultinfo === '') {
7005 $defaultinfo = get_string('emptysettingvalue', 'admin');
7007 $defaults[] = $defaultinfo;
7010 $setting->get_setting_flag_defaults($defaults);
7012 if (!empty($defaults)) {
7013 $defaultinfo = implode(', ', $defaults);
7014 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7015 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
7019 $adminroot = admin_get_root();
7020 $error = '';
7021 if (array_key_exists($fullname, $adminroot->errors)) {
7022 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
7025 $str = '
7026 <div class="form-item clearfix" id="admin-'.$setting->name.'">
7027 <div class="form-label">
7028 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
7029 <span class="form-shortname">'.highlightfast($query, $name).'</span>
7030 </div>
7031 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
7032 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
7033 </div>';
7035 return $str;
7039 * Based on find_new_settings{@link ()} in upgradesettings.php
7040 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7042 * @param object $node Instance of admin_category, or admin_settingpage
7043 * @return boolean true if any settings haven't been initialised, false if they all have
7045 function any_new_admin_settings($node) {
7047 if ($node instanceof admin_category) {
7048 $entries = array_keys($node->children);
7049 foreach ($entries as $entry) {
7050 if (any_new_admin_settings($node->children[$entry])) {
7051 return true;
7055 } else if ($node instanceof admin_settingpage) {
7056 foreach ($node->settings as $setting) {
7057 if ($setting->get_setting() === NULL) {
7058 return true;
7063 return false;
7067 * Moved from admin/replace.php so that we can use this in cron
7069 * @param string $search string to look for
7070 * @param string $replace string to replace
7071 * @return bool success or fail
7073 function db_replace($search, $replace) {
7074 global $DB, $CFG, $OUTPUT;
7076 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7077 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7078 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7079 'block_instances', '');
7081 // Turn off time limits, sometimes upgrades can be slow.
7082 core_php_time_limit::raise();
7084 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7085 return false;
7087 foreach ($tables as $table) {
7089 if (in_array($table, $skiptables)) { // Don't process these
7090 continue;
7093 if ($columns = $DB->get_columns($table)) {
7094 $DB->set_debug(true);
7095 foreach ($columns as $column) {
7096 $DB->replace_all_text($table, $column, $search, $replace);
7098 $DB->set_debug(false);
7102 // delete modinfo caches
7103 rebuild_course_cache(0, true);
7105 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7106 $blocks = core_component::get_plugin_list('block');
7107 foreach ($blocks as $blockname=>$fullblock) {
7108 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7109 continue;
7112 if (!is_readable($fullblock.'/lib.php')) {
7113 continue;
7116 $function = 'block_'.$blockname.'_global_db_replace';
7117 include_once($fullblock.'/lib.php');
7118 if (!function_exists($function)) {
7119 continue;
7122 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7123 $function($search, $replace);
7124 echo $OUTPUT->notification("...finished", 'notifysuccess');
7127 purge_all_caches();
7129 return true;
7133 * Manage repository settings
7135 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7137 class admin_setting_managerepository extends admin_setting {
7138 /** @var string */
7139 private $baseurl;
7142 * calls parent::__construct with specific arguments
7144 public function __construct() {
7145 global $CFG;
7146 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7147 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7151 * Always returns true, does nothing
7153 * @return true
7155 public function get_setting() {
7156 return true;
7160 * Always returns true does nothing
7162 * @return true
7164 public function get_defaultsetting() {
7165 return true;
7169 * Always returns s_managerepository
7171 * @return string Always return 's_managerepository'
7173 public function get_full_name() {
7174 return 's_managerepository';
7178 * Always returns '' doesn't do anything
7180 public function write_setting($data) {
7181 $url = $this->baseurl . '&amp;new=' . $data;
7182 return '';
7183 // TODO
7184 // Should not use redirect and exit here
7185 // Find a better way to do this.
7186 // redirect($url);
7187 // exit;
7191 * Searches repository plugins for one that matches $query
7193 * @param string $query The string to search for
7194 * @return bool true if found, false if not
7196 public function is_related($query) {
7197 if (parent::is_related($query)) {
7198 return true;
7201 $repositories= core_component::get_plugin_list('repository');
7202 foreach ($repositories as $p => $dir) {
7203 if (strpos($p, $query) !== false) {
7204 return true;
7207 foreach (repository::get_types() as $instance) {
7208 $title = $instance->get_typename();
7209 if (strpos(core_text::strtolower($title), $query) !== false) {
7210 return true;
7213 return false;
7217 * Helper function that generates a moodle_url object
7218 * relevant to the repository
7221 function repository_action_url($repository) {
7222 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7226 * Builds XHTML to display the control
7228 * @param string $data Unused
7229 * @param string $query
7230 * @return string XHTML
7232 public function output_html($data, $query='') {
7233 global $CFG, $USER, $OUTPUT;
7235 // Get strings that are used
7236 $strshow = get_string('on', 'repository');
7237 $strhide = get_string('off', 'repository');
7238 $strdelete = get_string('disabled', 'repository');
7240 $actionchoicesforexisting = array(
7241 'show' => $strshow,
7242 'hide' => $strhide,
7243 'delete' => $strdelete
7246 $actionchoicesfornew = array(
7247 'newon' => $strshow,
7248 'newoff' => $strhide,
7249 'delete' => $strdelete
7252 $return = '';
7253 $return .= $OUTPUT->box_start('generalbox');
7255 // Set strings that are used multiple times
7256 $settingsstr = get_string('settings');
7257 $disablestr = get_string('disable');
7259 // Table to list plug-ins
7260 $table = new html_table();
7261 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7262 $table->align = array('left', 'center', 'center', 'center', 'center');
7263 $table->data = array();
7265 // Get list of used plug-ins
7266 $repositorytypes = repository::get_types();
7267 if (!empty($repositorytypes)) {
7268 // Array to store plugins being used
7269 $alreadyplugins = array();
7270 $totalrepositorytypes = count($repositorytypes);
7271 $updowncount = 1;
7272 foreach ($repositorytypes as $i) {
7273 $settings = '';
7274 $typename = $i->get_typename();
7275 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7276 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7277 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7279 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7280 // Calculate number of instances in order to display them for the Moodle administrator
7281 if (!empty($instanceoptionnames)) {
7282 $params = array();
7283 $params['context'] = array(context_system::instance());
7284 $params['onlyvisible'] = false;
7285 $params['type'] = $typename;
7286 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7287 // site instances
7288 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7289 $params['context'] = array();
7290 $instances = repository::static_function($typename, 'get_instances', $params);
7291 $courseinstances = array();
7292 $userinstances = array();
7294 foreach ($instances as $instance) {
7295 $repocontext = context::instance_by_id($instance->instance->contextid);
7296 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7297 $courseinstances[] = $instance;
7298 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7299 $userinstances[] = $instance;
7302 // course instances
7303 $instancenumber = count($courseinstances);
7304 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7306 // user private instances
7307 $instancenumber = count($userinstances);
7308 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7309 } else {
7310 $admininstancenumbertext = "";
7311 $courseinstancenumbertext = "";
7312 $userinstancenumbertext = "";
7315 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7317 $settings .= $OUTPUT->container_start('mdl-left');
7318 $settings .= '<br/>';
7319 $settings .= $admininstancenumbertext;
7320 $settings .= '<br/>';
7321 $settings .= $courseinstancenumbertext;
7322 $settings .= '<br/>';
7323 $settings .= $userinstancenumbertext;
7324 $settings .= $OUTPUT->container_end();
7326 // Get the current visibility
7327 if ($i->get_visible()) {
7328 $currentaction = 'show';
7329 } else {
7330 $currentaction = 'hide';
7333 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7335 // Display up/down link
7336 $updown = '';
7337 // Should be done with CSS instead.
7338 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7340 if ($updowncount > 1) {
7341 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7342 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7344 else {
7345 $updown .= $spacer;
7347 if ($updowncount < $totalrepositorytypes) {
7348 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7349 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7351 else {
7352 $updown .= $spacer;
7355 $updowncount++;
7357 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7359 if (!in_array($typename, $alreadyplugins)) {
7360 $alreadyplugins[] = $typename;
7365 // Get all the plugins that exist on disk
7366 $plugins = core_component::get_plugin_list('repository');
7367 if (!empty($plugins)) {
7368 foreach ($plugins as $plugin => $dir) {
7369 // Check that it has not already been listed
7370 if (!in_array($plugin, $alreadyplugins)) {
7371 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7372 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7377 $return .= html_writer::table($table);
7378 $return .= $OUTPUT->box_end();
7379 return highlight($query, $return);
7384 * Special checkbox for enable mobile web service
7385 * If enable then we store the service id of the mobile service into config table
7386 * If disable then we unstore the service id from the config table
7388 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7390 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7391 private $xmlrpcuse;
7392 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7393 private $restuse;
7396 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7398 * @return boolean
7400 private function is_protocol_cap_allowed() {
7401 global $DB, $CFG;
7403 // We keep xmlrpc enabled for backward compatibility.
7404 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7405 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7406 $params = array();
7407 $params['permission'] = CAP_ALLOW;
7408 $params['roleid'] = $CFG->defaultuserroleid;
7409 $params['capability'] = 'webservice/xmlrpc:use';
7410 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7413 // If the $this->restuse variable is not set, it needs to be set.
7414 if (empty($this->restuse) and $this->restuse!==false) {
7415 $params = array();
7416 $params['permission'] = CAP_ALLOW;
7417 $params['roleid'] = $CFG->defaultuserroleid;
7418 $params['capability'] = 'webservice/rest:use';
7419 $this->restuse = $DB->record_exists('role_capabilities', $params);
7422 return ($this->xmlrpcuse && $this->restuse);
7426 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7427 * @param type $status true to allow, false to not set
7429 private function set_protocol_cap($status) {
7430 global $CFG;
7431 if ($status and !$this->is_protocol_cap_allowed()) {
7432 //need to allow the cap
7433 $permission = CAP_ALLOW;
7434 $assign = true;
7435 } else if (!$status and $this->is_protocol_cap_allowed()){
7436 //need to disallow the cap
7437 $permission = CAP_INHERIT;
7438 $assign = true;
7440 if (!empty($assign)) {
7441 $systemcontext = context_system::instance();
7442 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7443 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7448 * Builds XHTML to display the control.
7449 * The main purpose of this overloading is to display a warning when https
7450 * is not supported by the server
7451 * @param string $data Unused
7452 * @param string $query
7453 * @return string XHTML
7455 public function output_html($data, $query='') {
7456 global $CFG, $OUTPUT;
7457 $html = parent::output_html($data, $query);
7459 if ((string)$data === $this->yes) {
7460 require_once($CFG->dirroot . "/lib/filelib.php");
7461 $curl = new curl();
7462 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7463 $curl->head($httpswwwroot . "/login/index.php");
7464 $info = $curl->get_info();
7465 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7466 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7470 return $html;
7474 * Retrieves the current setting using the objects name
7476 * @return string
7478 public function get_setting() {
7479 global $CFG;
7481 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7482 // Or if web services aren't enabled this can't be,
7483 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7484 return 0;
7487 require_once($CFG->dirroot . '/webservice/lib.php');
7488 $webservicemanager = new webservice();
7489 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7490 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7491 return $this->config_read($this->name); //same as returning 1
7492 } else {
7493 return 0;
7498 * Save the selected setting
7500 * @param string $data The selected site
7501 * @return string empty string or error message
7503 public function write_setting($data) {
7504 global $DB, $CFG;
7506 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7507 if (empty($CFG->defaultuserroleid)) {
7508 return '';
7511 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7513 require_once($CFG->dirroot . '/webservice/lib.php');
7514 $webservicemanager = new webservice();
7516 $updateprotocol = false;
7517 if ((string)$data === $this->yes) {
7518 //code run when enable mobile web service
7519 //enable web service systeme if necessary
7520 set_config('enablewebservices', true);
7522 //enable mobile service
7523 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7524 $mobileservice->enabled = 1;
7525 $webservicemanager->update_external_service($mobileservice);
7527 //enable xml-rpc server
7528 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7530 if (!in_array('xmlrpc', $activeprotocols)) {
7531 $activeprotocols[] = 'xmlrpc';
7532 $updateprotocol = true;
7535 if (!in_array('rest', $activeprotocols)) {
7536 $activeprotocols[] = 'rest';
7537 $updateprotocol = true;
7540 if ($updateprotocol) {
7541 set_config('webserviceprotocols', implode(',', $activeprotocols));
7544 //allow xml-rpc:use capability for authenticated user
7545 $this->set_protocol_cap(true);
7547 } else {
7548 //disable web service system if no other services are enabled
7549 $otherenabledservices = $DB->get_records_select('external_services',
7550 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7551 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7552 if (empty($otherenabledservices)) {
7553 set_config('enablewebservices', false);
7555 //also disable xml-rpc server
7556 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7557 $protocolkey = array_search('xmlrpc', $activeprotocols);
7558 if ($protocolkey !== false) {
7559 unset($activeprotocols[$protocolkey]);
7560 $updateprotocol = true;
7563 $protocolkey = array_search('rest', $activeprotocols);
7564 if ($protocolkey !== false) {
7565 unset($activeprotocols[$protocolkey]);
7566 $updateprotocol = true;
7569 if ($updateprotocol) {
7570 set_config('webserviceprotocols', implode(',', $activeprotocols));
7573 //disallow xml-rpc:use capability for authenticated user
7574 $this->set_protocol_cap(false);
7577 //disable the mobile service
7578 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7579 $mobileservice->enabled = 0;
7580 $webservicemanager->update_external_service($mobileservice);
7583 return (parent::write_setting($data));
7588 * Special class for management of external services
7590 * @author Petr Skoda (skodak)
7592 class admin_setting_manageexternalservices extends admin_setting {
7594 * Calls parent::__construct with specific arguments
7596 public function __construct() {
7597 $this->nosave = true;
7598 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7602 * Always returns true, does nothing
7604 * @return true
7606 public function get_setting() {
7607 return true;
7611 * Always returns true, does nothing
7613 * @return true
7615 public function get_defaultsetting() {
7616 return true;
7620 * Always returns '', does not write anything
7622 * @return string Always returns ''
7624 public function write_setting($data) {
7625 // do not write any setting
7626 return '';
7630 * Checks if $query is one of the available external services
7632 * @param string $query The string to search for
7633 * @return bool Returns true if found, false if not
7635 public function is_related($query) {
7636 global $DB;
7638 if (parent::is_related($query)) {
7639 return true;
7642 $services = $DB->get_records('external_services', array(), 'id, name');
7643 foreach ($services as $service) {
7644 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7645 return true;
7648 return false;
7652 * Builds the XHTML to display the control
7654 * @param string $data Unused
7655 * @param string $query
7656 * @return string
7658 public function output_html($data, $query='') {
7659 global $CFG, $OUTPUT, $DB;
7661 // display strings
7662 $stradministration = get_string('administration');
7663 $stredit = get_string('edit');
7664 $strservice = get_string('externalservice', 'webservice');
7665 $strdelete = get_string('delete');
7666 $strplugin = get_string('plugin', 'admin');
7667 $stradd = get_string('add');
7668 $strfunctions = get_string('functions', 'webservice');
7669 $strusers = get_string('users');
7670 $strserviceusers = get_string('serviceusers', 'webservice');
7672 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7673 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7674 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7676 // built in services
7677 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7678 $return = "";
7679 if (!empty($services)) {
7680 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7684 $table = new html_table();
7685 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7686 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7687 $table->id = 'builtinservices';
7688 $table->attributes['class'] = 'admintable externalservices generaltable';
7689 $table->data = array();
7691 // iterate through auth plugins and add to the display table
7692 foreach ($services as $service) {
7693 $name = $service->name;
7695 // hide/show link
7696 if ($service->enabled) {
7697 $displayname = "<span>$name</span>";
7698 } else {
7699 $displayname = "<span class=\"dimmed_text\">$name</span>";
7702 $plugin = $service->component;
7704 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7706 if ($service->restrictedusers) {
7707 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7708 } else {
7709 $users = get_string('allusers', 'webservice');
7712 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7714 // add a row to the table
7715 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7717 $return .= html_writer::table($table);
7720 // Custom services
7721 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7722 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7724 $table = new html_table();
7725 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7726 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7727 $table->id = 'customservices';
7728 $table->attributes['class'] = 'admintable externalservices generaltable';
7729 $table->data = array();
7731 // iterate through auth plugins and add to the display table
7732 foreach ($services as $service) {
7733 $name = $service->name;
7735 // hide/show link
7736 if ($service->enabled) {
7737 $displayname = "<span>$name</span>";
7738 } else {
7739 $displayname = "<span class=\"dimmed_text\">$name</span>";
7742 // delete link
7743 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7745 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7747 if ($service->restrictedusers) {
7748 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7749 } else {
7750 $users = get_string('allusers', 'webservice');
7753 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7755 // add a row to the table
7756 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7758 // add new custom service option
7759 $return .= html_writer::table($table);
7761 $return .= '<br />';
7762 // add a token to the table
7763 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7765 return highlight($query, $return);
7770 * Special class for overview of external services
7772 * @author Jerome Mouneyrac
7774 class admin_setting_webservicesoverview extends admin_setting {
7777 * Calls parent::__construct with specific arguments
7779 public function __construct() {
7780 $this->nosave = true;
7781 parent::__construct('webservicesoverviewui',
7782 get_string('webservicesoverview', 'webservice'), '', '');
7786 * Always returns true, does nothing
7788 * @return true
7790 public function get_setting() {
7791 return true;
7795 * Always returns true, does nothing
7797 * @return true
7799 public function get_defaultsetting() {
7800 return true;
7804 * Always returns '', does not write anything
7806 * @return string Always returns ''
7808 public function write_setting($data) {
7809 // do not write any setting
7810 return '';
7814 * Builds the XHTML to display the control
7816 * @param string $data Unused
7817 * @param string $query
7818 * @return string
7820 public function output_html($data, $query='') {
7821 global $CFG, $OUTPUT;
7823 $return = "";
7824 $brtag = html_writer::empty_tag('br');
7826 // Enable mobile web service
7827 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7828 get_string('enablemobilewebservice', 'admin'),
7829 get_string('configenablemobilewebservice',
7830 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7831 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
7832 $wsmobileparam = new stdClass();
7833 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7834 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7835 get_string('mobile', 'admin'));
7836 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7837 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7838 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7839 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7840 . $brtag . $brtag;
7842 /// One system controlling Moodle with Token
7843 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7844 $table = new html_table();
7845 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7846 get_string('description'));
7847 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7848 $table->id = 'onesystemcontrol';
7849 $table->attributes['class'] = 'admintable wsoverview generaltable';
7850 $table->data = array();
7852 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7853 . $brtag . $brtag;
7855 /// 1. Enable Web Services
7856 $row = array();
7857 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7858 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7859 array('href' => $url));
7860 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7861 if ($CFG->enablewebservices) {
7862 $status = get_string('yes');
7864 $row[1] = $status;
7865 $row[2] = get_string('enablewsdescription', 'webservice');
7866 $table->data[] = $row;
7868 /// 2. Enable protocols
7869 $row = array();
7870 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7871 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7872 array('href' => $url));
7873 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7874 //retrieve activated protocol
7875 $active_protocols = empty($CFG->webserviceprotocols) ?
7876 array() : explode(',', $CFG->webserviceprotocols);
7877 if (!empty($active_protocols)) {
7878 $status = "";
7879 foreach ($active_protocols as $protocol) {
7880 $status .= $protocol . $brtag;
7883 $row[1] = $status;
7884 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7885 $table->data[] = $row;
7887 /// 3. Create user account
7888 $row = array();
7889 $url = new moodle_url("/user/editadvanced.php?id=-1");
7890 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7891 array('href' => $url));
7892 $row[1] = "";
7893 $row[2] = get_string('createuserdescription', 'webservice');
7894 $table->data[] = $row;
7896 /// 4. Add capability to users
7897 $row = array();
7898 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7899 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7900 array('href' => $url));
7901 $row[1] = "";
7902 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7903 $table->data[] = $row;
7905 /// 5. Select a web service
7906 $row = array();
7907 $url = new moodle_url("/admin/settings.php?section=externalservices");
7908 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7909 array('href' => $url));
7910 $row[1] = "";
7911 $row[2] = get_string('createservicedescription', 'webservice');
7912 $table->data[] = $row;
7914 /// 6. Add functions
7915 $row = array();
7916 $url = new moodle_url("/admin/settings.php?section=externalservices");
7917 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7918 array('href' => $url));
7919 $row[1] = "";
7920 $row[2] = get_string('addfunctionsdescription', 'webservice');
7921 $table->data[] = $row;
7923 /// 7. Add the specific user
7924 $row = array();
7925 $url = new moodle_url("/admin/settings.php?section=externalservices");
7926 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7927 array('href' => $url));
7928 $row[1] = "";
7929 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7930 $table->data[] = $row;
7932 /// 8. Create token for the specific user
7933 $row = array();
7934 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7935 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7936 array('href' => $url));
7937 $row[1] = "";
7938 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7939 $table->data[] = $row;
7941 /// 9. Enable the documentation
7942 $row = array();
7943 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7944 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7945 array('href' => $url));
7946 $status = '<span class="warning">' . get_string('no') . '</span>';
7947 if ($CFG->enablewsdocumentation) {
7948 $status = get_string('yes');
7950 $row[1] = $status;
7951 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7952 $table->data[] = $row;
7954 /// 10. Test the service
7955 $row = array();
7956 $url = new moodle_url("/admin/webservice/testclient.php");
7957 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7958 array('href' => $url));
7959 $row[1] = "";
7960 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7961 $table->data[] = $row;
7963 $return .= html_writer::table($table);
7965 /// Users as clients with token
7966 $return .= $brtag . $brtag . $brtag;
7967 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7968 $table = new html_table();
7969 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7970 get_string('description'));
7971 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7972 $table->id = 'userasclients';
7973 $table->attributes['class'] = 'admintable wsoverview generaltable';
7974 $table->data = array();
7976 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7977 $brtag . $brtag;
7979 /// 1. Enable Web Services
7980 $row = array();
7981 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7982 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7983 array('href' => $url));
7984 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7985 if ($CFG->enablewebservices) {
7986 $status = get_string('yes');
7988 $row[1] = $status;
7989 $row[2] = get_string('enablewsdescription', 'webservice');
7990 $table->data[] = $row;
7992 /// 2. Enable protocols
7993 $row = array();
7994 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7995 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7996 array('href' => $url));
7997 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7998 //retrieve activated protocol
7999 $active_protocols = empty($CFG->webserviceprotocols) ?
8000 array() : explode(',', $CFG->webserviceprotocols);
8001 if (!empty($active_protocols)) {
8002 $status = "";
8003 foreach ($active_protocols as $protocol) {
8004 $status .= $protocol . $brtag;
8007 $row[1] = $status;
8008 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8009 $table->data[] = $row;
8012 /// 3. Select a web service
8013 $row = array();
8014 $url = new moodle_url("/admin/settings.php?section=externalservices");
8015 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8016 array('href' => $url));
8017 $row[1] = "";
8018 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8019 $table->data[] = $row;
8021 /// 4. Add functions
8022 $row = array();
8023 $url = new moodle_url("/admin/settings.php?section=externalservices");
8024 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8025 array('href' => $url));
8026 $row[1] = "";
8027 $row[2] = get_string('addfunctionsdescription', 'webservice');
8028 $table->data[] = $row;
8030 /// 5. Add capability to users
8031 $row = array();
8032 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8033 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8034 array('href' => $url));
8035 $row[1] = "";
8036 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8037 $table->data[] = $row;
8039 /// 6. Test the service
8040 $row = array();
8041 $url = new moodle_url("/admin/webservice/testclient.php");
8042 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8043 array('href' => $url));
8044 $row[1] = "";
8045 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8046 $table->data[] = $row;
8048 $return .= html_writer::table($table);
8050 return highlight($query, $return);
8057 * Special class for web service protocol administration.
8059 * @author Petr Skoda (skodak)
8061 class admin_setting_managewebserviceprotocols extends admin_setting {
8064 * Calls parent::__construct with specific arguments
8066 public function __construct() {
8067 $this->nosave = true;
8068 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8072 * Always returns true, does nothing
8074 * @return true
8076 public function get_setting() {
8077 return true;
8081 * Always returns true, does nothing
8083 * @return true
8085 public function get_defaultsetting() {
8086 return true;
8090 * Always returns '', does not write anything
8092 * @return string Always returns ''
8094 public function write_setting($data) {
8095 // do not write any setting
8096 return '';
8100 * Checks if $query is one of the available webservices
8102 * @param string $query The string to search for
8103 * @return bool Returns true if found, false if not
8105 public function is_related($query) {
8106 if (parent::is_related($query)) {
8107 return true;
8110 $protocols = core_component::get_plugin_list('webservice');
8111 foreach ($protocols as $protocol=>$location) {
8112 if (strpos($protocol, $query) !== false) {
8113 return true;
8115 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8116 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8117 return true;
8120 return false;
8124 * Builds the XHTML to display the control
8126 * @param string $data Unused
8127 * @param string $query
8128 * @return string
8130 public function output_html($data, $query='') {
8131 global $CFG, $OUTPUT;
8133 // display strings
8134 $stradministration = get_string('administration');
8135 $strsettings = get_string('settings');
8136 $stredit = get_string('edit');
8137 $strprotocol = get_string('protocol', 'webservice');
8138 $strenable = get_string('enable');
8139 $strdisable = get_string('disable');
8140 $strversion = get_string('version');
8142 $protocols_available = core_component::get_plugin_list('webservice');
8143 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8144 ksort($protocols_available);
8146 foreach ($active_protocols as $key=>$protocol) {
8147 if (empty($protocols_available[$protocol])) {
8148 unset($active_protocols[$key]);
8152 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8153 $return .= $OUTPUT->box_start('generalbox webservicesui');
8155 $table = new html_table();
8156 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8157 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8158 $table->id = 'webserviceprotocols';
8159 $table->attributes['class'] = 'admintable generaltable';
8160 $table->data = array();
8162 // iterate through auth plugins and add to the display table
8163 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8164 foreach ($protocols_available as $protocol => $location) {
8165 $name = get_string('pluginname', 'webservice_'.$protocol);
8167 $plugin = new stdClass();
8168 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8169 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8171 $version = isset($plugin->version) ? $plugin->version : '';
8173 // hide/show link
8174 if (in_array($protocol, $active_protocols)) {
8175 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8176 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8177 $displayname = "<span>$name</span>";
8178 } else {
8179 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8180 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8181 $displayname = "<span class=\"dimmed_text\">$name</span>";
8184 // settings link
8185 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8186 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8187 } else {
8188 $settings = '';
8191 // add a row to the table
8192 $table->data[] = array($displayname, $version, $hideshow, $settings);
8194 $return .= html_writer::table($table);
8195 $return .= get_string('configwebserviceplugins', 'webservice');
8196 $return .= $OUTPUT->box_end();
8198 return highlight($query, $return);
8204 * Special class for web service token administration.
8206 * @author Jerome Mouneyrac
8208 class admin_setting_managewebservicetokens extends admin_setting {
8211 * Calls parent::__construct with specific arguments
8213 public function __construct() {
8214 $this->nosave = true;
8215 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8219 * Always returns true, does nothing
8221 * @return true
8223 public function get_setting() {
8224 return true;
8228 * Always returns true, does nothing
8230 * @return true
8232 public function get_defaultsetting() {
8233 return true;
8237 * Always returns '', does not write anything
8239 * @return string Always returns ''
8241 public function write_setting($data) {
8242 // do not write any setting
8243 return '';
8247 * Builds the XHTML to display the control
8249 * @param string $data Unused
8250 * @param string $query
8251 * @return string
8253 public function output_html($data, $query='') {
8254 global $CFG, $OUTPUT, $DB, $USER;
8256 // display strings
8257 $stroperation = get_string('operation', 'webservice');
8258 $strtoken = get_string('token', 'webservice');
8259 $strservice = get_string('service', 'webservice');
8260 $struser = get_string('user');
8261 $strcontext = get_string('context', 'webservice');
8262 $strvaliduntil = get_string('validuntil', 'webservice');
8263 $striprestriction = get_string('iprestriction', 'webservice');
8265 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8267 $table = new html_table();
8268 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8269 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8270 $table->id = 'webservicetokens';
8271 $table->attributes['class'] = 'admintable generaltable';
8272 $table->data = array();
8274 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8276 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8278 //here retrieve token list (including linked users firstname/lastname and linked services name)
8279 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8280 FROM {external_tokens} t, {user} u, {external_services} s
8281 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8282 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8283 if (!empty($tokens)) {
8284 foreach ($tokens as $token) {
8285 //TODO: retrieve context
8287 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8288 $delete .= get_string('delete')."</a>";
8290 $validuntil = '';
8291 if (!empty($token->validuntil)) {
8292 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8295 $iprestriction = '';
8296 if (!empty($token->iprestriction)) {
8297 $iprestriction = $token->iprestriction;
8300 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8301 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8302 $useratag .= $token->firstname." ".$token->lastname;
8303 $useratag .= html_writer::end_tag('a');
8305 //check user missing capabilities
8306 require_once($CFG->dirroot . '/webservice/lib.php');
8307 $webservicemanager = new webservice();
8308 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8309 array(array('id' => $token->userid)), $token->serviceid);
8311 if (!is_siteadmin($token->userid) and
8312 array_key_exists($token->userid, $usermissingcaps)) {
8313 $missingcapabilities = implode(', ',
8314 $usermissingcaps[$token->userid]);
8315 if (!empty($missingcapabilities)) {
8316 $useratag .= html_writer::tag('div',
8317 get_string('usermissingcaps', 'webservice',
8318 $missingcapabilities)
8319 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8320 array('class' => 'missingcaps'));
8324 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8327 $return .= html_writer::table($table);
8328 } else {
8329 $return .= get_string('notoken', 'webservice');
8332 $return .= $OUTPUT->box_end();
8333 // add a token to the table
8334 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8335 $return .= get_string('add')."</a>";
8337 return highlight($query, $return);
8343 * Colour picker
8345 * @copyright 2010 Sam Hemelryk
8346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8348 class admin_setting_configcolourpicker extends admin_setting {
8351 * Information for previewing the colour
8353 * @var array|null
8355 protected $previewconfig = null;
8358 * Use default when empty.
8360 protected $usedefaultwhenempty = true;
8364 * @param string $name
8365 * @param string $visiblename
8366 * @param string $description
8367 * @param string $defaultsetting
8368 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8370 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8371 $usedefaultwhenempty = true) {
8372 $this->previewconfig = $previewconfig;
8373 $this->usedefaultwhenempty = $usedefaultwhenempty;
8374 parent::__construct($name, $visiblename, $description, $defaultsetting);
8378 * Return the setting
8380 * @return mixed returns config if successful else null
8382 public function get_setting() {
8383 return $this->config_read($this->name);
8387 * Saves the setting
8389 * @param string $data
8390 * @return bool
8392 public function write_setting($data) {
8393 $data = $this->validate($data);
8394 if ($data === false) {
8395 return get_string('validateerror', 'admin');
8397 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8401 * Validates the colour that was entered by the user
8403 * @param string $data
8404 * @return string|false
8406 protected function validate($data) {
8408 * List of valid HTML colour names
8410 * @var array
8412 $colornames = array(
8413 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8414 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8415 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8416 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8417 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8418 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8419 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8420 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8421 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8422 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8423 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8424 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8425 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8426 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8427 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8428 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8429 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8430 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8431 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8432 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8433 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8434 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8435 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8436 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8437 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8438 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8439 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8440 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8441 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8442 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8443 'whitesmoke', 'yellow', 'yellowgreen'
8446 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8447 if (strpos($data, '#')!==0) {
8448 $data = '#'.$data;
8450 return $data;
8451 } else if (in_array(strtolower($data), $colornames)) {
8452 return $data;
8453 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8454 return $data;
8455 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8456 return $data;
8457 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8458 return $data;
8459 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8460 return $data;
8461 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8462 return $data;
8463 } else if (empty($data)) {
8464 if ($this->usedefaultwhenempty){
8465 return $this->defaultsetting;
8466 } else {
8467 return '';
8469 } else {
8470 return false;
8475 * Generates the HTML for the setting
8477 * @global moodle_page $PAGE
8478 * @global core_renderer $OUTPUT
8479 * @param string $data
8480 * @param string $query
8482 public function output_html($data, $query = '') {
8483 global $PAGE, $OUTPUT;
8484 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8485 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8486 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8487 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8488 if (!empty($this->previewconfig)) {
8489 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8491 $content .= html_writer::end_tag('div');
8492 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8498 * Class used for uploading of one file into file storage,
8499 * the file name is stored in config table.
8501 * Please note you need to implement your own '_pluginfile' callback function,
8502 * this setting only stores the file, it does not deal with file serving.
8504 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8507 class admin_setting_configstoredfile extends admin_setting {
8508 /** @var array file area options - should be one file only */
8509 protected $options;
8510 /** @var string name of the file area */
8511 protected $filearea;
8512 /** @var int intemid */
8513 protected $itemid;
8514 /** @var string used for detection of changes */
8515 protected $oldhashes;
8518 * Create new stored file setting.
8520 * @param string $name low level setting name
8521 * @param string $visiblename human readable setting name
8522 * @param string $description description of setting
8523 * @param mixed $filearea file area for file storage
8524 * @param int $itemid itemid for file storage
8525 * @param array $options file area options
8527 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8528 parent::__construct($name, $visiblename, $description, '');
8529 $this->filearea = $filearea;
8530 $this->itemid = $itemid;
8531 $this->options = (array)$options;
8535 * Applies defaults and returns all options.
8536 * @return array
8538 protected function get_options() {
8539 global $CFG;
8541 require_once("$CFG->libdir/filelib.php");
8542 require_once("$CFG->dirroot/repository/lib.php");
8543 $defaults = array(
8544 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8545 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8546 'context' => context_system::instance());
8547 foreach($this->options as $k => $v) {
8548 $defaults[$k] = $v;
8551 return $defaults;
8554 public function get_setting() {
8555 return $this->config_read($this->name);
8558 public function write_setting($data) {
8559 global $USER;
8561 // Let's not deal with validation here, this is for admins only.
8562 $current = $this->get_setting();
8563 if (empty($data) && $current === null) {
8564 // This will be the case when applying default settings (installation).
8565 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8566 } else if (!is_number($data)) {
8567 // Draft item id is expected here!
8568 return get_string('errorsetting', 'admin');
8571 $options = $this->get_options();
8572 $fs = get_file_storage();
8573 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8575 $this->oldhashes = null;
8576 if ($current) {
8577 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8578 if ($file = $fs->get_file_by_hash($hash)) {
8579 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8581 unset($file);
8584 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8585 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8586 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8587 // with an error because the draft area does not exist, as he did not use it.
8588 $usercontext = context_user::instance($USER->id);
8589 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8590 return get_string('errorsetting', 'admin');
8594 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8595 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8597 $filepath = '';
8598 if ($files) {
8599 /** @var stored_file $file */
8600 $file = reset($files);
8601 $filepath = $file->get_filepath().$file->get_filename();
8604 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8607 public function post_write_settings($original) {
8608 $options = $this->get_options();
8609 $fs = get_file_storage();
8610 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8612 $current = $this->get_setting();
8613 $newhashes = null;
8614 if ($current) {
8615 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8616 if ($file = $fs->get_file_by_hash($hash)) {
8617 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8619 unset($file);
8622 if ($this->oldhashes === $newhashes) {
8623 $this->oldhashes = null;
8624 return false;
8626 $this->oldhashes = null;
8628 $callbackfunction = $this->updatedcallback;
8629 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8630 $callbackfunction($this->get_full_name());
8632 return true;
8635 public function output_html($data, $query = '') {
8636 global $PAGE, $CFG;
8638 $options = $this->get_options();
8639 $id = $this->get_id();
8640 $elname = $this->get_full_name();
8641 $draftitemid = file_get_submitted_draft_itemid($elname);
8642 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8643 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8645 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8646 require_once("$CFG->dirroot/lib/form/filemanager.php");
8648 $fmoptions = new stdClass();
8649 $fmoptions->mainfile = $options['mainfile'];
8650 $fmoptions->maxbytes = $options['maxbytes'];
8651 $fmoptions->maxfiles = $options['maxfiles'];
8652 $fmoptions->client_id = uniqid();
8653 $fmoptions->itemid = $draftitemid;
8654 $fmoptions->subdirs = $options['subdirs'];
8655 $fmoptions->target = $id;
8656 $fmoptions->accepted_types = $options['accepted_types'];
8657 $fmoptions->return_types = $options['return_types'];
8658 $fmoptions->context = $options['context'];
8659 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8661 $fm = new form_filemanager($fmoptions);
8662 $output = $PAGE->get_renderer('core', 'files');
8663 $html = $output->render($fm);
8665 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8666 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8668 return format_admin_setting($this, $this->visiblename,
8669 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8675 * Administration interface for user specified regular expressions for device detection.
8677 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8679 class admin_setting_devicedetectregex extends admin_setting {
8682 * Calls parent::__construct with specific args
8684 * @param string $name
8685 * @param string $visiblename
8686 * @param string $description
8687 * @param mixed $defaultsetting
8689 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8690 global $CFG;
8691 parent::__construct($name, $visiblename, $description, $defaultsetting);
8695 * Return the current setting(s)
8697 * @return array Current settings array
8699 public function get_setting() {
8700 global $CFG;
8702 $config = $this->config_read($this->name);
8703 if (is_null($config)) {
8704 return null;
8707 return $this->prepare_form_data($config);
8711 * Save selected settings
8713 * @param array $data Array of settings to save
8714 * @return bool
8716 public function write_setting($data) {
8717 if (empty($data)) {
8718 $data = array();
8721 if ($this->config_write($this->name, $this->process_form_data($data))) {
8722 return ''; // success
8723 } else {
8724 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8729 * Return XHTML field(s) for regexes
8731 * @param array $data Array of options to set in HTML
8732 * @return string XHTML string for the fields and wrapping div(s)
8734 public function output_html($data, $query='') {
8735 global $OUTPUT;
8737 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8738 $out .= html_writer::start_tag('thead');
8739 $out .= html_writer::start_tag('tr');
8740 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8741 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8742 $out .= html_writer::end_tag('tr');
8743 $out .= html_writer::end_tag('thead');
8744 $out .= html_writer::start_tag('tbody');
8746 if (empty($data)) {
8747 $looplimit = 1;
8748 } else {
8749 $looplimit = (count($data)/2)+1;
8752 for ($i=0; $i<$looplimit; $i++) {
8753 $out .= html_writer::start_tag('tr');
8755 $expressionname = 'expression'.$i;
8757 if (!empty($data[$expressionname])){
8758 $expression = $data[$expressionname];
8759 } else {
8760 $expression = '';
8763 $out .= html_writer::tag('td',
8764 html_writer::empty_tag('input',
8765 array(
8766 'type' => 'text',
8767 'class' => 'form-text',
8768 'name' => $this->get_full_name().'[expression'.$i.']',
8769 'value' => $expression,
8771 ), array('class' => 'c'.$i)
8774 $valuename = 'value'.$i;
8776 if (!empty($data[$valuename])){
8777 $value = $data[$valuename];
8778 } else {
8779 $value= '';
8782 $out .= html_writer::tag('td',
8783 html_writer::empty_tag('input',
8784 array(
8785 'type' => 'text',
8786 'class' => 'form-text',
8787 'name' => $this->get_full_name().'[value'.$i.']',
8788 'value' => $value,
8790 ), array('class' => 'c'.$i)
8793 $out .= html_writer::end_tag('tr');
8796 $out .= html_writer::end_tag('tbody');
8797 $out .= html_writer::end_tag('table');
8799 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8803 * Converts the string of regexes
8805 * @see self::process_form_data()
8806 * @param $regexes string of regexes
8807 * @return array of form fields and their values
8809 protected function prepare_form_data($regexes) {
8811 $regexes = json_decode($regexes);
8813 $form = array();
8815 $i = 0;
8817 foreach ($regexes as $value => $regex) {
8818 $expressionname = 'expression'.$i;
8819 $valuename = 'value'.$i;
8821 $form[$expressionname] = $regex;
8822 $form[$valuename] = $value;
8823 $i++;
8826 return $form;
8830 * Converts the data from admin settings form into a string of regexes
8832 * @see self::prepare_form_data()
8833 * @param array $data array of admin form fields and values
8834 * @return false|string of regexes
8836 protected function process_form_data(array $form) {
8838 $count = count($form); // number of form field values
8840 if ($count % 2) {
8841 // we must get five fields per expression
8842 return false;
8845 $regexes = array();
8846 for ($i = 0; $i < $count / 2; $i++) {
8847 $expressionname = "expression".$i;
8848 $valuename = "value".$i;
8850 $expression = trim($form['expression'.$i]);
8851 $value = trim($form['value'.$i]);
8853 if (empty($expression)){
8854 continue;
8857 $regexes[$value] = $expression;
8860 $regexes = json_encode($regexes);
8862 return $regexes;
8867 * Multiselect for current modules
8869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8871 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8872 private $excludesystem;
8875 * Calls parent::__construct - note array $choices is not required
8877 * @param string $name setting name
8878 * @param string $visiblename localised setting name
8879 * @param string $description setting description
8880 * @param array $defaultsetting a plain array of default module ids
8881 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8883 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8884 $excludesystem = true) {
8885 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8886 $this->excludesystem = $excludesystem;
8890 * Loads an array of current module choices
8892 * @return bool always return true
8894 public function load_choices() {
8895 if (is_array($this->choices)) {
8896 return true;
8898 $this->choices = array();
8900 global $CFG, $DB;
8901 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8902 foreach ($records as $record) {
8903 // Exclude modules if the code doesn't exist
8904 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8905 // Also exclude system modules (if specified)
8906 if (!($this->excludesystem &&
8907 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8908 MOD_ARCHETYPE_SYSTEM)) {
8909 $this->choices[$record->id] = $record->name;
8913 return true;
8918 * Admin setting to show if a php extension is enabled or not.
8920 * @copyright 2013 Damyon Wiese
8921 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8923 class admin_setting_php_extension_enabled extends admin_setting {
8925 /** @var string The name of the extension to check for */
8926 private $extension;
8929 * Calls parent::__construct with specific arguments
8931 public function __construct($name, $visiblename, $description, $extension) {
8932 $this->extension = $extension;
8933 $this->nosave = true;
8934 parent::__construct($name, $visiblename, $description, '');
8938 * Always returns true, does nothing
8940 * @return true
8942 public function get_setting() {
8943 return true;
8947 * Always returns true, does nothing
8949 * @return true
8951 public function get_defaultsetting() {
8952 return true;
8956 * Always returns '', does not write anything
8958 * @return string Always returns ''
8960 public function write_setting($data) {
8961 // Do not write any setting.
8962 return '';
8966 * Outputs the html for this setting.
8967 * @return string Returns an XHTML string
8969 public function output_html($data, $query='') {
8970 global $OUTPUT;
8972 $o = '';
8973 if (!extension_loaded($this->extension)) {
8974 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8976 $o .= format_admin_setting($this, $this->visiblename, $warning);
8978 return $o;