3156374c2dfbf0c8b046e1b023206b15bd3cf33e
[moodle.git] / lib / adminlib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Functions and classes used during installation, upgrades and for admin settings.
19  *
20  *  ADMIN SETTINGS TREE INTRODUCTION
21  *
22  *  This file performs the following tasks:
23  *   -it defines the necessary objects and interfaces to build the Moodle
24  *    admin hierarchy
25  *   -it defines the admin_externalpage_setup()
26  *
27  *  ADMIN_SETTING OBJECTS
28  *
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.
32  *
33  *  ADMIN_SETTINGPAGE OBJECTS
34  *
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.
38  *
39  *  ADMIN_EXTERNALPAGE OBJECTS
40  *
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.
45  *
46  *  If you're using an admin_externalpage object for some settings, you can take
47  *  advantage of the admin_externalpage_* functions. For example, suppose you wanted
48  *  to add a foo.php file into admin. First off, you add the following line to
49  *  admin/settings/first.php (at the end of the file) or to some other file in
50  *  admin/settings:
51  * <code>
52  *     $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53  *         $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54  * </code>
55  *
56  *  Next, in foo.php, your file structure would resemble the following:
57  * <code>
58  *         require(dirname(dirname(dirname(__FILE__))).'/config.php');
59  *         require_once($CFG->libdir.'/adminlib.php');
60  *         admin_externalpage_setup('foo');
61  *         // functionality like processing form submissions goes here
62  *         echo $OUTPUT->header();
63  *         // your HTML goes here
64  *         echo $OUTPUT->footer();
65  * </code>
66  *
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.
70  *
71  *  ADMIN_CATEGORY OBJECTS
72  *
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.
76  *
77  *  OTHER NOTES
78  *
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.
83  *
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.
88  *
89  *  Please note that the $this->name field of any part_of_admin_tree must be
90  *  UNIQUE throughout the ENTIRE admin tree.
91  *
92  *  The $this->name field of an admin_setting object (which is *not* part_of_
93  *  admin_tree) must be unique on the respective admin_settingpage where it is
94  *  used.
95  *
96  * Original author: Vincenzo K. Marcovecchio
97  * Maintainer:      Petr Skoda
98  *
99  * @package    core
100  * @subpackage admin
101  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
102  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
103  */
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
115 /**
116  * Automatically clean-up all plugin data and remove the plugin DB tables
117  *
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
121  * @return void
122  */
123 function uninstall_plugin($type, $name) {
124     global $CFG, $DB, $OUTPUT;
126     // This may take a long time.
127     @set_time_limit(0);
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);
139                 }
140             }
141         }
143     }
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);
151         } else {
152             $strpluginname = $component;
153         }
155     } else {
156         $pluginname = $component;
157         if (get_string_manager()->string_exists('pluginname', $component)) {
158             $strpluginname = get_string('pluginname', $component);
159         } else {
160             $strpluginname = $component;
161         }
162     }
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);
174             }
175         }
176     }
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');
183         }
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");
190                 }
191             }
192         }
194         // clear course.modinfo for courses that used this module
195         $sql = "UPDATE {course}
196                    SET modinfo=''
197                  WHERE id IN (SELECT DISTINCT course
198                                 FROM {course_modules}
199                                WHERE module=?)";
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
206         if ($coursemods) {
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");
210                 }
211             }
212         }
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.'!');
229                 }
230             }
231         }
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));
250             }
251         }
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);
258                 if ($blockobject) {
259                     $blockobject->before_delete();  //only if we can create instance, block might have been already removed
260                 }
261             }
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);
267             }
269             // Delete block
270             $DB->delete_records('block', array('id'=>$block->id));
271         }
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);
279             }
280         }
281         $DB->delete_records('course_format_options', array('format' => $name));
282     }
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);
308     }
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);
316     }
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');
327 /**
328  * Returns the version of installed component
329  *
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
333  */
334 function get_component_version($component, $source='installed') {
335     global $CFG, $DB;
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)) {
343                 return false;
344             } else {
345                 return $CFG->version;
346             }
347         } else {
348             if (!is_readable($CFG->dirroot.'/version.php')) {
349                 return false;
350             } else {
351                 $version = null; //initialize variable for IDEs
352                 include($CFG->dirroot.'/version.php');
353                 return $version;
354             }
355         }
356     }
358     // activity module
359     if ($type === 'mod') {
360         if ($source === 'installed') {
361             return $DB->get_field('modules', 'version', array('name'=>$name));
362         } else {
363             $mods = get_plugin_list('mod');
364             if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
365                 return false;
366             } else {
367                 $module = new stdclass();
368                 include($mods[$name].'/version.php');
369                 return $module->version;
370             }
371         }
372     }
374     // block
375     if ($type === 'block') {
376         if ($source === 'installed') {
377             return $DB->get_field('block', 'version', array('name'=>$name));
378         } else {
379             $blocks = get_plugin_list('block');
380             if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
381                 return false;
382             } else {
383                 $plugin = new stdclass();
384                 include($blocks[$name].'/version.php');
385                 return $plugin->version;
386             }
387         }
388     }
390     // all other plugin types
391     if ($source === 'installed') {
392         return get_config($type.'_'.$name, 'version');
393     } else {
394         $plugins = get_plugin_list($type);
395         if (empty($plugins[$name])) {
396             return false;
397         } else {
398             $plugin = new stdclass();
399             include($plugins[$name].'/version.php');
400             return $plugin->version;
401         }
402     }
405 /**
406  * Delete all plugin tables
407  *
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
412  */
413 function drop_plugin_tables($name, $file, $feedback=true) {
414     global $CFG, $DB;
416     // first try normal delete
417     if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
418         return true;
419     }
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)) {
429             continue;
430         }
432         if (strpos($table, $name) !== 0) {
433             continue;
434         }
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);
440         }
441     }
443     return true;
446 /**
447  * Returns names of all known tables == tables that moodle knows about.
448  *
449  * @return array Array of lowercase table names
450  */
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()) {
461             continue;
462         }
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());
470             }
471         }
472     }
474     return $table_names;
477 /**
478  * Returns list of all directories where we expect install.xml files
479  * @return array Array of paths
480  */
481 function get_db_directories() {
482     global $CFG;
484     $dbdirs = array();
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';
495             }
496         }
497     }
499     return $dbdirs;
502 /**
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
508  */
509 function set_cron_lock($name, $until, $ignorecurrent=false) {
510     global $DB;
511     if (empty($name)) {
512         debugging("Tried to get a cron lock for a null fieldname");
513         return false;
514     }
516     // remove lock by force == remove from config table
517     if (is_null($until)) {
518         set_config($name, null);
519         return true;
520     }
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()) {
527             //lock active
528             return false;
529         }
530     }
532     set_config($name, $until);
533     return true;
536 /**
537  * Test if and critical warnings are present
538  * @return bool
539  */
540 function admin_critical_warnings_present() {
541     global $SESSION;
543     if (!has_capability('moodle/site:config', context_system::instance())) {
544         return 0;
545     }
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;
551         }
552     }
554     return $SESSION->admin_critical_warning;
557 /**
558  * Detects if float supports at least 10 decimal digits
559  *
560  * Detects if float supports at least 10 decimal digits
561  * and also if float-->string conversion works as expected.
562  *
563  * @return bool true if problem found
564  */
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);
572 /**
573  * Try to verify that dataroot is not accessible from web.
574  *
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.
578  *
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
583  */
584 function is_dataroot_insecure($fetchtest=false) {
585     global $CFG;
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);
592     foreach($rp as $r) {
593         if (strpos($siteroot, '/'.$r.'/') === 0) {
594             $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
595         } else {
596             break; // probably alias root
597         }
598     }
600     $siteroot = strrev($siteroot);
601     $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
603     if (strpos($dataroot, $siteroot) !== 0) {
604         return false;
605     }
607     if (!$fetchtest) {
608         return INSECURE_DATAROOT_WARNING;
609     }
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');
621     }
622     $teststr = trim(file_get_contents($testfile));
623     if (empty($teststr)) {
624     // hmm, strange
625         return INSECURE_DATAROOT_WARNING;
626     }
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)) {
637             $data = trim($data);
638             if ($data === $teststr) {
639                 curl_close($ch);
640                 return INSECURE_DATAROOT_ERROR;
641             }
642         }
643         curl_close($ch);
644     }
646     if ($data = @file_get_contents($testurl)) {
647         $data = trim($data);
648         if ($data === $teststr) {
649             return INSECURE_DATAROOT_ERROR;
650         }
651     }
653     preg_match('|https?://([^/]+)|i', $testurl, $matches);
654     $sitename = $matches[1];
655     $error = 0;
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";
662         fwrite($fp, $out);
663         $data = '';
664         $incoming = false;
665         while (!feof($fp)) {
666             if ($incoming) {
667                 $data .= fgets($fp, 1024);
668             } else if (@fgets($fp, 1024) === "\r\n") {
669                     $incoming = true;
670                 }
671         }
672         fclose($fp);
673         $data = trim($data);
674         if ($data === $teststr) {
675             return INSECURE_DATAROOT_ERROR;
676         }
677     }
679     return INSECURE_DATAROOT_WARNING;
682 /**
683  * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
684  */
685 function enable_cli_maintenance_mode() {
686     global $CFG;
688     if (file_exists("$CFG->dataroot/climaintenance.html")) {
689         unlink("$CFG->dataroot/climaintenance.html");
690     }
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");
700     } else {
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);
704     }
706     file_put_contents("$CFG->dataroot/climaintenance.html", $data);
707     chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
710 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
713 /**
714  * Interface for anything appearing in the admin tree
715  *
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.
719  *
720  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
721  */
722 interface part_of_admin_tree {
724 /**
725  * Finds a named part_of_admin_tree.
726  *
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.
731  *
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).
735  *
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.
738  */
739     public function locate($name);
741     /**
742      * Removes named part_of_admin_tree.
743      *
744      * @param string $name The internal name of the part_of_admin_tree we want to remove.
745      * @return bool success.
746      */
747     public function prune($name);
749     /**
750      * Search using query
751      * @param string $query
752      * @return mixed array-object structure of found settings and pages
753      */
754     public function search($query);
756     /**
757      * Verifies current user's access to this part_of_admin_tree.
758      *
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.
762      *
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.
765      *
766      * @return bool True if the user has access, false if she doesn't.
767      */
768     public function check_access();
770     /**
771      * Mostly useful for removing of some parts of the tree in admin tree block.
772      *
773      * @return True is hidden from normal list view
774      */
775     public function is_hidden();
777     /**
778      * Show we display Save button at the page bottom?
779      * @return bool
780      */
781     public function show_save();
785 /**
786  * Interface implemented by any part_of_admin_tree that has children.
787  *
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.
792  *
793  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
794  */
795 interface parentable_part_of_admin_tree extends part_of_admin_tree {
797 /**
798  * Adds a part_of_admin_tree object to the admin tree.
799  *
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.
804  *
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.
809  *
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.
813  */
814     public function add($destinationname, $something, $beforesibling = null);
819 /**
820  * The object used to represent folders (a.k.a. categories) in the admin tree block.
821  *
822  * Each admin_category object contains a number of part_of_admin_tree objects.
823  *
824  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
825  */
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 */
829     public $children;
830     /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
831     public $name;
832     /** @var string The displayed name for this category. Usually obtained through get_string() */
833     public $visiblename;
834     /** @var bool Should this category be hidden in admin tree block? */
835     public $hidden;
836     /** @var mixed Either a string or an array or strings */
837     public $path;
838     /** @var mixed Either a string or an array or strings */
839     public $visiblepath;
841     /** @var array fast lookup category cache, all categories of one tree point to one cache */
842     protected $category_cache;
844     /**
845      * Constructor for an empty admin category
846      *
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
850      */
851     public function __construct($name, $visiblename, $hidden=false) {
852         $this->children    = array();
853         $this->name        = $name;
854         $this->visiblename = $visiblename;
855         $this->hidden      = $hidden;
856     }
858     /**
859      * Returns a reference to the part_of_admin_tree object with internal name $name.
860      *
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.
864      *                  defaults to false
865      */
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;
870         }
872         if ($this->name == $name) {
873             if ($findpath) {
874                 $this->visiblepath[] = $this->visiblename;
875                 $this->path[]        = $this->name;
876             }
877             return $this;
878         }
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];
883         }
885         $return = NULL;
886         foreach($this->children as $childid=>$unused) {
887             if ($return = $this->children[$childid]->locate($name, $findpath)) {
888                 break;
889             }
890         }
892         if (!is_null($return) and $findpath) {
893             $return->visiblepath[] = $this->visiblename;
894             $return->path[]        = $this->name;
895         }
897         return $return;
898     }
900     /**
901      * Search using query
902      *
903      * @param string query
904      * @return mixed array-object structure of found settings and pages
905      */
906     public function search($query) {
907         $result = array();
908         foreach ($this->children as $child) {
909             $subsearch = $child->search($query);
910             if (!is_array($subsearch)) {
911                 debugging('Incorrect search result from '.$child->name);
912                 continue;
913             }
914             $result = array_merge($result, $subsearch);
915         }
916         return $result;
917     }
919     /**
920      * Removes part_of_admin_tree object with internal name $name.
921      *
922      * @param string $name The internal name of the object we want to remove.
923      * @return bool success
924      */
925     public function prune($name) {
927         if ($this->name == $name) {
928             return false;  //can not remove itself
929         }
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);
938                     }
939                 }
940                 unset($this->children[$precedence]);
941                 return true;
942             } else if ($this->children[$precedence]->prune($name)) {
943                 return true;
944             }
945         }
946         return false;
947     }
949     /**
950      * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
951      *
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.
956      *
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.
962      */
963     public function add($parentname, $something, $beforesibling = null) {
964         $parent = $this->locate($parentname);
965         if (is_null($parent)) {
966             debugging('parent does not exist!');
967             return false;
968         }
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');
973                 return false;
974             }
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);
979             }
980             if (is_null($beforesibling)) {
981                 // Append $something as the parent's last child.
982                 $parent->children[] = $something;
983             } else {
984                 if (!is_string($beforesibling) or trim($beforesibling) === '') {
985                     throw new coding_exception('Unexpected value of the beforesibling parameter');
986                 }
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;
992                         break;
993                     }
994                 }
995                 if (is_null($siblingposition)) {
996                     debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
997                     $parent->children[] = $something;
998                 } else {
999                     $parent->children = array_merge(
1000                         array_slice($parent->children, 0, $siblingposition),
1001                         array($something),
1002                         array_slice($parent->children, $siblingposition)
1003                     );
1004                 }
1005             }
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);
1009                 } else {
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);
1017                             } else {
1018                                 $this->category_cache[$child->name] = $child;
1019                                 $child->category_cache =& $this->category_cache;
1020                             }
1021                         }
1022                     }
1023                 }
1024             }
1025             return true;
1027         } else {
1028             debugging('error - can not add this element');
1029             return false;
1030         }
1032     }
1034     /**
1035      * Checks if the user has access to anything in this category.
1036      *
1037      * @return bool True if the user has access to at least one child in this category, false otherwise.
1038      */
1039     public function check_access() {
1040         foreach ($this->children as $child) {
1041             if ($child->check_access()) {
1042                 return true;
1043             }
1044         }
1045         return false;
1046     }
1048     /**
1049      * Is this category hidden in admin tree block?
1050      *
1051      * @return bool True if hidden
1052      */
1053     public function is_hidden() {
1054         return $this->hidden;
1055     }
1057     /**
1058      * Show we display Save button at the page bottom?
1059      * @return bool
1060      */
1061     public function show_save() {
1062         foreach ($this->children as $child) {
1063             if ($child->show_save()) {
1064                 return true;
1065             }
1066         }
1067         return false;
1068     }
1072 /**
1073  * Root of admin settings tree, does not have any parent.
1074  *
1075  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1076  */
1077 class admin_root extends admin_category {
1078 /** @var array List of errors */
1079     public $errors;
1080     /** @var string search query */
1081     public $search;
1082     /** @var bool full tree flag - true means all settings required, false only pages required */
1083     public $fulltree;
1084     /** @var bool flag indicating loaded tree */
1085     public $loaded;
1086     /** @var mixed site custom defaults overriding defaults in settings files*/
1087     public $custom_defaults;
1089     /**
1090      * @param bool $fulltree true means all settings required,
1091      *                            false only pages required
1092      */
1093     public function __construct($fulltree) {
1094         global $CFG;
1096         parent::__construct('root', get_string('administration'), false);
1097         $this->errors   = array();
1098         $this->search   = '';
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;
1112             }
1113         }
1114     }
1116     /**
1117      * Empties children array, and sets loaded to false
1118      *
1119      * @param bool $requirefulltree
1120      */
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);
1128         }
1129         $this->category_cache = array();
1130     }
1134 /**
1135  * Links external PHP pages into the admin tree.
1136  *
1137  * See detailed usage example at the top of this document (adminlib.php)
1138  *
1139  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1140  */
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 */
1144     public $name;
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. */
1150     public $url;
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. */
1156     public $context;
1158     /** @var bool hidden in admin tree block. */
1159     public $hidden;
1161     /** @var mixed either string or array of string */
1162     public $path;
1164     /** @var array list of visible names of page parents */
1165     public $visiblepath;
1167     /**
1168      * Constructor for adding an external page into the admin tree.
1169      *
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.
1177      */
1178     public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1179         $this->name        = $name;
1180         $this->visiblename = $visiblename;
1181         $this->url         = $url;
1182         if (is_array($req_capability)) {
1183             $this->req_capability = $req_capability;
1184         } else {
1185             $this->req_capability = array($req_capability);
1186         }
1187         $this->hidden = $hidden;
1188         $this->context = $context;
1189     }
1191     /**
1192      * Returns a reference to the part_of_admin_tree object with internal name $name.
1193      *
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.
1197      */
1198     public function locate($name, $findpath=false) {
1199         if ($this->name == $name) {
1200             if ($findpath) {
1201                 $this->visiblepath = array($this->visiblename);
1202                 $this->path        = array($this->name);
1203             }
1204             return $this;
1205         } else {
1206             $return = NULL;
1207             return $return;
1208         }
1209     }
1211     /**
1212      * This function always returns false, required function by interface
1213      *
1214      * @param string $name
1215      * @return false
1216      */
1217     public function prune($name) {
1218         return false;
1219     }
1221     /**
1222      * Search using query
1223      *
1224      * @param string $query
1225      * @return mixed array-object structure of found settings and pages
1226      */
1227     public function search($query) {
1228         $found = false;
1229         if (strpos(strtolower($this->name), $query) !== false) {
1230             $found = true;
1231         } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1232                 $found = true;
1233             }
1234         if ($found) {
1235             $result = new stdClass();
1236             $result->page     = $this;
1237             $result->settings = array();
1238             return array($this->name => $result);
1239         } else {
1240             return array();
1241         }
1242     }
1244     /**
1245      * Determines if the current user has access to this external page based on $this->req_capability.
1246      *
1247      * @return bool True if user has access, false otherwise.
1248      */
1249     public function check_access() {
1250         global $CFG;
1251         $context = empty($this->context) ? context_system::instance() : $this->context;
1252         foreach($this->req_capability as $cap) {
1253             if (has_capability($cap, $context)) {
1254                 return true;
1255             }
1256         }
1257         return false;
1258     }
1260     /**
1261      * Is this external page hidden in admin tree block?
1262      *
1263      * @return bool True if hidden
1264      */
1265     public function is_hidden() {
1266         return $this->hidden;
1267     }
1269     /**
1270      * Show we display Save button at the page bottom?
1271      * @return bool
1272      */
1273     public function show_save() {
1274         return false;
1275     }
1279 /**
1280  * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1281  *
1282  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1283  */
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 */
1287     public $name;
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. */
1293     public $settings;
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. */
1299     public $context;
1301     /** @var bool hidden in admin tree block. */
1302     public $hidden;
1304     /** @var mixed string of paths or array of strings of paths */
1305     public $path;
1307     /** @var array list of visible names of page parents */
1308     public $visiblepath;
1310     /**
1311      * see admin_settingpage for details of this function
1312      *
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.
1319      */
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;
1326         } else {
1327             $this->req_capability = array($req_capability);
1328         }
1329         $this->hidden      = $hidden;
1330         $this->context     = $context;
1331     }
1333     /**
1334      * see admin_category
1335      *
1336      * @param string $name
1337      * @param bool $findpath
1338      * @return mixed Object (this) if name ==  this->name, else returns null
1339      */
1340     public function locate($name, $findpath=false) {
1341         if ($this->name == $name) {
1342             if ($findpath) {
1343                 $this->visiblepath = array($this->visiblename);
1344                 $this->path        = array($this->name);
1345             }
1346             return $this;
1347         } else {
1348             $return = NULL;
1349             return $return;
1350         }
1351     }
1353     /**
1354      * Search string in settings page.
1355      *
1356      * @param string $query
1357      * @return array
1358      */
1359     public function search($query) {
1360         $found = array();
1362         foreach ($this->settings as $setting) {
1363             if ($setting->is_related($query)) {
1364                 $found[] = $setting;
1365             }
1366         }
1368         if ($found) {
1369             $result = new stdClass();
1370             $result->page     = $this;
1371             $result->settings = $found;
1372             return array($this->name => $result);
1373         }
1375         $found = false;
1376         if (strpos(strtolower($this->name), $query) !== false) {
1377             $found = true;
1378         } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1379                 $found = true;
1380             }
1381         if ($found) {
1382             $result = new stdClass();
1383             $result->page     = $this;
1384             $result->settings = array();
1385             return array($this->name => $result);
1386         } else {
1387             return array();
1388         }
1389     }
1391     /**
1392      * This function always returns false, required by interface
1393      *
1394      * @param string $name
1395      * @return bool Always false
1396      */
1397     public function prune($name) {
1398         return false;
1399     }
1401     /**
1402      * adds an admin_setting to this admin_settingpage
1403      *
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
1406      *
1407      * @param object $setting is the admin_setting object you want to add
1408      * @return bool true if successful, false if not
1409      */
1410     public function add($setting) {
1411         if (!($setting instanceof admin_setting)) {
1412             debugging('error - not a setting instance');
1413             return false;
1414         }
1416         $this->settings->{$setting->name} = $setting;
1417         return true;
1418     }
1420     /**
1421      * see admin_externalpage
1422      *
1423      * @return bool Returns true for yes false for no
1424      */
1425     public function check_access() {
1426         global $CFG;
1427         $context = empty($this->context) ? context_system::instance() : $this->context;
1428         foreach($this->req_capability as $cap) {
1429             if (has_capability($cap, $context)) {
1430                 return true;
1431             }
1432         }
1433         return false;
1434     }
1436     /**
1437      * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1438      * @return string Returns an XHTML string
1439      */
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;
1447             } else {
1448                 $data = $setting->get_setting();
1449                 // do not use defaults if settings not available - upgrade settings handles the defaults!
1450             }
1451             $return .= $setting->output_html($data);
1452         }
1453         $return .= '</fieldset>';
1454         return $return;
1455     }
1457     /**
1458      * Is this settings page hidden in admin tree block?
1459      *
1460      * @return bool True if hidden
1461      */
1462     public function is_hidden() {
1463         return $this->hidden;
1464     }
1466     /**
1467      * Show we display Save button at the page bottom?
1468      * @return bool
1469      */
1470     public function show_save() {
1471         foreach($this->settings as $setting) {
1472             if (empty($setting->nosave)) {
1473                 return true;
1474             }
1475         }
1476         return false;
1477     }
1481 /**
1482  * Admin settings class. Only exists on setting pages.
1483  * Read & write happens at this level; no authentication.
1484  *
1485  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1486  */
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. */
1489     public $name;
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;
1496     /** @var string */
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;
1505     /**
1506      * Constructor
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
1512      */
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;
1518     }
1520     /**
1521      * Set up $this->name and potentially $this->plugin
1522      *
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_]+.
1527      *
1528      * @param string $name the setting name passed in to the constructor.
1529      */
1530     private function parse_setting_name($name) {
1531         $bits = explode('/', $name);
1532         if (count($bits) > 2) {
1533             throw new moodle_exception('invalidadminsettingname', '', '', $name);
1534         }
1535         $this->name = array_pop($bits);
1536         if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1537             throw new moodle_exception('invalidadminsettingname', '', '', $name);
1538         }
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);
1545                 }
1546         }
1547     }
1549     /**
1550      * Returns the fullname prefixed by the plugin
1551      * @return string
1552      */
1553     public function get_full_name() {
1554         return 's_'.$this->plugin.'_'.$this->name;
1555     }
1557     /**
1558      * Returns the ID string based on plugin and name
1559      * @return string
1560      */
1561     public function get_id() {
1562         return 'id_s_'.$this->plugin.'_'.$this->name;
1563     }
1565     /**
1566      * @param bool $affectsmodinfo If true, changes to this setting will
1567      *   cause the course cache to be rebuilt
1568      */
1569     public function set_affects_modinfo($affectsmodinfo) {
1570         $this->affectsmodinfo = $affectsmodinfo;
1571     }
1573     /**
1574      * Returns the config if possible
1575      *
1576      * @return mixed returns config if successful else null
1577      */
1578     public function config_read($name) {
1579         global $CFG;
1580         if (!empty($this->plugin)) {
1581             $value = get_config($this->plugin, $name);
1582             return $value === false ? NULL : $value;
1584         } else {
1585             if (isset($CFG->$name)) {
1586                 return $CFG->$name;
1587             } else {
1588                 return NULL;
1589             }
1590         }
1591     }
1593     /**
1594      * Used to set a config pair and log change
1595      *
1596      * @param string $name
1597      * @param mixed $value Gets converted to string if not null
1598      * @return bool Write setting to config table
1599      */
1600     public function config_write($name, $value) {
1601         global $DB, $USER, $CFG;
1603         if ($this->nosave) {
1604             return true;
1605         }
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) {
1613             return true;
1614         }
1616         // store change
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);
1623         }
1625         // log change
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;
1630         $log->name         = $name;
1631         $log->value        = $value;
1632         $log->oldvalue     = $oldvalue;
1633         $DB->insert_record('config_log', $log);
1635         return true; // BC only
1636     }
1638     /**
1639      * Returns current value of this setting
1640      * @return mixed array or string depending on instance, NULL means not set yet
1641      */
1642     public abstract function get_setting();
1644     /**
1645      * Returns default setting if exists
1646      * @return mixed array or string depending on instance; NULL means no default, user must supply
1647      */
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];
1655                 }
1656             }
1657         }
1658         return $this->defaultsetting;
1659     }
1661     /**
1662      * Store new setting
1663      *
1664      * @param mixed $data string or array, must not be NULL
1665      * @return string empty string if ok, string error message otherwise
1666      */
1667     public abstract function write_setting($data);
1669     /**
1670      * Return part of form with setting
1671      * This function should always be overwritten
1672      *
1673      * @param mixed $data array or string depending on setting
1674      * @param string $query
1675      * @return string
1676      */
1677     public function output_html($data, $query='') {
1678     // should be overridden
1679         return;
1680     }
1682     /**
1683      * Function called if setting updated - cleanup, cache reset, etc.
1684      * @param string $functionname Sets the function name
1685      * @return void
1686      */
1687     public function set_updatedcallback($functionname) {
1688         $this->updatedcallback = $functionname;
1689     }
1691     /**
1692      * Is setting related to query text - used when searching
1693      * @param string $query
1694      * @return bool
1695      */
1696     public function is_related($query) {
1697         if (strpos(strtolower($this->name), $query) !== false) {
1698             return true;
1699         }
1700         if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1701             return true;
1702         }
1703         if (strpos(textlib::strtolower($this->description), $query) !== false) {
1704             return true;
1705         }
1706         $current = $this->get_setting();
1707         if (!is_null($current)) {
1708             if (is_string($current)) {
1709                 if (strpos(textlib::strtolower($current), $query) !== false) {
1710                     return true;
1711                 }
1712             }
1713         }
1714         $default = $this->get_defaultsetting();
1715         if (!is_null($default)) {
1716             if (is_string($default)) {
1717                 if (strpos(textlib::strtolower($default), $query) !== false) {
1718                     return true;
1719                 }
1720             }
1721         }
1722         return false;
1723     }
1727 /**
1728  * No setting - just heading and text.
1729  *
1730  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1731  */
1732 class admin_setting_heading extends admin_setting {
1734     /**
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
1739      */
1740     public function __construct($name, $heading, $information) {
1741         $this->nosave = true;
1742         parent::__construct($name, $heading, $information, '');
1743     }
1745     /**
1746      * Always returns true
1747      * @return bool Always returns true
1748      */
1749     public function get_setting() {
1750         return true;
1751     }
1753     /**
1754      * Always returns true
1755      * @return bool Always returns true
1756      */
1757     public function get_defaultsetting() {
1758         return true;
1759     }
1761     /**
1762      * Never write settings
1763      * @return string Always returns an empty string
1764      */
1765     public function write_setting($data) {
1766     // do not write any setting
1767         return '';
1768     }
1770     /**
1771      * Returns an HTML string
1772      * @return string Returns an HTML string
1773      */
1774     public function output_html($data, $query='') {
1775         global $OUTPUT;
1776         $return = '';
1777         if ($this->visiblename != '') {
1778             $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1779         }
1780         if ($this->description != '') {
1781             $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1782         }
1783         return $return;
1784     }
1788 /**
1789  * The most flexibly setting, user is typing text
1790  *
1791  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1792  */
1793 class admin_setting_configtext extends admin_setting {
1795     /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1796     public $paramtype;
1797     /** @var int default field size */
1798     public $size;
1800     /**
1801      * Config text constructor
1802      *
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
1809      */
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;
1814         } else {
1815             $this->size  = ($paramtype === PARAM_INT) ? 5 : 30;
1816         }
1817         parent::__construct($name, $visiblename, $description, $defaultsetting);
1818     }
1820     /**
1821      * Return the setting
1822      *
1823      * @return mixed returns config if successful else null
1824      */
1825     public function get_setting() {
1826         return $this->config_read($this->name);
1827     }
1829     public function write_setting($data) {
1830         if ($this->paramtype === PARAM_INT and $data === '') {
1831         // do not complain if '' used instead of 0
1832             $data = 0;
1833         }
1834         // $data is a string
1835         $validated = $this->validate($data);
1836         if ($validated !== true) {
1837             return $validated;
1838         }
1839         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1840     }
1842     /**
1843      * Validate data before storage
1844      * @param string data
1845      * @return mixed true if ok string if error found
1846      */
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)) {
1851                 return true;
1852             } else {
1853                 return get_string('validateerror', 'admin');
1854             }
1856         } else if ($this->paramtype === PARAM_RAW) {
1857             return true;
1859         } else {
1860             $cleaned = clean_param($data, $this->paramtype);
1861             if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1862                 return true;
1863             } else {
1864                 return get_string('validateerror', 'admin');
1865             }
1866         }
1867     }
1869     /**
1870      * Return an XHTML string for the setting
1871      * @return string Returns an XHTML string
1872      */
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);
1879     }
1883 /**
1884  * General text area without html editor.
1885  *
1886  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1887  */
1888 class admin_setting_configtextarea extends admin_setting_configtext {
1889     private $rows;
1890     private $cols;
1892     /**
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
1900      */
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);
1905     }
1907     /**
1908      * Returns an XHTML string for the editor
1909      *
1910      * @param string $data
1911      * @param string $query
1912      * @return string XHTML string for the editor
1913      */
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;
1920         }
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);
1925     }
1929 /**
1930  * General text area with html editor.
1931  */
1932 class admin_setting_confightmleditor extends admin_setting_configtext {
1933     private $rows;
1934     private $cols;
1936     /**
1937      * @param string $name
1938      * @param string $visiblename
1939      * @param string $description
1940      * @param mixed $defaultsetting string or array
1941      * @param mixed $paramtype
1942      */
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();
1948     }
1950     /**
1951      * Returns an XHTML string for the editor
1952      *
1953      * @param string $data
1954      * @param string $query
1955      * @return string XHTML string for the editor
1956      */
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;
1963         }
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);
1971     }
1975 /**
1976  * Password field, allows unmasking of password
1977  *
1978  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1979  */
1980 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1981     /**
1982      * Constructor
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
1987      */
1988     public function __construct($name, $visiblename, $description, $defaultsetting) {
1989         parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1990     }
1992     /**
1993      * Returns XHTML for the field
1994      * Writes Javascript into the HTML below right before the last div
1995      *
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
2000      */
2001     public function output_html($data, $query='') {
2002         $id = $this->get_id();
2003         $unmask = get_string('unmaskpassword', 'form');
2004         $unmaskjs = '<script type="text/javascript">
2005 //<![CDATA[
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).'";
2020 if (is_ie) {
2021   unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2022 } else {
2023   unmasklbl.setAttribute("for", "'.$id.'unmask");
2025 unmaskdiv.appendChild(unmasklbl);
2027 if (is_ie) {
2028   // ugly hack to work around the famous onchange IE bug
2029   unmaskchb.onclick = function() {this.blur();};
2030   unmaskdiv.onclick = function() {this.blur();};
2032 //]]>
2033 </script>';
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);
2037     }
2041 /**
2042  * Path to directory
2043  *
2044  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2045  */
2046 class admin_setting_configfile extends admin_setting_configtext {
2047     /**
2048      * Constructor
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
2053      */
2054     public function __construct($name, $visiblename, $description, $defaultdirectory) {
2055         parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2056     }
2058     /**
2059      * Returns XHTML for the field
2060      *
2061      * Returns XHTML for the field and also checks whether the file
2062      * specified in $data exists using file_exists()
2063      *
2064      * @param string $data File name and path to use in value attr
2065      * @param string $query
2066      * @return string XHTML field
2067      */
2068     public function output_html($data, $query='') {
2069         $default = $this->get_defaultsetting();
2071         if ($data) {
2072             if (file_exists($data)) {
2073                 $executable = '<span class="pathok">&#x2714;</span>';
2074             } else {
2075                 $executable = '<span class="patherror">&#x2718;</span>';
2076             }
2077         } else {
2078             $executable = '';
2079         }
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);
2084     }
2088 /**
2089  * Path to executable file
2090  *
2091  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2092  */
2093 class admin_setting_configexecutable extends admin_setting_configfile {
2095     /**
2096      * Returns an XHTML field
2097      *
2098      * @param string $data This is the value for the field
2099      * @param string $query
2100      * @return string XHTML field
2101      */
2102     public function output_html($data, $query='') {
2103         $default = $this->get_defaultsetting();
2105         if ($data) {
2106             if (file_exists($data) and is_executable($data)) {
2107                 $executable = '<span class="pathok">&#x2714;</span>';
2108             } else {
2109                 $executable = '<span class="patherror">&#x2718;</span>';
2110             }
2111         } else {
2112             $executable = '';
2113         }
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);
2118     }
2122 /**
2123  * Path to directory
2124  *
2125  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2126  */
2127 class admin_setting_configdirectory extends admin_setting_configfile {
2129     /**
2130      * Returns an XHTML field
2131      *
2132      * @param string $data This is the value for the field
2133      * @param string $query
2134      * @return string XHTML
2135      */
2136     public function output_html($data, $query='') {
2137         $default = $this->get_defaultsetting();
2139         if ($data) {
2140             if (file_exists($data) and is_dir($data)) {
2141                 $executable = '<span class="pathok">&#x2714;</span>';
2142             } else {
2143                 $executable = '<span class="patherror">&#x2718;</span>';
2144             }
2145         } else {
2146             $executable = '';
2147         }
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);
2152     }
2156 /**
2157  * Checkbox
2158  *
2159  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2160  */
2161 class admin_setting_configcheckbox extends admin_setting {
2162     /** @var string Value used when checked */
2163     public $yes;
2164     /** @var string Value used when not checked */
2165     public $no;
2167     /**
2168      * Constructor
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
2175      */
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;
2180     }
2182     /**
2183      * Retrieves the current setting using the objects name
2184      *
2185      * @return string
2186      */
2187     public function get_setting() {
2188         return $this->config_read($this->name);
2189     }
2191     /**
2192      * Sets the value for the setting
2193      *
2194      * Sets the value for the setting to either the yes or no values
2195      * of the object by comparing $data to yes
2196      *
2197      * @param mixed $data Gets converted to str for comparison against yes value
2198      * @return string empty string or error
2199      */
2200     public function write_setting($data) {
2201         if ((string)$data === $this->yes) { // convert to strings before comparison
2202             $data = $this->yes;
2203         } else {
2204             $data = $this->no;
2205         }
2206         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2207     }
2209     /**
2210      * Returns an XHTML checkbox field
2211      *
2212      * @param string $data If $data matches yes then checkbox is checked
2213      * @param string $query
2214      * @return string XHTML field
2215      */
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');
2222             } else {
2223                 $defaultinfo = get_string('checkboxno', 'admin');
2224             }
2225         } else {
2226             $defaultinfo = NULL;
2227         }
2229         if ((string)$data === $this->yes) { // convert to strings before comparison
2230             $checked = 'checked="checked"';
2231         } else {
2232             $checked = '';
2233         }
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);
2239     }
2243 /**
2244  * Multiple checkboxes, each represents different value, stored in csv format
2245  *
2246  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2247  */
2248 class admin_setting_configmulticheckbox extends admin_setting {
2249     /** @var array Array of choices value=>label */
2250     public $choices;
2252     /**
2253      * Constructor: uses parent::__construct
2254      *
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
2260      */
2261     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2262         $this->choices = $choices;
2263         parent::__construct($name, $visiblename, $description, $defaultsetting);
2264     }
2266     /**
2267      * This public function may be used in ancestors for lazy loading of choices
2268      *
2269      * @todo Check if this function is still required content commented out only returns true
2270      * @return bool true if loaded, false if error
2271      */
2272     public function load_choices() {
2273         /*
2274         if (is_array($this->choices)) {
2275             return true;
2276         }
2277         .... load choices here
2278         */
2279         return true;
2280     }
2282     /**
2283      * Is setting related to query text - used when searching
2284      *
2285      * @param string $query
2286      * @return bool true on related, false on not or failure
2287      */
2288     public function is_related($query) {
2289         if (!$this->load_choices() or empty($this->choices)) {
2290             return false;
2291         }
2292         if (parent::is_related($query)) {
2293             return true;
2294         }
2296         foreach ($this->choices as $desc) {
2297             if (strpos(textlib::strtolower($desc), $query) !== false) {
2298                 return true;
2299             }
2300         }
2301         return false;
2302     }
2304     /**
2305      * Returns the current setting if it is set
2306      *
2307      * @return mixed null if null, else an array
2308      */
2309     public function get_setting() {
2310         $result = $this->config_read($this->name);
2312         if (is_null($result)) {
2313             return NULL;
2314         }
2315         if ($result === '') {
2316             return array();
2317         }
2318         $enabled = explode(',', $result);
2319         $setting = array();
2320         foreach ($enabled as $option) {
2321             $setting[$option] = 1;
2322         }
2323         return $setting;
2324     }
2326     /**
2327      * Saves the setting(s) provided in $data
2328      *
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
2331      */
2332     public function write_setting($data) {
2333         if (!is_array($data)) {
2334             return ''; // ignore it
2335         }
2336         if (!$this->load_choices() or empty($this->choices)) {
2337             return '';
2338         }
2339         unset($data['xxxxx']);
2340         $result = array();
2341         foreach ($data as $key => $value) {
2342             if ($value and array_key_exists($key, $this->choices)) {
2343                 $result[] = $key;
2344             }
2345         }
2346         return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2347     }
2349     /**
2350      * Returns XHTML field(s) as required by choices
2351      *
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
2355      *
2356      * @todo Add vartype handling to ensure $data is an array
2357      *
2358      * @param array $data An array of checked values
2359      * @param string $query
2360      * @return string XHTML field
2361      */
2362     public function output_html($data, $query='') {
2363         if (!$this->load_choices() or empty($this->choices)) {
2364             return '';
2365         }
2366         $default = $this->get_defaultsetting();
2367         if (is_null($default)) {
2368             $default = array();
2369         }
2370         if (is_null($data)) {
2371             $data = array();
2372         }
2373         $options = array();
2374         $defaults = array();
2375         foreach ($this->choices as $key=>$description) {
2376             if (!empty($data[$key])) {
2377                 $checked = 'checked="checked"';
2378             } else {
2379                 $checked = '';
2380             }
2381             if (!empty($default[$key])) {
2382                 $defaults[] = $description;
2383             }
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>';
2387         }
2389         if (is_null($default)) {
2390             $defaultinfo = NULL;
2391         } else if (!empty($defaults)) {
2392                 $defaultinfo = implode(', ', $defaults);
2393             } else {
2394                 $defaultinfo = get_string('none');
2395             }
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
2399         if ($options) {
2400             $return .= '<ul>';
2401             foreach ($options as $option) {
2402                 $return .= '<li>'.$option.'</li>';
2403             }
2404             $return .= '</ul>';
2405         }
2406         $return .= '</div>';
2408         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2410     }
2414 /**
2415  * Multiple checkboxes 2, value stored as string 00101011
2416  *
2417  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2418  */
2419 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2421     /**
2422      * Returns the setting if set
2423      *
2424      * @return mixed null if not set, else an array of set settings
2425      */
2426     public function get_setting() {
2427         $result = $this->config_read($this->name);
2428         if (is_null($result)) {
2429             return NULL;
2430         }
2431         if (!$this->load_choices()) {
2432             return NULL;
2433         }
2434         $result = str_pad($result, count($this->choices), '0');
2435         $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2436         $setting = array();
2437         foreach ($this->choices as $key=>$unused) {
2438             $value = array_shift($result);
2439             if ($value) {
2440                 $setting[$key] = 1;
2441             }
2442         }
2443         return $setting;
2444     }
2446     /**
2447      * Save setting(s) provided in $data param
2448      *
2449      * @param array $data An array of settings to save
2450      * @return mixed empty string for bad data or bool true=>success, false=>error
2451      */
2452     public function write_setting($data) {
2453         if (!is_array($data)) {
2454             return ''; // ignore it
2455         }
2456         if (!$this->load_choices() or empty($this->choices)) {
2457             return '';
2458         }
2459         $result = '';
2460         foreach ($this->choices as $key=>$unused) {
2461             if (!empty($data[$key])) {
2462                 $result .= '1';
2463             } else {
2464                 $result .= '0';
2465             }
2466         }
2467         return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2468     }
2472 /**
2473  * Select one value from list
2474  *
2475  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2476  */
2477 class admin_setting_configselect extends admin_setting {
2478     /** @var array Array of choices value=>label */
2479     public $choices;
2481     /**
2482      * Constructor
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
2488      */
2489     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2490         $this->choices = $choices;
2491         parent::__construct($name, $visiblename, $description, $defaultsetting);
2492     }
2494     /**
2495      * This function may be used in ancestors for lazy loading of choices
2496      *
2497      * Override this method if loading of choices is expensive, such
2498      * as when it requires multiple db requests.
2499      *
2500      * @return bool true if loaded, false if error
2501      */
2502     public function load_choices() {
2503         /*
2504         if (is_array($this->choices)) {
2505             return true;
2506         }
2507         .... load choices here
2508         */
2509         return true;
2510     }
2512     /**
2513      * Check if this is $query is related to a choice
2514      *
2515      * @param string $query
2516      * @return bool true if related, false if not
2517      */
2518     public function is_related($query) {
2519         if (parent::is_related($query)) {
2520             return true;
2521         }
2522         if (!$this->load_choices()) {
2523             return false;
2524         }
2525         foreach ($this->choices as $key=>$value) {
2526             if (strpos(textlib::strtolower($key), $query) !== false) {
2527                 return true;
2528             }
2529             if (strpos(textlib::strtolower($value), $query) !== false) {
2530                 return true;
2531             }
2532         }
2533         return false;
2534     }
2536     /**
2537      * Return the setting
2538      *
2539      * @return mixed returns config if successful else null
2540      */
2541     public function get_setting() {
2542         return $this->config_read($this->name);
2543     }
2545     /**
2546      * Save a setting
2547      *
2548      * @param string $data
2549      * @return string empty of error string
2550      */
2551     public function write_setting($data) {
2552         if (!$this->load_choices() or empty($this->choices)) {
2553             return '';
2554         }
2555         if (!array_key_exists($data, $this->choices)) {
2556             return ''; // ignore it
2557         }
2559         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2560     }
2562     /**
2563      * Returns XHTML select field
2564      *
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.
2568      *
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.
2573      */
2574     public function output_select_html($data, $current, $default, $extraname = '') {
2575         if (!$this->load_choices() or empty($this->choices)) {
2576             return array('', '');
2577         }
2579         $warning = '';
2580         if (is_null($current)) {
2581         // first run
2582         } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2583             // no warning
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
2588                     }
2589                 }
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>';
2595         }
2596         $selecthtml .= '</select>';
2597         return array($selecthtml, $warning);
2598     }
2600     /**
2601      * Returns XHTML select field and wrapping div(s)
2602      *
2603      * @see output_select_html()
2604      *
2605      * @param string $data the option to show as selected
2606      * @param string $query
2607      * @return string XHTML field and wrapping div
2608      */
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);
2614         if (!$selecthtml) {
2615             return '';
2616         }
2618         if (!is_null($default) and array_key_exists($default, $this->choices)) {
2619             $defaultinfo = $this->choices[$default];
2620         } else {
2621             $defaultinfo = NULL;
2622         }
2624         $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2626         return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2627     }
2631 /**
2632  * Select multiple items from list
2633  *
2634  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2635  */
2636 class admin_setting_configmultiselect extends admin_setting_configselect {
2637     /**
2638      * Constructor
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
2644      */
2645     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2646         parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2647     }
2649     /**
2650      * Returns the select setting(s)
2651      *
2652      * @return mixed null or array. Null if no settings else array of setting(s)
2653      */
2654     public function get_setting() {
2655         $result = $this->config_read($this->name);
2656         if (is_null($result)) {
2657             return NULL;
2658         }
2659         if ($result === '') {
2660             return array();
2661         }
2662         return explode(',', $result);
2663     }
2665     /**
2666      * Saves setting(s) provided through $data
2667      *
2668      * Potential bug in the works should anyone call with this function
2669      * using a vartype that is not an array
2670      *
2671      * @param array $data
2672      */
2673     public function write_setting($data) {
2674         if (!is_array($data)) {
2675             return ''; //ignore it
2676         }
2677         if (!$this->load_choices() or empty($this->choices)) {
2678             return '';
2679         }
2681         unset($data['xxxxx']);
2683         $save = array();
2684         foreach ($data as $value) {
2685             if (!array_key_exists($value, $this->choices)) {
2686                 continue; // ignore it
2687             }
2688             $save[] = $value;
2689         }
2691         return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2692     }
2694     /**
2695      * Is setting related to query text - used when searching
2696      *
2697      * @param string $query
2698      * @return bool true if related, false if not
2699      */
2700     public function is_related($query) {
2701         if (!$this->load_choices() or empty($this->choices)) {
2702             return false;
2703         }
2704         if (parent::is_related($query)) {
2705             return true;
2706         }
2708         foreach ($this->choices as $desc) {
2709             if (strpos(textlib::strtolower($desc), $query) !== false) {
2710                 return true;
2711             }
2712         }
2713         return false;
2714     }
2716     /**
2717      * Returns XHTML multi-select field
2718      *
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
2723      */
2724     public function output_html($data, $query='') {
2725         if (!$this->load_choices() or empty($this->choices)) {
2726             return '';
2727         }
2728         $choices = $this->choices;
2729         $default = $this->get_defaultsetting();
2730         if (is_null($default)) {
2731             $default = array();
2732         }
2733         if (is_null($data)) {
2734             $data = array();
2735         }
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"';
2744             } else {
2745                 $selected = '';
2746             }
2747             if (in_array($key, $default)) {
2748                 $defaults[] = $description;
2749             }
2751             $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2752         }
2754         if (is_null($default)) {
2755             $defaultinfo = NULL;
2756         } if (!empty($defaults)) {
2757             $defaultinfo = implode(', ', $defaults);
2758         } else {
2759             $defaultinfo = get_string('none');
2760         }
2762         $return .= '</select></div>';
2763         return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2764     }
2767 /**
2768  * Time selector
2769  *
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)
2772  *
2773  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2774  */
2775 class admin_setting_configtime extends admin_setting {
2776     /** @var string Used for setting second select (minutes) */
2777     public $name2;
2779     /**
2780      * Constructor
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
2786      */
2787     public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2788         $this->name2 = $minutesname;
2789         parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2790     }
2792     /**
2793      * Get the selected time
2794      *
2795      * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2796      */
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)) {
2801             return NULL;
2802         }
2804         return array('h' => $result1, 'm' => $result2);
2805     }
2807     /**
2808      * Store the time (hours and minutes)
2809      *
2810      * @param array $data Must be form 'h'=>xx, 'm'=>xx
2811      * @return bool true if success, false if not
2812      */
2813     public function write_setting($data) {
2814         if (!is_array($data)) {
2815             return '';
2816         }
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'));
2820     }
2822     /**
2823      * Returns XHTML time select fields
2824      *
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)
2828      */
2829     public function output_html($data, $query='') {
2830         $default = $this->get_defaultsetting();
2832         if (is_array($default)) {
2833             $defaultinfo = $default['h'].':'.$default['m'];
2834         } else {
2835             $defaultinfo = NULL;
2836         }
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>';
2842         }
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>';
2846         }
2847         $return .= '</select></div>';
2848         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2849     }
2854 /**
2855  * Seconds duration setting.
2856  *
2857  * @copyright 2012 Petr Skoda (http://skodak.org)
2858  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859  */
2860 class admin_setting_configduration extends admin_setting {
2862     /** @var int default duration unit */
2863     protected $defaultunit;
2865     /**
2866      * Constructor
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)
2873      */
2874     public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
2875         if (is_number($defaultsetting)) {
2876             $defaultsetting = self::parse_seconds($defaultsetting);
2877         }
2878         $units = self::get_units();
2879         if (isset($units[$defaultunit])) {
2880             $this->defaultunit = $defaultunit;
2881         } else {
2882             $this->defaultunit = 86400;
2883         }
2884         parent::__construct($name, $visiblename, $description, $defaultsetting);
2885     }
2887     /**
2888      * Returns selectable units.
2889      * @static
2890      * @return array
2891      */
2892     protected static function get_units() {
2893         return array(
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'),
2899         );
2900     }
2902     /**
2903      * Converts seconds to some more user friendly string.
2904      * @static
2905      * @param int $seconds
2906      * @return string
2907      */
2908     protected static function get_duration_text($seconds) {
2909         if (empty($seconds)) {
2910             return get_string('none');
2911         }
2912         $data = self::parse_seconds($seconds);
2913         switch ($data['u']) {
2914             case (60*60*24*7):
2915                 return get_string('numweeks', '', $data['v']);
2916             case (60*60*24):
2917                 return get_string('numdays', '', $data['v']);
2918             case (60*60):
2919                 return get_string('numhours', '', $data['v']);
2920             case (60):
2921                 return get_string('numminutes', '', $data['v']);
2922             default:
2923                 return get_string('numseconds', '', $data['v']*$data['u']);
2924         }
2925     }
2927     /**
2928      * Finds suitable units for given duration.
2929      * @static
2930      * @param int $seconds
2931      * @return array
2932      */
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);
2937             }
2938         }
2939         return array('v'=>(int)$seconds, 'u'=>1);
2940     }
2942     /**
2943      * Get the selected duration as array.
2944      *
2945      * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
2946      */
2947     public function get_setting() {
2948         $seconds = $this->config_read($this->name);
2949         if (is_null($seconds)) {
2950             return null;
2951         }
2953         return self::parse_seconds($seconds);
2954     }
2956     /**
2957      * Store the duration as seconds.
2958      *
2959      * @param array $data Must be form 'h'=>xx, 'm'=>xx
2960      * @return bool true if success, false if not
2961      */
2962     public function write_setting($data) {
2963         if (!is_array($data)) {
2964             return '';
2965         }
2967         $seconds = (int)($data['v']*$data['u']);
2968         if ($seconds < 0) {
2969             return get_string('errorsetting', 'admin');
2970         }
2972         $result = $this->config_write($this->name, $seconds);
2973         return ($result ? '' : get_string('errorsetting', 'admin'));
2974     }
2976     /**
2977      * Returns duration text+select fields.
2978      *
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)
2982      */
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']);
2990         } else {
2991             $defaultinfo = null;
2992         }
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) {
3000             $selected = '';
3001             if ($data['v'] == 0) {
3002                 if ($val == $this->defaultunit) {
3003                     $selected = ' selected="selected"';
3004                 }
3005             } else if ($val == $data['u']) {
3006                 $selected = ' selected="selected"';
3007             }
3008             $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3009         }
3010         $return .= '</select></div>';
3011         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3012     }
3016 /**
3017  * Used to validate a textarea used for ip addresses
3018  *
3019  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3020  */
3021 class admin_setting_configiplist extends admin_setting_configtextarea {
3023     /**
3024      * Validate the contents of the textarea as IP addresses
3025      *
3026      * Used to validate a new line separated list of IP addresses collected from
3027      * a textarea control
3028      *
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
3031      */
3032     public function validate($data) {
3033         if(!empty($data)) {
3034             $ips = explode("\n", $data);
3035         } else {
3036             return true;
3037         }
3038         $result = true;
3039         foreach($ips as $ip) {
3040             $ip = trim($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)) {
3044                 $result = true;
3045             } else {
3046                 $result = false;
3047                 break;
3048             }
3049         }
3050         if($result) {
3051             return true;
3052         } else {
3053             return get_string('validateerror', 'admin');
3054         }
3055     }
3059 /**
3060  * An admin setting for selecting one or more users who have a capability
3061  * in the system context
3062  *
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.
3066  *
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.
3069  *
3070  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3071  */
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;
3078     /**
3079      * Constructor.
3080      *
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
3087      */
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);
3092     }
3094     /**
3095      * Load all of the uses who have the capability into choice array
3096      *
3097      * @return bool Always returns true
3098      */
3099     function load_choices() {
3100         if (is_array($this->choices)) {
3101             return true;
3102         }
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.');
3108         }
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)),
3114         );
3115         if ($this->includeadmins) {
3116             $admins = get_admins();
3117             foreach ($admins as $user) {
3118                 $this->choices[$user->id] = fullname($user);
3119             }
3120         }
3121         if (is_array($users)) {
3122             foreach ($users as $user) {
3123                 $this->choices[$user->id] = fullname($user);
3124             }
3125         }
3126         return true;
3127     }
3129     /**
3130      * Returns the default setting for class
3131      *
3132      * @return mixed Array, or string. Empty string if no default
3133      */
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;
3141             } else {
3142                 return '';
3143             }
3144     }
3146     /**
3147      * Returns the current setting
3148      *
3149      * @return mixed array or string
3150      */
3151     public function get_setting() {
3152         $result = parent::get_setting();
3153         if ($result === null) {
3154             // this is necessary for settings upgrade
3155             return null;
3156         }
3157         if (empty($result)) {
3158             $result = array('$@NONE@$');
3159         }
3160         return $result;
3161     }
3163     /**
3164      * Save the chosen setting provided as $data
3165      *
3166      * @param array $data
3167      * @return mixed string or array
3168      */
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@$');
3173         }
3174         // None never needs to be written to the DB.
3175         if (in_array('$@NONE@$', $data)) {
3176             unset($data[array_search('$@NONE@$', $data)]);
3177         }
3178         return parent::write_setting($data);
3179     }
3183 /**
3184  * Special checkbox for calendar - resets SESSION vars.
3185  *
3186  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3187  */
3188 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3189     /**
3190      * Calls the parent::__construct with default values
3191      *
3192      * name =>  calendar_adminseesall
3193      * visiblename => get_string('adminseesall', 'admin')
3194      * description => get_string('helpadminseesall', 'admin')
3195      * defaultsetting => 0
3196      */
3197     public function __construct() {
3198         parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3199             get_string('helpadminseesall', 'admin'), '0');
3200     }
3202     /**
3203      * Stores the setting passed in $data
3204      *
3205      * @param mixed gets converted to string for comparison
3206      * @return string empty string or error message
3207      */
3208     public function write_setting($data) {
3209         global $SESSION;
3210         return parent::write_setting($data);
3211     }
3214 /**
3215  * Special select for settings that are altered in setup.php and can not be altered on the fly
3216  *
3217  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3218  */
3219 class admin_setting_special_selectsetup extends admin_setting_configselect {
3220     /**
3221      * Reads the setting directly from the database
3222      *
3223      * @return mixed
3224      */
3225     public function get_setting() {
3226     // read directly from db!
3227         return get_config(NULL, $this->name);
3228     }
3230     /**
3231      * Save the setting passed in $data
3232      *
3233      * @param string $data The setting to save
3234      * @return string empty or error message
3235      */
3236     public function write_setting($data) {
3237         global $CFG;
3238         // do not change active CFG setting!
3239         $current = $CFG->{$this->name};
3240         $result = parent::write_setting($data);
3241         $CFG->{$this->name} = $current;
3242         return $result;
3243     }
3247 /**
3248  * Special select for frontpage - stores data in course table
3249  *
3250  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3251  */
3252 class admin_setting_sitesetselect extends admin_setting_configselect {
3253     /**
3254      * Returns the site name for the selected site
3255      *
3256      * @see get_site()
3257      * @return string The site name of the selected site
3258      */
3259     public function get_setting() {
3260         $site = course_get_format(get_site())->get_course();
3261         return $site->{$this->name};
3262     }
3264     /**
3265      * Updates the database and save the setting
3266      *
3267      * @param string data
3268      * @return string empty or error message
3269      */
3270     public function write_setting($data) {
3271         global $DB, $SITE;
3272         if (!in_array($data, array_keys($this->choices))) {
3273             return get_string('errorsetting', 'admin');
3274         }
3275         $record = new stdClass();
3276         $record->id           = SITEID;
3277         $temp                 = $this->name;
3278         $record->$temp        = $data;
3279         $record->timemodified = time();
3280         // update $SITE
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'));
3284     }
3288 /**
3289  * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3290  * block to hidden.
3291  *
3292  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3293  */
3294 class admin_setting_bloglevel extends admin_setting_configselect {
3295     /**
3296      * Updates the database and save the setting
3297      *
3298      * @param string data
3299      * @return string empty or error message
3300      */
3301     public function write_setting($data) {
3302         global $DB, $CFG;
3303         if ($data == 0) {
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));
3307             }
3308         } else {
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));
3314                 }
3315             }
3316         }
3317         return parent::write_setting($data);
3318     }
3322 /**
3323  * Special select - lists on the frontpage - hacky
3324  *
3325  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3326  */
3327 class admin_setting_courselist_frontpage extends admin_setting {
3328     /** @var array Array of choices value=>label */
3329     public $choices;
3331     /**
3332      * Construct override, requires one param
3333      *
3334      * @param bool $loggedin Is the user logged in
3335      */
3336     public function __construct($loggedin) {
3337         global $CFG;
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);
3344     }
3346     /**
3347      * Loads the choices available
3348      *
3349      * @return bool always returns true
3350      */
3351     public function load_choices() {
3352         global $DB;
3353         if (is_array($this->choices)) {
3354             return true;
3355         }
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]);
3363         }
3364         return true;
3365     }
3367     /**
3368      * Returns the selected settings
3369      *
3370      * @param mixed array or setting or null
3371      */
3372     public function get_setting() {
3373         $result = $this->config_read($this->name);
3374         if (is_null($result)) {
3375             return NULL;
3376         }
3377         if ($result === '') {
3378             return array();
3379         }
3380         return explode(',', $result);
3381     }
3383     /**
3384      * Save the selected options
3385      *
3386      * @param array $data
3387      * @return mixed empty string (data is not an array) or bool true=success false=failure
3388      */
3389     public function write_setting($data) {
3390         if (!is_array($data)) {
3391             return '';
3392         }
3393         $this->load_choices();
3394         $save = array();
3395         foreach($data as $datum) {
3396             if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3397                 continue;
3398             }
3399             $save[$datum] = $datum; // no duplicates
3400         }
3401         return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3402     }
3404     /**
3405      * Return XHTML select field and wrapping div
3406      *
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
3410      */
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
3417             }
3418         }
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
3424             }
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>';
3428             }
3429             $return .= '</select>';
3430             if ($i !== count($this->choices) - 2) {
3431                 $return .= '<br />';
3432             }
3433         }
3434         $return .= '</div>';
3436         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3437     }
3441 /**
3442  * Special checkbox for frontpage - stores data in course table
3443  *
3444  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3445  */
3446 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3447     /**
3448      * Returns the current sites name
3449      *
3450      * @return string
3451      */
3452     public function get_setting() {
3453         $site = course_get_format(get_site())->get_course();
3454         return $site->{$this->name};
3455     }
3457     /**
3458      * Save the selected setting
3459      *
3460      * @param string $data The selected site
3461      * @return string empty string or error message
3462      */
3463     public function write_setting($data) {
3464         global $DB, $SITE;
3465         $record = new stdClass();
3466         $record->id            = $SITE->id;
3467         $record->{$this->name} = ($data == '1' ? 1 : 0);
3468         $record->timemodified  = time();
3469         // update $SITE
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();
3475         return '';
3476     }
3479 /**
3480  * Special text for frontpage - stores data in course table.
3481  * Empty string means not set here. Manual setting is required.
3482  *
3483  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3484  */
3485 class admin_setting_sitesettext extends admin_setting_configtext {
3486     /**
3487      * Return the current setting
3488      *
3489      * @return mixed string or null
3490      */
3491     public function get_setting() {
3492         $site = course_get_format(get_site())->get_course();
3493         return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3494     }
3496     /**
3497      * Validate the selected data
3498      *
3499      * @param string $data The selected value to validate
3500      * @return mixed true or message string
3501      */
3502     public function validate($data) {
3503         $cleaned = clean_param($data, PARAM_TEXT);
3504         if ($cleaned === '') {
3505             return get_string('required');
3506         }
3507         if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3508             return true;
3509         } else {
3510             return get_string('validateerror', 'admin');
3511         }
3512     }
3514     /**
3515      * Save the selected setting
3516      *
3517      * @param string $data The selected value
3518      * @return string empty or error message
3519      */
3520     public function write_setting($data) {
3521         global $DB, $SITE;
3522         $data = trim($data);
3523         $validated = $this->validate($data);
3524         if ($validated !== true) {
3525             return $validated;
3526         }
3528         $record = new stdClass();
3529         $record->id            = $SITE->id;
3530         $record->{$this->name} = $data;
3531         $record->timemodified  = time();
3532         // update $SITE
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();
3538         return '';
3539     }
3543 /**
3544  * Special text editor for site description.
3545  *
3546  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3547  */
3548 class admin_setting_special_frontpagedesc extends admin_setting {
3549     /**
3550      * Calls parent::__construct with specific arguments
3551      */
3552     public function __construct() {
3553         parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3554         editors_head_setup();
3555     }
3557     /**
3558      * Return the current setting
3559      * @return string The current setting
3560      */
3561     public function get_setting() {
3562         $site = course_get_format(get_site())->get_course();
3563         return $site->{$this->name};
3564     }
3566     /**
3567      * Save the new setting
3568      *
3569      * @param string $data The new value to save
3570      * @return string empty or error message
3571      */
3572     public function write_setting($data) {
3573         global $DB, $SITE;
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();
3583         return '';
3584     }
3586     /**
3587      * Returns XHTML for the field plus wrapping div
3588      *
3589      * @param string $data The current value
3590      * @param string $query
3591      * @return string The XHTML output
3592      */
3593     public function output_html($data, $query='') {
3594         global $CFG;
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);
3600     }
3604 /**
3605  * Administration interface for emoticon_manager settings.
3606  *
3607  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3608  */
3609 class admin_setting_emoticons extends admin_setting {
3611     /**
3612      * Calls parent::__construct with specific args
3613      */
3614     public function __construct() {
3615         global $CFG;
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);
3620     }
3622     /**
3623      * Return the current setting(s)
3624      *
3625      * @return array Current settings array
3626      */
3627     public function get_setting() {
3628         global $CFG;
3630         $manager = get_emoticon_manager();
3632         $config = $this->config_read($this->name);
3633         if (is_null($config)) {
3634             return null;
3635         }
3637         $config = $manager->decode_stored_config($config);
3638         if (is_null($config)) {
3639             return null;
3640         }
3642         return $this->prepare_form_data($config);
3643     }
3645     /**
3646      * Save selected settings
3647      *
3648      * @param array $data Array of settings to save
3649      * @return bool
3650      */
3651     public function write_setting($data) {
3653         $manager = get_emoticon_manager();
3654         $emoticons = $this->process_form_data($data);
3656         if ($emoticons === false) {
3657             return false;
3658         }
3660         if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3661             return ''; // success
3662         } else {
3663             return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3664         }
3665     }
3667     /**
3668      * Return XHTML field(s) for options
3669      *
3670      * @param array $data Array of options to set in HTML
3671      * @return string XHTML string for the fields and wrapping div(s)
3672      */
3673     public function output_html($data, $query='') {
3674         global $OUTPUT;
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');
3687         $i = 0;
3688         foreach($data as $field => $value) {
3689             switch ($i) {
3690             case 0:
3691                 $out .= html_writer::start_tag('tr');
3692                 $current_text = $value;
3693                 $current_filename = '';
3694                 $current_imagecomponent = '';
3695                 $current_altidentifier = '';
3696                 $current_altcomponent = '';
3697             case 1:
3698                 $current_filename = $value;
3699             case 2:
3700                 $current_imagecomponent = $value;
3701             case 3:
3702                 $current_altidentifier = $value;
3703             case 4:
3704                 $current_altcomponent = $value;
3705             }
3707             $out .= html_writer::tag('td',
3708                 html_writer::empty_tag('input',
3709                     array(
3710                         'type'  => 'text',
3711                         'class' => 'form-text',
3712                         'name'  => $this->get_full_name().'['.$field.']',
3713                         'value' => $value,
3714                     )
3715                 ), array('class' => 'c'.$i)
3716             );
3718             if ($i == 4) {
3719                 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3720                     $alt = get_string($current_altidentifier, $current_altcomponent);
3721                 } else {
3722                     $alt = $current_text;
3723                 }
3724                 if ($current_filename) {
3725                     $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3726                 } else {
3727                     $out .= html_writer::tag('td', '');
3728                 }
3729                 $out .= html_writer::end_tag('tr');
3730                 $i = 0;
3731             } else {
3732                 $i++;
3733             }
3735         }
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);
3742     }
3744     /**
3745      * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3746      *
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
3750      */
3751     protected function prepare_form_data(array $emoticons) {
3753         $form = array();
3754         $i = 0;
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;
3761             $i++;
3762         }
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]    = '';
3770         return $form;
3771     }
3773     /**
3774      * Converts the data from admin settings form into an array of emoticon objects
3775      *
3776      * @see self::prepare_form_data()
3777      * @param array $data array of admin form fields and values
3778      * @return false|array of emoticon objects
3779      */
3780     protected function process_form_data(array $form) {
3782         $count = count($form); // number of form field values
3784         if ($count % 5) {
3785             // we must get five fields per emoticon object
3786             return false;
3787         }
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 = '';
3801             }
3803             if (strlen($emoticon->text) < 2) {
3804                 // do not allow single character emoticons
3805                 $emoticon->text = '';
3806             }
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 = '';
3812             }
3814             if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3815                 $emoticons[] = $emoticon;
3816             }
3817         }
3818         return $emoticons;
3819     }
3823 /**
3824  * Special setting for limiting of the list of available languages.
3825  *
3826  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3827  */
3828 class admin_setting_langlist extends admin_setting_configtext {
3829     /**
3830      * Calls parent::__construct with specific arguments
3831      */
3832     public function __construct() {
3833         parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3834     }
3836     /**
3837      * Save the new setting
3838      *
3839      * @param string $data The new setting
3840      * @return bool
3841      */
3842     public function write_setting($data) {
3843         $return = parent::write_setting($data);
3844         get_string_manager()->reset_caches();
3845         return $return;
3846     }
3850 /**
3851  * Selection of one of the recognised countries using the list
3852  * returned by {@link get_list_of_countries()}.
3853  *
3854  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3855  */
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);
3861     }
3863     /**
3864      * Lazy-load the available choices for the select box
3865      */
3866     public function load_choices() {
3867         global $CFG;
3868         if (is_array($this->choices)) {
3869             return true;
3870         }
3871         $this->choices = array_merge(
3872                 array('0' => get_string('choosedots')),
3873                 get_string_manager()->get_list_of_countries($this->includeall));
3874         return true;
3875     }
3879 /**
3880  * admin_setting_configselect for the default number of sections in a course,
3881  * simply so we can lazy-load the choices.
3882  *
3883  * @copyright 2011 The Open University
3884  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3885  */
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());
3889     }
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)) {
3895             $max = 52;
3896         }
3897         for ($i = 0; $i <= $max; $i++) {
3898             $this->choices[$i] = "$i";
3899         }
3900         return true;
3901     }
3905 /**
3906  * Course category selection
3907  *
3908  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3909  */
3910 class admin_settings_coursecat_select extends admin_setting_configselect {
3911     /**
3912      * Calls parent::__construct with specific arguments
3913      */
3914     public function __construct($name, $visiblename, $description, $defaultsetting) {
3915         parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3916     }
3918     /**
3919      * Load the available choices for the select box
3920      *
3921      * @return bool
3922      */
3923     public function load_choices() {
3924         global $CFG;
3925         require_once($CFG->dirroot.'/course/lib.php');
3926         if (is_array($this->choices)) {
3927             return true;
3928         }
3929         $this->choices = make_categories_options();
3930         return true;
3931     }
3935 /**
3936  * Special control for selecting days to backup
3937  *
3938  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3939  */
3940 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3941     /**
3942      * Calls parent::__construct with specific arguments
3943      */
3944     public function __construct() {
3945         parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3946         $this->plugin = 'backup';
3947     }
3949     /**
3950      * Load the available choices for the select box
3951      *
3952      * @return bool Always returns true
3953      */
3954     public function load_choices() {
3955         if (is_array($this->choices)) {
3956             return true;
3957         }
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');
3962         }
3963         return true;
3964     }
3968 /**
3969  * Special debug setting
3970  *
3971  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3972  */
3973 class admin_setting_special_debug extends admin_setting_configselect {
3974     /**
3975      * Calls parent::__construct with specific arguments
3976      */
3977     public function __construct() {
3978         parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3979     }
3981     /**
3982      * Load the available choices for the select box
3983      *
3984      * @return bool
3985      */
3986     public function load_choices() {
3987         if (is_array($this->choices)) {
3988             return true;
3989         }
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'));
3995         return true;
3996     }
4000 /**
4001  * Special admin control
4002  *
4003  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4004  */
4005 class admin_setting_special_calendar_weekend extends admin_setting {
4006     /**
4007      * Calls parent::__construct with specific arguments
4008      */
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);
4015     }
4017     /**
4018      * Gets the current settings as an array
4019      *
4020      * @return mixed Null if none, else array of settings
4021      */
4022     public function get_setting() {
4023         $result = $this->config_read($this->name);
4024         if (is_null($result)) {
4025             return NULL;
4026         }
4027         if ($result === '') {
4028             return array();
4029         }
4030         $settings = array();
4031         for ($i=0; $i<7; $i++) {
4032             if ($result & (1 << $i)) {
4033                 $settings[] = $i;
4034             }
4035         }
4036         return $settings;
4037     }
4039     /**
4040      * Save the new settings
4041      *
4042      * @param array $data Array of new settings
4043      * @return bool
4044      */
4045     public function write_setting($data) {
4046         if (!is_array($data)) {
4047             return '';
4048         }
4049         unset($data['xxxxx']);
4050         $result = 0;
4051         foreach($data as $index) {
4052             $result |= 1 << $index;
4053         }
4054         return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4055     }
4057     /**
4058      * Return XHTML to display the control
4059      *
4060      * @param array $data array of selected days
4061      * @param string $query
4062      * @return string XHTML for display (field + wrapping div(s)
4063      */
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>';
4071         }
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>';
4075         }
4076         $return .= '</tr></tbody></table>';
4078         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4080     }
4084 /**
4085  * Admin setting that allows a user to pick a behaviour.
4086  *
4087  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4088  */
4089 class admin_setting_question_behaviour extends admin_setting_configselect {
4090     /**
4091      * @param string $name name of config variable
4092      * @param string $visiblename display name
4093      * @param string $description description
4094      * @param string $default default.
4095      */
4096     public function __construct($name, $visiblename, $description, $default) {
4097         parent::__construct($name, $visiblename, $description, $default, NULL);
4098     }
4100     /**
4101      * Load list of behaviours as choices
4102      * @return bool true => success, false => error.
4103      */
4104     public function load_choices() {
4105         global $CFG;
4106         require_once($CFG->dirroot . '/question/engine/lib.php');
4107         $this->choices = question_engine::get_archetypal_behaviours();
4108         return true;
4109     }
4113 /**
4114  * Admin setting that allows a user to pick appropriate roles for something.
4115  *
4116  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4117  */
4118 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4119     /** @var array Array of capabilities which identify roles */
4120     private $types;
4122     /**
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.
4128      */
4129     public function __construct($name, $visiblename, $description, $types) {
4130         parent::__construct($name, $visiblename, $description, NULL, NULL);
4131         $this->types = $types;
4132     }
4134     /**
4135      * Load roles as choices
4136      *
4137      * @return bool true=>success, false=>error
4138      */
4139     public function load_choices() {
4140         global $CFG, $DB;
4141         if (during_initial_install()) {
4142             return false;
4143         }
4144         if (is_array($this->choices)) {
4145             return true;
4146         }
4147         if ($roles = get_all_roles()) {
4148             $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4149             return true;
4150         } else {
4151             return false;
4152         }
4153     }
4155     /**
4156      * Return the default setting for this control
4157      *
4158      * @return array Array of default settings
4159      */
4160     public function get_defaultsetting() {
4161         global $CFG;
4163         if (during_initial_install()) {
4164             return null;
4165         }
4166         $result = array();
4167         foreach($this->types as $archetype) {
4168             if ($caproles = get_archetype_roles($archetype)) {
4169                 foreach ($caproles as $caprole) {
4170                     $result[$caprole->id] = 1;
4171                 }
4172             }
4173         }
4174         return $result;
4175     }
4179 /**
4180  * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4181  *
4182  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4183  */
4184 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4185     /**
4186      * Constructor
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
4193      */
4194     public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4195         parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4196     }
4198     /**
4199      * Loads the current setting and returns array
4200      *
4201      * @return array Returns array value=>xx, __construct=>xx
4202      */
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)) {
4207             return NULL;
4208         }
4209         return array('value' => $value, 'adv' => $adv);
4210     }
4212     /**
4213      * Saves the new settings passed in $data
4214      *
4215      * @todo Add vartype handling to ensure $data is an array
4216      * @param array $data
4217      * @return mixed string or Array
4218      */
4219     public function write_setting($data) {
4220         $error = parent::write_setting($data['value']);
4221         if (!$error) {
4222             $value = empty($data['adv']) ? 0 : 1;
4223             $this->config_write($this->name.'_adv', $value);
4224         }
4225         return $error;
4226     }
4228     /**
4229      * Return XHTML for the control
4230      *
4231      * @param array $data Default data array
4232      * @param string $query
4233      * @return string XHTML to display control
4234      */
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[] = "''";
4241             } else {
4242                 $defaultinfo[] = $default['value'];
4243             }
4244         }
4245         if (!empty($default['adv'])) {
4246             $defaultinfo[] = get_string('advanced');
4247         }
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);
4262     }
4266 /**
4267  * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4268  *
4269  * @copyright 2009 Petr Skoda (http://skodak.org)
4270  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4271  */
4272 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4274     /**
4275      * Constructor
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
4282      */
4283     public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4284         parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4285     }
4287     /**
4288      * Loads the current setting and returns array
4289      *
4290      * @return array Returns array value=>xx, adv=>xx
4291      */
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)) {
4296             return NULL;
4297         }
4298         return array('value' => $value, 'adv' => $adv);
4299     }
4301     /**
4302      * Sets the value for the setting
4303      *
4304      * Sets the value for the setting to either the yes or no values
4305      * of the object by comparing $data to yes
4306      *
4307      * @param mixed $data Gets converted to str for comparison against yes value
4308      * @return string empty string or error
4309      */
4310     public function write_setting($data) {
4311         $error = parent::write_setting($data['value']);
4312         if (!$error) {
4313             $value = empty($data['adv']) ? 0 : 1;
4314             $this->config_write($this->name.'_adv', $value);
4315         }
4316         return $error;
4317     }
4319     /**
4320      * Returns an XHTML checkbox field and with extra advanced cehckbox
4321      *
4322      * @param string $data If $data matches yes then checkbox is checked
4323      * @param string $query
4324      * @return string XHTML field
4325      */
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');
4332             } else {
4333                 $defaultinfo[] = get_string('checkboxno', 'admin');