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 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
328 * Returns the version of installed component
330 * @param string $component component name
331 * @param string $source either 'disk' or 'installed' - where to get the version information from
332 * @return string|bool version number or false if the component is not found
334 function get_component_version($component, $source='installed') {
337 list($type, $name) = normalize_component($component);
339 // moodle core or a core subsystem
340 if ($type === 'core') {
341 if ($source === 'installed') {
342 if (empty($CFG->version)) {
345 return $CFG->version;
348 if (!is_readable($CFG->dirroot.'/version.php')) {
351 $version = null; //initialize variable for IDEs
352 include($CFG->dirroot.'/version.php');
359 if ($type === 'mod') {
360 if ($source === 'installed') {
361 return $DB->get_field('modules', 'version', array('name'=>$name));
363 $mods = get_plugin_list('mod');
364 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
367 $module = new stdclass();
368 include($mods[$name].'/version.php');
369 return $module->version;
375 if ($type === 'block') {
376 if ($source === 'installed') {
377 return $DB->get_field('block', 'version', array('name'=>$name));
379 $blocks = get_plugin_list('block');
380 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
383 $plugin = new stdclass();
384 include($blocks[$name].'/version.php');
385 return $plugin->version;
390 // all other plugin types
391 if ($source === 'installed') {
392 return get_config($type.'_'.$name, 'version');
394 $plugins = get_plugin_list($type);
395 if (empty($plugins[$name])) {
398 $plugin = new stdclass();
399 include($plugins[$name].'/version.php');
400 return $plugin->version;
406 * Delete all plugin tables
408 * @param string $name Name of plugin, used as table prefix
409 * @param string $file Path to install.xml file
410 * @param bool $feedback defaults to true
411 * @return bool Always returns true
413 function drop_plugin_tables($name, $file, $feedback=true) {
416 // first try normal delete
417 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
421 // then try to find all tables that start with name and are not in any xml file
422 $used_tables = get_used_table_names();
424 $tables = $DB->get_tables();
426 /// Iterate over, fixing id fields as necessary
427 foreach ($tables as $table) {
428 if (in_array($table, $used_tables)) {
432 if (strpos($table, $name) !== 0) {
436 // found orphan table --> delete it
437 if ($DB->get_manager()->table_exists($table)) {
438 $xmldb_table = new xmldb_table($table);
439 $DB->get_manager()->drop_table($xmldb_table);
447 * Returns names of all known tables == tables that moodle knows about.
449 * @return array Array of lowercase table names
451 function get_used_table_names() {
452 $table_names = array();
453 $dbdirs = get_db_directories();
455 foreach ($dbdirs as $dbdir) {
456 $file = $dbdir.'/install.xml';
458 $xmldb_file = new xmldb_file($file);
460 if (!$xmldb_file->fileExists()) {
464 $loaded = $xmldb_file->loadXMLStructure();
465 $structure = $xmldb_file->getStructure();
467 if ($loaded and $tables = $structure->getTables()) {
468 foreach($tables as $table) {
469 $table_names[] = strtolower($table->getName());
478 * Returns list of all directories where we expect install.xml files
479 * @return array Array of paths
481 function get_db_directories() {
486 /// First, the main one (lib/db)
487 $dbdirs[] = $CFG->libdir.'/db';
489 /// Then, all the ones defined by get_plugin_types()
490 $plugintypes = get_plugin_types();
491 foreach ($plugintypes as $plugintype => $pluginbasedir) {
492 if ($plugins = get_plugin_list($plugintype)) {
493 foreach ($plugins as $plugin => $plugindir) {
494 $dbdirs[] = $plugindir.'/db';
503 * Try to obtain or release the cron lock.
504 * @param string $name name of lock
505 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
506 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
507 * @return bool true if lock obtained
509 function set_cron_lock($name, $until, $ignorecurrent=false) {
512 debugging("Tried to get a cron lock for a null fieldname");
516 // remove lock by force == remove from config table
517 if (is_null($until)) {
518 set_config($name, null);
522 if (!$ignorecurrent) {
523 // read value from db - other processes might have changed it
524 $value = $DB->get_field('config', 'value', array('name'=>$name));
526 if ($value and $value > time()) {
532 set_config($name, $until);
537 * Test if and critical warnings are present
540 function admin_critical_warnings_present() {
543 if (!has_capability('moodle/site:config', context_system::instance())) {
547 if (!isset($SESSION->admin_critical_warning)) {
548 $SESSION->admin_critical_warning = 0;
549 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
550 $SESSION->admin_critical_warning = 1;
554 return $SESSION->admin_critical_warning;
558 * Detects if float supports at least 10 decimal digits
560 * Detects if float supports at least 10 decimal digits
561 * and also if float-->string conversion works as expected.
563 * @return bool true if problem found
565 function is_float_problem() {
566 $num1 = 2009010200.01;
567 $num2 = 2009010200.02;
569 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
573 * Try to verify that dataroot is not accessible from web.
575 * Try to verify that dataroot is not accessible from web.
576 * It is not 100% correct but might help to reduce number of vulnerable sites.
577 * Protection from httpd.conf and .htaccess is not detected properly.
579 * @uses INSECURE_DATAROOT_WARNING
580 * @uses INSECURE_DATAROOT_ERROR
581 * @param bool $fetchtest try to test public access by fetching file, default false
582 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
584 function is_dataroot_insecure($fetchtest=false) {
587 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
589 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
590 $rp = strrev(trim($rp, '/'));
591 $rp = explode('/', $rp);
593 if (strpos($siteroot, '/'.$r.'/') === 0) {
594 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
596 break; // probably alias root
600 $siteroot = strrev($siteroot);
601 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
603 if (strpos($dataroot, $siteroot) !== 0) {
608 return INSECURE_DATAROOT_WARNING;
611 // now try all methods to fetch a test file using http protocol
613 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
614 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
615 $httpdocroot = $matches[1];
616 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
617 make_upload_directory('diag');
618 $testfile = $CFG->dataroot.'/diag/public.txt';
619 if (!file_exists($testfile)) {
620 file_put_contents($testfile, 'test file, do not delete');
622 $teststr = trim(file_get_contents($testfile));
623 if (empty($teststr)) {
625 return INSECURE_DATAROOT_WARNING;
628 $testurl = $datarooturl.'/diag/public.txt';
629 if (extension_loaded('curl') and
630 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
631 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
632 ($ch = @curl_init($testurl)) !== false) {
633 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
634 curl_setopt($ch, CURLOPT_HEADER, false);
635 $data = curl_exec($ch);
636 if (!curl_errno($ch)) {
638 if ($data === $teststr) {
640 return INSECURE_DATAROOT_ERROR;
646 if ($data = @file_get_contents($testurl)) {
648 if ($data === $teststr) {
649 return INSECURE_DATAROOT_ERROR;
653 preg_match('|https?://([^/]+)|i', $testurl, $matches);
654 $sitename = $matches[1];
656 if ($fp = @fsockopen($sitename, 80, $error)) {
657 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
658 $localurl = $matches[1];
659 $out = "GET $localurl HTTP/1.1\r\n";
660 $out .= "Host: $sitename\r\n";
661 $out .= "Connection: Close\r\n\r\n";
667 $data .= fgets($fp, 1024);
668 } else if (@fgets($fp, 1024) === "\r\n") {
674 if ($data === $teststr) {
675 return INSECURE_DATAROOT_ERROR;
679 return INSECURE_DATAROOT_WARNING;
683 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
685 function enable_cli_maintenance_mode() {
688 if (file_exists("$CFG->dataroot/climaintenance.html")) {
689 unlink("$CFG->dataroot/climaintenance.html");
692 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
693 $data = $CFG->maintenance_message;
694 $data = bootstrap_renderer::early_error_content($data, null, null, null);
695 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
697 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
698 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
701 $data = get_string('sitemaintenance', 'admin');
702 $data = bootstrap_renderer::early_error_content($data, null, null, null);
703 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
706 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
707 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
710 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
714 * Interface for anything appearing in the admin tree
716 * The interface that is implemented by anything that appears in the admin tree
717 * block. It forces inheriting classes to define a method for checking user permissions
718 * and methods for finding something in the admin tree.
720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
722 interface part_of_admin_tree {
725 * Finds a named part_of_admin_tree.
727 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
728 * and not parentable_part_of_admin_tree, then this function should only check if
729 * $this->name matches $name. If it does, it should return a reference to $this,
730 * otherwise, it should return a reference to NULL.
732 * If a class inherits parentable_part_of_admin_tree, this method should be called
733 * recursively on all child objects (assuming, of course, the parent object's name
734 * doesn't match the search criterion).
736 * @param string $name The internal name of the part_of_admin_tree we're searching for.
737 * @return mixed An object reference or a NULL reference.
739 public function locate($name);
742 * Removes named part_of_admin_tree.
744 * @param string $name The internal name of the part_of_admin_tree we want to remove.
745 * @return bool success.
747 public function prune($name);
751 * @param string $query
752 * @return mixed array-object structure of found settings and pages
754 public function search($query);
757 * Verifies current user's access to this part_of_admin_tree.
759 * Used to check if the current user has access to this part of the admin tree or
760 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
761 * then this method is usually just a call to has_capability() in the site context.
763 * If a class inherits parentable_part_of_admin_tree, this method should return the
764 * logical OR of the return of check_access() on all child objects.
766 * @return bool True if the user has access, false if she doesn't.
768 public function check_access();
771 * Mostly useful for removing of some parts of the tree in admin tree block.
773 * @return True is hidden from normal list view
775 public function is_hidden();
778 * Show we display Save button at the page bottom?
781 public function show_save();
786 * Interface implemented by any part_of_admin_tree that has children.
788 * The interface implemented by any part_of_admin_tree that can be a parent
789 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
790 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
791 * include an add method for adding other part_of_admin_tree objects as children.
793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795 interface parentable_part_of_admin_tree extends part_of_admin_tree {
798 * Adds a part_of_admin_tree object to the admin tree.
800 * Used to add a part_of_admin_tree object to this object or a child of this
801 * object. $something should only be added if $destinationname matches
802 * $this->name. If it doesn't, add should be called on child objects that are
803 * also parentable_part_of_admin_tree's.
805 * $something should be appended as the last child in the $destinationname. If the
806 * $beforesibling is specified, $something should be prepended to it. If the given
807 * sibling is not found, $something should be appended to the end of $destinationname
808 * and a developer debugging message should be displayed.
810 * @param string $destinationname The internal name of the new parent for $something.
811 * @param part_of_admin_tree $something The object to be added.
812 * @return bool True on success, false on failure.
814 public function add($destinationname, $something, $beforesibling = null);
820 * The object used to represent folders (a.k.a. categories) in the admin tree block.
822 * Each admin_category object contains a number of part_of_admin_tree objects.
824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
826 class admin_category implements parentable_part_of_admin_tree {
828 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
830 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
832 /** @var string The displayed name for this category. Usually obtained through get_string() */
834 /** @var bool Should this category be hidden in admin tree block? */
836 /** @var mixed Either a string or an array or strings */
838 /** @var mixed Either a string or an array or strings */
841 /** @var array fast lookup category cache, all categories of one tree point to one cache */
842 protected $category_cache;
845 * Constructor for an empty admin category
847 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
848 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
849 * @param bool $hidden hide category in admin tree block, defaults to false
851 public function __construct($name, $visiblename, $hidden=false) {
852 $this->children = array();
854 $this->visiblename = $visiblename;
855 $this->hidden = $hidden;
859 * Returns a reference to the part_of_admin_tree object with internal name $name.
861 * @param string $name The internal name of the object we want.
862 * @param bool $findpath initialize path and visiblepath arrays
863 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
866 public function locate($name, $findpath=false) {
867 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
868 // somebody much have purged the cache
869 $this->category_cache[$this->name] = $this;
872 if ($this->name == $name) {
874 $this->visiblepath[] = $this->visiblename;
875 $this->path[] = $this->name;
880 // quick category lookup
881 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
882 return $this->category_cache[$name];
886 foreach($this->children as $childid=>$unused) {
887 if ($return = $this->children[$childid]->locate($name, $findpath)) {
892 if (!is_null($return) and $findpath) {
893 $return->visiblepath[] = $this->visiblename;
894 $return->path[] = $this->name;
903 * @param string query
904 * @return mixed array-object structure of found settings and pages
906 public function search($query) {
908 foreach ($this->children as $child) {
909 $subsearch = $child->search($query);
910 if (!is_array($subsearch)) {
911 debugging('Incorrect search result from '.$child->name);
914 $result = array_merge($result, $subsearch);
920 * Removes part_of_admin_tree object with internal name $name.
922 * @param string $name The internal name of the object we want to remove.
923 * @return bool success
925 public function prune($name) {
927 if ($this->name == $name) {
928 return false; //can not remove itself
931 foreach($this->children as $precedence => $child) {
932 if ($child->name == $name) {
933 // clear cache and delete self
934 if (is_array($this->category_cache)) {
935 while($this->category_cache) {
936 // delete the cache, but keep the original array address
937 array_pop($this->category_cache);
940 unset($this->children[$precedence]);
942 } else if ($this->children[$precedence]->prune($name)) {
950 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
952 * By default the new part of the tree is appended as the last child of the parent. You
953 * can specify a sibling node that the new part should be prepended to. If the given
954 * sibling is not found, the part is appended to the end (as it would be by default) and
955 * a developer debugging message is displayed.
957 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
958 * @param string $destinationame The internal name of the immediate parent that we want for $something.
959 * @param mixed $something A part_of_admin_tree or setting instance to be added.
960 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
961 * @return bool True if successfully added, false if $something can not be added.
963 public function add($parentname, $something, $beforesibling = null) {
964 $parent = $this->locate($parentname);
965 if (is_null($parent)) {
966 debugging('parent does not exist!');
970 if ($something instanceof part_of_admin_tree) {
971 if (!($parent instanceof parentable_part_of_admin_tree)) {
972 debugging('error - parts of tree can be inserted only into parentable parts');
975 if (debugging('', DEBUG_DEVELOPER) && !is_null($this->locate($something->name))) {
976 // The name of the node is already used, simply warn the developer that this should not happen.
977 // It is intentional to check for the debug level before performing the check.
978 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
980 if (is_null($beforesibling)) {
981 // Append $something as the parent's last child.
982 $parent->children[] = $something;
984 if (!is_string($beforesibling) or trim($beforesibling) === '') {
985 throw new coding_exception('Unexpected value of the beforesibling parameter');
987 // Try to find the position of the sibling.
988 $siblingposition = null;
989 foreach ($parent->children as $childposition => $child) {
990 if ($child->name === $beforesibling) {
991 $siblingposition = $childposition;
995 if (is_null($siblingposition)) {
996 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
997 $parent->children[] = $something;
999 $parent->children = array_merge(
1000 array_slice($parent->children, 0, $siblingposition),
1002 array_slice($parent->children, $siblingposition)
1006 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
1007 if (isset($this->category_cache[$something->name])) {
1008 debugging('Duplicate admin category name: '.$something->name);
1010 $this->category_cache[$something->name] = $something;
1011 $something->category_cache =& $this->category_cache;
1012 foreach ($something->children as $child) {
1013 // just in case somebody already added subcategories
1014 if ($child instanceof admin_category) {
1015 if (isset($this->category_cache[$child->name])) {
1016 debugging('Duplicate admin category name: '.$child->name);
1018 $this->category_cache[$child->name] = $child;
1019 $child->category_cache =& $this->category_cache;
1028 debugging('error - can not add this element');
1035 * Checks if the user has access to anything in this category.
1037 * @return bool True if the user has access to at least one child in this category, false otherwise.
1039 public function check_access() {
1040 foreach ($this->children as $child) {
1041 if ($child->check_access()) {
1049 * Is this category hidden in admin tree block?
1051 * @return bool True if hidden
1053 public function is_hidden() {
1054 return $this->hidden;
1058 * Show we display Save button at the page bottom?
1061 public function show_save() {
1062 foreach ($this->children as $child) {
1063 if ($child->show_save()) {
1073 * Root of admin settings tree, does not have any parent.
1075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1077 class admin_root extends admin_category {
1078 /** @var array List of errors */
1080 /** @var string search query */
1082 /** @var bool full tree flag - true means all settings required, false only pages required */
1084 /** @var bool flag indicating loaded tree */
1086 /** @var mixed site custom defaults overriding defaults in settings files*/
1087 public $custom_defaults;
1090 * @param bool $fulltree true means all settings required,
1091 * false only pages required
1093 public function __construct($fulltree) {
1096 parent::__construct('root', get_string('administration'), false);
1097 $this->errors = array();
1099 $this->fulltree = $fulltree;
1100 $this->loaded = false;
1102 $this->category_cache = array();
1104 // load custom defaults if found
1105 $this->custom_defaults = null;
1106 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1107 if (is_readable($defaultsfile)) {
1108 $defaults = array();
1109 include($defaultsfile);
1110 if (is_array($defaults) and count($defaults)) {
1111 $this->custom_defaults = $defaults;
1117 * Empties children array, and sets loaded to false
1119 * @param bool $requirefulltree
1121 public function purge_children($requirefulltree) {
1122 $this->children = array();
1123 $this->fulltree = ($requirefulltree || $this->fulltree);
1124 $this->loaded = false;
1125 //break circular dependencies - this helps PHP 5.2
1126 while($this->category_cache) {
1127 array_pop($this->category_cache);
1129 $this->category_cache = array();
1135 * Links external PHP pages into the admin tree.
1137 * See detailed usage example at the top of this document (adminlib.php)
1139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1141 class admin_externalpage implements part_of_admin_tree {
1143 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1146 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1147 public $visiblename;
1149 /** @var string The external URL that we should link to when someone requests this external page. */
1152 /** @var string The role capability/permission a user must have to access this external page. */
1153 public $req_capability;
1155 /** @var object The context in which capability/permission should be checked, default is site context. */
1158 /** @var bool hidden in admin tree block. */
1161 /** @var mixed either string or array of string */
1164 /** @var array list of visible names of page parents */
1165 public $visiblepath;
1168 * Constructor for adding an external page into the admin tree.
1170 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1171 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1172 * @param string $url The external URL that we should link to when someone requests this external page.
1173 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1174 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1175 * @param stdClass $context The context the page relates to. Not sure what happens
1176 * if you specify something other than system or front page. Defaults to system.
1178 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1179 $this->name = $name;
1180 $this->visiblename = $visiblename;
1182 if (is_array($req_capability)) {
1183 $this->req_capability = $req_capability;
1185 $this->req_capability = array($req_capability);
1187 $this->hidden = $hidden;
1188 $this->context = $context;
1192 * Returns a reference to the part_of_admin_tree object with internal name $name.
1194 * @param string $name The internal name of the object we want.
1195 * @param bool $findpath defaults to false
1196 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1198 public function locate($name, $findpath=false) {
1199 if ($this->name == $name) {
1201 $this->visiblepath = array($this->visiblename);
1202 $this->path = array($this->name);
1212 * This function always returns false, required function by interface
1214 * @param string $name
1217 public function prune($name) {
1222 * Search using query
1224 * @param string $query
1225 * @return mixed array-object structure of found settings and pages
1227 public function search($query) {
1229 if (strpos(strtolower($this->name), $query) !== false) {
1231 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1235 $result = new stdClass();
1236 $result->page = $this;
1237 $result->settings = array();
1238 return array($this->name => $result);
1245 * Determines if the current user has access to this external page based on $this->req_capability.
1247 * @return bool True if user has access, false otherwise.
1249 public function check_access() {
1251 $context = empty($this->context) ? context_system::instance() : $this->context;
1252 foreach($this->req_capability as $cap) {
1253 if (has_capability($cap, $context)) {
1261 * Is this external page hidden in admin tree block?
1263 * @return bool True if hidden
1265 public function is_hidden() {
1266 return $this->hidden;
1270 * Show we display Save button at the page bottom?
1273 public function show_save() {
1280 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1284 class admin_settingpage implements part_of_admin_tree {
1286 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1289 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1290 public $visiblename;
1292 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1295 /** @var string The role capability/permission a user must have to access this external page. */
1296 public $req_capability;
1298 /** @var object The context in which capability/permission should be checked, default is site context. */
1301 /** @var bool hidden in admin tree block. */
1304 /** @var mixed string of paths or array of strings of paths */
1307 /** @var array list of visible names of page parents */
1308 public $visiblepath;
1311 * see admin_settingpage for details of this function
1313 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1314 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1315 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1316 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1317 * @param stdClass $context The context the page relates to. Not sure what happens
1318 * if you specify something other than system or front page. Defaults to system.
1320 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1321 $this->settings = new stdClass();
1322 $this->name = $name;
1323 $this->visiblename = $visiblename;
1324 if (is_array($req_capability)) {
1325 $this->req_capability = $req_capability;
1327 $this->req_capability = array($req_capability);
1329 $this->hidden = $hidden;
1330 $this->context = $context;
1334 * see admin_category
1336 * @param string $name
1337 * @param bool $findpath
1338 * @return mixed Object (this) if name == this->name, else returns null
1340 public function locate($name, $findpath=false) {
1341 if ($this->name == $name) {
1343 $this->visiblepath = array($this->visiblename);
1344 $this->path = array($this->name);
1354 * Search string in settings page.
1356 * @param string $query
1359 public function search($query) {
1362 foreach ($this->settings as $setting) {
1363 if ($setting->is_related($query)) {
1364 $found[] = $setting;
1369 $result = new stdClass();
1370 $result->page = $this;
1371 $result->settings = $found;
1372 return array($this->name => $result);
1376 if (strpos(strtolower($this->name), $query) !== false) {
1378 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1382 $result = new stdClass();
1383 $result->page = $this;
1384 $result->settings = array();
1385 return array($this->name => $result);
1392 * This function always returns false, required by interface
1394 * @param string $name
1395 * @return bool Always false
1397 public function prune($name) {
1402 * adds an admin_setting to this admin_settingpage
1404 * 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
1405 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1407 * @param object $setting is the admin_setting object you want to add
1408 * @return bool true if successful, false if not
1410 public function add($setting) {
1411 if (!($setting instanceof admin_setting)) {
1412 debugging('error - not a setting instance');
1416 $this->settings->{$setting->name} = $setting;
1421 * see admin_externalpage
1423 * @return bool Returns true for yes false for no
1425 public function check_access() {
1427 $context = empty($this->context) ? context_system::instance() : $this->context;
1428 foreach($this->req_capability as $cap) {
1429 if (has_capability($cap, $context)) {
1437 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1438 * @return string Returns an XHTML string
1440 public function output_html() {
1441 $adminroot = admin_get_root();
1442 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1443 foreach($this->settings as $setting) {
1444 $fullname = $setting->get_full_name();
1445 if (array_key_exists($fullname, $adminroot->errors)) {
1446 $data = $adminroot->errors[$fullname]->data;
1448 $data = $setting->get_setting();
1449 // do not use defaults if settings not available - upgrade settings handles the defaults!
1451 $return .= $setting->output_html($data);
1453 $return .= '</fieldset>';
1458 * Is this settings page hidden in admin tree block?
1460 * @return bool True if hidden
1462 public function is_hidden() {
1463 return $this->hidden;
1467 * Show we display Save button at the page bottom?
1470 public function show_save() {
1471 foreach($this->settings as $setting) {
1472 if (empty($setting->nosave)) {
1482 * Admin settings class. Only exists on setting pages.
1483 * Read & write happens at this level; no authentication.
1485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1487 abstract class admin_setting {
1488 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1490 /** @var string localised name */
1491 public $visiblename;
1492 /** @var string localised long description in Markdown format */
1493 public $description;
1494 /** @var mixed Can be string or array of string */
1495 public $defaultsetting;
1497 public $updatedcallback;
1498 /** @var mixed can be String or Null. Null means main config table */
1499 public $plugin; // null means main config table
1500 /** @var bool true indicates this setting does not actually save anything, just information */
1501 public $nosave = false;
1502 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1503 public $affectsmodinfo = false;
1507 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1508 * or 'myplugin/mysetting' for ones in config_plugins.
1509 * @param string $visiblename localised name
1510 * @param string $description localised long description
1511 * @param mixed $defaultsetting string or array depending on implementation
1513 public function __construct($name, $visiblename, $description, $defaultsetting) {
1514 $this->parse_setting_name($name);
1515 $this->visiblename = $visiblename;
1516 $this->description = $description;
1517 $this->defaultsetting = $defaultsetting;
1521 * Set up $this->name and potentially $this->plugin
1523 * Set up $this->name and possibly $this->plugin based on whether $name looks
1524 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1525 * on the names, that is, output a developer debug warning if the name
1526 * contains anything other than [a-zA-Z0-9_]+.
1528 * @param string $name the setting name passed in to the constructor.
1530 private function parse_setting_name($name) {
1531 $bits = explode('/', $name);
1532 if (count($bits) > 2) {
1533 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1535 $this->name = array_pop($bits);
1536 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1537 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1539 if (!empty($bits)) {
1540 $this->plugin = array_pop($bits);
1541 if ($this->plugin === 'moodle') {
1542 $this->plugin = null;
1543 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1544 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1550 * Returns the fullname prefixed by the plugin
1553 public function get_full_name() {
1554 return 's_'.$this->plugin.'_'.$this->name;
1558 * Returns the ID string based on plugin and name
1561 public function get_id() {
1562 return 'id_s_'.$this->plugin.'_'.$this->name;
1566 * @param bool $affectsmodinfo If true, changes to this setting will
1567 * cause the course cache to be rebuilt
1569 public function set_affects_modinfo($affectsmodinfo) {
1570 $this->affectsmodinfo = $affectsmodinfo;
1574 * Returns the config if possible
1576 * @return mixed returns config if successful else null
1578 public function config_read($name) {
1580 if (!empty($this->plugin)) {
1581 $value = get_config($this->plugin, $name);
1582 return $value === false ? NULL : $value;
1585 if (isset($CFG->$name)) {
1594 * Used to set a config pair and log change
1596 * @param string $name
1597 * @param mixed $value Gets converted to string if not null
1598 * @return bool Write setting to config table
1600 public function config_write($name, $value) {
1601 global $DB, $USER, $CFG;
1603 if ($this->nosave) {
1607 // make sure it is a real change
1608 $oldvalue = get_config($this->plugin, $name);
1609 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1610 $value = is_null($value) ? null : (string)$value;
1612 if ($oldvalue === $value) {
1617 set_config($name, $value, $this->plugin);
1619 // Some admin settings affect course modinfo
1620 if ($this->affectsmodinfo) {
1621 // Clear course cache for all courses
1622 rebuild_course_cache(0, true);
1626 $log = new stdClass();
1627 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1628 $log->timemodified = time();
1629 $log->plugin = $this->plugin;
1631 $log->value = $value;
1632 $log->oldvalue = $oldvalue;
1633 $DB->insert_record('config_log', $log);
1635 return true; // BC only
1639 * Returns current value of this setting
1640 * @return mixed array or string depending on instance, NULL means not set yet
1642 public abstract function get_setting();
1645 * Returns default setting if exists
1646 * @return mixed array or string depending on instance; NULL means no default, user must supply
1648 public function get_defaultsetting() {
1649 $adminroot = admin_get_root(false, false);
1650 if (!empty($adminroot->custom_defaults)) {
1651 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1652 if (isset($adminroot->custom_defaults[$plugin])) {
1653 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1654 return $adminroot->custom_defaults[$plugin][$this->name];
1658 return $this->defaultsetting;
1664 * @param mixed $data string or array, must not be NULL
1665 * @return string empty string if ok, string error message otherwise
1667 public abstract function write_setting($data);
1670 * Return part of form with setting
1671 * This function should always be overwritten
1673 * @param mixed $data array or string depending on setting
1674 * @param string $query
1677 public function output_html($data, $query='') {
1678 // should be overridden
1683 * Function called if setting updated - cleanup, cache reset, etc.
1684 * @param string $functionname Sets the function name
1687 public function set_updatedcallback($functionname) {
1688 $this->updatedcallback = $functionname;
1692 * Is setting related to query text - used when searching
1693 * @param string $query
1696 public function is_related($query) {
1697 if (strpos(strtolower($this->name), $query) !== false) {
1700 if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1703 if (strpos(textlib::strtolower($this->description), $query) !== false) {
1706 $current = $this->get_setting();
1707 if (!is_null($current)) {
1708 if (is_string($current)) {
1709 if (strpos(textlib::strtolower($current), $query) !== false) {
1714 $default = $this->get_defaultsetting();
1715 if (!is_null($default)) {
1716 if (is_string($default)) {
1717 if (strpos(textlib::strtolower($default), $query) !== false) {
1728 * No setting - just heading and text.
1730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1732 class admin_setting_heading extends admin_setting {
1735 * not a setting, just text
1736 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1737 * @param string $heading heading
1738 * @param string $information text in box
1740 public function __construct($name, $heading, $information) {
1741 $this->nosave = true;
1742 parent::__construct($name, $heading, $information, '');
1746 * Always returns true
1747 * @return bool Always returns true
1749 public function get_setting() {
1754 * Always returns true
1755 * @return bool Always returns true
1757 public function get_defaultsetting() {
1762 * Never write settings
1763 * @return string Always returns an empty string
1765 public function write_setting($data) {
1766 // do not write any setting
1771 * Returns an HTML string
1772 * @return string Returns an HTML string
1774 public function output_html($data, $query='') {
1777 if ($this->visiblename != '') {
1778 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1780 if ($this->description != '') {
1781 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1789 * The most flexibly setting, user is typing text
1791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1793 class admin_setting_configtext extends admin_setting {
1795 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1797 /** @var int default field size */
1801 * Config text constructor
1803 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1804 * @param string $visiblename localised
1805 * @param string $description long localised info
1806 * @param string $defaultsetting
1807 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1808 * @param int $size default field size
1810 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1811 $this->paramtype = $paramtype;
1812 if (!is_null($size)) {
1813 $this->size = $size;
1815 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1817 parent::__construct($name, $visiblename, $description, $defaultsetting);
1821 * Return the setting
1823 * @return mixed returns config if successful else null
1825 public function get_setting() {
1826 return $this->config_read($this->name);
1829 public function write_setting($data) {
1830 if ($this->paramtype === PARAM_INT and $data === '') {
1831 // do not complain if '' used instead of 0
1834 // $data is a string
1835 $validated = $this->validate($data);
1836 if ($validated !== true) {
1839 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1843 * Validate data before storage
1844 * @param string data
1845 * @return mixed true if ok string if error found
1847 public function validate($data) {
1848 // allow paramtype to be a custom regex if it is the form of /pattern/
1849 if (preg_match('#^/.*/$#', $this->paramtype)) {
1850 if (preg_match($this->paramtype, $data)) {
1853 return get_string('validateerror', 'admin');
1856 } else if ($this->paramtype === PARAM_RAW) {
1860 $cleaned = clean_param($data, $this->paramtype);
1861 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1864 return get_string('validateerror', 'admin');
1870 * Return an XHTML string for the setting
1871 * @return string Returns an XHTML string
1873 public function output_html($data, $query='') {
1874 $default = $this->get_defaultsetting();
1876 return format_admin_setting($this, $this->visiblename,
1877 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1878 $this->description, true, '', $default, $query);
1884 * General text area without html editor.
1886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1888 class admin_setting_configtextarea extends admin_setting_configtext {
1893 * @param string $name
1894 * @param string $visiblename
1895 * @param string $description
1896 * @param mixed $defaultsetting string or array
1897 * @param mixed $paramtype
1898 * @param string $cols The number of columns to make the editor
1899 * @param string $rows The number of rows to make the editor
1901 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1902 $this->rows = $rows;
1903 $this->cols = $cols;
1904 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1908 * Returns an XHTML string for the editor
1910 * @param string $data
1911 * @param string $query
1912 * @return string XHTML string for the editor
1914 public function output_html($data, $query='') {
1915 $default = $this->get_defaultsetting();
1917 $defaultinfo = $default;
1918 if (!is_null($default) and $default !== '') {
1919 $defaultinfo = "\n".$default;
1922 return format_admin_setting($this, $this->visiblename,
1923 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1924 $this->description, true, '', $defaultinfo, $query);
1930 * General text area with html editor.
1932 class admin_setting_confightmleditor extends admin_setting_configtext {
1937 * @param string $name
1938 * @param string $visiblename
1939 * @param string $description
1940 * @param mixed $defaultsetting string or array
1941 * @param mixed $paramtype
1943 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1944 $this->rows = $rows;
1945 $this->cols = $cols;
1946 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1947 editors_head_setup();
1951 * Returns an XHTML string for the editor
1953 * @param string $data
1954 * @param string $query
1955 * @return string XHTML string for the editor
1957 public function output_html($data, $query='') {
1958 $default = $this->get_defaultsetting();
1960 $defaultinfo = $default;
1961 if (!is_null($default) and $default !== '') {
1962 $defaultinfo = "\n".$default;
1965 $editor = editors_get_preferred_editor(FORMAT_HTML);
1966 $editor->use_editor($this->get_id(), array('noclean'=>true));
1968 return format_admin_setting($this, $this->visiblename,
1969 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1970 $this->description, true, '', $defaultinfo, $query);
1976 * Password field, allows unmasking of password
1978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1980 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1983 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1984 * @param string $visiblename localised
1985 * @param string $description long localised info
1986 * @param string $defaultsetting default password
1988 public function __construct($name, $visiblename, $description, $defaultsetting) {
1989 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1993 * Returns XHTML for the field
1994 * Writes Javascript into the HTML below right before the last div
1996 * @todo Make javascript available through newer methods if possible
1997 * @param string $data Value for the field
1998 * @param string $query Passed as final argument for format_admin_setting
1999 * @return string XHTML field
2001 public function output_html($data, $query='') {
2002 $id = $this->get_id();
2003 $unmask = get_string('unmaskpassword', 'form');
2004 $unmaskjs = '<script type="text/javascript">
2006 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2008 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2010 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2012 var unmaskchb = document.createElement("input");
2013 unmaskchb.setAttribute("type", "checkbox");
2014 unmaskchb.setAttribute("id", "'.$id.'unmask");
2015 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2016 unmaskdiv.appendChild(unmaskchb);
2018 var unmasklbl = document.createElement("label");
2019 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2021 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2023 unmasklbl.setAttribute("for", "'.$id.'unmask");
2025 unmaskdiv.appendChild(unmasklbl);
2028 // ugly hack to work around the famous onchange IE bug
2029 unmaskchb.onclick = function() {this.blur();};
2030 unmaskdiv.onclick = function() {this.blur();};
2034 return format_admin_setting($this, $this->visiblename,
2035 '<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>',
2036 $this->description, true, '', NULL, $query);
2044 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2046 class admin_setting_configfile extends admin_setting_configtext {
2049 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2050 * @param string $visiblename localised
2051 * @param string $description long localised info
2052 * @param string $defaultdirectory default directory location
2054 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2055 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2059 * Returns XHTML for the field
2061 * Returns XHTML for the field and also checks whether the file
2062 * specified in $data exists using file_exists()
2064 * @param string $data File name and path to use in value attr
2065 * @param string $query
2066 * @return string XHTML field
2068 public function output_html($data, $query='') {
2069 $default = $this->get_defaultsetting();
2072 if (file_exists($data)) {
2073 $executable = '<span class="pathok">✔</span>';
2075 $executable = '<span class="patherror">✘</span>';
2081 return format_admin_setting($this, $this->visiblename,
2082 '<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>',
2083 $this->description, true, '', $default, $query);
2089 * Path to executable file
2091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2093 class admin_setting_configexecutable extends admin_setting_configfile {
2096 * Returns an XHTML field
2098 * @param string $data This is the value for the field
2099 * @param string $query
2100 * @return string XHTML field
2102 public function output_html($data, $query='') {
2103 $default = $this->get_defaultsetting();
2106 if (file_exists($data) and is_executable($data)) {
2107 $executable = '<span class="pathok">✔</span>';
2109 $executable = '<span class="patherror">✘</span>';
2115 return format_admin_setting($this, $this->visiblename,
2116 '<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>',
2117 $this->description, true, '', $default, $query);
2125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2127 class admin_setting_configdirectory extends admin_setting_configfile {
2130 * Returns an XHTML field
2132 * @param string $data This is the value for the field
2133 * @param string $query
2134 * @return string XHTML
2136 public function output_html($data, $query='') {
2137 $default = $this->get_defaultsetting();
2140 if (file_exists($data) and is_dir($data)) {
2141 $executable = '<span class="pathok">✔</span>';
2143 $executable = '<span class="patherror">✘</span>';
2149 return format_admin_setting($this, $this->visiblename,
2150 '<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>',
2151 $this->description, true, '', $default, $query);
2159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2161 class admin_setting_configcheckbox extends admin_setting {
2162 /** @var string Value used when checked */
2164 /** @var string Value used when not checked */
2169 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2170 * @param string $visiblename localised
2171 * @param string $description long localised info
2172 * @param string $defaultsetting
2173 * @param string $yes value used when checked
2174 * @param string $no value used when not checked
2176 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2177 parent::__construct($name, $visiblename, $description, $defaultsetting);
2178 $this->yes = (string)$yes;
2179 $this->no = (string)$no;
2183 * Retrieves the current setting using the objects name
2187 public function get_setting() {
2188 return $this->config_read($this->name);
2192 * Sets the value for the setting
2194 * Sets the value for the setting to either the yes or no values
2195 * of the object by comparing $data to yes
2197 * @param mixed $data Gets converted to str for comparison against yes value
2198 * @return string empty string or error
2200 public function write_setting($data) {
2201 if ((string)$data === $this->yes) { // convert to strings before comparison
2206 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2210 * Returns an XHTML checkbox field
2212 * @param string $data If $data matches yes then checkbox is checked
2213 * @param string $query
2214 * @return string XHTML field
2216 public function output_html($data, $query='') {
2217 $default = $this->get_defaultsetting();
2219 if (!is_null($default)) {
2220 if ((string)$default === $this->yes) {
2221 $defaultinfo = get_string('checkboxyes', 'admin');
2223 $defaultinfo = get_string('checkboxno', 'admin');
2226 $defaultinfo = NULL;
2229 if ((string)$data === $this->yes) { // convert to strings before comparison
2230 $checked = 'checked="checked"';
2235 return format_admin_setting($this, $this->visiblename,
2236 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2237 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2238 $this->description, true, '', $defaultinfo, $query);
2244 * Multiple checkboxes, each represents different value, stored in csv format
2246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2248 class admin_setting_configmulticheckbox extends admin_setting {
2249 /** @var array Array of choices value=>label */
2253 * Constructor: uses parent::__construct
2255 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2256 * @param string $visiblename localised
2257 * @param string $description long localised info
2258 * @param array $defaultsetting array of selected
2259 * @param array $choices array of $value=>$label for each checkbox
2261 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2262 $this->choices = $choices;
2263 parent::__construct($name, $visiblename, $description, $defaultsetting);
2267 * This public function may be used in ancestors for lazy loading of choices
2269 * @todo Check if this function is still required content commented out only returns true
2270 * @return bool true if loaded, false if error
2272 public function load_choices() {
2274 if (is_array($this->choices)) {
2277 .... load choices here
2283 * Is setting related to query text - used when searching
2285 * @param string $query
2286 * @return bool true on related, false on not or failure
2288 public function is_related($query) {
2289 if (!$this->load_choices() or empty($this->choices)) {
2292 if (parent::is_related($query)) {
2296 foreach ($this->choices as $desc) {
2297 if (strpos(textlib::strtolower($desc), $query) !== false) {
2305 * Returns the current setting if it is set
2307 * @return mixed null if null, else an array
2309 public function get_setting() {
2310 $result = $this->config_read($this->name);
2312 if (is_null($result)) {
2315 if ($result === '') {
2318 $enabled = explode(',', $result);
2320 foreach ($enabled as $option) {
2321 $setting[$option] = 1;
2327 * Saves the setting(s) provided in $data
2329 * @param array $data An array of data, if not array returns empty str
2330 * @return mixed empty string on useless data or bool true=success, false=failed
2332 public function write_setting($data) {
2333 if (!is_array($data)) {
2334 return ''; // ignore it
2336 if (!$this->load_choices() or empty($this->choices)) {
2339 unset($data['xxxxx']);
2341 foreach ($data as $key => $value) {
2342 if ($value and array_key_exists($key, $this->choices)) {
2346 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2350 * Returns XHTML field(s) as required by choices
2352 * Relies on data being an array should data ever be another valid vartype with
2353 * acceptable value this may cause a warning/error
2354 * if (!is_array($data)) would fix the problem
2356 * @todo Add vartype handling to ensure $data is an array
2358 * @param array $data An array of checked values
2359 * @param string $query
2360 * @return string XHTML field
2362 public function output_html($data, $query='') {
2363 if (!$this->load_choices() or empty($this->choices)) {
2366 $default = $this->get_defaultsetting();
2367 if (is_null($default)) {
2370 if (is_null($data)) {
2374 $defaults = array();
2375 foreach ($this->choices as $key=>$description) {
2376 if (!empty($data[$key])) {
2377 $checked = 'checked="checked"';
2381 if (!empty($default[$key])) {
2382 $defaults[] = $description;
2385 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2386 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2389 if (is_null($default)) {
2390 $defaultinfo = NULL;
2391 } else if (!empty($defaults)) {
2392 $defaultinfo = implode(', ', $defaults);
2394 $defaultinfo = get_string('none');
2397 $return = '<div class="form-multicheckbox">';
2398 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2401 foreach ($options as $option) {
2402 $return .= '<li>'.$option.'</li>';
2406 $return .= '</div>';
2408 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2415 * Multiple checkboxes 2, value stored as string 00101011
2417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2419 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2422 * Returns the setting if set
2424 * @return mixed null if not set, else an array of set settings
2426 public function get_setting() {
2427 $result = $this->config_read($this->name);
2428 if (is_null($result)) {
2431 if (!$this->load_choices()) {
2434 $result = str_pad($result, count($this->choices), '0');
2435 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2437 foreach ($this->choices as $key=>$unused) {
2438 $value = array_shift($result);
2447 * Save setting(s) provided in $data param
2449 * @param array $data An array of settings to save
2450 * @return mixed empty string for bad data or bool true=>success, false=>error
2452 public function write_setting($data) {
2453 if (!is_array($data)) {
2454 return ''; // ignore it
2456 if (!$this->load_choices() or empty($this->choices)) {
2460 foreach ($this->choices as $key=>$unused) {
2461 if (!empty($data[$key])) {
2467 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2473 * Select one value from list
2475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2477 class admin_setting_configselect extends admin_setting {
2478 /** @var array Array of choices value=>label */
2483 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2484 * @param string $visiblename localised
2485 * @param string $description long localised info
2486 * @param string|int $defaultsetting
2487 * @param array $choices array of $value=>$label for each selection
2489 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2490 $this->choices = $choices;
2491 parent::__construct($name, $visiblename, $description, $defaultsetting);
2495 * This function may be used in ancestors for lazy loading of choices
2497 * Override this method if loading of choices is expensive, such
2498 * as when it requires multiple db requests.
2500 * @return bool true if loaded, false if error
2502 public function load_choices() {
2504 if (is_array($this->choices)) {
2507 .... load choices here
2513 * Check if this is $query is related to a choice
2515 * @param string $query
2516 * @return bool true if related, false if not
2518 public function is_related($query) {
2519 if (parent::is_related($query)) {
2522 if (!$this->load_choices()) {
2525 foreach ($this->choices as $key=>$value) {
2526 if (strpos(textlib::strtolower($key), $query) !== false) {
2529 if (strpos(textlib::strtolower($value), $query) !== false) {
2537 * Return the setting
2539 * @return mixed returns config if successful else null
2541 public function get_setting() {
2542 return $this->config_read($this->name);
2548 * @param string $data
2549 * @return string empty of error string
2551 public function write_setting($data) {
2552 if (!$this->load_choices() or empty($this->choices)) {
2555 if (!array_key_exists($data, $this->choices)) {
2556 return ''; // ignore it
2559 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2563 * Returns XHTML select field
2565 * Ensure the options are loaded, and generate the XHTML for the select
2566 * element and any warning message. Separating this out from output_html
2567 * makes it easier to subclass this class.
2569 * @param string $data the option to show as selected.
2570 * @param string $current the currently selected option in the database, null if none.
2571 * @param string $default the default selected option.
2572 * @return array the HTML for the select element, and a warning message.
2574 public function output_select_html($data, $current, $default, $extraname = '') {
2575 if (!$this->load_choices() or empty($this->choices)) {
2576 return array('', '');
2580 if (is_null($current)) {
2582 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2584 } else if (!array_key_exists($current, $this->choices)) {
2585 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2586 if (!is_null($default) and $data == $current) {
2587 $data = $default; // use default instead of first value when showing the form
2591 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2592 foreach ($this->choices as $key => $value) {
2593 // the string cast is needed because key may be integer - 0 is equal to most strings!
2594 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2596 $selecthtml .= '</select>';
2597 return array($selecthtml, $warning);
2601 * Returns XHTML select field and wrapping div(s)
2603 * @see output_select_html()
2605 * @param string $data the option to show as selected
2606 * @param string $query
2607 * @return string XHTML field and wrapping div
2609 public function output_html($data, $query='') {
2610 $default = $this->get_defaultsetting();
2611 $current = $this->get_setting();
2613 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2618 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2619 $defaultinfo = $this->choices[$default];
2621 $defaultinfo = NULL;
2624 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2626 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2632 * Select multiple items from list
2634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2636 class admin_setting_configmultiselect extends admin_setting_configselect {
2639 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2640 * @param string $visiblename localised
2641 * @param string $description long localised info
2642 * @param array $defaultsetting array of selected items
2643 * @param array $choices array of $value=>$label for each list item
2645 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2646 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2650 * Returns the select setting(s)
2652 * @return mixed null or array. Null if no settings else array of setting(s)
2654 public function get_setting() {
2655 $result = $this->config_read($this->name);
2656 if (is_null($result)) {
2659 if ($result === '') {
2662 return explode(',', $result);
2666 * Saves setting(s) provided through $data
2668 * Potential bug in the works should anyone call with this function
2669 * using a vartype that is not an array
2671 * @param array $data
2673 public function write_setting($data) {
2674 if (!is_array($data)) {
2675 return ''; //ignore it
2677 if (!$this->load_choices() or empty($this->choices)) {
2681 unset($data['xxxxx']);
2684 foreach ($data as $value) {
2685 if (!array_key_exists($value, $this->choices)) {
2686 continue; // ignore it
2691 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2695 * Is setting related to query text - used when searching
2697 * @param string $query
2698 * @return bool true if related, false if not
2700 public function is_related($query) {
2701 if (!$this->load_choices() or empty($this->choices)) {
2704 if (parent::is_related($query)) {
2708 foreach ($this->choices as $desc) {
2709 if (strpos(textlib::strtolower($desc), $query) !== false) {
2717 * Returns XHTML multi-select field
2719 * @todo Add vartype handling to ensure $data is an array
2720 * @param array $data Array of values to select by default
2721 * @param string $query
2722 * @return string XHTML multi-select field
2724 public function output_html($data, $query='') {
2725 if (!$this->load_choices() or empty($this->choices)) {
2728 $choices = $this->choices;
2729 $default = $this->get_defaultsetting();
2730 if (is_null($default)) {
2733 if (is_null($data)) {
2737 $defaults = array();
2738 $size = min(10, count($this->choices));
2739 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2740 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2741 foreach ($this->choices as $key => $description) {
2742 if (in_array($key, $data)) {
2743 $selected = 'selected="selected"';
2747 if (in_array($key, $default)) {
2748 $defaults[] = $description;
2751 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2754 if (is_null($default)) {
2755 $defaultinfo = NULL;
2756 } if (!empty($defaults)) {
2757 $defaultinfo = implode(', ', $defaults);
2759 $defaultinfo = get_string('none');
2762 $return .= '</select></div>';
2763 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2770 * This is a liiitle bit messy. we're using two selects, but we're returning
2771 * them as an array named after $name (so we only use $name2 internally for the setting)
2773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2775 class admin_setting_configtime extends admin_setting {
2776 /** @var string Used for setting second select (minutes) */
2781 * @param string $hoursname setting for hours
2782 * @param string $minutesname setting for hours
2783 * @param string $visiblename localised
2784 * @param string $description long localised info
2785 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2787 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2788 $this->name2 = $minutesname;
2789 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2793 * Get the selected time
2795 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2797 public function get_setting() {
2798 $result1 = $this->config_read($this->name);
2799 $result2 = $this->config_read($this->name2);
2800 if (is_null($result1) or is_null($result2)) {
2804 return array('h' => $result1, 'm' => $result2);
2808 * Store the time (hours and minutes)
2810 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2811 * @return bool true if success, false if not
2813 public function write_setting($data) {
2814 if (!is_array($data)) {
2818 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2819 return ($result ? '' : get_string('errorsetting', 'admin'));
2823 * Returns XHTML time select fields
2825 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2826 * @param string $query
2827 * @return string XHTML time select fields and wrapping div(s)
2829 public function output_html($data, $query='') {
2830 $default = $this->get_defaultsetting();
2832 if (is_array($default)) {
2833 $defaultinfo = $default['h'].':'.$default['m'];
2835 $defaultinfo = NULL;
2838 $return = '<div class="form-time defaultsnext">'.
2839 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2840 for ($i = 0; $i < 24; $i++) {
2841 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2843 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2844 for ($i = 0; $i < 60; $i += 5) {
2845 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2847 $return .= '</select></div>';
2848 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2855 * Seconds duration setting.
2857 * @copyright 2012 Petr Skoda (http://skodak.org)
2858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2860 class admin_setting_configduration extends admin_setting {
2862 /** @var int default duration unit */
2863 protected $defaultunit;
2867 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2868 * or 'myplugin/mysetting' for ones in config_plugins.
2869 * @param string $visiblename localised name
2870 * @param string $description localised long description
2871 * @param mixed $defaultsetting string or array depending on implementation
2872 * @param int $defaultunit - day, week, etc. (in seconds)
2874 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
2875 if (is_number($defaultsetting)) {
2876 $defaultsetting = self::parse_seconds($defaultsetting);
2878 $units = self::get_units();
2879 if (isset($units[$defaultunit])) {
2880 $this->defaultunit = $defaultunit;
2882 $this->defaultunit = 86400;
2884 parent::__construct($name, $visiblename, $description, $defaultsetting);
2888 * Returns selectable units.
2892 protected static function get_units() {
2894 604800 => get_string('weeks'),
2895 86400 => get_string('days'),
2896 3600 => get_string('hours'),
2897 60 => get_string('minutes'),
2898 1 => get_string('seconds'),
2903 * Converts seconds to some more user friendly string.
2905 * @param int $seconds
2908 protected static function get_duration_text($seconds) {
2909 if (empty($seconds)) {
2910 return get_string('none');
2912 $data = self::parse_seconds($seconds);
2913 switch ($data['u']) {
2915 return get_string('numweeks', '', $data['v']);
2917 return get_string('numdays', '', $data['v']);
2919 return get_string('numhours', '', $data['v']);
2921 return get_string('numminutes', '', $data['v']);
2923 return get_string('numseconds', '', $data['v']*$data['u']);
2928 * Finds suitable units for given duration.
2930 * @param int $seconds
2933 protected static function parse_seconds($seconds) {
2934 foreach (self::get_units() as $unit => $unused) {
2935 if ($seconds % $unit === 0) {
2936 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
2939 return array('v'=>(int)$seconds, 'u'=>1);
2943 * Get the selected duration as array.
2945 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
2947 public function get_setting() {
2948 $seconds = $this->config_read($this->name);
2949 if (is_null($seconds)) {
2953 return self::parse_seconds($seconds);
2957 * Store the duration as seconds.
2959 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2960 * @return bool true if success, false if not
2962 public function write_setting($data) {
2963 if (!is_array($data)) {
2967 $seconds = (int)($data['v']*$data['u']);
2969 return get_string('errorsetting', 'admin');
2972 $result = $this->config_write($this->name, $seconds);
2973 return ($result ? '' : get_string('errorsetting', 'admin'));
2977 * Returns duration text+select fields.
2979 * @param array $data Must be form 'v'=>xx, 'u'=>xx
2980 * @param string $query
2981 * @return string duration text+select fields and wrapping div(s)
2983 public function output_html($data, $query='') {
2984 $default = $this->get_defaultsetting();
2986 if (is_number($default)) {
2987 $defaultinfo = self::get_duration_text($default);
2988 } else if (is_array($default)) {
2989 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
2991 $defaultinfo = null;
2994 $units = self::get_units();
2996 $return = '<div class="form-duration defaultsnext">';
2997 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
2998 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
2999 foreach ($units as $val => $text) {
3001 if ($data['v'] == 0) {
3002 if ($val == $this->defaultunit) {
3003 $selected = ' selected="selected"';
3005 } else if ($val == $data['u']) {
3006 $selected = ' selected="selected"';
3008 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3010 $return .= '</select></div>';
3011 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3017 * Used to validate a textarea used for ip addresses
3019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3021 class admin_setting_configiplist extends admin_setting_configtextarea {
3024 * Validate the contents of the textarea as IP addresses
3026 * Used to validate a new line separated list of IP addresses collected from
3027 * a textarea control
3029 * @param string $data A list of IP Addresses separated by new lines
3030 * @return mixed bool true for success or string:error on failure
3032 public function validate($data) {
3034 $ips = explode("\n", $data);
3039 foreach($ips as $ip) {
3041 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3042 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3043 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3053 return get_string('validateerror', 'admin');
3060 * An admin setting for selecting one or more users who have a capability
3061 * in the system context
3063 * An admin setting for selecting one or more users, who have a particular capability
3064 * in the system context. Warning, make sure the list will never be too long. There is
3065 * no paging or searching of this list.
3067 * To correctly get a list of users from this config setting, you need to call the
3068 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3070 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3072 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3073 /** @var string The capabilities name */
3074 protected $capability;
3075 /** @var int include admin users too */
3076 protected $includeadmins;
3081 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3082 * @param string $visiblename localised name
3083 * @param string $description localised long description
3084 * @param array $defaultsetting array of usernames
3085 * @param string $capability string capability name.
3086 * @param bool $includeadmins include administrators
3088 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3089 $this->capability = $capability;
3090 $this->includeadmins = $includeadmins;
3091 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3095 * Load all of the uses who have the capability into choice array
3097 * @return bool Always returns true
3099 function load_choices() {
3100 if (is_array($this->choices)) {
3103 list($sort, $sortparams) = users_order_by_sql('u');
3104 if (!empty($sortparams)) {
3105 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3106 'This is unexpected, and a problem because there is no way to pass these ' .
3107 'parameters to get_users_by_capability. See MDL-34657.');
3109 $users = get_users_by_capability(context_system::instance(),
3110 $this->capability, 'u.id,u.username,u.firstname,u.lastname', $sort);
3111 $this->choices = array(
3112 '$@NONE@$' => get_string('nobody'),
3113 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3115 if ($this->includeadmins) {
3116 $admins = get_admins();
3117 foreach ($admins as $user) {
3118 $this->choices[$user->id] = fullname($user);
3121 if (is_array($users)) {
3122 foreach ($users as $user) {
3123 $this->choices[$user->id] = fullname($user);
3130 * Returns the default setting for class
3132 * @return mixed Array, or string. Empty string if no default
3134 public function get_defaultsetting() {
3135 $this->load_choices();
3136 $defaultsetting = parent::get_defaultsetting();
3137 if (empty($defaultsetting)) {
3138 return array('$@NONE@$');
3139 } else if (array_key_exists($defaultsetting, $this->choices)) {
3140 return $defaultsetting;
3147 * Returns the current setting
3149 * @return mixed array or string
3151 public function get_setting() {
3152 $result = parent::get_setting();
3153 if ($result === null) {
3154 // this is necessary for settings upgrade
3157 if (empty($result)) {
3158 $result = array('$@NONE@$');
3164 * Save the chosen setting provided as $data
3166 * @param array $data
3167 * @return mixed string or array
3169 public function write_setting($data) {
3170 // If all is selected, remove any explicit options.
3171 if (in_array('$@ALL@$', $data)) {
3172 $data = array('$@ALL@$');
3174 // None never needs to be written to the DB.
3175 if (in_array('$@NONE@$', $data)) {
3176 unset($data[array_search('$@NONE@$', $data)]);
3178 return parent::write_setting($data);
3184 * Special checkbox for calendar - resets SESSION vars.
3186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3188 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3190 * Calls the parent::__construct with default values
3192 * name => calendar_adminseesall
3193 * visiblename => get_string('adminseesall', 'admin')
3194 * description => get_string('helpadminseesall', 'admin')
3195 * defaultsetting => 0
3197 public function __construct() {
3198 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3199 get_string('helpadminseesall', 'admin'), '0');
3203 * Stores the setting passed in $data
3205 * @param mixed gets converted to string for comparison
3206 * @return string empty string or error message
3208 public function write_setting($data) {
3210 return parent::write_setting($data);
3215 * Special select for settings that are altered in setup.php and can not be altered on the fly
3217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3219 class admin_setting_special_selectsetup extends admin_setting_configselect {
3221 * Reads the setting directly from the database
3225 public function get_setting() {
3226 // read directly from db!
3227 return get_config(NULL, $this->name);
3231 * Save the setting passed in $data
3233 * @param string $data The setting to save
3234 * @return string empty or error message
3236 public function write_setting($data) {
3238 // do not change active CFG setting!
3239 $current = $CFG->{$this->name};
3240 $result = parent::write_setting($data);
3241 $CFG->{$this->name} = $current;
3248 * Special select for frontpage - stores data in course table
3250 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3252 class admin_setting_sitesetselect extends admin_setting_configselect {
3254 * Returns the site name for the selected site
3257 * @return string The site name of the selected site
3259 public function get_setting() {
3260 $site = course_get_format(get_site())->get_course();
3261 return $site->{$this->name};
3265 * Updates the database and save the setting
3267 * @param string data
3268 * @return string empty or error message
3270 public function write_setting($data) {
3272 if (!in_array($data, array_keys($this->choices))) {
3273 return get_string('errorsetting', 'admin');
3275 $record = new stdClass();
3276 $record->id = SITEID;
3277 $temp = $this->name;
3278 $record->$temp = $data;
3279 $record->timemodified = time();
3281 $SITE->{$this->name} = $data;
3282 course_get_format($SITE)->update_course_format_options($record);
3283 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3289 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3292 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3294 class admin_setting_bloglevel extends admin_setting_configselect {
3296 * Updates the database and save the setting
3298 * @param string data
3299 * @return string empty or error message
3301 public function write_setting($data) {
3304 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3305 foreach ($blogblocks as $block) {
3306 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3309 // reenable all blocks only when switching from disabled blogs
3310 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3311 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3312 foreach ($blogblocks as $block) {
3313 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3317 return parent::write_setting($data);
3323 * Special select - lists on the frontpage - hacky
3325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3327 class admin_setting_courselist_frontpage extends admin_setting {
3328 /** @var array Array of choices value=>label */
3332 * Construct override, requires one param
3334 * @param bool $loggedin Is the user logged in
3336 public function __construct($loggedin) {
3338 require_once($CFG->dirroot.'/course/lib.php');
3339 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3340 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3341 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3342 $defaults = array(FRONTPAGECOURSELIST);
3343 parent::__construct($name, $visiblename, $description, $defaults);
3347 * Loads the choices available
3349 * @return bool always returns true
3351 public function load_choices() {
3353 if (is_array($this->choices)) {
3356 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3357 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3358 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3359 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3360 'none' => get_string('none'));
3361 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3362 unset($this->choices[FRONTPAGECOURSELIST]);
3368 * Returns the selected settings
3370 * @param mixed array or setting or null
3372 public function get_setting() {
3373 $result = $this->config_read($this->name);
3374 if (is_null($result)) {
3377 if ($result === '') {
3380 return explode(',', $result);
3384 * Save the selected options
3386 * @param array $data
3387 * @return mixed empty string (data is not an array) or bool true=success false=failure
3389 public function write_setting($data) {
3390 if (!is_array($data)) {
3393 $this->load_choices();
3395 foreach($data as $datum) {
3396 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3399 $save[$datum] = $datum; // no duplicates
3401 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3405 * Return XHTML select field and wrapping div
3407 * @todo Add vartype handling to make sure $data is an array
3408 * @param array $data Array of elements to select by default
3409 * @return string XHTML select field and wrapping div
3411 public function output_html($data, $query='') {
3412 $this->load_choices();
3413 $currentsetting = array();
3414 foreach ($data as $key) {
3415 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3416 $currentsetting[] = $key; // already selected first
3420 $return = '<div class="form-group">';
3421 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3422 if (!array_key_exists($i, $currentsetting)) {
3423 $currentsetting[$i] = 'none'; //none
3425 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3426 foreach ($this->choices as $key => $value) {
3427 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3429 $return .= '</select>';
3430 if ($i !== count($this->choices) - 2) {
3431 $return .= '<br />';
3434 $return .= '</div>';
3436 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3442 * Special checkbox for frontpage - stores data in course table
3444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3446 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3448 * Returns the current sites name
3452 public function get_setting() {
3453 $site = course_get_format(get_site())->get_course();
3454 return $site->{$this->name};
3458 * Save the selected setting
3460 * @param string $data The selected site
3461 * @return string empty string or error message
3463 public function write_setting($data) {
3465 $record = new stdClass();
3466 $record->id = $SITE->id;
3467 $record->{$this->name} = ($data == '1' ? 1 : 0);
3468 $record->timemodified = time();
3470 $SITE->{$this->name} = $data;
3471 course_get_format($SITE)->update_course_format_options($record);
3472 $DB->update_record('course', $record);
3473 // There is something wrong in cache updates somewhere, let's reset everything.
3474 format_base::reset_course_cache();
3480 * Special text for frontpage - stores data in course table.
3481 * Empty string means not set here. Manual setting is required.
3483 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3485 class admin_setting_sitesettext extends admin_setting_configtext {
3487 * Return the current setting
3489 * @return mixed string or null
3491 public function get_setting() {
3492 $site = course_get_format(get_site())->get_course();
3493 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3497 * Validate the selected data
3499 * @param string $data The selected value to validate
3500 * @return mixed true or message string
3502 public function validate($data) {
3503 $cleaned = clean_param($data, PARAM_TEXT);
3504 if ($cleaned === '') {
3505 return get_string('required');
3507 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3510 return get_string('validateerror', 'admin');
3515 * Save the selected setting
3517 * @param string $data The selected value
3518 * @return string empty or error message
3520 public function write_setting($data) {
3522 $data = trim($data);
3523 $validated = $this->validate($data);
3524 if ($validated !== true) {
3528 $record = new stdClass();
3529 $record->id = $SITE->id;
3530 $record->{$this->name} = $data;
3531 $record->timemodified = time();
3533 $SITE->{$this->name} = $data;
3534 course_get_format($SITE)->update_course_format_options($record);
3535 $DB->update_record('course', $record);
3536 // There is something wrong in cache updates somewhere, let's reset everything.
3537 format_base::reset_course_cache();
3544 * Special text editor for site description.
3546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3548 class admin_setting_special_frontpagedesc extends admin_setting {
3550 * Calls parent::__construct with specific arguments
3552 public function __construct() {
3553 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3554 editors_head_setup();
3558 * Return the current setting
3559 * @return string The current setting
3561 public function get_setting() {
3562 $site = course_get_format(get_site())->get_course();
3563 return $site->{$this->name};
3567 * Save the new setting
3569 * @param string $data The new value to save
3570 * @return string empty or error message
3572 public function write_setting($data) {
3574 $record = new stdClass();
3575 $record->id = $SITE->id;
3576 $record->{$this->name} = $data;
3577 $record->timemodified = time();
3578 $SITE->{$this->name} = $data;
3579 course_get_format($SITE)->update_course_format_options($record);
3580 $DB->update_record('course', $record);
3581 // There is something wrong in cache updates somewhere, let's reset everything.
3582 format_base::reset_course_cache();
3587 * Returns XHTML for the field plus wrapping div
3589 * @param string $data The current value
3590 * @param string $query
3591 * @return string The XHTML output
3593 public function output_html($data, $query='') {
3596 $CFG->adminusehtmleditor = can_use_html_editor();
3597 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3599 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3605 * Administration interface for emoticon_manager settings.
3607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3609 class admin_setting_emoticons extends admin_setting {
3612 * Calls parent::__construct with specific args
3614 public function __construct() {
3617 $manager = get_emoticon_manager();
3618 $defaults = $this->prepare_form_data($manager->default_emoticons());
3619 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3623 * Return the current setting(s)
3625 * @return array Current settings array
3627 public function get_setting() {
3630 $manager = get_emoticon_manager();
3632 $config = $this->config_read($this->name);
3633 if (is_null($config)) {
3637 $config = $manager->decode_stored_config($config);
3638 if (is_null($config)) {
3642 return $this->prepare_form_data($config);
3646 * Save selected settings
3648 * @param array $data Array of settings to save
3651 public function write_setting($data) {
3653 $manager = get_emoticon_manager();
3654 $emoticons = $this->process_form_data($data);
3656 if ($emoticons === false) {
3660 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3661 return ''; // success
3663 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3668 * Return XHTML field(s) for options
3670 * @param array $data Array of options to set in HTML
3671 * @return string XHTML string for the fields and wrapping div(s)
3673 public function output_html($data, $query='') {
3676 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
3677 $out .= html_writer::start_tag('thead');
3678 $out .= html_writer::start_tag('tr');
3679 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3680 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3681 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3682 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3683 $out .= html_writer::tag('th', '');
3684 $out .= html_writer::end_tag('tr');
3685 $out .= html_writer::end_tag('thead');
3686 $out .= html_writer::start_tag('tbody');
3688 foreach($data as $field => $value) {
3691 $out .= html_writer::start_tag('tr');
3692 $current_text = $value;
3693 $current_filename = '';
3694 $current_imagecomponent = '';
3695 $current_altidentifier = '';
3696 $current_altcomponent = '';
3698 $current_filename = $value;
3700 $current_imagecomponent = $value;
3702 $current_altidentifier = $value;
3704 $current_altcomponent = $value;
3707 $out .= html_writer::tag('td',
3708 html_writer::empty_tag('input',
3711 'class' => 'form-text',
3712 'name' => $this->get_full_name().'['.$field.']',
3715 ), array('class' => 'c'.$i)
3719 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3720 $alt = get_string($current_altidentifier, $current_altcomponent);
3722 $alt = $current_text;
3724 if ($current_filename) {
3725 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3727 $out .= html_writer::tag('td', '');
3729 $out .= html_writer::end_tag('tr');
3736 $out .= html_writer::end_tag('tbody');
3737 $out .= html_writer::end_tag('table');
3738 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3739 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3741 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3745 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3747 * @see self::process_form_data()
3748 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3749 * @return array of form fields and their values
3751 protected function prepare_form_data(array $emoticons) {
3755 foreach ($emoticons as $emoticon) {
3756 $form['text'.$i] = $emoticon->text;
3757 $form['imagename'.$i] = $emoticon->imagename;
3758 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3759 $form['altidentifier'.$i] = $emoticon->altidentifier;
3760 $form['altcomponent'.$i] = $emoticon->altcomponent;
3763 // add one more blank field set for new object
3764 $form['text'.$i] = '';
3765 $form['imagename'.$i] = '';
3766 $form['imagecomponent'.$i] = '';
3767 $form['altidentifier'.$i] = '';
3768 $form['altcomponent'.$i] = '';
3774 * Converts the data from admin settings form into an array of emoticon objects
3776 * @see self::prepare_form_data()
3777 * @param array $data array of admin form fields and values
3778 * @return false|array of emoticon objects
3780 protected function process_form_data(array $form) {
3782 $count = count($form); // number of form field values
3785 // we must get five fields per emoticon object
3789 $emoticons = array();
3790 for ($i = 0; $i < $count / 5; $i++) {
3791 $emoticon = new stdClass();
3792 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3793 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3794 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3795 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3796 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3798 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3799 // prevent from breaking http://url.addresses by accident
3800 $emoticon->text = '';
3803 if (strlen($emoticon->text) < 2) {
3804 // do not allow single character emoticons
3805 $emoticon->text = '';
3808 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3809 // emoticon text must contain some non-alphanumeric character to prevent
3810 // breaking HTML tags
3811 $emoticon->text = '';
3814 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3815 $emoticons[] = $emoticon;
3824 * Special setting for limiting of the list of available languages.
3826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3828 class admin_setting_langlist extends admin_setting_configtext {
3830 * Calls parent::__construct with specific arguments
3832 public function __construct() {
3833 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3837 * Save the new setting
3839 * @param string $data The new setting
3842 public function write_setting($data) {
3843 $return = parent::write_setting($data);
3844 get_string_manager()->reset_caches();
3851 * Selection of one of the recognised countries using the list
3852 * returned by {@link get_list_of_countries()}.
3854 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3856 class admin_settings_country_select extends admin_setting_configselect {
3857 protected $includeall;
3858 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3859 $this->includeall = $includeall;
3860 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3864 * Lazy-load the available choices for the select box
3866 public function load_choices() {
3868 if (is_array($this->choices)) {
3871 $this->choices = array_merge(
3872 array('0' => get_string('choosedots')),
3873 get_string_manager()->get_list_of_countries($this->includeall));
3880 * admin_setting_configselect for the default number of sections in a course,
3881 * simply so we can lazy-load the choices.
3883 * @copyright 2011 The Open University
3884 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3886 class admin_settings_num_course_sections extends admin_setting_configselect {
3887 public function __construct($name, $visiblename, $description, $defaultsetting) {
3888 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3891 /** Lazy-load the available choices for the select box */
3892 public function load_choices() {
3893 $max = get_config('moodlecourse', 'maxsections');
3894 if (!isset($max) || !is_numeric($max)) {
3897 for ($i = 0; $i <= $max; $i++) {
3898 $this->choices[$i] = "$i";
3906 * Course category selection
3908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3910 class admin_settings_coursecat_select extends admin_setting_configselect {
3912 * Calls parent::__construct with specific arguments
3914 public function __construct($name, $visiblename, $description, $defaultsetting) {
3915 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3919 * Load the available choices for the select box
3923 public function load_choices() {
3925 require_once($CFG->dirroot.'/course/lib.php');
3926 if (is_array($this->choices)) {
3929 $this->choices = make_categories_options();
3936 * Special control for selecting days to backup
3938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3940 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3942 * Calls parent::__construct with specific arguments
3944 public function __construct() {
3945 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3946 $this->plugin = 'backup';
3950 * Load the available choices for the select box
3952 * @return bool Always returns true
3954 public function load_choices() {
3955 if (is_array($this->choices)) {
3958 $this->choices = array();
3959 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3960 foreach ($days as $day) {
3961 $this->choices[$day] = get_string($day, 'calendar');
3969 * Special debug setting
3971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3973 class admin_setting_special_debug extends admin_setting_configselect {
3975 * Calls parent::__construct with specific arguments
3977 public function __construct() {
3978 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3982 * Load the available choices for the select box
3986 public function load_choices() {
3987 if (is_array($this->choices)) {
3990 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3991 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3992 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3993 DEBUG_ALL => get_string('debugall', 'admin'),
3994 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4001 * Special admin control
4003 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4005 class admin_setting_special_calendar_weekend extends admin_setting {
4007 * Calls parent::__construct with specific arguments
4009 public function __construct() {
4010 $name = 'calendar_weekend';
4011 $visiblename = get_string('calendar_weekend', 'admin');
4012 $description = get_string('helpweekenddays', 'admin');
4013 $default = array ('0', '6'); // Saturdays and Sundays
4014 parent::__construct($name, $visiblename, $description, $default);
4018 * Gets the current settings as an array
4020 * @return mixed Null if none, else array of settings
4022 public function get_setting() {
4023 $result = $this->config_read($this->name);
4024 if (is_null($result)) {
4027 if ($result === '') {
4030 $settings = array();
4031 for ($i=0; $i<7; $i++) {
4032 if ($result & (1 << $i)) {
4040 * Save the new settings
4042 * @param array $data Array of new settings
4045 public function write_setting($data) {
4046 if (!is_array($data)) {
4049 unset($data['xxxxx']);
4051 foreach($data as $index) {
4052 $result |= 1 << $index;
4054 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4058 * Return XHTML to display the control
4060 * @param array $data array of selected days
4061 * @param string $query
4062 * @return string XHTML for display (field + wrapping div(s)
4064 public function output_html($data, $query='') {
4065 // The order matters very much because of the implied numeric keys
4066 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4067 $return = '<table><thead><tr>';
4068 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4069 foreach($days as $index => $day) {
4070 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4072 $return .= '</tr></thead><tbody><tr>';
4073 foreach($days as $index => $day) {
4074 $return .= '<td><input type="checkbox" class="form-checkbox" id="'.$this->get_id().$index.'" name="'.$this->get_full_name().'[]" value="'.$index.'" '.(in_array("$index", $data) ? 'checked="checked"' : '').' /></td>';
4076 $return .= '</tr></tbody></table>';
4078 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4085 * Admin setting that allows a user to pick a behaviour.
4087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4089 class admin_setting_question_behaviour extends admin_setting_configselect {
4091 * @param string $name name of config variable
4092 * @param string $visiblename display name
4093 * @param string $description description
4094 * @param string $default default.
4096 public function __construct($name, $visiblename, $description, $default) {
4097 parent::__construct($name, $visiblename, $description, $default, NULL);
4101 * Load list of behaviours as choices
4102 * @return bool true => success, false => error.
4104 public function load_choices() {
4106 require_once($CFG->dirroot . '/question/engine/lib.php');
4107 $this->choices = question_engine::get_archetypal_behaviours();
4114 * Admin setting that allows a user to pick appropriate roles for something.
4116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4118 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4119 /** @var array Array of capabilities which identify roles */
4123 * @param string $name Name of config variable
4124 * @param string $visiblename Display name
4125 * @param string $description Description
4126 * @param array $types Array of archetypes which identify
4127 * roles that will be enabled by default.
4129 public function __construct($name, $visiblename, $description, $types) {
4130 parent::__construct($name, $visiblename, $description, NULL, NULL);
4131 $this->types = $types;
4135 * Load roles as choices
4137 * @return bool true=>success, false=>error
4139 public function load_choices() {
4141 if (during_initial_install()) {
4144 if (is_array($this->choices)) {
4147 if ($roles = get_all_roles()) {
4148 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4156 * Return the default setting for this control
4158 * @return array Array of default settings
4160 public function get_defaultsetting() {
4163 if (during_initial_install()) {
4167 foreach($this->types as $archetype) {
4168 if ($caproles = get_archetype_roles($archetype)) {
4169 foreach ($caproles as $caprole) {
4170 $result[$caprole->id] = 1;
4180 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4184 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4187 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4188 * @param string $visiblename localised
4189 * @param string $description long localised info
4190 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4191 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4192 * @param int $size default field size
4194 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4195 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4199 * Loads the current setting and returns array
4201 * @return array Returns array value=>xx, __construct=>xx
4203 public function get_setting() {
4204 $value = parent::get_setting();
4205 $adv = $this->config_read($this->name.'_adv');
4206 if (is_null($value) or is_null($adv)) {
4209 return array('value' => $value, 'adv' => $adv);
4213 * Saves the new settings passed in $data
4215 * @todo Add vartype handling to ensure $data is an array
4216 * @param array $data
4217 * @return mixed string or Array
4219 public function write_setting($data) {
4220 $error = parent::write_setting($data['value']);
4222 $value = empty($data['adv']) ? 0 : 1;
4223 $this->config_write($this->name.'_adv', $value);
4229 * Return XHTML for the control
4231 * @param array $data Default data array
4232 * @param string $query
4233 * @return string XHTML to display control
4235 public function output_html($data, $query='') {
4236 $default = $this->get_defaultsetting();
4237 $defaultinfo = array();
4238 if (isset($default['value'])) {
4239 if ($default['value'] === '') {
4240 $defaultinfo[] = "''";
4242 $defaultinfo[] = $default['value'];
4245 if (!empty($default['adv'])) {
4246 $defaultinfo[] = get_string('advanced');
4248 $defaultinfo = implode(', ', $defaultinfo);
4250 $adv = !empty($data['adv']);
4251 $return = '<div class="form-text defaultsnext">' .
4252 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
4253 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
4254 ' <input type="checkbox" class="form-checkbox" id="' .
4255 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4256 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4257 ' <label for="' . $this->get_id() . '_adv">' .
4258 get_string('advanced') . '</label></div>';
4260 return format_admin_setting($this, $this->visiblename, $return,
4261 $this->description, true, '', $defaultinfo, $query);
4267 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4269 * @copyright 2009 Petr Skoda (http://skodak.org)
4270 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4272 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4276 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4277 * @param string $visiblename localised
4278 * @param string $description long localised info
4279 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4280 * @param string $yes value used when checked
4281 * @param string $no value used when not checked
4283 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4284 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4288 * Loads the current setting and returns array
4290 * @return array Returns array value=>xx, adv=>xx
4292 public function get_setting() {
4293 $value = parent::get_setting();
4294 $adv = $this->config_read($this->name.'_adv');
4295 if (is_null($value) or is_null($adv)) {
4298 return array('value' => $value, 'adv' => $adv);
4302 * Sets the value for the setting
4304 * Sets the value for the setting to either the yes or no values
4305 * of the object by comparing $data to yes
4307 * @param mixed $data Gets converted to str for comparison against yes value
4308 * @return string empty string or error
4310 public function write_setting($data) {
4311 $error = parent::write_setting($data['value']);
4313 $value = empty($data['adv']) ? 0 : 1;
4314 $this->config_write($this->name.'_adv', $value);
4320 * Returns an XHTML checkbox field and with extra advanced cehckbox
4322 * @param string $data If $data matches yes then checkbox is checked
4323 * @param string $query
4324 * @return string XHTML field
4326 public function output_html($data, $query='') {
4327 $defaults = $this->get_defaultsetting();
4328 $defaultinfo = array();
4329 if (!is_null($defaults)) {
4330 if ((string)$defaults['value'] === $this->yes) {
4331 $defaultinfo[] = get_string('checkboxyes', 'admin');
4333 $defaultinfo[] = get_string('checkboxno', 'admin');