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 // This may take a long time.
129 // recursively uninstall all module/editor subplugins first
130 if ($type === 'mod' || $type === 'editor') {
131 $base = get_component_directory($type . '_' . $name);
132 if (file_exists("$base/db/subplugins.php")) {
133 $subplugins = array();
134 include("$base/db/subplugins.php");
135 foreach ($subplugins as $subplugintype=>$dir) {
136 $instances = get_plugin_list($subplugintype);
137 foreach ($instances as $subpluginname => $notusedpluginpath) {
138 uninstall_plugin($subplugintype, $subpluginname);
145 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
147 if ($type === 'mod') {
148 $pluginname = $name; // eg. 'forum'
149 if (get_string_manager()->string_exists('modulename', $component)) {
150 $strpluginname = get_string('modulename', $component);
152 $strpluginname = $component;
156 $pluginname = $component;
157 if (get_string_manager()->string_exists('pluginname', $component)) {
158 $strpluginname = get_string('pluginname', $component);
160 $strpluginname = $component;
164 echo $OUTPUT->heading($pluginname);
166 $plugindirectory = get_plugin_directory($type, $name);
167 $uninstalllib = $plugindirectory . '/db/uninstall.php';
168 if (file_exists($uninstalllib)) {
169 require_once($uninstalllib);
170 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
171 if (function_exists($uninstallfunction)) {
172 if (!$uninstallfunction()) {
173 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
178 if ($type === 'mod') {
179 // perform cleanup tasks specific for activity modules
181 if (!$module = $DB->get_record('modules', array('name' => $name))) {
182 print_error('moduledoesnotexist', 'error');
185 // delete all the relevant instances from all course sections
186 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
187 foreach ($coursemods as $coursemod) {
188 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
189 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
194 // clear course.modinfo for courses that used this module
195 $sql = "UPDATE {course}
197 WHERE id IN (SELECT DISTINCT course
198 FROM {course_modules}
200 $DB->execute($sql, array($module->id));
202 // delete all the course module records
203 $DB->delete_records('course_modules', array('module' => $module->id));
205 // delete module contexts
207 foreach ($coursemods as $coursemod) {
208 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
209 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
214 // delete the module entry itself
215 $DB->delete_records('modules', array('name' => $module->name));
217 // cleanup the gradebook
218 require_once($CFG->libdir.'/gradelib.php');
219 grade_uninstalled_module($module->name);
221 // Perform any custom uninstall tasks
222 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
223 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
224 $uninstallfunction = $module->name . '_uninstall';
225 if (function_exists($uninstallfunction)) {
226 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
227 if (!$uninstallfunction()) {
228 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
233 } else if ($type === 'enrol') {
234 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
235 // nuke all role assignments
236 role_unassign_all(array('component'=>$component));
237 // purge participants
238 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
239 // purge enrol instances
240 $DB->delete_records('enrol', array('enrol'=>$name));
241 // tweak enrol settings
242 if (!empty($CFG->enrol_plugins_enabled)) {
243 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
244 $enabledenrols = array_unique($enabledenrols);
245 $enabledenrols = array_flip($enabledenrols);
246 unset($enabledenrols[$name]);
247 $enabledenrols = array_flip($enabledenrols);
248 if (is_array($enabledenrols)) {
249 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
253 } else if ($type === 'block') {
254 if ($block = $DB->get_record('block', array('name'=>$name))) {
255 // Inform block it's about to be deleted
256 if (file_exists("$CFG->dirroot/blocks/$block->name/block_$block->name.php")) {
257 $blockobject = block_instance($block->name);
259 $blockobject->before_delete(); //only if we can create instance, block might have been already removed
263 // First delete instances and related contexts
264 $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
265 foreach($instances as $instance) {
266 blocks_delete_instance($instance);
270 $DB->delete_records('block', array('id'=>$block->id));
272 } else if ($type === 'format') {
273 if (($defaultformat = get_config('moodlecourse', 'format')) && $defaultformat !== $name) {
274 $courses = $DB->get_records('course', array('format' => $name), 'id');
275 $data = (object)array('id' => null, 'format' => $defaultformat);
276 foreach ($courses as $record) {
277 $data->id = $record->id;
278 update_course($data);
281 $DB->delete_records('course_format_options', array('format' => $name));
284 // perform clean-up task common for all the plugin/subplugin types
286 //delete the web service functions and pre-built services
287 require_once($CFG->dirroot.'/lib/externallib.php');
288 external_delete_descriptions($component);
290 // delete calendar events
291 $DB->delete_records('event', array('modulename' => $pluginname));
293 // delete all the logs
294 $DB->delete_records('log', array('module' => $pluginname));
296 // delete log_display information
297 $DB->delete_records('log_display', array('component' => $component));
299 // delete the module configuration records
300 unset_all_config_for_plugin($pluginname);
302 // delete message provider
303 message_provider_uninstall($component);
305 // delete message processor
306 if ($type === 'message') {
307 message_processor_uninstall($name);
310 // delete the plugin tables
311 $xmldbfilepath = $plugindirectory . '/db/install.xml';
312 drop_plugin_tables($component, $xmldbfilepath, false);
313 if ($type === 'mod' or $type === 'block') {
314 // non-frankenstyle table prefixes
315 drop_plugin_tables($name, $xmldbfilepath, false);
318 // delete the capabilities that were defined by this module
319 capabilities_cleanup($component);
321 // remove event handlers and dequeue pending events
322 events_uninstall($component);
324 // Finally purge all caches.
327 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
331 * Returns the version of installed component
333 * @param string $component component name
334 * @param string $source either 'disk' or 'installed' - where to get the version information from
335 * @return string|bool version number or false if the component is not found
337 function get_component_version($component, $source='installed') {
340 list($type, $name) = normalize_component($component);
342 // moodle core or a core subsystem
343 if ($type === 'core') {
344 if ($source === 'installed') {
345 if (empty($CFG->version)) {
348 return $CFG->version;
351 if (!is_readable($CFG->dirroot.'/version.php')) {
354 $version = null; //initialize variable for IDEs
355 include($CFG->dirroot.'/version.php');
362 if ($type === 'mod') {
363 if ($source === 'installed') {
364 return $DB->get_field('modules', 'version', array('name'=>$name));
366 $mods = get_plugin_list('mod');
367 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
370 $module = new stdclass();
371 include($mods[$name].'/version.php');
372 return $module->version;
378 if ($type === 'block') {
379 if ($source === 'installed') {
380 return $DB->get_field('block', 'version', array('name'=>$name));
382 $blocks = get_plugin_list('block');
383 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
386 $plugin = new stdclass();
387 include($blocks[$name].'/version.php');
388 return $plugin->version;
393 // all other plugin types
394 if ($source === 'installed') {
395 return get_config($type.'_'.$name, 'version');
397 $plugins = get_plugin_list($type);
398 if (empty($plugins[$name])) {
401 $plugin = new stdclass();
402 include($plugins[$name].'/version.php');
403 return $plugin->version;
409 * Delete all plugin tables
411 * @param string $name Name of plugin, used as table prefix
412 * @param string $file Path to install.xml file
413 * @param bool $feedback defaults to true
414 * @return bool Always returns true
416 function drop_plugin_tables($name, $file, $feedback=true) {
419 // first try normal delete
420 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
424 // then try to find all tables that start with name and are not in any xml file
425 $used_tables = get_used_table_names();
427 $tables = $DB->get_tables();
429 /// Iterate over, fixing id fields as necessary
430 foreach ($tables as $table) {
431 if (in_array($table, $used_tables)) {
435 if (strpos($table, $name) !== 0) {
439 // found orphan table --> delete it
440 if ($DB->get_manager()->table_exists($table)) {
441 $xmldb_table = new xmldb_table($table);
442 $DB->get_manager()->drop_table($xmldb_table);
450 * Returns names of all known tables == tables that moodle knows about.
452 * @return array Array of lowercase table names
454 function get_used_table_names() {
455 $table_names = array();
456 $dbdirs = get_db_directories();
458 foreach ($dbdirs as $dbdir) {
459 $file = $dbdir.'/install.xml';
461 $xmldb_file = new xmldb_file($file);
463 if (!$xmldb_file->fileExists()) {
467 $loaded = $xmldb_file->loadXMLStructure();
468 $structure = $xmldb_file->getStructure();
470 if ($loaded and $tables = $structure->getTables()) {
471 foreach($tables as $table) {
472 $table_names[] = strtolower($table->getName());
481 * Returns list of all directories where we expect install.xml files
482 * @return array Array of paths
484 function get_db_directories() {
489 /// First, the main one (lib/db)
490 $dbdirs[] = $CFG->libdir.'/db';
492 /// Then, all the ones defined by get_plugin_types()
493 $plugintypes = get_plugin_types();
494 foreach ($plugintypes as $plugintype => $pluginbasedir) {
495 if ($plugins = get_plugin_list($plugintype)) {
496 foreach ($plugins as $plugin => $plugindir) {
497 $dbdirs[] = $plugindir.'/db';
506 * Try to obtain or release the cron lock.
507 * @param string $name name of lock
508 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
509 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
510 * @return bool true if lock obtained
512 function set_cron_lock($name, $until, $ignorecurrent=false) {
515 debugging("Tried to get a cron lock for a null fieldname");
519 // remove lock by force == remove from config table
520 if (is_null($until)) {
521 set_config($name, null);
525 if (!$ignorecurrent) {
526 // read value from db - other processes might have changed it
527 $value = $DB->get_field('config', 'value', array('name'=>$name));
529 if ($value and $value > time()) {
535 set_config($name, $until);
540 * Test if and critical warnings are present
543 function admin_critical_warnings_present() {
546 if (!has_capability('moodle/site:config', context_system::instance())) {
550 if (!isset($SESSION->admin_critical_warning)) {
551 $SESSION->admin_critical_warning = 0;
552 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
553 $SESSION->admin_critical_warning = 1;
557 return $SESSION->admin_critical_warning;
561 * Detects if float supports at least 10 decimal digits
563 * Detects if float supports at least 10 decimal digits
564 * and also if float-->string conversion works as expected.
566 * @return bool true if problem found
568 function is_float_problem() {
569 $num1 = 2009010200.01;
570 $num2 = 2009010200.02;
572 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
576 * Try to verify that dataroot is not accessible from web.
578 * Try to verify that dataroot is not accessible from web.
579 * It is not 100% correct but might help to reduce number of vulnerable sites.
580 * Protection from httpd.conf and .htaccess is not detected properly.
582 * @uses INSECURE_DATAROOT_WARNING
583 * @uses INSECURE_DATAROOT_ERROR
584 * @param bool $fetchtest try to test public access by fetching file, default false
585 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
587 function is_dataroot_insecure($fetchtest=false) {
590 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
592 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
593 $rp = strrev(trim($rp, '/'));
594 $rp = explode('/', $rp);
596 if (strpos($siteroot, '/'.$r.'/') === 0) {
597 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
599 break; // probably alias root
603 $siteroot = strrev($siteroot);
604 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
606 if (strpos($dataroot, $siteroot) !== 0) {
611 return INSECURE_DATAROOT_WARNING;
614 // now try all methods to fetch a test file using http protocol
616 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
617 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
618 $httpdocroot = $matches[1];
619 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
620 make_upload_directory('diag');
621 $testfile = $CFG->dataroot.'/diag/public.txt';
622 if (!file_exists($testfile)) {
623 file_put_contents($testfile, 'test file, do not delete');
625 $teststr = trim(file_get_contents($testfile));
626 if (empty($teststr)) {
628 return INSECURE_DATAROOT_WARNING;
631 $testurl = $datarooturl.'/diag/public.txt';
632 if (extension_loaded('curl') and
633 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
634 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
635 ($ch = @curl_init($testurl)) !== false) {
636 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
637 curl_setopt($ch, CURLOPT_HEADER, false);
638 $data = curl_exec($ch);
639 if (!curl_errno($ch)) {
641 if ($data === $teststr) {
643 return INSECURE_DATAROOT_ERROR;
649 if ($data = @file_get_contents($testurl)) {
651 if ($data === $teststr) {
652 return INSECURE_DATAROOT_ERROR;
656 preg_match('|https?://([^/]+)|i', $testurl, $matches);
657 $sitename = $matches[1];
659 if ($fp = @fsockopen($sitename, 80, $error)) {
660 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
661 $localurl = $matches[1];
662 $out = "GET $localurl HTTP/1.1\r\n";
663 $out .= "Host: $sitename\r\n";
664 $out .= "Connection: Close\r\n\r\n";
670 $data .= fgets($fp, 1024);
671 } else if (@fgets($fp, 1024) === "\r\n") {
677 if ($data === $teststr) {
678 return INSECURE_DATAROOT_ERROR;
682 return INSECURE_DATAROOT_WARNING;
686 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
688 function enable_cli_maintenance_mode() {
691 if (file_exists("$CFG->dataroot/climaintenance.html")) {
692 unlink("$CFG->dataroot/climaintenance.html");
695 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
696 $data = $CFG->maintenance_message;
697 $data = bootstrap_renderer::early_error_content($data, null, null, null);
698 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
700 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
701 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
704 $data = get_string('sitemaintenance', 'admin');
705 $data = bootstrap_renderer::early_error_content($data, null, null, null);
706 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
709 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
710 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
713 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
717 * Interface for anything appearing in the admin tree
719 * The interface that is implemented by anything that appears in the admin tree
720 * block. It forces inheriting classes to define a method for checking user permissions
721 * and methods for finding something in the admin tree.
723 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
725 interface part_of_admin_tree {
728 * Finds a named part_of_admin_tree.
730 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
731 * and not parentable_part_of_admin_tree, then this function should only check if
732 * $this->name matches $name. If it does, it should return a reference to $this,
733 * otherwise, it should return a reference to NULL.
735 * If a class inherits parentable_part_of_admin_tree, this method should be called
736 * recursively on all child objects (assuming, of course, the parent object's name
737 * doesn't match the search criterion).
739 * @param string $name The internal name of the part_of_admin_tree we're searching for.
740 * @return mixed An object reference or a NULL reference.
742 public function locate($name);
745 * Removes named part_of_admin_tree.
747 * @param string $name The internal name of the part_of_admin_tree we want to remove.
748 * @return bool success.
750 public function prune($name);
754 * @param string $query
755 * @return mixed array-object structure of found settings and pages
757 public function search($query);
760 * Verifies current user's access to this part_of_admin_tree.
762 * Used to check if the current user has access to this part of the admin tree or
763 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
764 * then this method is usually just a call to has_capability() in the site context.
766 * If a class inherits parentable_part_of_admin_tree, this method should return the
767 * logical OR of the return of check_access() on all child objects.
769 * @return bool True if the user has access, false if she doesn't.
771 public function check_access();
774 * Mostly useful for removing of some parts of the tree in admin tree block.
776 * @return True is hidden from normal list view
778 public function is_hidden();
781 * Show we display Save button at the page bottom?
784 public function show_save();
789 * Interface implemented by any part_of_admin_tree that has children.
791 * The interface implemented by any part_of_admin_tree that can be a parent
792 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
793 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
794 * include an add method for adding other part_of_admin_tree objects as children.
796 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
798 interface parentable_part_of_admin_tree extends part_of_admin_tree {
801 * Adds a part_of_admin_tree object to the admin tree.
803 * Used to add a part_of_admin_tree object to this object or a child of this
804 * object. $something should only be added if $destinationname matches
805 * $this->name. If it doesn't, add should be called on child objects that are
806 * also parentable_part_of_admin_tree's.
808 * $something should be appended as the last child in the $destinationname. If the
809 * $beforesibling is specified, $something should be prepended to it. If the given
810 * sibling is not found, $something should be appended to the end of $destinationname
811 * and a developer debugging message should be displayed.
813 * @param string $destinationname The internal name of the new parent for $something.
814 * @param part_of_admin_tree $something The object to be added.
815 * @return bool True on success, false on failure.
817 public function add($destinationname, $something, $beforesibling = null);
823 * The object used to represent folders (a.k.a. categories) in the admin tree block.
825 * Each admin_category object contains a number of part_of_admin_tree objects.
827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
829 class admin_category implements parentable_part_of_admin_tree {
831 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
833 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
835 /** @var string The displayed name for this category. Usually obtained through get_string() */
837 /** @var bool Should this category be hidden in admin tree block? */
839 /** @var mixed Either a string or an array or strings */
841 /** @var mixed Either a string or an array or strings */
844 /** @var array fast lookup category cache, all categories of one tree point to one cache */
845 protected $category_cache;
848 * Constructor for an empty admin category
850 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
851 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
852 * @param bool $hidden hide category in admin tree block, defaults to false
854 public function __construct($name, $visiblename, $hidden=false) {
855 $this->children = array();
857 $this->visiblename = $visiblename;
858 $this->hidden = $hidden;
862 * Returns a reference to the part_of_admin_tree object with internal name $name.
864 * @param string $name The internal name of the object we want.
865 * @param bool $findpath initialize path and visiblepath arrays
866 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
869 public function locate($name, $findpath=false) {
870 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
871 // somebody much have purged the cache
872 $this->category_cache[$this->name] = $this;
875 if ($this->name == $name) {
877 $this->visiblepath[] = $this->visiblename;
878 $this->path[] = $this->name;
883 // quick category lookup
884 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
885 return $this->category_cache[$name];
889 foreach($this->children as $childid=>$unused) {
890 if ($return = $this->children[$childid]->locate($name, $findpath)) {
895 if (!is_null($return) and $findpath) {
896 $return->visiblepath[] = $this->visiblename;
897 $return->path[] = $this->name;
906 * @param string query
907 * @return mixed array-object structure of found settings and pages
909 public function search($query) {
911 foreach ($this->children as $child) {
912 $subsearch = $child->search($query);
913 if (!is_array($subsearch)) {
914 debugging('Incorrect search result from '.$child->name);
917 $result = array_merge($result, $subsearch);
923 * Removes part_of_admin_tree object with internal name $name.
925 * @param string $name The internal name of the object we want to remove.
926 * @return bool success
928 public function prune($name) {
930 if ($this->name == $name) {
931 return false; //can not remove itself
934 foreach($this->children as $precedence => $child) {
935 if ($child->name == $name) {
936 // clear cache and delete self
937 if (is_array($this->category_cache)) {
938 while($this->category_cache) {
939 // delete the cache, but keep the original array address
940 array_pop($this->category_cache);
943 unset($this->children[$precedence]);
945 } else if ($this->children[$precedence]->prune($name)) {
953 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
955 * By default the new part of the tree is appended as the last child of the parent. You
956 * can specify a sibling node that the new part should be prepended to. If the given
957 * sibling is not found, the part is appended to the end (as it would be by default) and
958 * a developer debugging message is displayed.
960 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
961 * @param string $destinationame The internal name of the immediate parent that we want for $something.
962 * @param mixed $something A part_of_admin_tree or setting instance to be added.
963 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
964 * @return bool True if successfully added, false if $something can not be added.
966 public function add($parentname, $something, $beforesibling = null) {
967 $parent = $this->locate($parentname);
968 if (is_null($parent)) {
969 debugging('parent does not exist!');
973 if ($something instanceof part_of_admin_tree) {
974 if (!($parent instanceof parentable_part_of_admin_tree)) {
975 debugging('error - parts of tree can be inserted only into parentable parts');
978 if (debugging('', DEBUG_DEVELOPER) && !is_null($this->locate($something->name))) {
979 // The name of the node is already used, simply warn the developer that this should not happen.
980 // It is intentional to check for the debug level before performing the check.
981 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
983 if (is_null($beforesibling)) {
984 // Append $something as the parent's last child.
985 $parent->children[] = $something;
987 if (!is_string($beforesibling) or trim($beforesibling) === '') {
988 throw new coding_exception('Unexpected value of the beforesibling parameter');
990 // Try to find the position of the sibling.
991 $siblingposition = null;
992 foreach ($parent->children as $childposition => $child) {
993 if ($child->name === $beforesibling) {
994 $siblingposition = $childposition;
998 if (is_null($siblingposition)) {
999 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
1000 $parent->children[] = $something;
1002 $parent->children = array_merge(
1003 array_slice($parent->children, 0, $siblingposition),
1005 array_slice($parent->children, $siblingposition)
1009 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
1010 if (isset($this->category_cache[$something->name])) {
1011 debugging('Duplicate admin category name: '.$something->name);
1013 $this->category_cache[$something->name] = $something;
1014 $something->category_cache =& $this->category_cache;
1015 foreach ($something->children as $child) {
1016 // just in case somebody already added subcategories
1017 if ($child instanceof admin_category) {
1018 if (isset($this->category_cache[$child->name])) {
1019 debugging('Duplicate admin category name: '.$child->name);
1021 $this->category_cache[$child->name] = $child;
1022 $child->category_cache =& $this->category_cache;
1031 debugging('error - can not add this element');
1038 * Checks if the user has access to anything in this category.
1040 * @return bool True if the user has access to at least one child in this category, false otherwise.
1042 public function check_access() {
1043 foreach ($this->children as $child) {
1044 if ($child->check_access()) {
1052 * Is this category hidden in admin tree block?
1054 * @return bool True if hidden
1056 public function is_hidden() {
1057 return $this->hidden;
1061 * Show we display Save button at the page bottom?
1064 public function show_save() {
1065 foreach ($this->children as $child) {
1066 if ($child->show_save()) {
1076 * Root of admin settings tree, does not have any parent.
1078 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1080 class admin_root extends admin_category {
1081 /** @var array List of errors */
1083 /** @var string search query */
1085 /** @var bool full tree flag - true means all settings required, false only pages required */
1087 /** @var bool flag indicating loaded tree */
1089 /** @var mixed site custom defaults overriding defaults in settings files*/
1090 public $custom_defaults;
1093 * @param bool $fulltree true means all settings required,
1094 * false only pages required
1096 public function __construct($fulltree) {
1099 parent::__construct('root', get_string('administration'), false);
1100 $this->errors = array();
1102 $this->fulltree = $fulltree;
1103 $this->loaded = false;
1105 $this->category_cache = array();
1107 // load custom defaults if found
1108 $this->custom_defaults = null;
1109 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1110 if (is_readable($defaultsfile)) {
1111 $defaults = array();
1112 include($defaultsfile);
1113 if (is_array($defaults) and count($defaults)) {
1114 $this->custom_defaults = $defaults;
1120 * Empties children array, and sets loaded to false
1122 * @param bool $requirefulltree
1124 public function purge_children($requirefulltree) {
1125 $this->children = array();
1126 $this->fulltree = ($requirefulltree || $this->fulltree);
1127 $this->loaded = false;
1128 //break circular dependencies - this helps PHP 5.2
1129 while($this->category_cache) {
1130 array_pop($this->category_cache);
1132 $this->category_cache = array();
1138 * Links external PHP pages into the admin tree.
1140 * See detailed usage example at the top of this document (adminlib.php)
1142 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1144 class admin_externalpage implements part_of_admin_tree {
1146 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1149 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1150 public $visiblename;
1152 /** @var string The external URL that we should link to when someone requests this external page. */
1155 /** @var string The role capability/permission a user must have to access this external page. */
1156 public $req_capability;
1158 /** @var object The context in which capability/permission should be checked, default is site context. */
1161 /** @var bool hidden in admin tree block. */
1164 /** @var mixed either string or array of string */
1167 /** @var array list of visible names of page parents */
1168 public $visiblepath;
1171 * Constructor for adding an external page into the admin tree.
1173 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1174 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1175 * @param string $url The external URL that we should link to when someone requests this external page.
1176 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1177 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1178 * @param stdClass $context The context the page relates to. Not sure what happens
1179 * if you specify something other than system or front page. Defaults to system.
1181 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1182 $this->name = $name;
1183 $this->visiblename = $visiblename;
1185 if (is_array($req_capability)) {
1186 $this->req_capability = $req_capability;
1188 $this->req_capability = array($req_capability);
1190 $this->hidden = $hidden;
1191 $this->context = $context;
1195 * Returns a reference to the part_of_admin_tree object with internal name $name.
1197 * @param string $name The internal name of the object we want.
1198 * @param bool $findpath defaults to false
1199 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1201 public function locate($name, $findpath=false) {
1202 if ($this->name == $name) {
1204 $this->visiblepath = array($this->visiblename);
1205 $this->path = array($this->name);
1215 * This function always returns false, required function by interface
1217 * @param string $name
1220 public function prune($name) {
1225 * Search using query
1227 * @param string $query
1228 * @return mixed array-object structure of found settings and pages
1230 public function search($query) {
1232 if (strpos(strtolower($this->name), $query) !== false) {
1234 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1238 $result = new stdClass();
1239 $result->page = $this;
1240 $result->settings = array();
1241 return array($this->name => $result);
1248 * Determines if the current user has access to this external page based on $this->req_capability.
1250 * @return bool True if user has access, false otherwise.
1252 public function check_access() {
1254 $context = empty($this->context) ? context_system::instance() : $this->context;
1255 foreach($this->req_capability as $cap) {
1256 if (has_capability($cap, $context)) {
1264 * Is this external page hidden in admin tree block?
1266 * @return bool True if hidden
1268 public function is_hidden() {
1269 return $this->hidden;
1273 * Show we display Save button at the page bottom?
1276 public function show_save() {
1283 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1287 class admin_settingpage implements part_of_admin_tree {
1289 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1292 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1293 public $visiblename;
1295 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1298 /** @var string The role capability/permission a user must have to access this external page. */
1299 public $req_capability;
1301 /** @var object The context in which capability/permission should be checked, default is site context. */
1304 /** @var bool hidden in admin tree block. */
1307 /** @var mixed string of paths or array of strings of paths */
1310 /** @var array list of visible names of page parents */
1311 public $visiblepath;
1314 * see admin_settingpage for details of this function
1316 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1317 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1318 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1319 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1320 * @param stdClass $context The context the page relates to. Not sure what happens
1321 * if you specify something other than system or front page. Defaults to system.
1323 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1324 $this->settings = new stdClass();
1325 $this->name = $name;
1326 $this->visiblename = $visiblename;
1327 if (is_array($req_capability)) {
1328 $this->req_capability = $req_capability;
1330 $this->req_capability = array($req_capability);
1332 $this->hidden = $hidden;
1333 $this->context = $context;
1337 * see admin_category
1339 * @param string $name
1340 * @param bool $findpath
1341 * @return mixed Object (this) if name == this->name, else returns null
1343 public function locate($name, $findpath=false) {
1344 if ($this->name == $name) {
1346 $this->visiblepath = array($this->visiblename);
1347 $this->path = array($this->name);
1357 * Search string in settings page.
1359 * @param string $query
1362 public function search($query) {
1365 foreach ($this->settings as $setting) {
1366 if ($setting->is_related($query)) {
1367 $found[] = $setting;
1372 $result = new stdClass();
1373 $result->page = $this;
1374 $result->settings = $found;
1375 return array($this->name => $result);
1379 if (strpos(strtolower($this->name), $query) !== false) {
1381 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1385 $result = new stdClass();
1386 $result->page = $this;
1387 $result->settings = array();
1388 return array($this->name => $result);
1395 * This function always returns false, required by interface
1397 * @param string $name
1398 * @return bool Always false
1400 public function prune($name) {
1405 * adds an admin_setting to this admin_settingpage
1407 * 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
1408 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1410 * @param object $setting is the admin_setting object you want to add
1411 * @return bool true if successful, false if not
1413 public function add($setting) {
1414 if (!($setting instanceof admin_setting)) {
1415 debugging('error - not a setting instance');
1419 $this->settings->{$setting->name} = $setting;
1424 * see admin_externalpage
1426 * @return bool Returns true for yes false for no
1428 public function check_access() {
1430 $context = empty($this->context) ? context_system::instance() : $this->context;
1431 foreach($this->req_capability as $cap) {
1432 if (has_capability($cap, $context)) {
1440 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1441 * @return string Returns an XHTML string
1443 public function output_html() {
1444 $adminroot = admin_get_root();
1445 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1446 foreach($this->settings as $setting) {
1447 $fullname = $setting->get_full_name();
1448 if (array_key_exists($fullname, $adminroot->errors)) {
1449 $data = $adminroot->errors[$fullname]->data;
1451 $data = $setting->get_setting();
1452 // do not use defaults if settings not available - upgrade settings handles the defaults!
1454 $return .= $setting->output_html($data);
1456 $return .= '</fieldset>';
1461 * Is this settings page hidden in admin tree block?
1463 * @return bool True if hidden
1465 public function is_hidden() {
1466 return $this->hidden;
1470 * Show we display Save button at the page bottom?
1473 public function show_save() {
1474 foreach($this->settings as $setting) {
1475 if (empty($setting->nosave)) {
1485 * Admin settings class. Only exists on setting pages.
1486 * Read & write happens at this level; no authentication.
1488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1490 abstract class admin_setting {
1491 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1493 /** @var string localised name */
1494 public $visiblename;
1495 /** @var string localised long description in Markdown format */
1496 public $description;
1497 /** @var mixed Can be string or array of string */
1498 public $defaultsetting;
1500 public $updatedcallback;
1501 /** @var mixed can be String or Null. Null means main config table */
1502 public $plugin; // null means main config table
1503 /** @var bool true indicates this setting does not actually save anything, just information */
1504 public $nosave = false;
1505 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1506 public $affectsmodinfo = false;
1510 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1511 * or 'myplugin/mysetting' for ones in config_plugins.
1512 * @param string $visiblename localised name
1513 * @param string $description localised long description
1514 * @param mixed $defaultsetting string or array depending on implementation
1516 public function __construct($name, $visiblename, $description, $defaultsetting) {
1517 $this->parse_setting_name($name);
1518 $this->visiblename = $visiblename;
1519 $this->description = $description;
1520 $this->defaultsetting = $defaultsetting;
1524 * Set up $this->name and potentially $this->plugin
1526 * Set up $this->name and possibly $this->plugin based on whether $name looks
1527 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1528 * on the names, that is, output a developer debug warning if the name
1529 * contains anything other than [a-zA-Z0-9_]+.
1531 * @param string $name the setting name passed in to the constructor.
1533 private function parse_setting_name($name) {
1534 $bits = explode('/', $name);
1535 if (count($bits) > 2) {
1536 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1538 $this->name = array_pop($bits);
1539 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1540 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1542 if (!empty($bits)) {
1543 $this->plugin = array_pop($bits);
1544 if ($this->plugin === 'moodle') {
1545 $this->plugin = null;
1546 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1547 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1553 * Returns the fullname prefixed by the plugin
1556 public function get_full_name() {
1557 return 's_'.$this->plugin.'_'.$this->name;
1561 * Returns the ID string based on plugin and name
1564 public function get_id() {
1565 return 'id_s_'.$this->plugin.'_'.$this->name;
1569 * @param bool $affectsmodinfo If true, changes to this setting will
1570 * cause the course cache to be rebuilt
1572 public function set_affects_modinfo($affectsmodinfo) {
1573 $this->affectsmodinfo = $affectsmodinfo;
1577 * Returns the config if possible
1579 * @return mixed returns config if successful else null
1581 public function config_read($name) {
1583 if (!empty($this->plugin)) {
1584 $value = get_config($this->plugin, $name);
1585 return $value === false ? NULL : $value;
1588 if (isset($CFG->$name)) {
1597 * Used to set a config pair and log change
1599 * @param string $name
1600 * @param mixed $value Gets converted to string if not null
1601 * @return bool Write setting to config table
1603 public function config_write($name, $value) {
1604 global $DB, $USER, $CFG;
1606 if ($this->nosave) {
1610 // make sure it is a real change
1611 $oldvalue = get_config($this->plugin, $name);
1612 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1613 $value = is_null($value) ? null : (string)$value;
1615 if ($oldvalue === $value) {
1620 set_config($name, $value, $this->plugin);
1622 // Some admin settings affect course modinfo
1623 if ($this->affectsmodinfo) {
1624 // Clear course cache for all courses
1625 rebuild_course_cache(0, true);
1629 $log = new stdClass();
1630 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1631 $log->timemodified = time();
1632 $log->plugin = $this->plugin;
1634 $log->value = $value;
1635 $log->oldvalue = $oldvalue;
1636 $DB->insert_record('config_log', $log);
1638 return true; // BC only
1642 * Returns current value of this setting
1643 * @return mixed array or string depending on instance, NULL means not set yet
1645 public abstract function get_setting();
1648 * Returns default setting if exists
1649 * @return mixed array or string depending on instance; NULL means no default, user must supply
1651 public function get_defaultsetting() {
1652 $adminroot = admin_get_root(false, false);
1653 if (!empty($adminroot->custom_defaults)) {
1654 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1655 if (isset($adminroot->custom_defaults[$plugin])) {
1656 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1657 return $adminroot->custom_defaults[$plugin][$this->name];
1661 return $this->defaultsetting;
1667 * @param mixed $data string or array, must not be NULL
1668 * @return string empty string if ok, string error message otherwise
1670 public abstract function write_setting($data);
1673 * Return part of form with setting
1674 * This function should always be overwritten
1676 * @param mixed $data array or string depending on setting
1677 * @param string $query
1680 public function output_html($data, $query='') {
1681 // should be overridden
1686 * Function called if setting updated - cleanup, cache reset, etc.
1687 * @param string $functionname Sets the function name
1690 public function set_updatedcallback($functionname) {
1691 $this->updatedcallback = $functionname;
1695 * Is setting related to query text - used when searching
1696 * @param string $query
1699 public function is_related($query) {
1700 if (strpos(strtolower($this->name), $query) !== false) {
1703 if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1706 if (strpos(textlib::strtolower($this->description), $query) !== false) {
1709 $current = $this->get_setting();
1710 if (!is_null($current)) {
1711 if (is_string($current)) {
1712 if (strpos(textlib::strtolower($current), $query) !== false) {
1717 $default = $this->get_defaultsetting();
1718 if (!is_null($default)) {
1719 if (is_string($default)) {
1720 if (strpos(textlib::strtolower($default), $query) !== false) {
1731 * No setting - just heading and text.
1733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1735 class admin_setting_heading extends admin_setting {
1738 * not a setting, just text
1739 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1740 * @param string $heading heading
1741 * @param string $information text in box
1743 public function __construct($name, $heading, $information) {
1744 $this->nosave = true;
1745 parent::__construct($name, $heading, $information, '');
1749 * Always returns true
1750 * @return bool Always returns true
1752 public function get_setting() {
1757 * Always returns true
1758 * @return bool Always returns true
1760 public function get_defaultsetting() {
1765 * Never write settings
1766 * @return string Always returns an empty string
1768 public function write_setting($data) {
1769 // do not write any setting
1774 * Returns an HTML string
1775 * @return string Returns an HTML string
1777 public function output_html($data, $query='') {
1780 if ($this->visiblename != '') {
1781 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1783 if ($this->description != '') {
1784 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1792 * The most flexibly setting, user is typing text
1794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1796 class admin_setting_configtext extends admin_setting {
1798 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1800 /** @var int default field size */
1804 * Config text constructor
1806 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1807 * @param string $visiblename localised
1808 * @param string $description long localised info
1809 * @param string $defaultsetting
1810 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1811 * @param int $size default field size
1813 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1814 $this->paramtype = $paramtype;
1815 if (!is_null($size)) {
1816 $this->size = $size;
1818 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1820 parent::__construct($name, $visiblename, $description, $defaultsetting);
1824 * Return the setting
1826 * @return mixed returns config if successful else null
1828 public function get_setting() {
1829 return $this->config_read($this->name);
1832 public function write_setting($data) {
1833 if ($this->paramtype === PARAM_INT and $data === '') {
1834 // do not complain if '' used instead of 0
1837 // $data is a string
1838 $validated = $this->validate($data);
1839 if ($validated !== true) {
1842 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1846 * Validate data before storage
1847 * @param string data
1848 * @return mixed true if ok string if error found
1850 public function validate($data) {
1851 // allow paramtype to be a custom regex if it is the form of /pattern/
1852 if (preg_match('#^/.*/$#', $this->paramtype)) {
1853 if (preg_match($this->paramtype, $data)) {
1856 return get_string('validateerror', 'admin');
1859 } else if ($this->paramtype === PARAM_RAW) {
1863 $cleaned = clean_param($data, $this->paramtype);
1864 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1867 return get_string('validateerror', 'admin');
1873 * Return an XHTML string for the setting
1874 * @return string Returns an XHTML string
1876 public function output_html($data, $query='') {
1877 $default = $this->get_defaultsetting();
1879 return format_admin_setting($this, $this->visiblename,
1880 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1881 $this->description, true, '', $default, $query);
1887 * General text area without html editor.
1889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1891 class admin_setting_configtextarea extends admin_setting_configtext {
1896 * @param string $name
1897 * @param string $visiblename
1898 * @param string $description
1899 * @param mixed $defaultsetting string or array
1900 * @param mixed $paramtype
1901 * @param string $cols The number of columns to make the editor
1902 * @param string $rows The number of rows to make the editor
1904 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1905 $this->rows = $rows;
1906 $this->cols = $cols;
1907 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1911 * Returns an XHTML string for the editor
1913 * @param string $data
1914 * @param string $query
1915 * @return string XHTML string for the editor
1917 public function output_html($data, $query='') {
1918 $default = $this->get_defaultsetting();
1920 $defaultinfo = $default;
1921 if (!is_null($default) and $default !== '') {
1922 $defaultinfo = "\n".$default;
1925 return format_admin_setting($this, $this->visiblename,
1926 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1927 $this->description, true, '', $defaultinfo, $query);
1933 * General text area with html editor.
1935 class admin_setting_confightmleditor extends admin_setting_configtext {
1940 * @param string $name
1941 * @param string $visiblename
1942 * @param string $description
1943 * @param mixed $defaultsetting string or array
1944 * @param mixed $paramtype
1946 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1947 $this->rows = $rows;
1948 $this->cols = $cols;
1949 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1950 editors_head_setup();
1954 * Returns an XHTML string for the editor
1956 * @param string $data
1957 * @param string $query
1958 * @return string XHTML string for the editor
1960 public function output_html($data, $query='') {
1961 $default = $this->get_defaultsetting();
1963 $defaultinfo = $default;
1964 if (!is_null($default) and $default !== '') {
1965 $defaultinfo = "\n".$default;
1968 $editor = editors_get_preferred_editor(FORMAT_HTML);
1969 $editor->use_editor($this->get_id(), array('noclean'=>true));
1971 return format_admin_setting($this, $this->visiblename,
1972 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1973 $this->description, true, '', $defaultinfo, $query);
1979 * Password field, allows unmasking of password
1981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1983 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1986 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1987 * @param string $visiblename localised
1988 * @param string $description long localised info
1989 * @param string $defaultsetting default password
1991 public function __construct($name, $visiblename, $description, $defaultsetting) {
1992 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1996 * Returns XHTML for the field
1997 * Writes Javascript into the HTML below right before the last div
1999 * @todo Make javascript available through newer methods if possible
2000 * @param string $data Value for the field
2001 * @param string $query Passed as final argument for format_admin_setting
2002 * @return string XHTML field
2004 public function output_html($data, $query='') {
2005 $id = $this->get_id();
2006 $unmask = get_string('unmaskpassword', 'form');
2007 $unmaskjs = '<script type="text/javascript">
2009 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2011 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2013 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2015 var unmaskchb = document.createElement("input");
2016 unmaskchb.setAttribute("type", "checkbox");
2017 unmaskchb.setAttribute("id", "'.$id.'unmask");
2018 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2019 unmaskdiv.appendChild(unmaskchb);
2021 var unmasklbl = document.createElement("label");
2022 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2024 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2026 unmasklbl.setAttribute("for", "'.$id.'unmask");
2028 unmaskdiv.appendChild(unmasklbl);
2031 // ugly hack to work around the famous onchange IE bug
2032 unmaskchb.onclick = function() {this.blur();};
2033 unmaskdiv.onclick = function() {this.blur();};
2037 return format_admin_setting($this, $this->visiblename,
2038 '<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>',
2039 $this->description, true, '', NULL, $query);
2047 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2049 class admin_setting_configfile extends admin_setting_configtext {
2052 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2053 * @param string $visiblename localised
2054 * @param string $description long localised info
2055 * @param string $defaultdirectory default directory location
2057 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2058 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2062 * Returns XHTML for the field
2064 * Returns XHTML for the field and also checks whether the file
2065 * specified in $data exists using file_exists()
2067 * @param string $data File name and path to use in value attr
2068 * @param string $query
2069 * @return string XHTML field
2071 public function output_html($data, $query='') {
2072 $default = $this->get_defaultsetting();
2075 if (file_exists($data)) {
2076 $executable = '<span class="pathok">✔</span>';
2078 $executable = '<span class="patherror">✘</span>';
2084 return format_admin_setting($this, $this->visiblename,
2085 '<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>',
2086 $this->description, true, '', $default, $query);
2092 * Path to executable file
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configexecutable extends admin_setting_configfile {
2099 * Returns an XHTML field
2101 * @param string $data This is the value for the field
2102 * @param string $query
2103 * @return string XHTML field
2105 public function output_html($data, $query='') {
2106 $default = $this->get_defaultsetting();
2109 if (file_exists($data) and is_executable($data)) {
2110 $executable = '<span class="pathok">✔</span>';
2112 $executable = '<span class="patherror">✘</span>';
2118 return format_admin_setting($this, $this->visiblename,
2119 '<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>',
2120 $this->description, true, '', $default, $query);
2128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2130 class admin_setting_configdirectory extends admin_setting_configfile {
2133 * Returns an XHTML field
2135 * @param string $data This is the value for the field
2136 * @param string $query
2137 * @return string XHTML
2139 public function output_html($data, $query='') {
2140 $default = $this->get_defaultsetting();
2143 if (file_exists($data) and is_dir($data)) {
2144 $executable = '<span class="pathok">✔</span>';
2146 $executable = '<span class="patherror">✘</span>';
2152 return format_admin_setting($this, $this->visiblename,
2153 '<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>',
2154 $this->description, true, '', $default, $query);
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2164 class admin_setting_configcheckbox extends admin_setting {
2165 /** @var string Value used when checked */
2167 /** @var string Value used when not checked */
2172 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2173 * @param string $visiblename localised
2174 * @param string $description long localised info
2175 * @param string $defaultsetting
2176 * @param string $yes value used when checked
2177 * @param string $no value used when not checked
2179 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2180 parent::__construct($name, $visiblename, $description, $defaultsetting);
2181 $this->yes = (string)$yes;
2182 $this->no = (string)$no;
2186 * Retrieves the current setting using the objects name
2190 public function get_setting() {
2191 return $this->config_read($this->name);
2195 * Sets the value for the setting
2197 * Sets the value for the setting to either the yes or no values
2198 * of the object by comparing $data to yes
2200 * @param mixed $data Gets converted to str for comparison against yes value
2201 * @return string empty string or error
2203 public function write_setting($data) {
2204 if ((string)$data === $this->yes) { // convert to strings before comparison
2209 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2213 * Returns an XHTML checkbox field
2215 * @param string $data If $data matches yes then checkbox is checked
2216 * @param string $query
2217 * @return string XHTML field
2219 public function output_html($data, $query='') {
2220 $default = $this->get_defaultsetting();
2222 if (!is_null($default)) {
2223 if ((string)$default === $this->yes) {
2224 $defaultinfo = get_string('checkboxyes', 'admin');
2226 $defaultinfo = get_string('checkboxno', 'admin');
2229 $defaultinfo = NULL;
2232 if ((string)$data === $this->yes) { // convert to strings before comparison
2233 $checked = 'checked="checked"';
2238 return format_admin_setting($this, $this->visiblename,
2239 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2240 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2241 $this->description, true, '', $defaultinfo, $query);
2247 * Multiple checkboxes, each represents different value, stored in csv format
2249 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2251 class admin_setting_configmulticheckbox extends admin_setting {
2252 /** @var array Array of choices value=>label */
2256 * Constructor: uses parent::__construct
2258 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2259 * @param string $visiblename localised
2260 * @param string $description long localised info
2261 * @param array $defaultsetting array of selected
2262 * @param array $choices array of $value=>$label for each checkbox
2264 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2265 $this->choices = $choices;
2266 parent::__construct($name, $visiblename, $description, $defaultsetting);
2270 * This public function may be used in ancestors for lazy loading of choices
2272 * @todo Check if this function is still required content commented out only returns true
2273 * @return bool true if loaded, false if error
2275 public function load_choices() {
2277 if (is_array($this->choices)) {
2280 .... load choices here
2286 * Is setting related to query text - used when searching
2288 * @param string $query
2289 * @return bool true on related, false on not or failure
2291 public function is_related($query) {
2292 if (!$this->load_choices() or empty($this->choices)) {
2295 if (parent::is_related($query)) {
2299 foreach ($this->choices as $desc) {
2300 if (strpos(textlib::strtolower($desc), $query) !== false) {
2308 * Returns the current setting if it is set
2310 * @return mixed null if null, else an array
2312 public function get_setting() {
2313 $result = $this->config_read($this->name);
2315 if (is_null($result)) {
2318 if ($result === '') {
2321 $enabled = explode(',', $result);
2323 foreach ($enabled as $option) {
2324 $setting[$option] = 1;
2330 * Saves the setting(s) provided in $data
2332 * @param array $data An array of data, if not array returns empty str
2333 * @return mixed empty string on useless data or bool true=success, false=failed
2335 public function write_setting($data) {
2336 if (!is_array($data)) {
2337 return ''; // ignore it
2339 if (!$this->load_choices() or empty($this->choices)) {
2342 unset($data['xxxxx']);
2344 foreach ($data as $key => $value) {
2345 if ($value and array_key_exists($key, $this->choices)) {
2349 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2353 * Returns XHTML field(s) as required by choices
2355 * Relies on data being an array should data ever be another valid vartype with
2356 * acceptable value this may cause a warning/error
2357 * if (!is_array($data)) would fix the problem
2359 * @todo Add vartype handling to ensure $data is an array
2361 * @param array $data An array of checked values
2362 * @param string $query
2363 * @return string XHTML field
2365 public function output_html($data, $query='') {
2366 if (!$this->load_choices() or empty($this->choices)) {
2369 $default = $this->get_defaultsetting();
2370 if (is_null($default)) {
2373 if (is_null($data)) {
2377 $defaults = array();
2378 foreach ($this->choices as $key=>$description) {
2379 if (!empty($data[$key])) {
2380 $checked = 'checked="checked"';
2384 if (!empty($default[$key])) {
2385 $defaults[] = $description;
2388 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2389 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2392 if (is_null($default)) {
2393 $defaultinfo = NULL;
2394 } else if (!empty($defaults)) {
2395 $defaultinfo = implode(', ', $defaults);
2397 $defaultinfo = get_string('none');
2400 $return = '<div class="form-multicheckbox">';
2401 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2404 foreach ($options as $option) {
2405 $return .= '<li>'.$option.'</li>';
2409 $return .= '</div>';
2411 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2418 * Multiple checkboxes 2, value stored as string 00101011
2420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2422 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2425 * Returns the setting if set
2427 * @return mixed null if not set, else an array of set settings
2429 public function get_setting() {
2430 $result = $this->config_read($this->name);
2431 if (is_null($result)) {
2434 if (!$this->load_choices()) {
2437 $result = str_pad($result, count($this->choices), '0');
2438 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2440 foreach ($this->choices as $key=>$unused) {
2441 $value = array_shift($result);
2450 * Save setting(s) provided in $data param
2452 * @param array $data An array of settings to save
2453 * @return mixed empty string for bad data or bool true=>success, false=>error
2455 public function write_setting($data) {
2456 if (!is_array($data)) {
2457 return ''; // ignore it
2459 if (!$this->load_choices() or empty($this->choices)) {
2463 foreach ($this->choices as $key=>$unused) {
2464 if (!empty($data[$key])) {
2470 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2476 * Select one value from list
2478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2480 class admin_setting_configselect extends admin_setting {
2481 /** @var array Array of choices value=>label */
2486 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2487 * @param string $visiblename localised
2488 * @param string $description long localised info
2489 * @param string|int $defaultsetting
2490 * @param array $choices array of $value=>$label for each selection
2492 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2493 $this->choices = $choices;
2494 parent::__construct($name, $visiblename, $description, $defaultsetting);
2498 * This function may be used in ancestors for lazy loading of choices
2500 * Override this method if loading of choices is expensive, such
2501 * as when it requires multiple db requests.
2503 * @return bool true if loaded, false if error
2505 public function load_choices() {
2507 if (is_array($this->choices)) {
2510 .... load choices here
2516 * Check if this is $query is related to a choice
2518 * @param string $query
2519 * @return bool true if related, false if not
2521 public function is_related($query) {
2522 if (parent::is_related($query)) {
2525 if (!$this->load_choices()) {
2528 foreach ($this->choices as $key=>$value) {
2529 if (strpos(textlib::strtolower($key), $query) !== false) {
2532 if (strpos(textlib::strtolower($value), $query) !== false) {
2540 * Return the setting
2542 * @return mixed returns config if successful else null
2544 public function get_setting() {
2545 return $this->config_read($this->name);
2551 * @param string $data
2552 * @return string empty of error string
2554 public function write_setting($data) {
2555 if (!$this->load_choices() or empty($this->choices)) {
2558 if (!array_key_exists($data, $this->choices)) {
2559 return ''; // ignore it
2562 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2566 * Returns XHTML select field
2568 * Ensure the options are loaded, and generate the XHTML for the select
2569 * element and any warning message. Separating this out from output_html
2570 * makes it easier to subclass this class.
2572 * @param string $data the option to show as selected.
2573 * @param string $current the currently selected option in the database, null if none.
2574 * @param string $default the default selected option.
2575 * @return array the HTML for the select element, and a warning message.
2577 public function output_select_html($data, $current, $default, $extraname = '') {
2578 if (!$this->load_choices() or empty($this->choices)) {
2579 return array('', '');
2583 if (is_null($current)) {
2585 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2587 } else if (!array_key_exists($current, $this->choices)) {
2588 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2589 if (!is_null($default) and $data == $current) {
2590 $data = $default; // use default instead of first value when showing the form
2594 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2595 foreach ($this->choices as $key => $value) {
2596 // the string cast is needed because key may be integer - 0 is equal to most strings!
2597 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2599 $selecthtml .= '</select>';
2600 return array($selecthtml, $warning);
2604 * Returns XHTML select field and wrapping div(s)
2606 * @see output_select_html()
2608 * @param string $data the option to show as selected
2609 * @param string $query
2610 * @return string XHTML field and wrapping div
2612 public function output_html($data, $query='') {
2613 $default = $this->get_defaultsetting();
2614 $current = $this->get_setting();
2616 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2621 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2622 $defaultinfo = $this->choices[$default];
2624 $defaultinfo = NULL;
2627 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2629 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2635 * Select multiple items from list
2637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2639 class admin_setting_configmultiselect extends admin_setting_configselect {
2642 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2643 * @param string $visiblename localised
2644 * @param string $description long localised info
2645 * @param array $defaultsetting array of selected items
2646 * @param array $choices array of $value=>$label for each list item
2648 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2649 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2653 * Returns the select setting(s)
2655 * @return mixed null or array. Null if no settings else array of setting(s)
2657 public function get_setting() {
2658 $result = $this->config_read($this->name);
2659 if (is_null($result)) {
2662 if ($result === '') {
2665 return explode(',', $result);
2669 * Saves setting(s) provided through $data
2671 * Potential bug in the works should anyone call with this function
2672 * using a vartype that is not an array
2674 * @param array $data
2676 public function write_setting($data) {
2677 if (!is_array($data)) {
2678 return ''; //ignore it
2680 if (!$this->load_choices() or empty($this->choices)) {
2684 unset($data['xxxxx']);
2687 foreach ($data as $value) {
2688 if (!array_key_exists($value, $this->choices)) {
2689 continue; // ignore it
2694 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2698 * Is setting related to query text - used when searching
2700 * @param string $query
2701 * @return bool true if related, false if not
2703 public function is_related($query) {
2704 if (!$this->load_choices() or empty($this->choices)) {
2707 if (parent::is_related($query)) {
2711 foreach ($this->choices as $desc) {
2712 if (strpos(textlib::strtolower($desc), $query) !== false) {
2720 * Returns XHTML multi-select field
2722 * @todo Add vartype handling to ensure $data is an array
2723 * @param array $data Array of values to select by default
2724 * @param string $query
2725 * @return string XHTML multi-select field
2727 public function output_html($data, $query='') {
2728 if (!$this->load_choices() or empty($this->choices)) {
2731 $choices = $this->choices;
2732 $default = $this->get_defaultsetting();
2733 if (is_null($default)) {
2736 if (is_null($data)) {
2740 $defaults = array();
2741 $size = min(10, count($this->choices));
2742 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2743 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2744 foreach ($this->choices as $key => $description) {
2745 if (in_array($key, $data)) {
2746 $selected = 'selected="selected"';
2750 if (in_array($key, $default)) {
2751 $defaults[] = $description;
2754 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2757 if (is_null($default)) {
2758 $defaultinfo = NULL;
2759 } if (!empty($defaults)) {
2760 $defaultinfo = implode(', ', $defaults);
2762 $defaultinfo = get_string('none');
2765 $return .= '</select></div>';
2766 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2773 * This is a liiitle bit messy. we're using two selects, but we're returning
2774 * them as an array named after $name (so we only use $name2 internally for the setting)
2776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2778 class admin_setting_configtime extends admin_setting {
2779 /** @var string Used for setting second select (minutes) */
2784 * @param string $hoursname setting for hours
2785 * @param string $minutesname setting for hours
2786 * @param string $visiblename localised
2787 * @param string $description long localised info
2788 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2790 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2791 $this->name2 = $minutesname;
2792 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2796 * Get the selected time
2798 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2800 public function get_setting() {
2801 $result1 = $this->config_read($this->name);
2802 $result2 = $this->config_read($this->name2);
2803 if (is_null($result1) or is_null($result2)) {
2807 return array('h' => $result1, 'm' => $result2);
2811 * Store the time (hours and minutes)
2813 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2814 * @return bool true if success, false if not
2816 public function write_setting($data) {
2817 if (!is_array($data)) {
2821 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2822 return ($result ? '' : get_string('errorsetting', 'admin'));
2826 * Returns XHTML time select fields
2828 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2829 * @param string $query
2830 * @return string XHTML time select fields and wrapping div(s)
2832 public function output_html($data, $query='') {
2833 $default = $this->get_defaultsetting();
2835 if (is_array($default)) {
2836 $defaultinfo = $default['h'].':'.$default['m'];
2838 $defaultinfo = NULL;
2841 $return = '<div class="form-time defaultsnext">'.
2842 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2843 for ($i = 0; $i < 24; $i++) {
2844 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2846 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2847 for ($i = 0; $i < 60; $i += 5) {
2848 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2850 $return .= '</select></div>';
2851 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2858 * Seconds duration setting.
2860 * @copyright 2012 Petr Skoda (http://skodak.org)
2861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2863 class admin_setting_configduration extends admin_setting {
2865 /** @var int default duration unit */
2866 protected $defaultunit;
2870 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2871 * or 'myplugin/mysetting' for ones in config_plugins.
2872 * @param string $visiblename localised name
2873 * @param string $description localised long description
2874 * @param mixed $defaultsetting string or array depending on implementation
2875 * @param int $defaultunit - day, week, etc. (in seconds)
2877 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
2878 if (is_number($defaultsetting)) {
2879 $defaultsetting = self::parse_seconds($defaultsetting);
2881 $units = self::get_units();
2882 if (isset($units[$defaultunit])) {
2883 $this->defaultunit = $defaultunit;
2885 $this->defaultunit = 86400;
2887 parent::__construct($name, $visiblename, $description, $defaultsetting);
2891 * Returns selectable units.
2895 protected static function get_units() {
2897 604800 => get_string('weeks'),
2898 86400 => get_string('days'),
2899 3600 => get_string('hours'),
2900 60 => get_string('minutes'),
2901 1 => get_string('seconds'),
2906 * Converts seconds to some more user friendly string.
2908 * @param int $seconds
2911 protected static function get_duration_text($seconds) {
2912 if (empty($seconds)) {
2913 return get_string('none');
2915 $data = self::parse_seconds($seconds);
2916 switch ($data['u']) {
2918 return get_string('numweeks', '', $data['v']);
2920 return get_string('numdays', '', $data['v']);
2922 return get_string('numhours', '', $data['v']);
2924 return get_string('numminutes', '', $data['v']);
2926 return get_string('numseconds', '', $data['v']*$data['u']);
2931 * Finds suitable units for given duration.
2933 * @param int $seconds
2936 protected static function parse_seconds($seconds) {
2937 foreach (self::get_units() as $unit => $unused) {
2938 if ($seconds % $unit === 0) {
2939 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
2942 return array('v'=>(int)$seconds, 'u'=>1);
2946 * Get the selected duration as array.
2948 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
2950 public function get_setting() {
2951 $seconds = $this->config_read($this->name);
2952 if (is_null($seconds)) {
2956 return self::parse_seconds($seconds);
2960 * Store the duration as seconds.
2962 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2963 * @return bool true if success, false if not
2965 public function write_setting($data) {
2966 if (!is_array($data)) {
2970 $seconds = (int)($data['v']*$data['u']);
2972 return get_string('errorsetting', 'admin');
2975 $result = $this->config_write($this->name, $seconds);
2976 return ($result ? '' : get_string('errorsetting', 'admin'));
2980 * Returns duration text+select fields.
2982 * @param array $data Must be form 'v'=>xx, 'u'=>xx
2983 * @param string $query
2984 * @return string duration text+select fields and wrapping div(s)
2986 public function output_html($data, $query='') {
2987 $default = $this->get_defaultsetting();
2989 if (is_number($default)) {
2990 $defaultinfo = self::get_duration_text($default);
2991 } else if (is_array($default)) {
2992 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
2994 $defaultinfo = null;
2997 $units = self::get_units();
2999 $return = '<div class="form-duration defaultsnext">';
3000 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3001 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3002 foreach ($units as $val => $text) {
3004 if ($data['v'] == 0) {
3005 if ($val == $this->defaultunit) {
3006 $selected = ' selected="selected"';
3008 } else if ($val == $data['u']) {
3009 $selected = ' selected="selected"';
3011 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3013 $return .= '</select></div>';
3014 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3020 * Used to validate a textarea used for ip addresses
3022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3024 class admin_setting_configiplist extends admin_setting_configtextarea {
3027 * Validate the contents of the textarea as IP addresses
3029 * Used to validate a new line separated list of IP addresses collected from
3030 * a textarea control
3032 * @param string $data A list of IP Addresses separated by new lines
3033 * @return mixed bool true for success or string:error on failure
3035 public function validate($data) {
3037 $ips = explode("\n", $data);
3042 foreach($ips as $ip) {
3044 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3045 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3046 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3056 return get_string('validateerror', 'admin');
3063 * An admin setting for selecting one or more users who have a capability
3064 * in the system context
3066 * An admin setting for selecting one or more users, who have a particular capability
3067 * in the system context. Warning, make sure the list will never be too long. There is
3068 * no paging or searching of this list.
3070 * To correctly get a list of users from this config setting, you need to call the
3071 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3075 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3076 /** @var string The capabilities name */
3077 protected $capability;
3078 /** @var int include admin users too */
3079 protected $includeadmins;
3084 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3085 * @param string $visiblename localised name
3086 * @param string $description localised long description
3087 * @param array $defaultsetting array of usernames
3088 * @param string $capability string capability name.
3089 * @param bool $includeadmins include administrators
3091 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3092 $this->capability = $capability;
3093 $this->includeadmins = $includeadmins;
3094 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3098 * Load all of the uses who have the capability into choice array
3100 * @return bool Always returns true
3102 function load_choices() {
3103 if (is_array($this->choices)) {
3106 list($sort, $sortparams) = users_order_by_sql('u');
3107 if (!empty($sortparams)) {
3108 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3109 'This is unexpected, and a problem because there is no way to pass these ' .
3110 'parameters to get_users_by_capability. See MDL-34657.');
3112 $users = get_users_by_capability(context_system::instance(),
3113 $this->capability, 'u.id,u.username,u.firstname,u.lastname', $sort);
3114 $this->choices = array(
3115 '$@NONE@$' => get_string('nobody'),
3116 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3118 if ($this->includeadmins) {
3119 $admins = get_admins();
3120 foreach ($admins as $user) {
3121 $this->choices[$user->id] = fullname($user);
3124 if (is_array($users)) {
3125 foreach ($users as $user) {
3126 $this->choices[$user->id] = fullname($user);
3133 * Returns the default setting for class
3135 * @return mixed Array, or string. Empty string if no default
3137 public function get_defaultsetting() {
3138 $this->load_choices();
3139 $defaultsetting = parent::get_defaultsetting();
3140 if (empty($defaultsetting)) {
3141 return array('$@NONE@$');
3142 } else if (array_key_exists($defaultsetting, $this->choices)) {
3143 return $defaultsetting;
3150 * Returns the current setting
3152 * @return mixed array or string
3154 public function get_setting() {
3155 $result = parent::get_setting();
3156 if ($result === null) {
3157 // this is necessary for settings upgrade
3160 if (empty($result)) {
3161 $result = array('$@NONE@$');
3167 * Save the chosen setting provided as $data
3169 * @param array $data
3170 * @return mixed string or array
3172 public function write_setting($data) {
3173 // If all is selected, remove any explicit options.
3174 if (in_array('$@ALL@$', $data)) {
3175 $data = array('$@ALL@$');
3177 // None never needs to be written to the DB.
3178 if (in_array('$@NONE@$', $data)) {
3179 unset($data[array_search('$@NONE@$', $data)]);
3181 return parent::write_setting($data);
3187 * Special checkbox for calendar - resets SESSION vars.
3189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3191 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3193 * Calls the parent::__construct with default values
3195 * name => calendar_adminseesall
3196 * visiblename => get_string('adminseesall', 'admin')
3197 * description => get_string('helpadminseesall', 'admin')
3198 * defaultsetting => 0
3200 public function __construct() {
3201 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3202 get_string('helpadminseesall', 'admin'), '0');
3206 * Stores the setting passed in $data
3208 * @param mixed gets converted to string for comparison
3209 * @return string empty string or error message
3211 public function write_setting($data) {
3213 return parent::write_setting($data);
3218 * Special select for settings that are altered in setup.php and can not be altered on the fly
3220 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3222 class admin_setting_special_selectsetup extends admin_setting_configselect {
3224 * Reads the setting directly from the database
3228 public function get_setting() {
3229 // read directly from db!
3230 return get_config(NULL, $this->name);
3234 * Save the setting passed in $data
3236 * @param string $data The setting to save
3237 * @return string empty or error message
3239 public function write_setting($data) {
3241 // do not change active CFG setting!
3242 $current = $CFG->{$this->name};
3243 $result = parent::write_setting($data);
3244 $CFG->{$this->name} = $current;
3251 * Special select for frontpage - stores data in course table
3253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3255 class admin_setting_sitesetselect extends admin_setting_configselect {
3257 * Returns the site name for the selected site
3260 * @return string The site name of the selected site
3262 public function get_setting() {
3263 $site = course_get_format(get_site())->get_course();
3264 return $site->{$this->name};
3268 * Updates the database and save the setting
3270 * @param string data
3271 * @return string empty or error message
3273 public function write_setting($data) {
3275 if (!in_array($data, array_keys($this->choices))) {
3276 return get_string('errorsetting', 'admin');
3278 $record = new stdClass();
3279 $record->id = SITEID;
3280 $temp = $this->name;
3281 $record->$temp = $data;
3282 $record->timemodified = time();
3284 $SITE->{$this->name} = $data;
3285 course_get_format($SITE)->update_course_format_options($record);
3286 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3292 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3295 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3297 class admin_setting_bloglevel extends admin_setting_configselect {
3299 * Updates the database and save the setting
3301 * @param string data
3302 * @return string empty or error message
3304 public function write_setting($data) {
3307 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3308 foreach ($blogblocks as $block) {
3309 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3312 // reenable all blocks only when switching from disabled blogs
3313 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3314 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3315 foreach ($blogblocks as $block) {
3316 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3320 return parent::write_setting($data);
3326 * Special select - lists on the frontpage - hacky
3328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3330 class admin_setting_courselist_frontpage extends admin_setting {
3331 /** @var array Array of choices value=>label */
3335 * Construct override, requires one param
3337 * @param bool $loggedin Is the user logged in
3339 public function __construct($loggedin) {
3341 require_once($CFG->dirroot.'/course/lib.php');
3342 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3343 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3344 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3345 $defaults = array(FRONTPAGECOURSELIST);
3346 parent::__construct($name, $visiblename, $description, $defaults);
3350 * Loads the choices available
3352 * @return bool always returns true
3354 public function load_choices() {
3356 if (is_array($this->choices)) {
3359 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3360 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3361 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3362 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3363 'none' => get_string('none'));
3364 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3365 unset($this->choices[FRONTPAGECOURSELIST]);
3371 * Returns the selected settings
3373 * @param mixed array or setting or null
3375 public function get_setting() {
3376 $result = $this->config_read($this->name);
3377 if (is_null($result)) {
3380 if ($result === '') {
3383 return explode(',', $result);
3387 * Save the selected options
3389 * @param array $data
3390 * @return mixed empty string (data is not an array) or bool true=success false=failure
3392 public function write_setting($data) {
3393 if (!is_array($data)) {
3396 $this->load_choices();
3398 foreach($data as $datum) {
3399 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3402 $save[$datum] = $datum; // no duplicates
3404 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3408 * Return XHTML select field and wrapping div
3410 * @todo Add vartype handling to make sure $data is an array
3411 * @param array $data Array of elements to select by default
3412 * @return string XHTML select field and wrapping div
3414 public function output_html($data, $query='') {
3415 $this->load_choices();
3416 $currentsetting = array();
3417 foreach ($data as $key) {
3418 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3419 $currentsetting[] = $key; // already selected first
3423 $return = '<div class="form-group">';
3424 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3425 if (!array_key_exists($i, $currentsetting)) {
3426 $currentsetting[$i] = 'none'; //none
3428 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3429 foreach ($this->choices as $key => $value) {
3430 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3432 $return .= '</select>';
3433 if ($i !== count($this->choices) - 2) {
3434 $return .= '<br />';
3437 $return .= '</div>';
3439 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3445 * Special checkbox for frontpage - stores data in course table
3447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3449 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3451 * Returns the current sites name
3455 public function get_setting() {
3456 $site = course_get_format(get_site())->get_course();
3457 return $site->{$this->name};
3461 * Save the selected setting
3463 * @param string $data The selected site
3464 * @return string empty string or error message
3466 public function write_setting($data) {
3468 $record = new stdClass();
3469 $record->id = $SITE->id;
3470 $record->{$this->name} = ($data == '1' ? 1 : 0);
3471 $record->timemodified = time();
3473 $SITE->{$this->name} = $data;
3474 course_get_format($SITE)->update_course_format_options($record);
3475 $DB->update_record('course', $record);
3476 // There is something wrong in cache updates somewhere, let's reset everything.
3477 format_base::reset_course_cache();
3483 * Special text for frontpage - stores data in course table.
3484 * Empty string means not set here. Manual setting is required.
3486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3488 class admin_setting_sitesettext extends admin_setting_configtext {
3490 * Return the current setting
3492 * @return mixed string or null
3494 public function get_setting() {
3495 $site = course_get_format(get_site())->get_course();
3496 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3500 * Validate the selected data
3502 * @param string $data The selected value to validate
3503 * @return mixed true or message string
3505 public function validate($data) {
3506 $cleaned = clean_param($data, PARAM_TEXT);
3507 if ($cleaned === '') {
3508 return get_string('required');
3510 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3513 return get_string('validateerror', 'admin');
3518 * Save the selected setting
3520 * @param string $data The selected value
3521 * @return string empty or error message
3523 public function write_setting($data) {
3525 $data = trim($data);
3526 $validated = $this->validate($data);
3527 if ($validated !== true) {
3531 $record = new stdClass();
3532 $record->id = $SITE->id;
3533 $record->{$this->name} = $data;
3534 $record->timemodified = time();
3536 $SITE->{$this->name} = $data;
3537 course_get_format($SITE)->update_course_format_options($record);
3538 $DB->update_record('course', $record);
3539 // There is something wrong in cache updates somewhere, let's reset everything.
3540 format_base::reset_course_cache();
3547 * Special text editor for site description.
3549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3551 class admin_setting_special_frontpagedesc extends admin_setting {
3553 * Calls parent::__construct with specific arguments
3555 public function __construct() {
3556 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3557 editors_head_setup();
3561 * Return the current setting
3562 * @return string The current setting
3564 public function get_setting() {
3565 $site = course_get_format(get_site())->get_course();
3566 return $site->{$this->name};
3570 * Save the new setting
3572 * @param string $data The new value to save
3573 * @return string empty or error message
3575 public function write_setting($data) {
3577 $record = new stdClass();
3578 $record->id = $SITE->id;
3579 $record->{$this->name} = $data;
3580 $record->timemodified = time();
3581 $SITE->{$this->name} = $data;
3582 course_get_format($SITE)->update_course_format_options($record);
3583 $DB->update_record('course', $record);
3584 // There is something wrong in cache updates somewhere, let's reset everything.
3585 format_base::reset_course_cache();
3590 * Returns XHTML for the field plus wrapping div
3592 * @param string $data The current value
3593 * @param string $query
3594 * @return string The XHTML output
3596 public function output_html($data, $query='') {
3599 $CFG->adminusehtmleditor = can_use_html_editor();
3600 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3602 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3608 * Administration interface for emoticon_manager settings.
3610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3612 class admin_setting_emoticons extends admin_setting {
3615 * Calls parent::__construct with specific args
3617 public function __construct() {
3620 $manager = get_emoticon_manager();
3621 $defaults = $this->prepare_form_data($manager->default_emoticons());
3622 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3626 * Return the current setting(s)
3628 * @return array Current settings array
3630 public function get_setting() {
3633 $manager = get_emoticon_manager();
3635 $config = $this->config_read($this->name);
3636 if (is_null($config)) {
3640 $config = $manager->decode_stored_config($config);
3641 if (is_null($config)) {
3645 return $this->prepare_form_data($config);
3649 * Save selected settings
3651 * @param array $data Array of settings to save
3654 public function write_setting($data) {
3656 $manager = get_emoticon_manager();
3657 $emoticons = $this->process_form_data($data);
3659 if ($emoticons === false) {
3663 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3664 return ''; // success
3666 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');