2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
56 * Next, in foo.php, your file structure would resemble the following:
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();
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.
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
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
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();
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 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
119 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
120 * @uses global $OUTPUT to produce notices and other messages
123 function uninstall_plugin($type, $name) {
124 global $CFG, $DB, $OUTPUT;
126 // recursively uninstall all module subplugins first
127 if ($type === 'mod') {
128 if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
129 $subplugins = array();
130 include("$CFG->dirroot/mod/$name/db/subplugins.php");
131 foreach ($subplugins as $subplugintype=>$dir) {
132 $instances = get_plugin_list($subplugintype);
133 foreach ($instances as $subpluginname => $notusedpluginpath) {
134 uninstall_plugin($subplugintype, $subpluginname);
141 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
143 if ($type === 'mod') {
144 $pluginname = $name; // eg. 'forum'
145 if (get_string_manager()->string_exists('modulename', $component)) {
146 $strpluginname = get_string('modulename', $component);
148 $strpluginname = $component;
152 $pluginname = $component;
153 if (get_string_manager()->string_exists('pluginname', $component)) {
154 $strpluginname = get_string('pluginname', $component);
156 $strpluginname = $component;
160 echo $OUTPUT->heading($pluginname);
162 $plugindirectory = get_plugin_directory($type, $name);
163 $uninstalllib = $plugindirectory . '/db/uninstall.php';
164 if (file_exists($uninstalllib)) {
165 require_once($uninstalllib);
166 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
167 if (function_exists($uninstallfunction)) {
168 if (!$uninstallfunction()) {
169 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
174 if ($type === 'mod') {
175 // perform cleanup tasks specific for activity modules
177 if (!$module = $DB->get_record('modules', array('name' => $name))) {
178 print_error('moduledoesnotexist', 'error');
181 // delete all the relevant instances from all course sections
182 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
183 foreach ($coursemods as $coursemod) {
184 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
185 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
190 // clear course.modinfo for courses that used this module
191 $sql = "UPDATE {course}
193 WHERE id IN (SELECT DISTINCT course
194 FROM {course_modules}
196 $DB->execute($sql, array($module->id));
198 // delete all the course module records
199 $DB->delete_records('course_modules', array('module' => $module->id));
201 // delete module contexts
203 foreach ($coursemods as $coursemod) {
204 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
205 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
210 // delete the module entry itself
211 $DB->delete_records('modules', array('name' => $module->name));
213 // cleanup the gradebook
214 require_once($CFG->libdir.'/gradelib.php');
215 grade_uninstalled_module($module->name);
217 // Perform any custom uninstall tasks
218 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
219 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
220 $uninstallfunction = $module->name . '_uninstall';
221 if (function_exists($uninstallfunction)) {
222 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
223 if (!$uninstallfunction()) {
224 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
229 } else if ($type === 'enrol') {
230 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
231 // nuke all role assignments
232 role_unassign_all(array('component'=>$component));
233 // purge participants
234 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
235 // purge enrol instances
236 $DB->delete_records('enrol', array('enrol'=>$name));
237 // tweak enrol settings
238 if (!empty($CFG->enrol_plugins_enabled)) {
239 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
240 $enabledenrols = array_unique($enabledenrols);
241 $enabledenrols = array_flip($enabledenrols);
242 unset($enabledenrols[$name]);
243 $enabledenrols = array_flip($enabledenrols);
244 if (is_array($enabledenrols)) {
245 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
250 // perform clean-up task common for all the plugin/subplugin types
252 // delete calendar events
253 $DB->delete_records('event', array('modulename' => $pluginname));
255 // delete all the logs
256 $DB->delete_records('log', array('module' => $pluginname));
258 // delete log_display information
259 $DB->delete_records('log_display', array('component' => $component));
261 // delete the module configuration records
262 unset_all_config_for_plugin($pluginname);
264 // delete message provider
265 message_provider_uninstall($component);
267 // delete message processor
268 if ($type === 'message') {
269 message_processor_uninstall($name);
272 // delete the plugin tables
273 $xmldbfilepath = $plugindirectory . '/db/install.xml';
274 drop_plugin_tables($pluginname, $xmldbfilepath, false);
276 // delete the capabilities that were defined by this module
277 capabilities_cleanup($component);
279 // remove event handlers and dequeue pending events
280 events_uninstall($component);
282 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
286 * Returns the version of installed component
288 * @param string $component component name
289 * @param string $source either 'disk' or 'installed' - where to get the version information from
290 * @return string|bool version number or false if the component is not found
292 function get_component_version($component, $source='installed') {
295 list($type, $name) = normalize_component($component);
297 // moodle core or a core subsystem
298 if ($type === 'core') {
299 if ($source === 'installed') {
300 if (empty($CFG->version)) {
303 return $CFG->version;
306 if (!is_readable($CFG->dirroot.'/version.php')) {
309 $version = null; //initialize variable for IDEs
310 include($CFG->dirroot.'/version.php');
317 if ($type === 'mod') {
318 if ($source === 'installed') {
319 return $DB->get_field('modules', 'version', array('name'=>$name));
321 $mods = get_plugin_list('mod');
322 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
325 $module = new stdclass();
326 include($mods[$name].'/version.php');
327 return $module->version;
333 if ($type === 'block') {
334 if ($source === 'installed') {
335 return $DB->get_field('block', 'version', array('name'=>$name));
337 $blocks = get_plugin_list('block');
338 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
341 $plugin = new stdclass();
342 include($blocks[$name].'/version.php');
343 return $plugin->version;
348 // all other plugin types
349 if ($source === 'installed') {
350 return get_config($type.'_'.$name, 'version');
352 $plugins = get_plugin_list($type);
353 if (empty($plugins[$name])) {
356 $plugin = new stdclass();
357 include($plugins[$name].'/version.php');
358 return $plugin->version;
364 * Delete all plugin tables
366 * @param string $name Name of plugin, used as table prefix
367 * @param string $file Path to install.xml file
368 * @param bool $feedback defaults to true
369 * @return bool Always returns true
371 function drop_plugin_tables($name, $file, $feedback=true) {
374 // first try normal delete
375 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
379 // then try to find all tables that start with name and are not in any xml file
380 $used_tables = get_used_table_names();
382 $tables = $DB->get_tables();
384 /// Iterate over, fixing id fields as necessary
385 foreach ($tables as $table) {
386 if (in_array($table, $used_tables)) {
390 if (strpos($table, $name) !== 0) {
394 // found orphan table --> delete it
395 if ($DB->get_manager()->table_exists($table)) {
396 $xmldb_table = new xmldb_table($table);
397 $DB->get_manager()->drop_table($xmldb_table);
405 * Returns names of all known tables == tables that moodle knows about.
407 * @return array Array of lowercase table names
409 function get_used_table_names() {
410 $table_names = array();
411 $dbdirs = get_db_directories();
413 foreach ($dbdirs as $dbdir) {
414 $file = $dbdir.'/install.xml';
416 $xmldb_file = new xmldb_file($file);
418 if (!$xmldb_file->fileExists()) {
422 $loaded = $xmldb_file->loadXMLStructure();
423 $structure = $xmldb_file->getStructure();
425 if ($loaded and $tables = $structure->getTables()) {
426 foreach($tables as $table) {
427 $table_names[] = strtolower($table->name);
436 * Returns list of all directories where we expect install.xml files
437 * @return array Array of paths
439 function get_db_directories() {
444 /// First, the main one (lib/db)
445 $dbdirs[] = $CFG->libdir.'/db';
447 /// Then, all the ones defined by get_plugin_types()
448 $plugintypes = get_plugin_types();
449 foreach ($plugintypes as $plugintype => $pluginbasedir) {
450 if ($plugins = get_plugin_list($plugintype)) {
451 foreach ($plugins as $plugin => $plugindir) {
452 $dbdirs[] = $plugindir.'/db';
461 * Try to obtain or release the cron lock.
462 * @param string $name name of lock
463 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
464 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
465 * @return bool true if lock obtained
467 function set_cron_lock($name, $until, $ignorecurrent=false) {
470 debugging("Tried to get a cron lock for a null fieldname");
474 // remove lock by force == remove from config table
475 if (is_null($until)) {
476 set_config($name, null);
480 if (!$ignorecurrent) {
481 // read value from db - other processes might have changed it
482 $value = $DB->get_field('config', 'value', array('name'=>$name));
484 if ($value and $value > time()) {
490 set_config($name, $until);
495 * Test if and critical warnings are present
498 function admin_critical_warnings_present() {
501 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
505 if (!isset($SESSION->admin_critical_warning)) {
506 $SESSION->admin_critical_warning = 0;
507 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
508 $SESSION->admin_critical_warning = 1;
512 return $SESSION->admin_critical_warning;
516 * Detects if float supports at least 10 decimal digits
518 * Detects if float supports at least 10 decimal digits
519 * and also if float-->string conversion works as expected.
521 * @return bool true if problem found
523 function is_float_problem() {
524 $num1 = 2009010200.01;
525 $num2 = 2009010200.02;
527 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
531 * Try to verify that dataroot is not accessible from web.
533 * Try to verify that dataroot is not accessible from web.
534 * It is not 100% correct but might help to reduce number of vulnerable sites.
535 * Protection from httpd.conf and .htaccess is not detected properly.
537 * @uses INSECURE_DATAROOT_WARNING
538 * @uses INSECURE_DATAROOT_ERROR
539 * @param bool $fetchtest try to test public access by fetching file, default false
540 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
542 function is_dataroot_insecure($fetchtest=false) {
545 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
547 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
548 $rp = strrev(trim($rp, '/'));
549 $rp = explode('/', $rp);
551 if (strpos($siteroot, '/'.$r.'/') === 0) {
552 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
554 break; // probably alias root
558 $siteroot = strrev($siteroot);
559 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
561 if (strpos($dataroot, $siteroot) !== 0) {
566 return INSECURE_DATAROOT_WARNING;
569 // now try all methods to fetch a test file using http protocol
571 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
572 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
573 $httpdocroot = $matches[1];
574 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
575 make_upload_directory('diag');
576 $testfile = $CFG->dataroot.'/diag/public.txt';
577 if (!file_exists($testfile)) {
578 file_put_contents($testfile, 'test file, do not delete');
580 $teststr = trim(file_get_contents($testfile));
581 if (empty($teststr)) {
583 return INSECURE_DATAROOT_WARNING;
586 $testurl = $datarooturl.'/diag/public.txt';
587 if (extension_loaded('curl') and
588 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
589 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
590 ($ch = @curl_init($testurl)) !== false) {
591 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
592 curl_setopt($ch, CURLOPT_HEADER, false);
593 $data = curl_exec($ch);
594 if (!curl_errno($ch)) {
596 if ($data === $teststr) {
598 return INSECURE_DATAROOT_ERROR;
604 if ($data = @file_get_contents($testurl)) {
606 if ($data === $teststr) {
607 return INSECURE_DATAROOT_ERROR;
611 preg_match('|https?://([^/]+)|i', $testurl, $matches);
612 $sitename = $matches[1];
614 if ($fp = @fsockopen($sitename, 80, $error)) {
615 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
616 $localurl = $matches[1];
617 $out = "GET $localurl HTTP/1.1\r\n";
618 $out .= "Host: $sitename\r\n";
619 $out .= "Connection: Close\r\n\r\n";
625 $data .= fgets($fp, 1024);
626 } else if (@fgets($fp, 1024) === "\r\n") {
632 if ($data === $teststr) {
633 return INSECURE_DATAROOT_ERROR;
637 return INSECURE_DATAROOT_WARNING;
640 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
644 * Interface for anything appearing in the admin tree
646 * The interface that is implemented by anything that appears in the admin tree
647 * block. It forces inheriting classes to define a method for checking user permissions
648 * and methods for finding something in the admin tree.
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 interface part_of_admin_tree {
655 * Finds a named part_of_admin_tree.
657 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
658 * and not parentable_part_of_admin_tree, then this function should only check if
659 * $this->name matches $name. If it does, it should return a reference to $this,
660 * otherwise, it should return a reference to NULL.
662 * If a class inherits parentable_part_of_admin_tree, this method should be called
663 * recursively on all child objects (assuming, of course, the parent object's name
664 * doesn't match the search criterion).
666 * @param string $name The internal name of the part_of_admin_tree we're searching for.
667 * @return mixed An object reference or a NULL reference.
669 public function locate($name);
672 * Removes named part_of_admin_tree.
674 * @param string $name The internal name of the part_of_admin_tree we want to remove.
675 * @return bool success.
677 public function prune($name);
681 * @param string $query
682 * @return mixed array-object structure of found settings and pages
684 public function search($query);
687 * Verifies current user's access to this part_of_admin_tree.
689 * Used to check if the current user has access to this part of the admin tree or
690 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
691 * then this method is usually just a call to has_capability() in the site context.
693 * If a class inherits parentable_part_of_admin_tree, this method should return the
694 * logical OR of the return of check_access() on all child objects.
696 * @return bool True if the user has access, false if she doesn't.
698 public function check_access();
701 * Mostly useful for removing of some parts of the tree in admin tree block.
703 * @return True is hidden from normal list view
705 public function is_hidden();
708 * Show we display Save button at the page bottom?
711 public function show_save();
716 * Interface implemented by any part_of_admin_tree that has children.
718 * The interface implemented by any part_of_admin_tree that can be a parent
719 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
720 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
721 * include an add method for adding other part_of_admin_tree objects as children.
723 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
725 interface parentable_part_of_admin_tree extends part_of_admin_tree {
728 * Adds a part_of_admin_tree object to the admin tree.
730 * Used to add a part_of_admin_tree object to this object or a child of this
731 * object. $something should only be added if $destinationname matches
732 * $this->name. If it doesn't, add should be called on child objects that are
733 * also parentable_part_of_admin_tree's.
735 * @param string $destinationname The internal name of the new parent for $something.
736 * @param part_of_admin_tree $something The object to be added.
737 * @return bool True on success, false on failure.
739 public function add($destinationname, $something);
745 * The object used to represent folders (a.k.a. categories) in the admin tree block.
747 * Each admin_category object contains a number of part_of_admin_tree objects.
749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
751 class admin_category implements parentable_part_of_admin_tree {
753 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
755 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
757 /** @var string The displayed name for this category. Usually obtained through get_string() */
759 /** @var bool Should this category be hidden in admin tree block? */
761 /** @var mixed Either a string or an array or strings */
763 /** @var mixed Either a string or an array or strings */
766 /** @var array fast lookup category cache, all categories of one tree point to one cache */
767 protected $category_cache;
770 * Constructor for an empty admin category
772 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
773 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
774 * @param bool $hidden hide category in admin tree block, defaults to false
776 public function __construct($name, $visiblename, $hidden=false) {
777 $this->children = array();
779 $this->visiblename = $visiblename;
780 $this->hidden = $hidden;
784 * Returns a reference to the part_of_admin_tree object with internal name $name.
786 * @param string $name The internal name of the object we want.
787 * @param bool $findpath initialize path and visiblepath arrays
788 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
791 public function locate($name, $findpath=false) {
792 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
793 // somebody much have purged the cache
794 $this->category_cache[$this->name] = $this;
797 if ($this->name == $name) {
799 $this->visiblepath[] = $this->visiblename;
800 $this->path[] = $this->name;
805 // quick category lookup
806 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
807 return $this->category_cache[$name];
811 foreach($this->children as $childid=>$unused) {
812 if ($return = $this->children[$childid]->locate($name, $findpath)) {
817 if (!is_null($return) and $findpath) {
818 $return->visiblepath[] = $this->visiblename;
819 $return->path[] = $this->name;
828 * @param string query
829 * @return mixed array-object structure of found settings and pages
831 public function search($query) {
833 foreach ($this->children as $child) {
834 $subsearch = $child->search($query);
835 if (!is_array($subsearch)) {
836 debugging('Incorrect search result from '.$child->name);
839 $result = array_merge($result, $subsearch);
845 * Removes part_of_admin_tree object with internal name $name.
847 * @param string $name The internal name of the object we want to remove.
848 * @return bool success
850 public function prune($name) {
852 if ($this->name == $name) {
853 return false; //can not remove itself
856 foreach($this->children as $precedence => $child) {
857 if ($child->name == $name) {
858 // clear cache and delete self
859 if (is_array($this->category_cache)) {
860 while($this->category_cache) {
861 // delete the cache, but keep the original array address
862 array_pop($this->category_cache);
865 unset($this->children[$precedence]);
867 } else if ($this->children[$precedence]->prune($name)) {
875 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
877 * @param string $destinationame The internal name of the immediate parent that we want for $something.
878 * @param mixed $something A part_of_admin_tree or setting instance to be added.
879 * @return bool True if successfully added, false if $something can not be added.
881 public function add($parentname, $something) {
882 $parent = $this->locate($parentname);
883 if (is_null($parent)) {
884 debugging('parent does not exist!');
888 if ($something instanceof part_of_admin_tree) {
889 if (!($parent instanceof parentable_part_of_admin_tree)) {
890 debugging('error - parts of tree can be inserted only into parentable parts');
893 $parent->children[] = $something;
894 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
895 if (isset($this->category_cache[$something->name])) {
896 debugging('Duplicate admin category name: '.$something->name);
898 $this->category_cache[$something->name] = $something;
899 $something->category_cache =& $this->category_cache;
900 foreach ($something->children as $child) {
901 // just in case somebody already added subcategories
902 if ($child instanceof admin_category) {
903 if (isset($this->category_cache[$child->name])) {
904 debugging('Duplicate admin category name: '.$child->name);
906 $this->category_cache[$child->name] = $child;
907 $child->category_cache =& $this->category_cache;
916 debugging('error - can not add this element');
923 * Checks if the user has access to anything in this category.
925 * @return bool True if the user has access to at least one child in this category, false otherwise.
927 public function check_access() {
928 foreach ($this->children as $child) {
929 if ($child->check_access()) {
937 * Is this category hidden in admin tree block?
939 * @return bool True if hidden
941 public function is_hidden() {
942 return $this->hidden;
946 * Show we display Save button at the page bottom?
949 public function show_save() {
950 foreach ($this->children as $child) {
951 if ($child->show_save()) {
961 * Root of admin settings tree, does not have any parent.
963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
965 class admin_root extends admin_category {
966 /** @var array List of errors */
968 /** @var string search query */
970 /** @var bool full tree flag - true means all settings required, false only pages required */
972 /** @var bool flag indicating loaded tree */
974 /** @var mixed site custom defaults overriding defaults in settings files*/
975 public $custom_defaults;
978 * @param bool $fulltree true means all settings required,
979 * false only pages required
981 public function __construct($fulltree) {
984 parent::__construct('root', get_string('administration'), false);
985 $this->errors = array();
987 $this->fulltree = $fulltree;
988 $this->loaded = false;
990 $this->category_cache = array();
992 // load custom defaults if found
993 $this->custom_defaults = null;
994 $defaultsfile = "$CFG->dirroot/local/defaults.php";
995 if (is_readable($defaultsfile)) {
997 include($defaultsfile);
998 if (is_array($defaults) and count($defaults)) {
999 $this->custom_defaults = $defaults;
1005 * Empties children array, and sets loaded to false
1007 * @param bool $requirefulltree
1009 public function purge_children($requirefulltree) {
1010 $this->children = array();
1011 $this->fulltree = ($requirefulltree || $this->fulltree);
1012 $this->loaded = false;
1013 //break circular dependencies - this helps PHP 5.2
1014 while($this->category_cache) {
1015 array_pop($this->category_cache);
1017 $this->category_cache = array();
1023 * Links external PHP pages into the admin tree.
1025 * See detailed usage example at the top of this document (adminlib.php)
1027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1029 class admin_externalpage implements part_of_admin_tree {
1031 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1034 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1035 public $visiblename;
1037 /** @var string The external URL that we should link to when someone requests this external page. */
1040 /** @var string The role capability/permission a user must have to access this external page. */
1041 public $req_capability;
1043 /** @var object The context in which capability/permission should be checked, default is site context. */
1046 /** @var bool hidden in admin tree block. */
1049 /** @var mixed either string or array of string */
1052 /** @var array list of visible names of page parents */
1053 public $visiblepath;
1056 * Constructor for adding an external page into the admin tree.
1058 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1059 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1060 * @param string $url The external URL that we should link to when someone requests this external page.
1061 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1062 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1063 * @param stdClass $context The context the page relates to. Not sure what happens
1064 * if you specify something other than system or front page. Defaults to system.
1066 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1067 $this->name = $name;
1068 $this->visiblename = $visiblename;
1070 if (is_array($req_capability)) {
1071 $this->req_capability = $req_capability;
1073 $this->req_capability = array($req_capability);
1075 $this->hidden = $hidden;
1076 $this->context = $context;
1080 * Returns a reference to the part_of_admin_tree object with internal name $name.
1082 * @param string $name The internal name of the object we want.
1083 * @param bool $findpath defaults to false
1084 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1086 public function locate($name, $findpath=false) {
1087 if ($this->name == $name) {
1089 $this->visiblepath = array($this->visiblename);
1090 $this->path = array($this->name);
1100 * This function always returns false, required function by interface
1102 * @param string $name
1105 public function prune($name) {
1110 * Search using query
1112 * @param string $query
1113 * @return mixed array-object structure of found settings and pages
1115 public function search($query) {
1116 $textlib = textlib_get_instance();
1119 if (strpos(strtolower($this->name), $query) !== false) {
1121 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1125 $result = new stdClass();
1126 $result->page = $this;
1127 $result->settings = array();
1128 return array($this->name => $result);
1135 * Determines if the current user has access to this external page based on $this->req_capability.
1137 * @return bool True if user has access, false otherwise.
1139 public function check_access() {
1141 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1142 foreach($this->req_capability as $cap) {
1143 if (has_capability($cap, $context)) {
1151 * Is this external page hidden in admin tree block?
1153 * @return bool True if hidden
1155 public function is_hidden() {
1156 return $this->hidden;
1160 * Show we display Save button at the page bottom?
1163 public function show_save() {
1170 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1174 class admin_settingpage implements part_of_admin_tree {
1176 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1179 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1180 public $visiblename;
1182 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1185 /** @var string The role capability/permission a user must have to access this external page. */
1186 public $req_capability;
1188 /** @var object The context in which capability/permission should be checked, default is site context. */
1191 /** @var bool hidden in admin tree block. */
1194 /** @var mixed string of paths or array of strings of paths */
1197 /** @var array list of visible names of page parents */
1198 public $visiblepath;
1201 * see admin_settingpage for details of this function
1203 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1204 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1205 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1206 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1207 * @param stdClass $context The context the page relates to. Not sure what happens
1208 * if you specify something other than system or front page. Defaults to system.
1210 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1211 $this->settings = new stdClass();
1212 $this->name = $name;
1213 $this->visiblename = $visiblename;
1214 if (is_array($req_capability)) {
1215 $this->req_capability = $req_capability;
1217 $this->req_capability = array($req_capability);
1219 $this->hidden = $hidden;
1220 $this->context = $context;
1224 * see admin_category
1226 * @param string $name
1227 * @param bool $findpath
1228 * @return mixed Object (this) if name == this->name, else returns null
1230 public function locate($name, $findpath=false) {
1231 if ($this->name == $name) {
1233 $this->visiblepath = array($this->visiblename);
1234 $this->path = array($this->name);
1244 * Search string in settings page.
1246 * @param string $query
1249 public function search($query) {
1252 foreach ($this->settings as $setting) {
1253 if ($setting->is_related($query)) {
1254 $found[] = $setting;
1259 $result = new stdClass();
1260 $result->page = $this;
1261 $result->settings = $found;
1262 return array($this->name => $result);
1265 $textlib = textlib_get_instance();
1268 if (strpos(strtolower($this->name), $query) !== false) {
1270 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1274 $result = new stdClass();
1275 $result->page = $this;
1276 $result->settings = array();
1277 return array($this->name => $result);
1284 * This function always returns false, required by interface
1286 * @param string $name
1287 * @return bool Always false
1289 public function prune($name) {
1294 * adds an admin_setting to this admin_settingpage
1296 * 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
1297 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1299 * @param object $setting is the admin_setting object you want to add
1300 * @return bool true if successful, false if not
1302 public function add($setting) {
1303 if (!($setting instanceof admin_setting)) {
1304 debugging('error - not a setting instance');
1308 $this->settings->{$setting->name} = $setting;
1313 * see admin_externalpage
1315 * @return bool Returns true for yes false for no
1317 public function check_access() {
1319 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1320 foreach($this->req_capability as $cap) {
1321 if (has_capability($cap, $context)) {
1329 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1330 * @return string Returns an XHTML string
1332 public function output_html() {
1333 $adminroot = admin_get_root();
1334 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1335 foreach($this->settings as $setting) {
1336 $fullname = $setting->get_full_name();
1337 if (array_key_exists($fullname, $adminroot->errors)) {
1338 $data = $adminroot->errors[$fullname]->data;
1340 $data = $setting->get_setting();
1341 // do not use defaults if settings not available - upgrade settings handles the defaults!
1343 $return .= $setting->output_html($data);
1345 $return .= '</fieldset>';
1350 * Is this settings page hidden in admin tree block?
1352 * @return bool True if hidden
1354 public function is_hidden() {
1355 return $this->hidden;
1359 * Show we display Save button at the page bottom?
1362 public function show_save() {
1363 foreach($this->settings as $setting) {
1364 if (empty($setting->nosave)) {
1374 * Admin settings class. Only exists on setting pages.
1375 * Read & write happens at this level; no authentication.
1377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1379 abstract class admin_setting {
1380 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1382 /** @var string localised name */
1383 public $visiblename;
1384 /** @var string localised long description in Markdown format */
1385 public $description;
1386 /** @var mixed Can be string or array of string */
1387 public $defaultsetting;
1389 public $updatedcallback;
1390 /** @var mixed can be String or Null. Null means main config table */
1391 public $plugin; // null means main config table
1392 /** @var bool true indicates this setting does not actually save anything, just information */
1393 public $nosave = false;
1394 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1395 public $affectsmodinfo = false;
1399 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1400 * or 'myplugin/mysetting' for ones in config_plugins.
1401 * @param string $visiblename localised name
1402 * @param string $description localised long description
1403 * @param mixed $defaultsetting string or array depending on implementation
1405 public function __construct($name, $visiblename, $description, $defaultsetting) {
1406 $this->parse_setting_name($name);
1407 $this->visiblename = $visiblename;
1408 $this->description = $description;
1409 $this->defaultsetting = $defaultsetting;
1413 * Set up $this->name and potentially $this->plugin
1415 * Set up $this->name and possibly $this->plugin based on whether $name looks
1416 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1417 * on the names, that is, output a developer debug warning if the name
1418 * contains anything other than [a-zA-Z0-9_]+.
1420 * @param string $name the setting name passed in to the constructor.
1422 private function parse_setting_name($name) {
1423 $bits = explode('/', $name);
1424 if (count($bits) > 2) {
1425 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1427 $this->name = array_pop($bits);
1428 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1429 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1431 if (!empty($bits)) {
1432 $this->plugin = array_pop($bits);
1433 if ($this->plugin === 'moodle') {
1434 $this->plugin = null;
1435 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1436 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1442 * Returns the fullname prefixed by the plugin
1445 public function get_full_name() {
1446 return 's_'.$this->plugin.'_'.$this->name;
1450 * Returns the ID string based on plugin and name
1453 public function get_id() {
1454 return 'id_s_'.$this->plugin.'_'.$this->name;
1458 * @param bool $affectsmodinfo If true, changes to this setting will
1459 * cause the course cache to be rebuilt
1461 public function set_affects_modinfo($affectsmodinfo) {
1462 $this->affectsmodinfo = $affectsmodinfo;
1466 * Returns the config if possible
1468 * @return mixed returns config if successful else null
1470 public function config_read($name) {
1472 if (!empty($this->plugin)) {
1473 $value = get_config($this->plugin, $name);
1474 return $value === false ? NULL : $value;
1477 if (isset($CFG->$name)) {
1486 * Used to set a config pair and log change
1488 * @param string $name
1489 * @param mixed $value Gets converted to string if not null
1490 * @return bool Write setting to config table
1492 public function config_write($name, $value) {
1493 global $DB, $USER, $CFG;
1495 if ($this->nosave) {
1499 // make sure it is a real change
1500 $oldvalue = get_config($this->plugin, $name);
1501 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1502 $value = is_null($value) ? null : (string)$value;
1504 if ($oldvalue === $value) {
1509 set_config($name, $value, $this->plugin);
1511 // Some admin settings affect course modinfo
1512 if ($this->affectsmodinfo) {
1513 // Clear course cache for all courses
1514 rebuild_course_cache(0, true);
1518 $log = new stdClass();
1519 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1520 $log->timemodified = time();
1521 $log->plugin = $this->plugin;
1523 $log->value = $value;
1524 $log->oldvalue = $oldvalue;
1525 $DB->insert_record('config_log', $log);
1527 return true; // BC only
1531 * Returns current value of this setting
1532 * @return mixed array or string depending on instance, NULL means not set yet
1534 public abstract function get_setting();
1537 * Returns default setting if exists
1538 * @return mixed array or string depending on instance; NULL means no default, user must supply
1540 public function get_defaultsetting() {
1541 $adminroot = admin_get_root(false, false);
1542 if (!empty($adminroot->custom_defaults)) {
1543 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1544 if (isset($adminroot->custom_defaults[$plugin])) {
1545 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1546 return $adminroot->custom_defaults[$plugin][$this->name];
1550 return $this->defaultsetting;
1556 * @param mixed $data string or array, must not be NULL
1557 * @return string empty string if ok, string error message otherwise
1559 public abstract function write_setting($data);
1562 * Return part of form with setting
1563 * This function should always be overwritten
1565 * @param mixed $data array or string depending on setting
1566 * @param string $query
1569 public function output_html($data, $query='') {
1570 // should be overridden
1575 * Function called if setting updated - cleanup, cache reset, etc.
1576 * @param string $functionname Sets the function name
1579 public function set_updatedcallback($functionname) {
1580 $this->updatedcallback = $functionname;
1584 * Is setting related to query text - used when searching
1585 * @param string $query
1588 public function is_related($query) {
1589 if (strpos(strtolower($this->name), $query) !== false) {
1592 $textlib = textlib_get_instance();
1593 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1596 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1599 $current = $this->get_setting();
1600 if (!is_null($current)) {
1601 if (is_string($current)) {
1602 if (strpos($textlib->strtolower($current), $query) !== false) {
1607 $default = $this->get_defaultsetting();
1608 if (!is_null($default)) {
1609 if (is_string($default)) {
1610 if (strpos($textlib->strtolower($default), $query) !== false) {
1621 * No setting - just heading and text.
1623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1625 class admin_setting_heading extends admin_setting {
1628 * not a setting, just text
1629 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1630 * @param string $heading heading
1631 * @param string $information text in box
1633 public function __construct($name, $heading, $information) {
1634 $this->nosave = true;
1635 parent::__construct($name, $heading, $information, '');
1639 * Always returns true
1640 * @return bool Always returns true
1642 public function get_setting() {
1647 * Always returns true
1648 * @return bool Always returns true
1650 public function get_defaultsetting() {
1655 * Never write settings
1656 * @return string Always returns an empty string
1658 public function write_setting($data) {
1659 // do not write any setting
1664 * Returns an HTML string
1665 * @return string Returns an HTML string
1667 public function output_html($data, $query='') {
1670 if ($this->visiblename != '') {
1671 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1673 if ($this->description != '') {
1674 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1682 * The most flexibly setting, user is typing text
1684 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1686 class admin_setting_configtext extends admin_setting {
1688 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1690 /** @var int default field size */
1694 * Config text constructor
1696 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1697 * @param string $visiblename localised
1698 * @param string $description long localised info
1699 * @param string $defaultsetting
1700 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1701 * @param int $size default field size
1703 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1704 $this->paramtype = $paramtype;
1705 if (!is_null($size)) {
1706 $this->size = $size;
1708 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1710 parent::__construct($name, $visiblename, $description, $defaultsetting);
1714 * Return the setting
1716 * @return mixed returns config if successful else null
1718 public function get_setting() {
1719 return $this->config_read($this->name);
1722 public function write_setting($data) {
1723 if ($this->paramtype === PARAM_INT and $data === '') {
1724 // do not complain if '' used instead of 0
1727 // $data is a string
1728 $validated = $this->validate($data);
1729 if ($validated !== true) {
1732 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1736 * Validate data before storage
1737 * @param string data
1738 * @return mixed true if ok string if error found
1740 public function validate($data) {
1741 // allow paramtype to be a custom regex if it is the form of /pattern/
1742 if (preg_match('#^/.*/$#', $this->paramtype)) {
1743 if (preg_match($this->paramtype, $data)) {
1746 return get_string('validateerror', 'admin');
1749 } else if ($this->paramtype === PARAM_RAW) {
1753 $cleaned = clean_param($data, $this->paramtype);
1754 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1757 return get_string('validateerror', 'admin');
1763 * Return an XHTML string for the setting
1764 * @return string Returns an XHTML string
1766 public function output_html($data, $query='') {
1767 $default = $this->get_defaultsetting();
1769 return format_admin_setting($this, $this->visiblename,
1770 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1771 $this->description, true, '', $default, $query);
1777 * General text area without html editor.
1779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1781 class admin_setting_configtextarea extends admin_setting_configtext {
1786 * @param string $name
1787 * @param string $visiblename
1788 * @param string $description
1789 * @param mixed $defaultsetting string or array
1790 * @param mixed $paramtype
1791 * @param string $cols The number of columns to make the editor
1792 * @param string $rows The number of rows to make the editor
1794 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1795 $this->rows = $rows;
1796 $this->cols = $cols;
1797 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1801 * Returns an XHTML string for the editor
1803 * @param string $data
1804 * @param string $query
1805 * @return string XHTML string for the editor
1807 public function output_html($data, $query='') {
1808 $default = $this->get_defaultsetting();
1810 $defaultinfo = $default;
1811 if (!is_null($default) and $default !== '') {
1812 $defaultinfo = "\n".$default;
1815 return format_admin_setting($this, $this->visiblename,
1816 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1817 $this->description, true, '', $defaultinfo, $query);
1823 * General text area with html editor.
1825 class admin_setting_confightmleditor extends admin_setting_configtext {
1830 * @param string $name
1831 * @param string $visiblename
1832 * @param string $description
1833 * @param mixed $defaultsetting string or array
1834 * @param mixed $paramtype
1836 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1837 $this->rows = $rows;
1838 $this->cols = $cols;
1839 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1840 editors_head_setup();
1844 * Returns an XHTML string for the editor
1846 * @param string $data
1847 * @param string $query
1848 * @return string XHTML string for the editor
1850 public function output_html($data, $query='') {
1851 $default = $this->get_defaultsetting();
1853 $defaultinfo = $default;
1854 if (!is_null($default) and $default !== '') {
1855 $defaultinfo = "\n".$default;
1858 $editor = editors_get_preferred_editor(FORMAT_HTML);
1859 $editor->use_editor($this->get_id(), array('noclean'=>true));
1861 return format_admin_setting($this, $this->visiblename,
1862 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1863 $this->description, true, '', $defaultinfo, $query);
1869 * Password field, allows unmasking of password
1871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1873 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1876 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1877 * @param string $visiblename localised
1878 * @param string $description long localised info
1879 * @param string $defaultsetting default password
1881 public function __construct($name, $visiblename, $description, $defaultsetting) {
1882 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1886 * Returns XHTML for the field
1887 * Writes Javascript into the HTML below right before the last div
1889 * @todo Make javascript available through newer methods if possible
1890 * @param string $data Value for the field
1891 * @param string $query Passed as final argument for format_admin_setting
1892 * @return string XHTML field
1894 public function output_html($data, $query='') {
1895 $id = $this->get_id();
1896 $unmask = get_string('unmaskpassword', 'form');
1897 $unmaskjs = '<script type="text/javascript">
1899 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1901 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1903 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1905 var unmaskchb = document.createElement("input");
1906 unmaskchb.setAttribute("type", "checkbox");
1907 unmaskchb.setAttribute("id", "'.$id.'unmask");
1908 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1909 unmaskdiv.appendChild(unmaskchb);
1911 var unmasklbl = document.createElement("label");
1912 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1914 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1916 unmasklbl.setAttribute("for", "'.$id.'unmask");
1918 unmaskdiv.appendChild(unmasklbl);
1921 // ugly hack to work around the famous onchange IE bug
1922 unmaskchb.onclick = function() {this.blur();};
1923 unmaskdiv.onclick = function() {this.blur();};
1927 return format_admin_setting($this, $this->visiblename,
1928 '<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>',
1929 $this->description, true, '', NULL, $query);
1937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1939 class admin_setting_configfile extends admin_setting_configtext {
1942 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1943 * @param string $visiblename localised
1944 * @param string $description long localised info
1945 * @param string $defaultdirectory default directory location
1947 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1948 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1952 * Returns XHTML for the field
1954 * Returns XHTML for the field and also checks whether the file
1955 * specified in $data exists using file_exists()
1957 * @param string $data File name and path to use in value attr
1958 * @param string $query
1959 * @return string XHTML field
1961 public function output_html($data, $query='') {
1962 $default = $this->get_defaultsetting();
1965 if (file_exists($data)) {
1966 $executable = '<span class="pathok">✔</span>';
1968 $executable = '<span class="patherror">✘</span>';
1974 return format_admin_setting($this, $this->visiblename,
1975 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
1976 $this->description, true, '', $default, $query);
1982 * Path to executable file
1984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1986 class admin_setting_configexecutable extends admin_setting_configfile {
1989 * Returns an XHTML field
1991 * @param string $data This is the value for the field
1992 * @param string $query
1993 * @return string XHTML field
1995 public function output_html($data, $query='') {
1996 $default = $this->get_defaultsetting();
1999 if (file_exists($data) and is_executable($data)) {
2000 $executable = '<span class="pathok">✔</span>';
2002 $executable = '<span class="patherror">✘</span>';
2008 return format_admin_setting($this, $this->visiblename,
2009 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2010 $this->description, true, '', $default, $query);
2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2020 class admin_setting_configdirectory extends admin_setting_configfile {
2023 * Returns an XHTML field
2025 * @param string $data This is the value for the field
2026 * @param string $query
2027 * @return string XHTML
2029 public function output_html($data, $query='') {
2030 $default = $this->get_defaultsetting();
2033 if (file_exists($data) and is_dir($data)) {
2034 $executable = '<span class="pathok">✔</span>';
2036 $executable = '<span class="patherror">✘</span>';
2042 return format_admin_setting($this, $this->visiblename,
2043 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2044 $this->description, true, '', $default, $query);
2052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2054 class admin_setting_configcheckbox extends admin_setting {
2055 /** @var string Value used when checked */
2057 /** @var string Value used when not checked */
2062 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2063 * @param string $visiblename localised
2064 * @param string $description long localised info
2065 * @param string $defaultsetting
2066 * @param string $yes value used when checked
2067 * @param string $no value used when not checked
2069 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2070 parent::__construct($name, $visiblename, $description, $defaultsetting);
2071 $this->yes = (string)$yes;
2072 $this->no = (string)$no;
2076 * Retrieves the current setting using the objects name
2080 public function get_setting() {
2081 return $this->config_read($this->name);
2085 * Sets the value for the setting
2087 * Sets the value for the setting to either the yes or no values
2088 * of the object by comparing $data to yes
2090 * @param mixed $data Gets converted to str for comparison against yes value
2091 * @return string empty string or error
2093 public function write_setting($data) {
2094 if ((string)$data === $this->yes) { // convert to strings before comparison
2099 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2103 * Returns an XHTML checkbox field
2105 * @param string $data If $data matches yes then checkbox is checked
2106 * @param string $query
2107 * @return string XHTML field
2109 public function output_html($data, $query='') {
2110 $default = $this->get_defaultsetting();
2112 if (!is_null($default)) {
2113 if ((string)$default === $this->yes) {
2114 $defaultinfo = get_string('checkboxyes', 'admin');
2116 $defaultinfo = get_string('checkboxno', 'admin');
2119 $defaultinfo = NULL;
2122 if ((string)$data === $this->yes) { // convert to strings before comparison
2123 $checked = 'checked="checked"';
2128 return format_admin_setting($this, $this->visiblename,
2129 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2130 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2131 $this->description, true, '', $defaultinfo, $query);
2137 * Multiple checkboxes, each represents different value, stored in csv format
2139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2141 class admin_setting_configmulticheckbox extends admin_setting {
2142 /** @var array Array of choices value=>label */
2146 * Constructor: uses parent::__construct
2148 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2149 * @param string $visiblename localised
2150 * @param string $description long localised info
2151 * @param array $defaultsetting array of selected
2152 * @param array $choices array of $value=>$label for each checkbox
2154 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2155 $this->choices = $choices;
2156 parent::__construct($name, $visiblename, $description, $defaultsetting);
2160 * This public function may be used in ancestors for lazy loading of choices
2162 * @todo Check if this function is still required content commented out only returns true
2163 * @return bool true if loaded, false if error
2165 public function load_choices() {
2167 if (is_array($this->choices)) {
2170 .... load choices here
2176 * Is setting related to query text - used when searching
2178 * @param string $query
2179 * @return bool true on related, false on not or failure
2181 public function is_related($query) {
2182 if (!$this->load_choices() or empty($this->choices)) {
2185 if (parent::is_related($query)) {
2189 $textlib = textlib_get_instance();
2190 foreach ($this->choices as $desc) {
2191 if (strpos($textlib->strtolower($desc), $query) !== false) {
2199 * Returns the current setting if it is set
2201 * @return mixed null if null, else an array
2203 public function get_setting() {
2204 $result = $this->config_read($this->name);
2206 if (is_null($result)) {
2209 if ($result === '') {
2212 $enabled = explode(',', $result);
2214 foreach ($enabled as $option) {
2215 $setting[$option] = 1;
2221 * Saves the setting(s) provided in $data
2223 * @param array $data An array of data, if not array returns empty str
2224 * @return mixed empty string on useless data or bool true=success, false=failed
2226 public function write_setting($data) {
2227 if (!is_array($data)) {
2228 return ''; // ignore it
2230 if (!$this->load_choices() or empty($this->choices)) {
2233 unset($data['xxxxx']);
2235 foreach ($data as $key => $value) {
2236 if ($value and array_key_exists($key, $this->choices)) {
2240 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2244 * Returns XHTML field(s) as required by choices
2246 * Relies on data being an array should data ever be another valid vartype with
2247 * acceptable value this may cause a warning/error
2248 * if (!is_array($data)) would fix the problem
2250 * @todo Add vartype handling to ensure $data is an array
2252 * @param array $data An array of checked values
2253 * @param string $query
2254 * @return string XHTML field
2256 public function output_html($data, $query='') {
2257 if (!$this->load_choices() or empty($this->choices)) {
2260 $default = $this->get_defaultsetting();
2261 if (is_null($default)) {
2264 if (is_null($data)) {
2268 $defaults = array();
2269 foreach ($this->choices as $key=>$description) {
2270 if (!empty($data[$key])) {
2271 $checked = 'checked="checked"';
2275 if (!empty($default[$key])) {
2276 $defaults[] = $description;
2279 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2280 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2283 if (is_null($default)) {
2284 $defaultinfo = NULL;
2285 } else if (!empty($defaults)) {
2286 $defaultinfo = implode(', ', $defaults);
2288 $defaultinfo = get_string('none');
2291 $return = '<div class="form-multicheckbox">';
2292 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2295 foreach ($options as $option) {
2296 $return .= '<li>'.$option.'</li>';
2300 $return .= '</div>';
2302 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2309 * Multiple checkboxes 2, value stored as string 00101011
2311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2313 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2316 * Returns the setting if set
2318 * @return mixed null if not set, else an array of set settings
2320 public function get_setting() {
2321 $result = $this->config_read($this->name);
2322 if (is_null($result)) {
2325 if (!$this->load_choices()) {
2328 $result = str_pad($result, count($this->choices), '0');
2329 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2331 foreach ($this->choices as $key=>$unused) {
2332 $value = array_shift($result);
2341 * Save setting(s) provided in $data param
2343 * @param array $data An array of settings to save
2344 * @return mixed empty string for bad data or bool true=>success, false=>error
2346 public function write_setting($data) {
2347 if (!is_array($data)) {
2348 return ''; // ignore it
2350 if (!$this->load_choices() or empty($this->choices)) {
2354 foreach ($this->choices as $key=>$unused) {
2355 if (!empty($data[$key])) {
2361 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2367 * Select one value from list
2369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2371 class admin_setting_configselect extends admin_setting {
2372 /** @var array Array of choices value=>label */
2377 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2378 * @param string $visiblename localised
2379 * @param string $description long localised info
2380 * @param string|int $defaultsetting
2381 * @param array $choices array of $value=>$label for each selection
2383 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2384 $this->choices = $choices;
2385 parent::__construct($name, $visiblename, $description, $defaultsetting);
2389 * This function may be used in ancestors for lazy loading of choices
2391 * Override this method if loading of choices is expensive, such
2392 * as when it requires multiple db requests.
2394 * @return bool true if loaded, false if error
2396 public function load_choices() {
2398 if (is_array($this->choices)) {
2401 .... load choices here
2407 * Check if this is $query is related to a choice
2409 * @param string $query
2410 * @return bool true if related, false if not
2412 public function is_related($query) {
2413 if (parent::is_related($query)) {
2416 if (!$this->load_choices()) {
2419 $textlib = textlib_get_instance();
2420 foreach ($this->choices as $key=>$value) {
2421 if (strpos($textlib->strtolower($key), $query) !== false) {
2424 if (strpos($textlib->strtolower($value), $query) !== false) {
2432 * Return the setting
2434 * @return mixed returns config if successful else null
2436 public function get_setting() {
2437 return $this->config_read($this->name);
2443 * @param string $data
2444 * @return string empty of error string
2446 public function write_setting($data) {
2447 if (!$this->load_choices() or empty($this->choices)) {
2450 if (!array_key_exists($data, $this->choices)) {
2451 return ''; // ignore it
2454 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2458 * Returns XHTML select field
2460 * Ensure the options are loaded, and generate the XHTML for the select
2461 * element and any warning message. Separating this out from output_html
2462 * makes it easier to subclass this class.
2464 * @param string $data the option to show as selected.
2465 * @param string $current the currently selected option in the database, null if none.
2466 * @param string $default the default selected option.
2467 * @return array the HTML for the select element, and a warning message.
2469 public function output_select_html($data, $current, $default, $extraname = '') {
2470 if (!$this->load_choices() or empty($this->choices)) {
2471 return array('', '');
2475 if (is_null($current)) {
2477 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2479 } else if (!array_key_exists($current, $this->choices)) {
2480 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2481 if (!is_null($default) and $data == $current) {
2482 $data = $default; // use default instead of first value when showing the form
2486 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2487 foreach ($this->choices as $key => $value) {
2488 // the string cast is needed because key may be integer - 0 is equal to most strings!
2489 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2491 $selecthtml .= '</select>';
2492 return array($selecthtml, $warning);
2496 * Returns XHTML select field and wrapping div(s)
2498 * @see output_select_html()
2500 * @param string $data the option to show as selected
2501 * @param string $query
2502 * @return string XHTML field and wrapping div
2504 public function output_html($data, $query='') {
2505 $default = $this->get_defaultsetting();
2506 $current = $this->get_setting();
2508 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2513 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2514 $defaultinfo = $this->choices[$default];
2516 $defaultinfo = NULL;
2519 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2521 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2527 * Select multiple items from list
2529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 class admin_setting_configmultiselect extends admin_setting_configselect {
2534 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2535 * @param string $visiblename localised
2536 * @param string $description long localised info
2537 * @param array $defaultsetting array of selected items
2538 * @param array $choices array of $value=>$label for each list item
2540 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2541 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2545 * Returns the select setting(s)
2547 * @return mixed null or array. Null if no settings else array of setting(s)
2549 public function get_setting() {
2550 $result = $this->config_read($this->name);
2551 if (is_null($result)) {
2554 if ($result === '') {
2557 return explode(',', $result);
2561 * Saves setting(s) provided through $data
2563 * Potential bug in the works should anyone call with this function
2564 * using a vartype that is not an array
2566 * @param array $data
2568 public function write_setting($data) {
2569 if (!is_array($data)) {
2570 return ''; //ignore it
2572 if (!$this->load_choices() or empty($this->choices)) {
2576 unset($data['xxxxx']);
2579 foreach ($data as $value) {
2580 if (!array_key_exists($value, $this->choices)) {
2581 continue; // ignore it
2586 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2590 * Is setting related to query text - used when searching
2592 * @param string $query
2593 * @return bool true if related, false if not
2595 public function is_related($query) {
2596 if (!$this->load_choices() or empty($this->choices)) {
2599 if (parent::is_related($query)) {
2603 $textlib = textlib_get_instance();
2604 foreach ($this->choices as $desc) {
2605 if (strpos($textlib->strtolower($desc), $query) !== false) {
2613 * Returns XHTML multi-select field
2615 * @todo Add vartype handling to ensure $data is an array
2616 * @param array $data Array of values to select by default
2617 * @param string $query
2618 * @return string XHTML multi-select field
2620 public function output_html($data, $query='') {
2621 if (!$this->load_choices() or empty($this->choices)) {
2624 $choices = $this->choices;
2625 $default = $this->get_defaultsetting();
2626 if (is_null($default)) {
2629 if (is_null($data)) {
2633 $defaults = array();
2634 $size = min(10, count($this->choices));
2635 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2636 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2637 foreach ($this->choices as $key => $description) {
2638 if (in_array($key, $data)) {
2639 $selected = 'selected="selected"';
2643 if (in_array($key, $default)) {
2644 $defaults[] = $description;
2647 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2650 if (is_null($default)) {
2651 $defaultinfo = NULL;
2652 } if (!empty($defaults)) {
2653 $defaultinfo = implode(', ', $defaults);
2655 $defaultinfo = get_string('none');
2658 $return .= '</select></div>';
2659 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2666 * This is a liiitle bit messy. we're using two selects, but we're returning
2667 * them as an array named after $name (so we only use $name2 internally for the setting)
2669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2671 class admin_setting_configtime extends admin_setting {
2672 /** @var string Used for setting second select (minutes) */
2677 * @param string $hoursname setting for hours
2678 * @param string $minutesname setting for hours
2679 * @param string $visiblename localised
2680 * @param string $description long localised info
2681 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2683 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2684 $this->name2 = $minutesname;
2685 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2689 * Get the selected time
2691 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2693 public function get_setting() {
2694 $result1 = $this->config_read($this->name);
2695 $result2 = $this->config_read($this->name2);
2696 if (is_null($result1) or is_null($result2)) {
2700 return array('h' => $result1, 'm' => $result2);
2704 * Store the time (hours and minutes)
2706 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2707 * @return bool true if success, false if not
2709 public function write_setting($data) {
2710 if (!is_array($data)) {
2714 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2715 return ($result ? '' : get_string('errorsetting', 'admin'));
2719 * Returns XHTML time select fields
2721 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2722 * @param string $query
2723 * @return string XHTML time select fields and wrapping div(s)
2725 public function output_html($data, $query='') {
2726 $default = $this->get_defaultsetting();
2728 if (is_array($default)) {
2729 $defaultinfo = $default['h'].':'.$default['m'];
2731 $defaultinfo = NULL;
2734 $return = '<div class="form-time defaultsnext">'.
2735 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2736 for ($i = 0; $i < 24; $i++) {
2737 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2739 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2740 for ($i = 0; $i < 60; $i += 5) {
2741 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2743 $return .= '</select></div>';
2744 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2751 * Used to validate a textarea used for ip addresses
2753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2755 class admin_setting_configiplist extends admin_setting_configtextarea {
2758 * Validate the contents of the textarea as IP addresses
2760 * Used to validate a new line separated list of IP addresses collected from
2761 * a textarea control
2763 * @param string $data A list of IP Addresses separated by new lines
2764 * @return mixed bool true for success or string:error on failure
2766 public function validate($data) {
2768 $ips = explode("\n", $data);
2773 foreach($ips as $ip) {
2775 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2776 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2777 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2787 return get_string('validateerror', 'admin');
2794 * An admin setting for selecting one or more users who have a capability
2795 * in the system context
2797 * An admin setting for selecting one or more users, who have a particular capability
2798 * in the system context. Warning, make sure the list will never be too long. There is
2799 * no paging or searching of this list.
2801 * To correctly get a list of users from this config setting, you need to call the
2802 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2806 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2807 /** @var string The capabilities name */
2808 protected $capability;
2809 /** @var int include admin users too */
2810 protected $includeadmins;
2815 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2816 * @param string $visiblename localised name
2817 * @param string $description localised long description
2818 * @param array $defaultsetting array of usernames
2819 * @param string $capability string capability name.
2820 * @param bool $includeadmins include administrators
2822 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2823 $this->capability = $capability;
2824 $this->includeadmins = $includeadmins;
2825 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2829 * Load all of the uses who have the capability into choice array
2831 * @return bool Always returns true
2833 function load_choices() {
2834 if (is_array($this->choices)) {
2837 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2838 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2839 $this->choices = array(
2840 '$@NONE@$' => get_string('nobody'),
2841 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2843 if ($this->includeadmins) {
2844 $admins = get_admins();
2845 foreach ($admins as $user) {
2846 $this->choices[$user->id] = fullname($user);
2849 if (is_array($users)) {
2850 foreach ($users as $user) {
2851 $this->choices[$user->id] = fullname($user);
2858 * Returns the default setting for class
2860 * @return mixed Array, or string. Empty string if no default
2862 public function get_defaultsetting() {
2863 $this->load_choices();
2864 $defaultsetting = parent::get_defaultsetting();
2865 if (empty($defaultsetting)) {
2866 return array('$@NONE@$');
2867 } else if (array_key_exists($defaultsetting, $this->choices)) {
2868 return $defaultsetting;
2875 * Returns the current setting
2877 * @return mixed array or string
2879 public function get_setting() {
2880 $result = parent::get_setting();
2881 if ($result === null) {
2882 // this is necessary for settings upgrade
2885 if (empty($result)) {
2886 $result = array('$@NONE@$');
2892 * Save the chosen setting provided as $data
2894 * @param array $data
2895 * @return mixed string or array
2897 public function write_setting($data) {
2898 // If all is selected, remove any explicit options.
2899 if (in_array('$@ALL@$', $data)) {
2900 $data = array('$@ALL@$');
2902 // None never needs to be written to the DB.
2903 if (in_array('$@NONE@$', $data)) {
2904 unset($data[array_search('$@NONE@$', $data)]);
2906 return parent::write_setting($data);
2912 * Special checkbox for calendar - resets SESSION vars.
2914 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2916 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2918 * Calls the parent::__construct with default values
2920 * name => calendar_adminseesall
2921 * visiblename => get_string('adminseesall', 'admin')
2922 * description => get_string('helpadminseesall', 'admin')
2923 * defaultsetting => 0
2925 public function __construct() {
2926 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2927 get_string('helpadminseesall', 'admin'), '0');
2931 * Stores the setting passed in $data
2933 * @param mixed gets converted to string for comparison
2934 * @return string empty string or error message
2936 public function write_setting($data) {
2938 return parent::write_setting($data);
2943 * Special select for settings that are altered in setup.php and can not be altered on the fly
2945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2947 class admin_setting_special_selectsetup extends admin_setting_configselect {
2949 * Reads the setting directly from the database
2953 public function get_setting() {
2954 // read directly from db!
2955 return get_config(NULL, $this->name);
2959 * Save the setting passed in $data
2961 * @param string $data The setting to save
2962 * @return string empty or error message
2964 public function write_setting($data) {
2966 // do not change active CFG setting!
2967 $current = $CFG->{$this->name};
2968 $result = parent::write_setting($data);
2969 $CFG->{$this->name} = $current;
2976 * Special select for frontpage - stores data in course table
2978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2980 class admin_setting_sitesetselect extends admin_setting_configselect {
2982 * Returns the site name for the selected site
2985 * @return string The site name of the selected site
2987 public function get_setting() {
2989 return $site->{$this->name};
2993 * Updates the database and save the setting
2995 * @param string data
2996 * @return string empty or error message
2998 public function write_setting($data) {
3000 if (!in_array($data, array_keys($this->choices))) {
3001 return get_string('errorsetting', 'admin');
3003 $record = new stdClass();
3004 $record->id = SITEID;
3005 $temp = $this->name;
3006 $record->$temp = $data;
3007 $record->timemodified = time();
3009 $SITE->{$this->name} = $data;
3010 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3016 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3021 class admin_setting_bloglevel extends admin_setting_configselect {
3023 * Updates the database and save the setting
3025 * @param string data
3026 * @return string empty or error message
3028 public function write_setting($data) {
3030 if ($data['bloglevel'] == 0) {
3031 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3032 foreach ($blogblocks as $block) {
3033 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3036 // reenable all blocks only when switching from disabled blogs
3037 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3038 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3039 foreach ($blogblocks as $block) {
3040 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3044 return parent::write_setting($data);
3050 * Special select - lists on the frontpage - hacky
3052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3054 class admin_setting_courselist_frontpage extends admin_setting {
3055 /** @var array Array of choices value=>label */
3059 * Construct override, requires one param
3061 * @param bool $loggedin Is the user logged in
3063 public function __construct($loggedin) {
3065 require_once($CFG->dirroot.'/course/lib.php');
3066 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3067 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3068 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3069 $defaults = array(FRONTPAGECOURSELIST);
3070 parent::__construct($name, $visiblename, $description, $defaults);
3074 * Loads the choices available
3076 * @return bool always returns true
3078 public function load_choices() {
3080 if (is_array($this->choices)) {
3083 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3084 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3085 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3086 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3087 'none' => get_string('none'));
3088 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3089 unset($this->choices[FRONTPAGECOURSELIST]);
3095 * Returns the selected settings
3097 * @param mixed array or setting or null
3099 public function get_setting() {
3100 $result = $this->config_read($this->name);
3101 if (is_null($result)) {
3104 if ($result === '') {
3107 return explode(',', $result);
3111 * Save the selected options
3113 * @param array $data
3114 * @return mixed empty string (data is not an array) or bool true=success false=failure
3116 public function write_setting($data) {
3117 if (!is_array($data)) {
3120 $this->load_choices();
3122 foreach($data as $datum) {
3123 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3126 $save[$datum] = $datum; // no duplicates
3128 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3132 * Return XHTML select field and wrapping div
3134 * @todo Add vartype handling to make sure $data is an array
3135 * @param array $data Array of elements to select by default
3136 * @return string XHTML select field and wrapping div
3138 public function output_html($data, $query='') {
3139 $this->load_choices();
3140 $currentsetting = array();
3141 foreach ($data as $key) {
3142 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3143 $currentsetting[] = $key; // already selected first
3147 $return = '<div class="form-group">';
3148 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3149 if (!array_key_exists($i, $currentsetting)) {
3150 $currentsetting[$i] = 'none'; //none
3152 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3153 foreach ($this->choices as $key => $value) {
3154 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3156 $return .= '</select>';
3157 if ($i !== count($this->choices) - 2) {
3158 $return .= '<br />';
3161 $return .= '</div>';
3163 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3169 * Special checkbox for frontpage - stores data in course table
3171 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3173 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3175 * Returns the current sites name
3179 public function get_setting() {
3181 return $site->{$this->name};
3185 * Save the selected setting
3187 * @param string $data The selected site
3188 * @return string empty string or error message
3190 public function write_setting($data) {
3192 $record = new stdClass();
3193 $record->id = SITEID;
3194 $record->{$this->name} = ($data == '1' ? 1 : 0);
3195 $record->timemodified = time();
3197 $SITE->{$this->name} = $data;
3198 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3203 * Special text for frontpage - stores data in course table.
3204 * Empty string means not set here. Manual setting is required.
3206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3208 class admin_setting_sitesettext extends admin_setting_configtext {
3210 * Return the current setting
3212 * @return mixed string or null
3214 public function get_setting() {
3216 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3220 * Validate the selected data
3222 * @param string $data The selected value to validate
3223 * @return mixed true or message string
3225 public function validate($data) {
3226 $cleaned = clean_param($data, PARAM_MULTILANG);
3227 if ($cleaned === '') {
3228 return get_string('required');
3230 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3233 return get_string('validateerror', 'admin');
3238 * Save the selected setting
3240 * @param string $data The selected value
3241 * @return string empty or error message
3243 public function write_setting($data) {
3245 $data = trim($data);
3246 $validated = $this->validate($data);
3247 if ($validated !== true) {
3251 $record = new stdClass();
3252 $record->id = SITEID;
3253 $record->{$this->name} = $data;
3254 $record->timemodified = time();
3256 $SITE->{$this->name} = $data;
3257 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3263 * Special text editor for site description.
3265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3267 class admin_setting_special_frontpagedesc extends admin_setting {
3269 * Calls parent::__construct with specific arguments
3271 public function __construct() {
3272 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3273 editors_head_setup();
3277 * Return the current setting
3278 * @return string The current setting
3280 public function get_setting() {
3282 return $site->{$this->name};
3286 * Save the new setting
3288 * @param string $data The new value to save
3289 * @return string empty or error message
3291 public function write_setting($data) {
3293 $record = new stdClass();
3294 $record->id = SITEID;
3295 $record->{$this->name} = $data;
3296 $record->timemodified = time();
3297 $SITE->{$this->name} = $data;
3298 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3302 * Returns XHTML for the field plus wrapping div
3304 * @param string $data The current value
3305 * @param string $query
3306 * @return string The XHTML output
3308 public function output_html($data, $query='') {
3311 $CFG->adminusehtmleditor = can_use_html_editor();
3312 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3314 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3320 * Administration interface for emoticon_manager settings.
3322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3324 class admin_setting_emoticons extends admin_setting {
3327 * Calls parent::__construct with specific args
3329 public function __construct() {
3332 $manager = get_emoticon_manager();
3333 $defaults = $this->prepare_form_data($manager->default_emoticons());
3334 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3338 * Return the current setting(s)
3340 * @return array Current settings array
3342 public function get_setting() {
3345 $manager = get_emoticon_manager();
3347 $config = $this->config_read($this->name);
3348 if (is_null($config)) {
3352 $config = $manager->decode_stored_config($config);
3353 if (is_null($config)) {
3357 return $this->prepare_form_data($config);
3361 * Save selected settings
3363 * @param array $data Array of settings to save
3366 public function write_setting($data) {
3368 $manager = get_emoticon_manager();
3369 $emoticons = $this->process_form_data($data);
3371 if ($emoticons === false) {
3375 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3376 return ''; // success
3378 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3383 * Return XHTML field(s) for options
3385 * @param array $data Array of options to set in HTML
3386 * @return string XHTML string for the fields and wrapping div(s)
3388 public function output_html($data, $query='') {
3391 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3392 $out .= html_writer::start_tag('thead');
3393 $out .= html_writer::start_tag('tr');
3394 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3395 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3396 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3397 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3398 $out .= html_writer::tag('th', '');
3399 $out .= html_writer::end_tag('tr');
3400 $out .= html_writer::end_tag('thead');
3401 $out .= html_writer::start_tag('tbody');
3403 foreach($data as $field => $value) {
3406 $out .= html_writer::start_tag('tr');
3407 $current_text = $value;
3408 $current_filename = '';
3409 $current_imagecomponent = '';
3410 $current_altidentifier = '';
3411 $current_altcomponent = '';
3413 $current_filename = $value;
3415 $current_imagecomponent = $value;
3417 $current_altidentifier = $value;
3419 $current_altcomponent = $value;
3422 $out .= html_writer::tag('td',
3423 html_writer::empty_tag('input',
3426 'class' => 'form-text',
3427 'name' => $this->get_full_name().'['.$field.']',
3430 ), array('class' => 'c'.$i)
3434 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3435 $alt = get_string($current_altidentifier, $current_altcomponent);
3437 $alt = $current_text;
3439 if ($current_filename) {
3440 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3442 $out .= html_writer::tag('td', '');
3444 $out .= html_writer::end_tag('tr');
3451 $out .= html_writer::end_tag('tbody');
3452 $out .= html_writer::end_tag('table');
3453 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3454 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3456 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3460 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3462 * @see self::process_form_data()
3463 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3464 * @return array of form fields and their values
3466 protected function prepare_form_data(array $emoticons) {
3470 foreach ($emoticons as $emoticon) {
3471 $form['text'.$i] = $emoticon->text;
3472 $form['imagename'.$i] = $emoticon->imagename;
3473 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3474 $form['altidentifier'.$i] = $emoticon->altidentifier;
3475 $form['altcomponent'.$i] = $emoticon->altcomponent;
3478 // add one more blank field set for new object
3479 $form['text'.$i] = '';
3480 $form['imagename'.$i] = '';
3481 $form['imagecomponent'.$i] = '';
3482 $form['altidentifier'.$i] = '';
3483 $form['altcomponent'.$i] = '';
3489 * Converts the data from admin settings form into an array of emoticon objects
3491 * @see self::prepare_form_data()
3492 * @param array $data array of admin form fields and values
3493 * @return false|array of emoticon objects
3495 protected function process_form_data(array $form) {
3497 $count = count($form); // number of form field values
3500 // we must get five fields per emoticon object
3504 $emoticons = array();
3505 for ($i = 0; $i < $count / 5; $i++) {
3506 $emoticon = new stdClass();
3507 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3508 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3509 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_SAFEDIR);
3510 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3511 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_SAFEDIR);
3513 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3514 // prevent from breaking http://url.addresses by accident
3515 $emoticon->text = '';
3518 if (strlen($emoticon->text) < 2) {
3519 // do not allow single character emoticons
3520 $emoticon->text = '';
3523 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3524 // emoticon text must contain some non-alphanumeric character to prevent
3525 // breaking HTML tags
3526 $emoticon->text = '';
3529 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3530 $emoticons[] = $emoticon;
3539 * Special setting for limiting of the list of available languages.
3541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3543 class admin_setting_langlist extends admin_setting_configtext {
3545 * Calls parent::__construct with specific arguments
3547 public function __construct() {
3548 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3552 * Save the new setting
3554 * @param string $data The new setting
3557 public function write_setting($data) {
3558 $return = parent::write_setting($data);
3559 get_string_manager()->reset_caches();
3566 * Selection of one of the recognised countries using the list
3567 * returned by {@link get_list_of_countries()}.
3569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3571 class admin_settings_country_select extends admin_setting_configselect {
3572 protected $includeall;
3573 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3574 $this->includeall = $includeall;
3575 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3579 * Lazy-load the available choices for the select box
3581 public function load_choices() {
3583 if (is_array($this->choices)) {
3586 $this->choices = array_merge(
3587 array('0' => get_string('choosedots')),
3588 get_string_manager()->get_list_of_countries($this->includeall));
3595 * admin_setting_configselect for the default number of sections in a course,
3596 * simply so we can lazy-load the choices.
3598 * @copyright 2011 The Open University
3599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3601 class admin_settings_num_course_sections extends admin_setting_configselect {
3602 public function __construct($name, $visiblename, $description, $defaultsetting) {
3603 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3606 /** Lazy-load the available choices for the select box */
3607 public function load_choices() {
3608 $max = get_config('moodlecourse', 'maxsections');
3612 for ($i = 0; $i <= $max; $i++) {
3613 $this->choices[$i] = "$i";
3621 * Course category selection
3623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3625 class admin_settings_coursecat_select extends admin_setting_configselect {
3627 * Calls parent::__construct with specific arguments
3629 public function __construct($name, $visiblename, $description, $defaultsetting) {
3630 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3634 * Load the available choices for the select box
3638 public function load_choices() {
3640 require_once($CFG->dirroot.'/course/lib.php');
3641 if (is_array($this->choices)) {
3644 $this->choices = make_categories_options();
3651 * Special control for selecting days to backup
3653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3655 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3657 * Calls parent::__construct with specific arguments
3659 public function __construct() {
3660 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3661 $this->plugin = 'backup';
3665 * Load the available choices for the select box
3667 * @return bool Always returns true
3669 public function load_choices() {
3670 if (is_array($this->choices)) {
3673 $this->choices = array();
3674 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3675 foreach ($days as $day) {
3676 $this->choices[$day] = get_string($day, 'calendar');