theme-anomaly MDL-25621 Added support for the langmenu to the config.php file
[moodle.git] / lib / adminlib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * Functions and classes used during installation, upgrades and for admin settings.
20  *
21  *  ADMIN SETTINGS TREE INTRODUCTION
22  *
23  *  This file performs the following tasks:
24  *   -it defines the necessary objects and interfaces to build the Moodle
25  *    admin hierarchy
26  *   -it defines the admin_externalpage_setup()
27  *
28  *  ADMIN_SETTING OBJECTS
29  *
30  *  Moodle settings are represented by objects that inherit from the admin_setting
31  *  class. These objects encapsulate how to read a setting, how to write a new value
32  *  to a setting, and how to appropriately display the HTML to modify the setting.
33  *
34  *  ADMIN_SETTINGPAGE OBJECTS
35  *
36  *  The admin_setting objects are then grouped into admin_settingpages. The latter
37  *  appear in the Moodle admin tree block. All interaction with admin_settingpage
38  *  objects is handled by the admin/settings.php file.
39  *
40  *  ADMIN_EXTERNALPAGE OBJECTS
41  *
42  *  There are some settings in Moodle that are too complex to (efficiently) handle
43  *  with admin_settingpages. (Consider, for example, user management and displaying
44  *  lists of users.) In this case, we use the admin_externalpage object. This object
45  *  places a link to an external PHP file in the admin tree block.
46  *
47  *  If you're using an admin_externalpage object for some settings, you can take
48  *  advantage of the admin_externalpage_* functions. For example, suppose you wanted
49  *  to add a foo.php file into admin. First off, you add the following line to
50  *  admin/settings/first.php (at the end of the file) or to some other file in
51  *  admin/settings:
52  * <code>
53  *     $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
54  *         $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
55  * </code>
56  *
57  *  Next, in foo.php, your file structure would resemble the following:
58  * <code>
59  *         require(dirname(dirname(dirname(__FILE__))).'/config.php');
60  *         require_once($CFG->libdir.'/adminlib.php');
61  *         admin_externalpage_setup('foo');
62  *         // functionality like processing form submissions goes here
63  *         echo $OUTPUT->header();
64  *         // your HTML goes here
65  *         echo $OUTPUT->footer();
66  * </code>
67  *
68  *  The admin_externalpage_setup() function call ensures the user is logged in,
69  *  and makes sure that they have the proper role permission to access the page.
70  *  It also configures all $PAGE properties needed for navigation.
71  *
72  *  ADMIN_CATEGORY OBJECTS
73  *
74  *  Above and beyond all this, we have admin_category objects. These objects
75  *  appear as folders in the admin tree block. They contain admin_settingpage's,
76  *  admin_externalpage's, and other admin_category's.
77  *
78  *  OTHER NOTES
79  *
80  *  admin_settingpage's, admin_externalpage's, and admin_category's all inherit
81  *  from part_of_admin_tree (a pseudointerface). This interface insists that
82  *  a class has a check_access method for access permissions, a locate method
83  *  used to find a specific node in the admin tree and find parent path.
84  *
85  *  admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
86  *  interface ensures that the class implements a recursive add function which
87  *  accepts a part_of_admin_tree object and searches for the proper place to
88  *  put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89  *
90  *  Please note that the $this->name field of any part_of_admin_tree must be
91  *  UNIQUE throughout the ENTIRE admin tree.
92  *
93  *  The $this->name field of an admin_setting object (which is *not* part_of_
94  *  admin_tree) must be unique on the respective admin_settingpage where it is
95  *  used.
96  *
97  * Original author: Vincenzo K. Marcovecchio
98  * Maintainer:      Petr Skoda
99  *
100  * @package    core
101  * @subpackage admin
102  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
103  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
104  */
106 defined('MOODLE_INTERNAL') || die();
108 /// Add libraries
109 require_once($CFG->libdir.'/ddllib.php');
110 require_once($CFG->libdir.'/xmlize.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     // recursively uninstall all module subplugins first
127     if ($type === 'mod') {
128         if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
129             $subplugins = array();
130             include("$CFG->dirroot/mod/$name/db/subplugins.php");
131             foreach ($subplugins as $subplugintype=>$dir) {
132                 $instances = get_plugin_list($subplugintype);
133                 foreach ($instances as $subpluginname => $notusedpluginpath) {
134                     uninstall_plugin($subplugintype, $subpluginname);
135                 }
136             }
137         }
139     }
141     $component = $type . '_' . $name;  // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
143     if ($type === 'mod') {
144         $pluginname = $name;  // eg. 'forum'
145         if (get_string_manager()->string_exists('modulename', $component)) {
146             $strpluginname = get_string('modulename', $component);
147         } else {
148             $strpluginname = $component;
149         }
151     } else {
152         $pluginname = $component;
153         if (get_string_manager()->string_exists('pluginname', $component)) {
154             $strpluginname = get_string('pluginname', $component);
155         } else {
156             $strpluginname = $component;
157         }
158     }
160     echo $OUTPUT->heading($pluginname);
162     $plugindirectory = get_plugin_directory($type, $name);
163     $uninstalllib = $plugindirectory . '/db/uninstall.php';
164     if (file_exists($uninstalllib)) {
165         require_once($uninstalllib);
166         $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall';    // eg. 'xmldb_workshop_uninstall()'
167         if (function_exists($uninstallfunction)) {
168             if (!$uninstallfunction()) {
169                 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
170             }
171         }
172     }
174     if ($type === 'mod') {
175     // perform cleanup tasks specific for activity modules
177         if (!$module = $DB->get_record('modules', array('name' => $name))) {
178             print_error('moduledoesnotexist', 'error');
179         }
181         // delete all the relevant instances from all course sections
182         if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
183             foreach ($coursemods as $coursemod) {
184                 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
185                     echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
186                 }
187             }
188         }
190         // clear course.modinfo for courses that used this module
191         $sql = "UPDATE {course}
192                    SET modinfo=''
193                  WHERE id IN (SELECT DISTINCT course
194                                 FROM {course_modules}
195                                WHERE module=?)";
196         $DB->execute($sql, array($module->id));
198         // delete all the course module records
199         $DB->delete_records('course_modules', array('module' => $module->id));
201         // delete module contexts
202         if ($coursemods) {
203             foreach ($coursemods as $coursemod) {
204                 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
205                     echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
206                 }
207             }
208         }
210         // delete the module entry itself
211         $DB->delete_records('modules', array('name' => $module->name));
213         // cleanup the gradebook
214         require_once($CFG->libdir.'/gradelib.php');
215         grade_uninstalled_module($module->name);
217         // Perform any custom uninstall tasks
218         if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
219             require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
220             $uninstallfunction = $module->name . '_uninstall';
221             if (function_exists($uninstallfunction)) {
222                 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
223                 if (!$uninstallfunction()) {
224                     echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
225                 }
226             }
227         }
229     } else if ($type === 'enrol') {
230         // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
231         // nuke all role assignments
232         role_unassign_all(array('component'=>$component));
233         // purge participants
234         $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
235         // purge enrol instances
236         $DB->delete_records('enrol', array('enrol'=>$name));
237         // tweak enrol settings
238         if (!empty($CFG->enrol_plugins_enabled)) {
239             $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
240             $enabledenrols = array_unique($enabledenrols);
241             $enabledenrols = array_flip($enabledenrols);
242             unset($enabledenrols[$name]);
243             $enabledenrols = array_flip($enabledenrols);
244             if (is_array($enabledenrols)) {
245                 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
246             }
247         }
248     }
250     // perform clean-up task common for all the plugin/subplugin types
252     // delete calendar events
253     $DB->delete_records('event', array('modulename' => $pluginname));
255     // delete all the logs
256     $DB->delete_records('log', array('module' => $pluginname));
258     // delete log_display information
259     $DB->delete_records('log_display', array('component' => $component));
261     // delete the module configuration records
262     unset_all_config_for_plugin($pluginname);
264     // delete the plugin tables
265     $xmldbfilepath = $plugindirectory . '/db/install.xml';
266     drop_plugin_tables($pluginname, $xmldbfilepath, false);
268     // delete the capabilities that were defined by this module
269     capabilities_cleanup($component);
271     // remove event handlers and dequeue pending events
272     events_uninstall($component);
274     echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
277 /**
278  * Returns the version of installed component
279  *
280  * @param string $component component name
281  * @param string $source either 'disk' or 'installed' - where to get the version information from
282  * @return string|bool version number or false if the component is not found
283  */
284 function get_component_version($component, $source='installed') {
285     global $CFG, $DB;
287     list($type, $name) = normalize_component($component);
289     // moodle core or a core subsystem
290     if ($type === 'core') {
291         if ($source === 'installed') {
292             if (empty($CFG->version)) {
293                 return false;
294             } else {
295                 return $CFG->version;
296             }
297         } else {
298             if (!is_readable($CFG->dirroot.'/version.php')) {
299                 return false;
300             } else {
301                 $version = null; //initialize variable for IDEs
302                 include($CFG->dirroot.'/version.php');
303                 return $version;
304             }
305         }
306     }
308     // activity module
309     if ($type === 'mod') {
310         if ($source === 'installed') {
311             return $DB->get_field('modules', 'version', array('name'=>$name));
312         } else {
313             $mods = get_plugin_list('mod');
314             if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
315                 return false;
316             } else {
317                 $module = new stdclass();
318                 include($mods[$name].'/version.php');
319                 return $module->version;
320             }
321         }
322     }
324     // block
325     if ($type === 'block') {
326         if ($source === 'installed') {
327             return $DB->get_field('block', 'version', array('name'=>$name));
328         } else {
329             $blocks = get_plugin_list('block');
330             if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
331                 return false;
332             } else {
333                 $plugin = new stdclass();
334                 include($blocks[$name].'/version.php');
335                 return $plugin->version;
336             }
337         }
338     }
340     // all other plugin types
341     if ($source === 'installed') {
342         return get_config($type.'_'.$name, 'version');
343     } else {
344         $plugins = get_plugin_list($type);
345         if (empty($plugins[$name])) {
346             return false;
347         } else {
348             $plugin = new stdclass();
349             include($plugins[$name].'/version.php');
350             return $plugin->version;
351         }
352     }
355 /**
356  * Delete all plugin tables
357  *
358  * @param string $name Name of plugin, used as table prefix
359  * @param string $file Path to install.xml file
360  * @param bool $feedback defaults to true
361  * @return bool Always returns true
362  */
363 function drop_plugin_tables($name, $file, $feedback=true) {
364     global $CFG, $DB;
366     // first try normal delete
367     if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
368         return true;
369     }
371     // then try to find all tables that start with name and are not in any xml file
372     $used_tables = get_used_table_names();
374     $tables = $DB->get_tables();
376     /// Iterate over, fixing id fields as necessary
377     foreach ($tables as $table) {
378         if (in_array($table, $used_tables)) {
379             continue;
380         }
382         if (strpos($table, $name) !== 0) {
383             continue;
384         }
386         // found orphan table --> delete it
387         if ($DB->get_manager()->table_exists($table)) {
388             $xmldb_table = new xmldb_table($table);
389             $DB->get_manager()->drop_table($xmldb_table);
390         }
391     }
393     return true;
396 /**
397  * Returns names of all known tables == tables that moodle knows about.
398  *
399  * @return array Array of lowercase table names
400  */
401 function get_used_table_names() {
402     $table_names = array();
403     $dbdirs = get_db_directories();
405     foreach ($dbdirs as $dbdir) {
406         $file = $dbdir.'/install.xml';
408         $xmldb_file = new xmldb_file($file);
410         if (!$xmldb_file->fileExists()) {
411             continue;
412         }
414         $loaded    = $xmldb_file->loadXMLStructure();
415         $structure = $xmldb_file->getStructure();
417         if ($loaded and $tables = $structure->getTables()) {
418             foreach($tables as $table) {
419                 $table_names[] = strtolower($table->name);
420             }
421         }
422     }
424     return $table_names;
427 /**
428  * Returns list of all directories where we expect install.xml files
429  * @return array Array of paths
430  */
431 function get_db_directories() {
432     global $CFG;
434     $dbdirs = array();
436     /// First, the main one (lib/db)
437     $dbdirs[] = $CFG->libdir.'/db';
439     /// Then, all the ones defined by get_plugin_types()
440     $plugintypes = get_plugin_types();
441     foreach ($plugintypes as $plugintype => $pluginbasedir) {
442         if ($plugins = get_plugin_list($plugintype)) {
443             foreach ($plugins as $plugin => $plugindir) {
444                 $dbdirs[] = $plugindir.'/db';
445             }
446         }
447     }
449     return $dbdirs;
452 /**
453  * Try to obtain or release the cron lock.
454  * @param string  $name  name of lock
455  * @param int  $until timestamp when this lock considered stale, null means remove lock unconditionally
456  * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
457  * @return bool true if lock obtained
458  */
459 function set_cron_lock($name, $until, $ignorecurrent=false) {
460     global $DB;
461     if (empty($name)) {
462         debugging("Tried to get a cron lock for a null fieldname");
463         return false;
464     }
466     // remove lock by force == remove from config table
467     if (is_null($until)) {
468         set_config($name, null);
469         return true;
470     }
472     if (!$ignorecurrent) {
473     // read value from db - other processes might have changed it
474         $value = $DB->get_field('config', 'value', array('name'=>$name));
476         if ($value and $value > time()) {
477         //lock active
478             return false;
479         }
480     }
482     set_config($name, $until);
483     return true;
486 /**
487  * Test if and critical warnings are present
488  * @return bool
489  */
490 function admin_critical_warnings_present() {
491     global $SESSION;
493     if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
494         return 0;
495     }
497     if (!isset($SESSION->admin_critical_warning)) {
498         $SESSION->admin_critical_warning = 0;
499         if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
500             $SESSION->admin_critical_warning = 1;
501         }
502     }
504     return $SESSION->admin_critical_warning;
507 /**
508  * Detects if float supports at least 10 decimal digits
509  *
510  * Detects if float supports at least 10 decimal digits
511  * and also if float-->string conversion works as expected.
512  *
513  * @return bool true if problem found
514  */
515 function is_float_problem() {
516     $num1 = 2009010200.01;
517     $num2 = 2009010200.02;
519     return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
522 /**
523  * Try to verify that dataroot is not accessible from web.
524  *
525  * Try to verify that dataroot is not accessible from web.
526  * It is not 100% correct but might help to reduce number of vulnerable sites.
527  * Protection from httpd.conf and .htaccess is not detected properly.
528  *
529  * @uses INSECURE_DATAROOT_WARNING
530  * @uses INSECURE_DATAROOT_ERROR
531  * @param bool $fetchtest try to test public access by fetching file, default false
532  * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
533  */
534 function is_dataroot_insecure($fetchtest=false) {
535     global $CFG;
537     $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
539     $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
540     $rp = strrev(trim($rp, '/'));
541     $rp = explode('/', $rp);
542     foreach($rp as $r) {
543         if (strpos($siteroot, '/'.$r.'/') === 0) {
544             $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
545         } else {
546             break; // probably alias root
547         }
548     }
550     $siteroot = strrev($siteroot);
551     $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
553     if (strpos($dataroot, $siteroot) !== 0) {
554         return false;
555     }
557     if (!$fetchtest) {
558         return INSECURE_DATAROOT_WARNING;
559     }
561     // now try all methods to fetch a test file using http protocol
563     $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
564     preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
565     $httpdocroot = $matches[1];
566     $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
567     make_upload_directory('diag');
568     $testfile = $CFG->dataroot.'/diag/public.txt';
569     if (!file_exists($testfile)) {
570         file_put_contents($testfile, 'test file, do not delete');
571     }
572     $teststr = trim(file_get_contents($testfile));
573     if (empty($teststr)) {
574     // hmm, strange
575         return INSECURE_DATAROOT_WARNING;
576     }
578     $testurl = $datarooturl.'/diag/public.txt';
579     if (extension_loaded('curl') and
580         !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
581         !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
582         ($ch = @curl_init($testurl)) !== false) {
583         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
584         curl_setopt($ch, CURLOPT_HEADER, false);
585         $data = curl_exec($ch);
586         if (!curl_errno($ch)) {
587             $data = trim($data);
588             if ($data === $teststr) {
589                 curl_close($ch);
590                 return INSECURE_DATAROOT_ERROR;
591             }
592         }
593         curl_close($ch);
594     }
596     if ($data = @file_get_contents($testurl)) {
597         $data = trim($data);
598         if ($data === $teststr) {
599             return INSECURE_DATAROOT_ERROR;
600         }
601     }
603     preg_match('|https?://([^/]+)|i', $testurl, $matches);
604     $sitename = $matches[1];
605     $error = 0;
606     if ($fp = @fsockopen($sitename, 80, $error)) {
607         preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
608         $localurl = $matches[1];
609         $out = "GET $localurl HTTP/1.1\r\n";
610         $out .= "Host: $sitename\r\n";
611         $out .= "Connection: Close\r\n\r\n";
612         fwrite($fp, $out);
613         $data = '';
614         $incoming = false;
615         while (!feof($fp)) {
616             if ($incoming) {
617                 $data .= fgets($fp, 1024);
618             } else if (@fgets($fp, 1024) === "\r\n") {
619                     $incoming = true;
620                 }
621         }
622         fclose($fp);
623         $data = trim($data);
624         if ($data === $teststr) {
625             return INSECURE_DATAROOT_ERROR;
626         }
627     }
629     return INSECURE_DATAROOT_WARNING;
632 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
634 /**
635  * Interface for anything appearing in the admin tree
636  *
637  * The interface that is implemented by anything that appears in the admin tree
638  * block. It forces inheriting classes to define a method for checking user permissions
639  * and methods for finding something in the admin tree.
640  *
641  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
642  */
643 interface part_of_admin_tree {
645 /**
646  * Finds a named part_of_admin_tree.
647  *
648  * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
649  * and not parentable_part_of_admin_tree, then this function should only check if
650  * $this->name matches $name. If it does, it should return a reference to $this,
651  * otherwise, it should return a reference to NULL.
652  *
653  * If a class inherits parentable_part_of_admin_tree, this method should be called
654  * recursively on all child objects (assuming, of course, the parent object's name
655  * doesn't match the search criterion).
656  *
657  * @param string $name The internal name of the part_of_admin_tree we're searching for.
658  * @return mixed An object reference or a NULL reference.
659  */
660     public function locate($name);
662     /**
663      * Removes named part_of_admin_tree.
664      *
665      * @param string $name The internal name of the part_of_admin_tree we want to remove.
666      * @return bool success.
667      */
668     public function prune($name);
670     /**
671      * Search using query
672      * @param string $query
673      * @return mixed array-object structure of found settings and pages
674      */
675     public function search($query);
677     /**
678      * Verifies current user's access to this part_of_admin_tree.
679      *
680      * Used to check if the current user has access to this part of the admin tree or
681      * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
682      * then this method is usually just a call to has_capability() in the site context.
683      *
684      * If a class inherits parentable_part_of_admin_tree, this method should return the
685      * logical OR of the return of check_access() on all child objects.
686      *
687      * @return bool True if the user has access, false if she doesn't.
688      */
689     public function check_access();
691     /**
692      * Mostly useful for removing of some parts of the tree in admin tree block.
693      *
694      * @return True is hidden from normal list view
695      */
696     public function is_hidden();
698     /**
699      * Show we display Save button at the page bottom?
700      * @return bool
701      */
702     public function show_save();
705 /**
706  * Interface implemented by any part_of_admin_tree that has children.
707  *
708  * The interface implemented by any part_of_admin_tree that can be a parent
709  * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
710  * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
711  * include an add method for adding other part_of_admin_tree objects as children.
712  *
713  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
714  */
715 interface parentable_part_of_admin_tree extends part_of_admin_tree {
717 /**
718  * Adds a part_of_admin_tree object to the admin tree.
719  *
720  * Used to add a part_of_admin_tree object to this object or a child of this
721  * object. $something should only be added if $destinationname matches
722  * $this->name. If it doesn't, add should be called on child objects that are
723  * also parentable_part_of_admin_tree's.
724  *
725  * @param string $destinationname The internal name of the new parent for $something.
726  * @param part_of_admin_tree $something The object to be added.
727  * @return bool True on success, false on failure.
728  */
729     public function add($destinationname, $something);
733 /**
734  * The object used to represent folders (a.k.a. categories) in the admin tree block.
735  *
736  * Each admin_category object contains a number of part_of_admin_tree objects.
737  *
738  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
739  */
740 class admin_category implements parentable_part_of_admin_tree {
742     /** @var mixed An array of part_of_admin_tree objects that are this object's children */
743     public $children;
744     /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
745     public $name;
746     /** @var string The displayed name for this category. Usually obtained through get_string() */
747     public $visiblename;
748     /** @var bool Should this category be hidden in admin tree block? */
749     public $hidden;
750     /** @var mixed Either a string or an array or strings */
751     public $path;
752     /** @var mixed Either a string or an array or strings */
753     public $visiblepath;
755     /** @var array fast lookup category cache, all categories of one tree point to one cache */
756     protected $category_cache;
758     /**
759      * Constructor for an empty admin category
760      *
761      * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
762      * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
763      * @param bool $hidden hide category in admin tree block, defaults to false
764      */
765     public function __construct($name, $visiblename, $hidden=false) {
766         $this->children    = array();
767         $this->name        = $name;
768         $this->visiblename = $visiblename;
769         $this->hidden      = $hidden;
770     }
772     /**
773      * Returns a reference to the part_of_admin_tree object with internal name $name.
774      *
775      * @param string $name The internal name of the object we want.
776      * @param bool $findpath initialize path and visiblepath arrays
777      * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
778      *                  defaults to false
779      */
780     public function locate($name, $findpath=false) {
781         if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
782             // somebody much have purged the cache
783             $this->category_cache[$this->name] = $this;
784         }
786         if ($this->name == $name) {
787             if ($findpath) {
788                 $this->visiblepath[] = $this->visiblename;
789                 $this->path[]        = $this->name;
790             }
791             return $this;
792         }
794         // quick category lookup
795         if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
796             return $this->category_cache[$name];
797         }
799         $return = NULL;
800         foreach($this->children as $childid=>$unused) {
801             if ($return = $this->children[$childid]->locate($name, $findpath)) {
802                 break;
803             }
804         }
806         if (!is_null($return) and $findpath) {
807             $return->visiblepath[] = $this->visiblename;
808             $return->path[]        = $this->name;
809         }
811         return $return;
812     }
814     /**
815      * Search using query
816      *
817      * @param string query
818      * @return mixed array-object structure of found settings and pages
819      */
820     public function search($query) {
821         $result = array();
822         foreach ($this->children as $child) {
823             $subsearch = $child->search($query);
824             if (!is_array($subsearch)) {
825                 debugging('Incorrect search result from '.$child->name);
826                 continue;
827             }
828             $result = array_merge($result, $subsearch);
829         }
830         return $result;
831     }
833     /**
834      * Removes part_of_admin_tree object with internal name $name.
835      *
836      * @param string $name The internal name of the object we want to remove.
837      * @return bool success
838      */
839     public function prune($name) {
841         if ($this->name == $name) {
842             return false;  //can not remove itself
843         }
845         foreach($this->children as $precedence => $child) {
846             if ($child->name == $name) {
847                 // clear cache and delete self
848                 if (is_array($this->category_cache)) {
849                     while($this->category_cache) {
850                         // delete the cache, but keep the original array address
851                         array_pop($this->category_cache);
852                     }
853                 }
854                 unset($this->children[$precedence]);
855                 return true;
856             } else if ($this->children[$precedence]->prune($name)) {
857                 return true;
858             }
859         }
860         return false;
861     }
863     /**
864      * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
865      *
866      * @param string $destinationame The internal name of the immediate parent that we want for $something.
867      * @param mixed $something A part_of_admin_tree or setting instance to be added.
868      * @return bool True if successfully added, false if $something can not be added.
869      */
870     public function add($parentname, $something) {
871         $parent = $this->locate($parentname);
872         if (is_null($parent)) {
873             debugging('parent does not exist!');
874             return false;
875         }
877         if ($something instanceof part_of_admin_tree) {
878             if (!($parent instanceof parentable_part_of_admin_tree)) {
879                 debugging('error - parts of tree can be inserted only into parentable parts');
880                 return false;
881             }
882             $parent->children[] = $something;
883             if (is_array($this->category_cache) and ($something instanceof admin_category)) {
884                 if (isset($this->category_cache[$something->name])) {
885                     debugging('Duplicate admin catefory name: '.$something->name);
886                 } else {
887                     $this->category_cache[$something->name] = $something;
888                     $something->category_cache =& $this->category_cache;
889                     foreach ($something->children as $child) {
890                         // just in case somebody already added subcategories
891                         if ($child instanceof admin_category) {
892                             if (isset($this->category_cache[$child->name])) {
893                                 debugging('Duplicate admin catefory name: '.$child->name);
894                             } else {
895                                 $this->category_cache[$child->name] = $child;
896                                 $child->category_cache =& $this->category_cache;
897                             }
898                         }
899                     }
900                 }
901             }
902             return true;
904         } else {
905             debugging('error - can not add this element');
906             return false;
907         }
909     }
911     /**
912      * Checks if the user has access to anything in this category.
913      *
914      * @return bool True if the user has access to at least one child in this category, false otherwise.
915      */
916     public function check_access() {
917         foreach ($this->children as $child) {
918             if ($child->check_access()) {
919                 return true;
920             }
921         }
922         return false;
923     }
925     /**
926      * Is this category hidden in admin tree block?
927      *
928      * @return bool True if hidden
929      */
930     public function is_hidden() {
931         return $this->hidden;
932     }
934     /**
935      * Show we display Save button at the page bottom?
936      * @return bool
937      */
938     public function show_save() {
939         foreach ($this->children as $child) {
940             if ($child->show_save()) {
941                 return true;
942             }
943         }
944         return false;
945     }
948 /**
949  * Root of admin settings tree, does not have any parent.
950  *
951  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
952  */
953 class admin_root extends admin_category {
954 /** @var array List of errors */
955     public $errors;
956     /** @var string search query */
957     public $search;
958     /** @var bool full tree flag - true means all settings required, false only pages required */
959     public $fulltree;
960     /** @var bool flag indicating loaded tree */
961     public $loaded;
962     /** @var mixed site custom defaults overriding defaults in settings files*/
963     public $custom_defaults;
965     /**
966      * @param bool $fulltree true means all settings required,
967      *                            false only pages required
968      */
969     public function __construct($fulltree) {
970         global $CFG;
972         parent::__construct('root', get_string('administration'), false);
973         $this->errors   = array();
974         $this->search   = '';
975         $this->fulltree = $fulltree;
976         $this->loaded   = false;
978         $this->category_cache = array();
980         // load custom defaults if found
981         $this->custom_defaults = null;
982         $defaultsfile = "$CFG->dirroot/local/defaults.php";
983         if (is_readable($defaultsfile)) {
984             $defaults = array();
985             include($defaultsfile);
986             if (is_array($defaults) and count($defaults)) {
987                 $this->custom_defaults = $defaults;
988             }
989         }
990     }
992     /**
993      * Empties children array, and sets loaded to false
994      *
995      * @param bool $requirefulltree
996      */
997     public function purge_children($requirefulltree) {
998         $this->children = array();
999         $this->fulltree = ($requirefulltree || $this->fulltree);
1000         $this->loaded   = false;
1001         //break circular dependencies - this helps PHP 5.2
1002         while($this->category_cache) {
1003             array_pop($this->category_cache);
1004         }
1005         $this->category_cache = array();
1006     }
1009 /**
1010  * Links external PHP pages into the admin tree.
1011  *
1012  * See detailed usage example at the top of this document (adminlib.php)
1013  *
1014  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1015  */
1016 class admin_externalpage implements part_of_admin_tree {
1018 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1019     public $name;
1021     /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1022     public $visiblename;
1024     /** @var string The external URL that we should link to when someone requests this external page. */
1025     public $url;
1027     /** @var string The role capability/permission a user must have to access this external page. */
1028     public $req_capability;
1030     /** @var object The context in which capability/permission should be checked, default is site context. */
1031     public $context;
1033     /** @var bool hidden in admin tree block. */
1034     public $hidden;
1036     /** @var mixed either string or array of string */
1037     public $path;
1038     public $visiblepath;
1040     /**
1041      * Constructor for adding an external page into the admin tree.
1042      *
1043      * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1044      * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1045      * @param string $url The external URL that we should link to when someone requests this external page.
1046      * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1047      * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1048      * @param stdClass $context The context the page relates to. Not sure what happens
1049      *      if you specify something other than system or front page. Defaults to system.
1050      */
1051     public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1052         $this->name        = $name;
1053         $this->visiblename = $visiblename;
1054         $this->url         = $url;
1055         if (is_array($req_capability)) {
1056             $this->req_capability = $req_capability;
1057         } else {
1058             $this->req_capability = array($req_capability);
1059         }
1060         $this->hidden = $hidden;
1061         $this->context = $context;
1062     }
1064     /**
1065      * Returns a reference to the part_of_admin_tree object with internal name $name.
1066      *
1067      * @param string $name The internal name of the object we want.
1068      * @param bool $findpath defaults to false
1069      * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1070      */
1071     public function locate($name, $findpath=false) {
1072         if ($this->name == $name) {
1073             if ($findpath) {
1074                 $this->visiblepath = array($this->visiblename);
1075                 $this->path        = array($this->name);
1076             }
1077             return $this;
1078         } else {
1079             $return = NULL;
1080             return $return;
1081         }
1082     }
1084     /**
1085      * This function always returns false, required function by interface
1086      *
1087      * @param string $name
1088      * @return false
1089      */
1090     public function prune($name) {
1091         return false;
1092     }
1094     /**
1095      * Search using query
1096      *
1097      * @param string $query
1098      * @return mixed array-object structure of found settings and pages
1099      */
1100     public function search($query) {
1101         $textlib = textlib_get_instance();
1103         $found = false;
1104         if (strpos(strtolower($this->name), $query) !== false) {
1105             $found = true;
1106         } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1107                 $found = true;
1108             }
1109         if ($found) {
1110             $result = new stdClass();
1111             $result->page     = $this;
1112             $result->settings = array();
1113             return array($this->name => $result);
1114         } else {
1115             return array();
1116         }
1117     }
1119     /**
1120      * Determines if the current user has access to this external page based on $this->req_capability.
1121      *
1122      * @return bool True if user has access, false otherwise.
1123      */
1124     public function check_access() {
1125         global $CFG;
1126         $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1127         foreach($this->req_capability as $cap) {
1128             if (has_capability($cap, $context)) {
1129                 return true;
1130             }
1131         }
1132         return false;
1133     }
1135     /**
1136      * Is this external page hidden in admin tree block?
1137      *
1138      * @return bool True if hidden
1139      */
1140     public function is_hidden() {
1141         return $this->hidden;
1142     }
1144     /**
1145      * Show we display Save button at the page bottom?
1146      * @return bool
1147      */
1148     public function show_save() {
1149         return false;
1150     }
1153 /**
1154  * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1155  *
1156  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1157  */
1158 class admin_settingpage implements part_of_admin_tree {
1160 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1161     public $name;
1163     /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1164     public $visiblename;
1166     /** @var mixed An array of admin_setting objects that are part of this setting page. */
1167     public $settings;
1169     /** @var string The role capability/permission a user must have to access this external page. */
1170     public $req_capability;
1172     /** @var object The context in which capability/permission should be checked, default is site context. */
1173     public $context;
1175     /** @var bool hidden in admin tree block. */
1176     public $hidden;
1178     /** @var mixed string of paths or array of strings of paths */
1179     public $path;
1180     public $visiblepath;
1182     /**
1183      * see admin_settingpage for details of this function
1184      *
1185      * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1186      * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1187      * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1188      * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1189      * @param stdClass $context The context the page relates to. Not sure what happens
1190      *      if you specify something other than system or front page. Defaults to system.
1191      */
1192     public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1193         $this->settings    = new stdClass();
1194         $this->name        = $name;
1195         $this->visiblename = $visiblename;
1196         if (is_array($req_capability)) {
1197             $this->req_capability = $req_capability;
1198         } else {
1199             $this->req_capability = array($req_capability);
1200         }
1201         $this->hidden      = $hidden;
1202         $this->context     = $context;
1203     }
1205     /**
1206      * see admin_category
1207      *
1208      * @param string $name
1209      * @param bool $findpath
1210      * @return mixed Object (this) if name ==  this->name, else returns null
1211      */
1212     public function locate($name, $findpath=false) {
1213         if ($this->name == $name) {
1214             if ($findpath) {
1215                 $this->visiblepath = array($this->visiblename);
1216                 $this->path        = array($this->name);
1217             }
1218             return $this;
1219         } else {
1220             $return = NULL;
1221             return $return;
1222         }
1223     }
1225     /**
1226      * Search string in settings page.
1227      *
1228      * @param string $query
1229      * @return array
1230      */
1231     public function search($query) {
1232         $found = array();
1234         foreach ($this->settings as $setting) {
1235             if ($setting->is_related($query)) {
1236                 $found[] = $setting;
1237             }
1238         }
1240         if ($found) {
1241             $result = new stdClass();
1242             $result->page     = $this;
1243             $result->settings = $found;
1244             return array($this->name => $result);
1245         }
1247         $textlib = textlib_get_instance();
1249         $found = false;
1250         if (strpos(strtolower($this->name), $query) !== false) {
1251             $found = true;
1252         } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1253                 $found = true;
1254             }
1255         if ($found) {
1256             $result = new stdClass();
1257             $result->page     = $this;
1258             $result->settings = array();
1259             return array($this->name => $result);
1260         } else {
1261             return array();
1262         }
1263     }
1265     /**
1266      * This function always returns false, required by interface
1267      *
1268      * @param string $name
1269      * @return bool Always false
1270      */
1271     public function prune($name) {
1272         return false;
1273     }
1275     /**
1276      * adds an admin_setting to this admin_settingpage
1277      *
1278      * 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
1279      * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1280      *
1281      * @param object $setting is the admin_setting object you want to add
1282      * @return bool true if successful, false if not
1283      */
1284     public function add($setting) {
1285         if (!($setting instanceof admin_setting)) {
1286             debugging('error - not a setting instance');
1287             return false;
1288         }
1290         $this->settings->{$setting->name} = $setting;
1291         return true;
1292     }
1294     /**
1295      * see admin_externalpage
1296      *
1297      * @return bool Returns true for yes false for no
1298      */
1299     public function check_access() {
1300         global $CFG;
1301         $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1302         foreach($this->req_capability as $cap) {
1303             if (has_capability($cap, $context)) {
1304                 return true;
1305             }
1306         }
1307         return false;
1308     }
1310     /**
1311      * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1312      * @return string Returns an XHTML string
1313      */
1314     public function output_html() {
1315         $adminroot = admin_get_root();
1316         $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1317         foreach($this->settings as $setting) {
1318             $fullname = $setting->get_full_name();
1319             if (array_key_exists($fullname, $adminroot->errors)) {
1320                 $data = $adminroot->errors[$fullname]->data;
1321             } else {
1322                 $data = $setting->get_setting();
1323                 // do not use defaults if settings not available - upgrade settings handles the defaults!
1324             }
1325             $return .= $setting->output_html($data);
1326         }
1327         $return .= '</fieldset>';
1328         return $return;
1329     }
1331     /**
1332      * Is this settings page hidden in admin tree block?
1333      *
1334      * @return bool True if hidden
1335      */
1336     public function is_hidden() {
1337         return $this->hidden;
1338     }
1340     /**
1341      * Show we display Save button at the page bottom?
1342      * @return bool
1343      */
1344     public function show_save() {
1345         foreach($this->settings as $setting) {
1346             if (empty($setting->nosave)) {
1347                 return true;
1348             }
1349         }
1350         return false;
1351     }
1355 /**
1356  * Admin settings class. Only exists on setting pages.
1357  * Read & write happens at this level; no authentication.
1358  *
1359  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1360  */
1361 abstract class admin_setting {
1362 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1363     public $name;
1364     /** @var string localised name */
1365     public $visiblename;
1366     /** @var string localised long description in Markdown format */
1367     public $description;
1368     /** @var mixed Can be string or array of string */
1369     public $defaultsetting;
1370     /** @var string */
1371     public $updatedcallback;
1372     /** @var mixed can be String or Null.  Null means main config table */
1373     public $plugin; // null means main config table
1374     /** @var bool true indicates this setting does not actually save anything, just information */
1375     public $nosave = false;
1377     /**
1378      * Constructor
1379      * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1380      *                     or 'myplugin/mysetting' for ones in config_plugins.
1381      * @param string $visiblename localised name
1382      * @param string $description localised long description
1383      * @param mixed $defaultsetting string or array depending on implementation
1384      */
1385     public function __construct($name, $visiblename, $description, $defaultsetting) {
1386         $this->parse_setting_name($name);
1387         $this->visiblename    = $visiblename;
1388         $this->description    = $description;
1389         $this->defaultsetting = $defaultsetting;
1390     }
1392     /**
1393      * Set up $this->name and potentially $this->plugin
1394      *
1395      * Set up $this->name and possibly $this->plugin based on whether $name looks
1396      * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1397      * on the names, that is, output a developer debug warning if the name
1398      * contains anything other than [a-zA-Z0-9_]+.
1399      *
1400      * @param string $name the setting name passed in to the constructor.
1401      */
1402     private function parse_setting_name($name) {
1403         $bits = explode('/', $name);
1404         if (count($bits) > 2) {
1405             throw new moodle_exception('invalidadminsettingname', '', '', $name);
1406         }
1407         $this->name = array_pop($bits);
1408         if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1409             throw new moodle_exception('invalidadminsettingname', '', '', $name);
1410         }
1411         if (!empty($bits)) {
1412             $this->plugin = array_pop($bits);
1413             if ($this->plugin === 'moodle') {
1414                 $this->plugin = null;
1415             } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1416                     throw new moodle_exception('invalidadminsettingname', '', '', $name);
1417                 }
1418         }
1419     }
1421     /**
1422      * Returns the fullname prefixed by the plugin
1423      * @return string
1424      */
1425     public function get_full_name() {
1426         return 's_'.$this->plugin.'_'.$this->name;
1427     }
1429     /**
1430      * Returns the ID string based on plugin and name
1431      * @return string
1432      */
1433     public function get_id() {
1434         return 'id_s_'.$this->plugin.'_'.$this->name;
1435     }
1437     /**
1438      * Returns the config if possible
1439      *
1440      * @return mixed returns config if successfull else null
1441      */
1442     public function config_read($name) {
1443         global $CFG;
1444         if (!empty($this->plugin)) {
1445             $value = get_config($this->plugin, $name);
1446             return $value === false ? NULL : $value;
1448         } else {
1449             if (isset($CFG->$name)) {
1450                 return $CFG->$name;
1451             } else {
1452                 return NULL;
1453             }
1454         }
1455     }
1457     /**
1458      * Used to set a config pair and log change
1459      *
1460      * @param string $name
1461      * @param mixed $value Gets converted to string if not null
1462      * @return bool Write setting to config table
1463      */
1464     public function config_write($name, $value) {
1465         global $DB, $USER, $CFG;
1467         if ($this->nosave) {
1468             return true;
1469         }
1471         // make sure it is a real change
1472         $oldvalue = get_config($this->plugin, $name);
1473         $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1474         $value = is_null($value) ? null : (string)$value;
1476         if ($oldvalue === $value) {
1477             return true;
1478         }
1480         // store change
1481         set_config($name, $value, $this->plugin);
1483         // log change
1484         $log = new stdClass();
1485         $log->userid       = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1486         $log->timemodified = time();
1487         $log->plugin       = $this->plugin;
1488         $log->name         = $name;
1489         $log->value        = $value;
1490         $log->oldvalue     = $oldvalue;
1491         $DB->insert_record('config_log', $log);
1493         return true; // BC only
1494     }
1496     /**
1497      * Returns current value of this setting
1498      * @return mixed array or string depending on instance, NULL means not set yet
1499      */
1500     public abstract function get_setting();
1502     /**
1503      * Returns default setting if exists
1504      * @return mixed array or string depending on instance; NULL means no default, user must supply
1505      */
1506     public function get_defaultsetting() {
1507         $adminroot =  admin_get_root(false, false);
1508         if (!empty($adminroot->custom_defaults)) {
1509             $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1510             if (isset($adminroot->custom_defaults[$plugin])) {
1511                 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1512                     return $adminroot->custom_defaults[$plugin][$this->name];
1513                 }
1514             }
1515         }
1516         return $this->defaultsetting;
1517     }
1519     /**
1520      * Store new setting
1521      *
1522      * @param mixed $data string or array, must not be NULL
1523      * @return string empty string if ok, string error message otherwise
1524      */
1525     public abstract function write_setting($data);
1527     /**
1528      * Return part of form with setting
1529      * This function should always be overwritten
1530      *
1531      * @param mixed $data array or string depending on setting
1532      * @param string $query
1533      * @return string
1534      */
1535     public function output_html($data, $query='') {
1536     // should be overridden
1537         return;
1538     }
1540     /**
1541      * Function called if setting updated - cleanup, cache reset, etc.
1542      * @param string $functionname Sets the function name
1543      */
1544     public function set_updatedcallback($functionname) {
1545         $this->updatedcallback = $functionname;
1546     }
1548     /**
1549      * Is setting related to query text - used when searching
1550      * @param string $query
1551      * @return bool
1552      */
1553     public function is_related($query) {
1554         if (strpos(strtolower($this->name), $query) !== false) {
1555             return true;
1556         }
1557         $textlib = textlib_get_instance();
1558         if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1559             return true;
1560         }
1561         if (strpos($textlib->strtolower($this->description), $query) !== false) {
1562             return true;
1563         }
1564         $current = $this->get_setting();
1565         if (!is_null($current)) {
1566             if (is_string($current)) {
1567                 if (strpos($textlib->strtolower($current), $query) !== false) {
1568                     return true;
1569                 }
1570             }
1571         }
1572         $default = $this->get_defaultsetting();
1573         if (!is_null($default)) {
1574             if (is_string($default)) {
1575                 if (strpos($textlib->strtolower($default), $query) !== false) {
1576                     return true;
1577                 }
1578             }
1579         }
1580         return false;
1581     }
1584 /**
1585  * No setting - just heading and text.
1586  *
1587  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1588  */
1589 class admin_setting_heading extends admin_setting {
1590 /**
1591  * not a setting, just text
1592  * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1593  * @param string $heading heading
1594  * @param string $information text in box
1595  */
1596     public function __construct($name, $heading, $information) {
1597         $this->nosave = true;
1598         parent::__construct($name, $heading, $information, '');
1599     }
1601     /**
1602      * Always returns true
1603      * @return bool Always returns true
1604      */
1605     public function get_setting() {
1606         return true;
1607     }
1609     /**
1610      * Always returns true
1611      * @return bool Always returns true
1612      */
1613     public function get_defaultsetting() {
1614         return true;
1615     }
1617     /**
1618      * Never write settings
1619      * @return string Always returns an empty string
1620      */
1621     public function write_setting($data) {
1622     // do not write any setting
1623         return '';
1624     }
1626     /**
1627      * Returns an HTML string
1628      * @return string Returns an HTML string
1629      */
1630     public function output_html($data, $query='') {
1631         global $OUTPUT;
1632         $return = '';
1633         if ($this->visiblename != '') {
1634             $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1635         }
1636         if ($this->description != '') {
1637             $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1638         }
1639         return $return;
1640     }
1643 /**
1644  * The most flexibly setting, user is typing text
1645  *
1646  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1647  */
1648 class admin_setting_configtext extends admin_setting {
1650 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1651     public $paramtype;
1652     /** @var int default field size */
1653     public $size;
1655     /**
1656      * Config text constructor
1657      *
1658      * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1659      * @param string $visiblename localised
1660      * @param string $description long localised info
1661      * @param string $defaultsetting
1662      * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1663      * @param int $size default field size
1664      */
1665     public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1666         $this->paramtype = $paramtype;
1667         if (!is_null($size)) {
1668             $this->size  = $size;
1669         } else {
1670             $this->size  = ($paramtype === PARAM_INT) ? 5 : 30;
1671         }
1672         parent::__construct($name, $visiblename, $description, $defaultsetting);
1673     }
1675     /**
1676      * Return the setting
1677      *
1678      * @return mixed returns config if successful else null
1679      */
1680     public function get_setting() {
1681         return $this->config_read($this->name);
1682     }
1684     public function write_setting($data) {
1685         if ($this->paramtype === PARAM_INT and $data === '') {
1686         // do not complain if '' used instead of 0
1687             $data = 0;
1688         }
1689         // $data is a string
1690         $validated = $this->validate($data);
1691         if ($validated !== true) {
1692             return $validated;
1693         }
1694         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1695     }
1697     /**
1698      * Validate data before storage
1699      * @param string data
1700      * @return mixed true if ok string if error found
1701      */
1702     public function validate($data) {
1703         // allow paramtype to be a custom regex if it is the form of /pattern/
1704         if (preg_match('#^/.*/$#', $this->paramtype)) {
1705             if (preg_match($this->paramtype, $data)) {
1706                 return true;
1707             } else {
1708                 return get_string('validateerror', 'admin');
1709             }
1711         } else if ($this->paramtype === PARAM_RAW) {
1712             return true;
1714         } else {
1715             $cleaned = clean_param($data, $this->paramtype);
1716             if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1717                 return true;
1718             } else {
1719                 return get_string('validateerror', 'admin');
1720             }
1721         }
1722     }
1724     /**
1725      * Return an XHTML string for the setting
1726      * @return string Returns an XHTML string
1727      */
1728     public function output_html($data, $query='') {
1729         $default = $this->get_defaultsetting();
1731         return format_admin_setting($this, $this->visiblename,
1732         '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1733         $this->description, true, '', $default, $query);
1734     }
1737 /**
1738  * General text area without html editor.
1739  *
1740  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1741  */
1742 class admin_setting_configtextarea extends admin_setting_configtext {
1743     private $rows;
1744     private $cols;
1746     /**
1747      * @param string $name
1748      * @param string $visiblename
1749      * @param string $description
1750      * @param mixed $defaultsetting string or array
1751      * @param mixed $paramtype
1752      * @param string $cols The number of columns to make the editor
1753      * @param string $rows The number of rows to make the editor
1754      */
1755     public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1756         $this->rows = $rows;
1757         $this->cols = $cols;
1758         parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1759     }
1760     /**
1761      * Returns an XHTML string for the editor
1762      *
1763      * @param string $data
1764      * @param string $query
1765      * @return string XHTML string for the editor
1766      */
1767     public function output_html($data, $query='') {
1768         $default = $this->get_defaultsetting();
1770         $defaultinfo = $default;
1771         if (!is_null($default) and $default !== '') {
1772             $defaultinfo = "\n".$default;
1773         }
1775         return format_admin_setting($this, $this->visiblename,
1776         '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1777         $this->description, true, '', $defaultinfo, $query);
1778     }
1781 /**
1782  * General text area with html editor.
1783  */
1784 class admin_setting_confightmleditor extends admin_setting_configtext {
1785     private $rows;
1786     private $cols;
1788     /**
1789      * @param string $name
1790      * @param string $visiblename
1791      * @param string $description
1792      * @param mixed $defaultsetting string or array
1793      * @param mixed $paramtype
1794      */
1795     public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1796         $this->rows = $rows;
1797         $this->cols = $cols;
1798         parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1799         editors_head_setup();
1800     }
1801     /**
1802      * Returns an XHTML string for the editor
1803      *
1804      * @param string $data
1805      * @param string $query
1806      * @return string XHTML string for the editor
1807      */
1808     public function output_html($data, $query='') {
1809         $default = $this->get_defaultsetting();
1811         $defaultinfo = $default;
1812         if (!is_null($default) and $default !== '') {
1813             $defaultinfo = "\n".$default;
1814         }
1816         $editor = editors_get_preferred_editor(FORMAT_HTML);
1817         $editor->use_editor($this->get_id(), array('noclean'=>true));
1819         return format_admin_setting($this, $this->visiblename,
1820         '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1821         $this->description, true, '', $defaultinfo, $query);
1822     }
1825 /**
1826  * Password field, allows unmasking of password
1827  *
1828  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1829  */
1830 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1831 /**
1832  * Constructor
1833  * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1834  * @param string $visiblename localised
1835  * @param string $description long localised info
1836  * @param string $defaultsetting default password
1837  */
1838     public function __construct($name, $visiblename, $description, $defaultsetting) {
1839         parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1840     }
1842     /**
1843      * Returns XHTML for the field
1844      * Writes Javascript into the HTML below right before the last div
1845      *
1846      * @todo Make javascript available through newer methods if possible
1847      * @param string $data Value for the field
1848      * @param string $query Passed as final argument for format_admin_setting
1849      * @return string XHTML field
1850      */
1851     public function output_html($data, $query='') {
1852         $id = $this->get_id();
1853         $unmask = get_string('unmaskpassword', 'form');
1854         $unmaskjs = '<script type="text/javascript">
1855 //<![CDATA[
1856 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1858 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1860 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1862 var unmaskchb = document.createElement("input");
1863 unmaskchb.setAttribute("type", "checkbox");
1864 unmaskchb.setAttribute("id", "'.$id.'unmask");
1865 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1866 unmaskdiv.appendChild(unmaskchb);
1868 var unmasklbl = document.createElement("label");
1869 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1870 if (is_ie) {
1871   unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1872 } else {
1873   unmasklbl.setAttribute("for", "'.$id.'unmask");
1875 unmaskdiv.appendChild(unmasklbl);
1877 if (is_ie) {
1878   // ugly hack to work around the famous onchange IE bug
1879   unmaskchb.onclick = function() {this.blur();};
1880   unmaskdiv.onclick = function() {this.blur();};
1882 //]]>
1883 </script>';
1884         return format_admin_setting($this, $this->visiblename,
1885         '<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>',
1886         $this->description, true, '', NULL, $query);
1887     }
1890 /**
1891  * Path to directory
1892  *
1893  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1894  */
1895 class admin_setting_configfile extends admin_setting_configtext {
1896 /**
1897  * Constructor
1898  * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1899  * @param string $visiblename localised
1900  * @param string $description long localised info
1901  * @param string $defaultdirectory default directory location
1902  */
1903     public function __construct($name, $visiblename, $description, $defaultdirectory) {
1904         parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1905     }
1907     /**
1908      * Returns XHTML for the field
1909      *
1910      * Returns XHTML for the field and also checks whether the file
1911      * specified in $data exists using file_exists()
1912      *
1913      * @param string $data File name and path to use in value attr
1914      * @param string $query
1915      * @return string XHTML field
1916      */
1917     public function output_html($data, $query='') {
1918         $default = $this->get_defaultsetting();
1920         if ($data) {
1921             if (file_exists($data)) {
1922                 $executable = '<span class="pathok">&#x2714;</span>';
1923             } else {
1924                 $executable = '<span class="patherror">&#x2718;</span>';
1925             }
1926         } else {
1927             $executable = '';
1928         }
1930         return format_admin_setting($this, $this->visiblename,
1931         '<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>',
1932         $this->description, true, '', $default, $query);
1933     }
1936 /**
1937  * Path to executable file
1938  *
1939  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1940  */
1941 class admin_setting_configexecutable extends admin_setting_configfile {
1943 /**
1944  * Returns an XHTML field
1945  *
1946  * @param string $data This is the value for the field
1947  * @param string $query
1948  * @return string XHTML field
1949  */
1950     public function output_html($data, $query='') {
1951         $default = $this->get_defaultsetting();
1953         if ($data) {
1954             if (file_exists($data) and is_executable($data)) {
1955                 $executable = '<span class="pathok">&#x2714;</span>';
1956             } else {
1957                 $executable = '<span class="patherror">&#x2718;</span>';
1958             }
1959         } else {
1960             $executable = '';
1961         }
1963         return format_admin_setting($this, $this->visiblename,
1964         '<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>',
1965         $this->description, true, '', $default, $query);
1966     }
1969 /**
1970  * Path to directory
1971  *
1972  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1973  */
1974 class admin_setting_configdirectory extends admin_setting_configfile {
1976 /**
1977  * Returns an XHTML field
1978  *
1979  * @param string $data This is the value for the field
1980  * @param string $query
1981  * @return string XHTML
1982  */
1983     public function output_html($data, $query='') {
1984         $default = $this->get_defaultsetting();
1986         if ($data) {
1987             if (file_exists($data) and is_dir($data)) {
1988                 $executable = '<span class="pathok">&#x2714;</span>';
1989             } else {
1990                 $executable = '<span class="patherror">&#x2718;</span>';
1991             }
1992         } else {
1993             $executable = '';
1994         }
1996         return format_admin_setting($this, $this->visiblename,
1997         '<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>',
1998         $this->description, true, '', $default, $query);
1999     }
2002 /**
2003  * Checkbox
2004  *
2005  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2006  */
2007 class admin_setting_configcheckbox extends admin_setting {
2008 /** @var string Value used when checked */
2009     public $yes;
2010     /** @var string Value used when not checked */
2011     public $no;
2013     /**
2014      * Constructor
2015      * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2016      * @param string $visiblename localised
2017      * @param string $description long localised info
2018      * @param string $defaultsetting
2019      * @param string $yes value used when checked
2020      * @param string $no value used when not checked
2021      */
2022     public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2023         parent::__construct($name, $visiblename, $description, $defaultsetting);
2024         $this->yes = (string)$yes;
2025         $this->no  = (string)$no;
2026     }
2028     /**
2029      * Retrieves the current setting using the objects name
2030      *
2031      * @return string
2032      */
2033     public function get_setting() {
2034         return $this->config_read($this->name);
2035     }
2037     /**
2038      * Sets the value for the setting
2039      *
2040      * Sets the value for the setting to either the yes or no values
2041      * of the object by comparing $data to yes
2042      *
2043      * @param mixed $data Gets converted to str for comparison against yes value
2044      * @return string empty string or error
2045      */
2046     public function write_setting($data) {
2047         if ((string)$data === $this->yes) { // convert to strings before comparison
2048             $data = $this->yes;
2049         } else {
2050             $data = $this->no;
2051         }
2052         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2053     }
2055     /**
2056      * Returns an XHTML checkbox field
2057      *
2058      * @param string $data If $data matches yes then checkbox is checked
2059      * @param string $query
2060      * @return string XHTML field
2061      */
2062     public function output_html($data, $query='') {
2063         $default = $this->get_defaultsetting();
2065         if (!is_null($default)) {
2066             if ((string)$default === $this->yes) {
2067                 $defaultinfo = get_string('checkboxyes', 'admin');
2068             } else {
2069                 $defaultinfo = get_string('checkboxno', 'admin');
2070             }
2071         } else {
2072             $defaultinfo = NULL;
2073         }
2075         if ((string)$data === $this->yes) { // convert to strings before comparison
2076             $checked = 'checked="checked"';
2077         } else {
2078             $checked = '';
2079         }
2081         return format_admin_setting($this, $this->visiblename,
2082         '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2083             .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2084         $this->description, true, '', $defaultinfo, $query);
2085     }
2088 /**
2089  * Multiple checkboxes, each represents different value, stored in csv format
2090  *
2091  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2092  */
2093 class admin_setting_configmulticheckbox extends admin_setting {
2094 /** @var array Array of choices value=>label */
2095     public $choices;
2097     /**
2098      * Constructor: uses parent::__construct
2099      *
2100      * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2101      * @param string $visiblename localised
2102      * @param string $description long localised info
2103      * @param array $defaultsetting array of selected
2104      * @param array $choices array of $value=>$label for each checkbox
2105      */
2106     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2107         $this->choices = $choices;
2108         parent::__construct($name, $visiblename, $description, $defaultsetting);
2109     }
2111     /**
2112      * This public function may be used in ancestors for lazy loading of choices
2113      *
2114      * @todo Check if this function is still required content commented out only returns true
2115      * @return bool true if loaded, false if error
2116      */
2117     public function load_choices() {
2118         /*
2119         if (is_array($this->choices)) {
2120             return true;
2121         }
2122         .... load choices here
2123         */
2124         return true;
2125     }
2127     /**
2128      * Is setting related to query text - used when searching
2129      *
2130      * @param string $query
2131      * @return bool true on related, false on not or failure
2132      */
2133     public function is_related($query) {
2134         if (!$this->load_choices() or empty($this->choices)) {
2135             return false;
2136         }
2137         if (parent::is_related($query)) {
2138             return true;
2139         }
2141         $textlib = textlib_get_instance();
2142         foreach ($this->choices as $desc) {
2143             if (strpos($textlib->strtolower($desc), $query) !== false) {
2144                 return true;
2145             }
2146         }
2147         return false;
2148     }
2150     /**
2151      * Returns the current setting if it is set
2152      *
2153      * @return mixed null if null, else an array
2154      */
2155     public function get_setting() {
2156         $result = $this->config_read($this->name);
2158         if (is_null($result)) {
2159             return NULL;
2160         }
2161         if ($result === '') {
2162             return array();
2163         }
2164         $enabled = explode(',', $result);
2165         $setting = array();
2166         foreach ($enabled as $option) {
2167             $setting[$option] = 1;
2168         }
2169         return $setting;
2170     }
2172     /**
2173      * Saves the setting(s) provided in $data
2174      *
2175      * @param array $data An array of data, if not array returns empty str
2176      * @return mixed empty string on useless data or bool true=success, false=failed
2177      */
2178     public function write_setting($data) {
2179         if (!is_array($data)) {
2180             return ''; // ignore it
2181         }
2182         if (!$this->load_choices() or empty($this->choices)) {
2183             return '';
2184         }
2185         unset($data['xxxxx']);
2186         $result = array();
2187         foreach ($data as $key => $value) {
2188             if ($value and array_key_exists($key, $this->choices)) {
2189                 $result[] = $key;
2190             }
2191         }
2192         return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2193     }
2195     /**
2196      * Returns XHTML field(s) as required by choices
2197      *
2198      * Relies on data being an array should data ever be another valid vartype with
2199      * acceptable value this may cause a warning/error
2200      * if (!is_array($data)) would fix the problem
2201      *
2202      * @todo Add vartype handling to ensure $data is an array
2203      *
2204      * @param array $data An array of checked values
2205      * @param string $query
2206      * @return string XHTML field
2207      */
2208     public function output_html($data, $query='') {
2209         if (!$this->load_choices() or empty($this->choices)) {
2210             return '';
2211         }
2212         $default = $this->get_defaultsetting();
2213         if (is_null($default)) {
2214             $default = array();
2215         }
2216         if (is_null($data)) {
2217             $data = array();
2218         }
2219         $options = array();
2220         $defaults = array();
2221         foreach ($this->choices as $key=>$description) {
2222             if (!empty($data[$key])) {
2223                 $checked = 'checked="checked"';
2224             } else {
2225                 $checked = '';
2226             }
2227             if (!empty($default[$key])) {
2228                 $defaults[] = $description;
2229             }
2231             $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2232                 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2233         }
2235         if (is_null($default)) {
2236             $defaultinfo = NULL;
2237         } else if (!empty($defaults)) {
2238                 $defaultinfo = implode(', ', $defaults);
2239             } else {
2240                 $defaultinfo = get_string('none');
2241             }
2243         $return = '<div class="form-multicheckbox">';
2244         $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2245         if ($options) {
2246             $return .= '<ul>';
2247             foreach ($options as $option) {
2248                 $return .= '<li>'.$option.'</li>';
2249             }
2250             $return .= '</ul>';
2251         }
2252         $return .= '</div>';
2254         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2256     }
2259 /**
2260  * Multiple checkboxes 2, value stored as string 00101011
2261  *
2262  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2263  */
2264 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2266 /**
2267  * Returns the setting if set
2268  *
2269  * @return mixed null if not set, else an array of set settings
2270  */
2271     public function get_setting() {
2272         $result = $this->config_read($this->name);
2273         if (is_null($result)) {
2274             return NULL;
2275         }
2276         if (!$this->load_choices()) {
2277             return NULL;
2278         }
2279         $result = str_pad($result, count($this->choices), '0');
2280         $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2281         $setting = array();
2282         foreach ($this->choices as $key=>$unused) {
2283             $value = array_shift($result);
2284             if ($value) {
2285                 $setting[$key] = 1;
2286             }
2287         }
2288         return $setting;
2289     }
2291     /**
2292      * Save setting(s) provided in $data param
2293      *
2294      * @param array $data An array of settings to save
2295      * @return mixed empty string for bad data or bool true=>success, false=>error
2296      */
2297     public function write_setting($data) {
2298         if (!is_array($data)) {
2299             return ''; // ignore it
2300         }
2301         if (!$this->load_choices() or empty($this->choices)) {
2302             return '';
2303         }
2304         $result = '';
2305         foreach ($this->choices as $key=>$unused) {
2306             if (!empty($data[$key])) {
2307                 $result .= '1';
2308             } else {
2309                 $result .= '0';
2310             }
2311         }
2312         return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2313     }
2316 /**
2317  * Select one value from list
2318  *
2319  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2320  */
2321 class admin_setting_configselect extends admin_setting {
2322 /** @var array Array of choices value=>label */
2323     public $choices;
2325     /**
2326      * Constructor
2327      * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2328      * @param string $visiblename localised
2329      * @param string $description long localised info
2330      * @param string|int $defaultsetting
2331      * @param array $choices array of $value=>$label for each selection
2332      */
2333     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2334         $this->choices = $choices;
2335         parent::__construct($name, $visiblename, $description, $defaultsetting);
2336     }
2338     /**
2339      * This function may be used in ancestors for lazy loading of choices
2340      *
2341      * Override this method if loading of choices is expensive, such
2342      * as when it requires multiple db requests.
2343      *
2344      * @return bool true if loaded, false if error
2345      */
2346     public function load_choices() {
2347         /*
2348         if (is_array($this->choices)) {
2349             return true;
2350         }
2351         .... load choices here
2352         */
2353         return true;
2354     }
2356     /**
2357      * Check if this is $query is related to a choice
2358      *
2359      * @param string $query
2360      * @return bool true if related, false if not
2361      */
2362     public function is_related($query) {
2363         if (parent::is_related($query)) {
2364             return true;
2365         }
2366         if (!$this->load_choices()) {
2367             return false;
2368         }
2369         $textlib = textlib_get_instance();
2370         foreach ($this->choices as $key=>$value) {
2371             if (strpos($textlib->strtolower($key), $query) !== false) {
2372                 return true;
2373             }
2374             if (strpos($textlib->strtolower($value), $query) !== false) {
2375                 return true;
2376             }
2377         }
2378         return false;
2379     }
2381     /**
2382      * Return the setting
2383      *
2384      * @return mixed returns config if successful else null
2385      */
2386     public function get_setting() {
2387         return $this->config_read($this->name);
2388     }
2390     /**
2391      * Save a setting
2392      *
2393      * @param string $data
2394      * @return string empty of error string
2395      */
2396     public function write_setting($data) {
2397         if (!$this->load_choices() or empty($this->choices)) {
2398             return '';
2399         }
2400         if (!array_key_exists($data, $this->choices)) {
2401             return ''; // ignore it
2402         }
2404         return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2405     }
2407     /**
2408      * Returns XHTML select field
2409      *
2410      * Ensure the options are loaded, and generate the XHTML for the select
2411      * element and any warning message. Separating this out from output_html
2412      * makes it easier to subclass this class.
2413      *
2414      * @param string $data the option to show as selected.
2415      * @param string $current the currently selected option in the database, null if none.
2416      * @param string $default the default selected option.
2417      * @return array the HTML for the select element, and a warning message.
2418      */
2419     public function output_select_html($data, $current, $default, $extraname = '') {
2420         if (!$this->load_choices() or empty($this->choices)) {
2421             return array('', '');
2422         }
2424         $warning = '';
2425         if (is_null($current)) {
2426         // first run
2427         } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2428             // no warning
2429             } else if (!array_key_exists($current, $this->choices)) {
2430                     $warning = get_string('warningcurrentsetting', 'admin', s($current));
2431                     if (!is_null($default) and $data == $current) {
2432                         $data = $default; // use default instead of first value when showing the form
2433                     }
2434                 }
2436         $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2437         foreach ($this->choices as $key => $value) {
2438         // the string cast is needed because key may be integer - 0 is equal to most strings!
2439             $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2440         }
2441         $selecthtml .= '</select>';
2442         return array($selecthtml, $warning);
2443     }
2445     /**
2446      * Returns XHTML select field and wrapping div(s)
2447      *
2448      * @see output_select_html()
2449      *
2450      * @param string $data the option to show as selected
2451      * @param string $query
2452      * @return string XHTML field and wrapping div
2453      */
2454     public function output_html($data, $query='') {
2455         $default = $this->get_defaultsetting();
2456         $current = $this->get_setting();
2458         list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2459         if (!$selecthtml) {
2460             return '';
2461         }
2463         if (!is_null($default) and array_key_exists($default, $this->choices)) {
2464             $defaultinfo = $this->choices[$default];
2465         } else {
2466             $defaultinfo = NULL;
2467         }
2469         $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2471         return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2472     }
2475 /**
2476  * Select multiple items from list
2477  *
2478  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2479  */
2480 class admin_setting_configmultiselect extends admin_setting_configselect {
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 array $defaultsetting array of selected items
2487  * @param array $choices array of $value=>$label for each list item
2488  */
2489     public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2490         parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2491     }
2493     /**
2494      * Returns the select setting(s)
2495      *
2496      * @return mixed null or array. Null if no settings else array of setting(s)
2497      */
2498     public function get_setting() {
2499         $result = $this->config_read($this->name);
2500         if (is_null($result)) {
2501             return NULL;
2502         }
2503         if ($result === '') {
2504             return array();
2505         }
2506         return explode(',', $result);
2507     }
2509     /**
2510      * Saves setting(s) provided through $data
2511      *
2512      * Potential bug in the works should anyone call with this function
2513      * using a vartype that is not an array
2514      *
2515      * @todo Add vartype handling to ensure $data is an array
2516      * @param array $data
2517      */
2518     public function write_setting($data) {
2519         if (!is_array($data)) {
2520             return ''; //ignore it
2521         }
2522         if (!$this->load_choices() or empty($this->choices)) {
2523             return '';
2524         }
2526         unset($data['xxxxx']);
2528         $save = array();
2529         foreach ($data as $value) {
2530             if (!array_key_exists($value, $this->choices)) {
2531                 continue; // ignore it
2532             }
2533             $save[] = $value;
2534         }
2536         return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2537     }
2539     /**
2540      * Is setting related to query text - used when searching
2541      *
2542      * @param string $query
2543      * @return bool true if related, false if not
2544      */
2545     public function is_related($query) {
2546         if (!$this->load_choices() or empty($this->choices)) {
2547             return false;
2548         }
2549         if (parent::is_related($query)) {
2550             return true;
2551         }
2553         $textlib = textlib_get_instance();
2554         foreach ($this->choices as $desc) {
2555             if (strpos($textlib->strtolower($desc), $query) !== false) {
2556                 return true;
2557             }
2558         }
2559         return false;
2560     }
2562     /**
2563      * Returns XHTML multi-select field
2564      *
2565      * @todo Add vartype handling to ensure $data is an array
2566      * @param array $data Array of values to select by default
2567      * @param string $query
2568      * @return string XHTML multi-select field
2569      */
2570     public function output_html($data, $query='') {
2571         if (!$this->load_choices() or empty($this->choices)) {
2572             return '';
2573         }
2574         $choices = $this->choices;
2575         $default = $this->get_defaultsetting();
2576         if (is_null($default)) {
2577             $default = array();
2578         }
2579         if (is_null($data)) {
2580             $data = array();
2581         }
2583         $defaults = array();
2584         $size = min(10, count($this->choices));
2585         $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2586         $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2587         foreach ($this->choices as $key => $description) {
2588             if (in_array($key, $data)) {
2589                 $selected = 'selected="selected"';
2590             } else {
2591                 $selected = '';
2592             }
2593             if (in_array($key, $default)) {
2594                 $defaults[] = $description;
2595             }
2597             $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2598         }
2600         if (is_null($default)) {
2601             $defaultinfo = NULL;
2602         } if (!empty($defaults)) {
2603             $defaultinfo = implode(', ', $defaults);
2604         } else {
2605             $defaultinfo = get_string('none');
2606         }
2608         $return .= '</select></div>';
2609         return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2610     }
2613 /**
2614  * Time selector
2615  *
2616  * This is a liiitle bit messy. we're using two selects, but we're returning
2617  * them as an array named after $name (so we only use $name2 internally for the setting)
2618  *
2619  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2620  */
2621 class admin_setting_configtime extends admin_setting {
2622 /** @var string Used for setting second select (minutes) */
2623     public $name2;
2625     /**
2626      * Constructor
2627      * @param string $hoursname setting for hours
2628      * @param string $minutesname setting for hours
2629      * @param string $visiblename localised
2630      * @param string $description long localised info
2631      * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2632      */
2633     public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2634         $this->name2 = $minutesname;
2635         parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2636     }
2638     /**
2639      * Get the selected time
2640      *
2641      * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2642      */
2643     public function get_setting() {
2644         $result1 = $this->config_read($this->name);
2645         $result2 = $this->config_read($this->name2);
2646         if (is_null($result1) or is_null($result2)) {
2647             return NULL;
2648         }
2650         return array('h' => $result1, 'm' => $result2);
2651     }
2653     /**
2654      * Store the time (hours and minutes)
2655      *
2656      * @param array $data Must be form 'h'=>xx, 'm'=>xx
2657      * @return bool true if success, false if not
2658      */
2659     public function write_setting($data) {
2660         if (!is_array($data)) {
2661             return '';
2662         }
2664         $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2665         return ($result ? '' : get_string('errorsetting', 'admin'));
2666     }
2668     /**
2669      * Returns XHTML time select fields
2670      *
2671      * @param array $data Must be form 'h'=>xx, 'm'=>xx
2672      * @param string $query
2673      * @return string XHTML time select fields and wrapping div(s)
2674      */
2675     public function output_html($data, $query='') {
2676         $default = $this->get_defaultsetting();
2678         if (is_array($default)) {
2679             $defaultinfo = $default['h'].':'.$default['m'];
2680         } else {
2681             $defaultinfo = NULL;
2682         }
2684         $return = '<div class="form-time defaultsnext">'.
2685             '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2686         for ($i = 0; $i < 24; $i++) {
2687             $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2688         }
2689         $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2690         for ($i = 0; $i < 60; $i += 5) {
2691             $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2692         }
2693         $return .= '</select></div>';
2694         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2695     }
2699 /**
2700  * Used to validate a textarea used for ip addresses
2701  *
2702  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2703  */
2704 class admin_setting_configiplist extends admin_setting_configtextarea {
2706 /**
2707  * Validate the contents of the textarea as IP addresses
2708  *
2709  * Used to validate a new line separated list of IP addresses collected from
2710  * a textarea control
2711  *
2712  * @param string $data A list of IP Addresses separated by new lines
2713  * @return mixed bool true for success or string:error on failure
2714  */
2715     public function validate($data) {
2716         if(!empty($data)) {
2717             $ips = explode("\n", $data);
2718         } else {
2719             return true;
2720         }
2721         $result = true;
2722         foreach($ips as $ip) {
2723             $ip = trim($ip);
2724             if(preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2725                 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2726                 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2727                 $result = true;
2728             } else {
2729                 $result = false;
2730                 break;
2731             }
2732         }
2733         if($result) {
2734             return true;
2735         } else {
2736             return get_string('validateerror', 'admin');
2737         }
2738     }
2741 /**
2742  * An admin setting for selecting one or more users who have a capability
2743  * in the system context
2744  *
2745  * An admin setting for selecting one or more users, who have a particular capability
2746  * in the system context. Warning, make sure the list will never be too long. There is
2747  * no paging or searching of this list.
2748  *
2749  * To correctly get a list of users from this config setting, you need to call the
2750  * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2751  *
2752  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2753  */
2754 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2755     /** @var string The capabilities name */
2756     protected $capability;
2757     /** @var int include admin users too */
2758     protected $includeadmins;
2760     /**
2761      * Constructor.
2762      *
2763      * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2764      * @param string $visiblename localised name
2765      * @param string $description localised long description
2766      * @param array $defaultsetting array of usernames
2767      * @param string $capability string capability name.
2768      * @param bool $includeadmins include administrators
2769      */
2770     function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2771         $this->capability    = $capability;
2772         $this->includeadmins = $includeadmins;
2773         parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2774     }
2776     /**
2777      * Load all of the uses who have the capability into choice array
2778      *
2779      * @return bool Always returns true
2780      */
2781     function load_choices() {
2782         if (is_array($this->choices)) {
2783             return true;
2784         }
2785         $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2786             $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2787         $this->choices = array(
2788             '$@NONE@$' => get_string('nobody'),
2789             '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2790         );
2791         if ($this->includeadmins) {
2792             $admins = get_admins();
2793             foreach ($admins as $user) {
2794                 $this->choices[$user->id] = fullname($user);
2795             }
2796         }
2797         if (is_array($users)) {
2798             foreach ($users as $user) {
2799                 $this->choices[$user->id] = fullname($user);
2800             }
2801         }
2802         return true;
2803     }
2805     /**
2806      * Returns the default setting for class
2807      *
2808      * @return mixed Array, or string. Empty string if no default
2809      */
2810     public function get_defaultsetting() {
2811         $this->load_choices();
2812         $defaultsetting = parent::get_defaultsetting();
2813         if (empty($defaultsetting)) {
2814             return array('$@NONE@$');
2815         } else if (array_key_exists($defaultsetting, $this->choices)) {
2816                 return $defaultsetting;
2817             } else {
2818                 return '';
2819             }
2820     }
2822     /**
2823      * Returns the current setting
2824      *
2825      * @return mixed array or string
2826      */
2827     public function get_setting() {
2828         $result = parent::get_setting();
2829         if ($result === null) {
2830             // this is necessary for settings upgrade
2831             return null;
2832         }
2833         if (empty($result)) {
2834             $result = array('$@NONE@$');
2835         }
2836         return $result;
2837     }
2839     /**
2840      * Save the chosen setting provided as $data
2841      *
2842      * @param array $data
2843      * @return mixed string or array
2844      */
2845     public function write_setting($data) {
2846     // If all is selected, remove any explicit options.
2847         if (in_array('$@ALL@$', $data)) {
2848             $data = array('$@ALL@$');
2849         }
2850         // None never needs to be written to the DB.
2851         if (in_array('$@NONE@$', $data)) {
2852             unset($data[array_search('$@NONE@$', $data)]);
2853         }
2854         return parent::write_setting($data);
2855     }
2858 /**
2859  * Special checkbox for calendar - resets SESSION vars.
2860  *
2861  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2862  */
2863 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2864 /**
2865  * Calls the parent::__construct with default values
2866  *
2867  * name =>  calendar_adminseesall
2868  * visiblename => get_string('adminseesall', 'admin')
2869  * description => get_string('helpadminseesall', 'admin')
2870  * defaultsetting => 0
2871  */
2872     public function __construct() {
2873         parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2874             get_string('helpadminseesall', 'admin'), '0');
2875     }
2877     /**
2878      * Stores the setting passed in $data
2879      *
2880      * @param mixed gets converted to string for comparison
2881      * @return string empty string or error message
2882      */
2883     public function write_setting($data) {
2884         global $SESSION;
2885         unset($SESSION->cal_courses_shown);
2886         return parent::write_setting($data);
2887     }
2890 /**
2891  * Special select for settings that are altered in setup.php and can not be altered on the fly
2892  *
2893  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2894  */
2895 class admin_setting_special_selectsetup extends admin_setting_configselect {
2896 /**
2897  * Reads the setting directly from the database
2898  *
2899  * @return mixed
2900  */
2901     public function get_setting() {
2902     // read directly from db!
2903         return get_config(NULL, $this->name);
2904     }
2906     /**
2907      * Save the setting passed in $data
2908      *
2909      * @param string $data The setting to save
2910      * @return string empty or error message
2911      */
2912     public function write_setting($data) {
2913         global $CFG;
2914         // do not change active CFG setting!
2915         $current = $CFG->{$this->name};
2916         $result = parent::write_setting($data);
2917         $CFG->{$this->name} = $current;
2918         return $result;
2919     }
2922 /**
2923  * Special select for frontpage - stores data in course table
2924  *
2925  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2926  */
2927 class admin_setting_sitesetselect extends admin_setting_configselect {
2928 /**
2929  * Returns the site name for the selected site
2930  *
2931  * @see get_site()
2932  * @return string The site name of the selected site
2933  */
2934     public function get_setting() {
2935         $site = get_site();
2936         return $site->{$this->name};
2937     }
2938     /**
2939      * Updates the database and save the setting
2940      *
2941      * @param string data
2942      * @return string empty or error message
2943      */
2944     public function write_setting($data) {
2945         global $DB, $SITE;
2946         if (!in_array($data, array_keys($this->choices))) {
2947             return get_string('errorsetting', 'admin');
2948         }
2949         $record = new stdClass();
2950         $record->id           = SITEID;
2951         $temp                 = $this->name;
2952         $record->$temp        = $data;
2953         $record->timemodified = time();
2954         // update $SITE
2955         $SITE->{$this->name} = $data;
2956         return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
2957     }
2960 /**
2961  * Select for blog's bloglevel setting: if set to 0, will set blog_menu
2962  * block to hidden.
2963  *
2964  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2965  */
2966 class admin_setting_bloglevel extends admin_setting_configselect {
2967     /**
2968      * Updates the database and save the setting
2969      *
2970      * @param string data
2971      * @return string empty or error message
2972      */
2973     public function write_setting($data) {
2974         global $DB;
2975         if ($data['bloglevel'] == 0) {
2976             $DB->set_field('block', 'visible', 0, array('name' => 'blog_menu'));
2977         } else {
2978             $DB->set_field('block', 'visible', 1, array('name' => 'blog_menu'));
2979         }
2980         return parent::write_setting($data);
2981     }
2984 /**
2985  * Special select - lists on the frontpage - hacky
2986  *
2987  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2988  */
2989 class admin_setting_courselist_frontpage extends admin_setting {
2990 /** @var array Array of choices value=>label */
2991     public $choices;
2993     /**
2994      * Construct override, requires one param
2995      *
2996      * @param bool $loggedin Is the user logged in
2997      */
2998     public function __construct($loggedin) {
2999         global $CFG;
3000         require_once($CFG->dirroot.'/course/lib.php');
3001         $name        = 'frontpage'.($loggedin ? 'loggedin' : '');
3002         $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3003         $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3004         $defaults    = array(FRONTPAGECOURSELIST);
3005         parent::__construct($name, $visiblename, $description, $defaults);
3006     }
3008     /**
3009      * Loads the choices available
3010      *
3011      * @return bool always returns true
3012      */
3013     public function load_choices() {
3014         global $DB;
3015         if (is_array($this->choices)) {
3016             return true;
3017         }
3018         $this->choices = array(FRONTPAGENEWS          => get_string('frontpagenews'),
3019             FRONTPAGECOURSELIST    => get_string('frontpagecourselist'),
3020             FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3021             FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3022             'none'                 => get_string('none'));
3023         if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3024             unset($this->choices[FRONTPAGECOURSELIST]);
3025         }
3026         return true;
3027     }
3028     /**
3029      * Returns the selected settings
3030      *
3031      * @param mixed array or setting or null
3032      */
3033     public function get_setting() {
3034         $result = $this->config_read($this->name);
3035         if (is_null($result)) {
3036             return NULL;
3037         }
3038         if ($result === '') {
3039             return array();
3040         }
3041         return explode(',', $result);
3042     }
3044     /**
3045      * Save the selected options
3046      *
3047      * @param array $data
3048      * @return mixed empty string (data is not an array) or bool true=success false=failure
3049      */
3050     public function write_setting($data) {
3051         if (!is_array($data)) {
3052             return '';
3053         }
3054         $this->load_choices();
3055         $save = array();
3056         foreach($data as $datum) {
3057             if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3058                 continue;
3059             }
3060             $save[$datum] = $datum; // no duplicates
3061         }
3062         return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3063     }
3065     /**
3066      * Return XHTML select field and wrapping div
3067      *
3068      * @todo Add vartype handling to make sure $data is an array
3069      * @param array $data Array of elements to select by default
3070      * @return string XHTML select field and wrapping div
3071      */
3072     public function output_html($data, $query='') {
3073         $this->load_choices();
3074         $currentsetting = array();
3075         foreach ($data as $key) {
3076             if ($key != 'none' and array_key_exists($key, $this->choices)) {
3077                 $currentsetting[] = $key; // already selected first
3078             }
3079         }
3081         $return = '<div class="form-group">';
3082         for ($i = 0; $i < count($this->choices) - 1; $i++) {
3083             if (!array_key_exists($i, $currentsetting)) {
3084                 $currentsetting[$i] = 'none'; //none
3085             }
3086             $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3087             foreach ($this->choices as $key => $value) {
3088                 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3089             }
3090             $return .= '</select>';
3091             if ($i !== count($this->choices) - 2) {
3092                 $return .= '<br />';
3093             }
3094         }
3095         $return .= '</div>';
3097         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3098     }
3101 /**
3102  * Special checkbox for frontpage - stores data in course table
3103  *
3104  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3105  */
3106 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3107 /**
3108  * Returns the current sites name
3109  *
3110  * @return string
3111  */
3112     public function get_setting() {
3113         $site = get_site();
3114         return $site->{$this->name};
3115     }
3117     /**
3118      * Save the selected setting
3119      *
3120      * @param string $data The selected site
3121      * @return string empty string or error message
3122      */
3123     public function write_setting($data) {
3124         global $DB, $SITE;
3125         $record = new stdClass();
3126         $record->id            = SITEID;
3127         $record->{$this->name} = ($data == '1' ? 1 : 0);
3128         $record->timemodified  = time();
3129         // update $SITE
3130         $SITE->{$this->name} = $data;
3131         return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3132     }
3135 /**
3136  * Special text for frontpage - stores data in course table.
3137  * Empty string means not set here. Manual setting is required.
3138  *
3139  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3140  */
3141 class admin_setting_sitesettext extends admin_setting_configtext {
3142 /**
3143  * Return the current setting
3144  *
3145  * @return mixed string or null
3146  */
3147     public function get_setting() {
3148         $site = get_site();
3149         return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3150     }
3152     /**
3153      * Validate the selected data
3154      *
3155      * @param string $data The selected value to validate
3156      * @return mixed true or message string
3157      */
3158     public function validate($data) {
3159         $cleaned = clean_param($data, PARAM_MULTILANG);
3160         if ($cleaned === '') {
3161             return get_string('required');
3162         }
3163         if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3164             return true;
3165         } else {
3166             return get_string('validateerror', 'admin');
3167         }
3168     }
3170     /**
3171      * Save the selected setting
3172      *
3173      * @param string $data The selected value
3174      * @return string empty or error message
3175      */
3176     public function write_setting($data) {
3177         global $DB, $SITE;
3178         $data = trim($data);
3179         $validated = $this->validate($data);
3180         if ($validated !== true) {
3181             return $validated;
3182         }
3184         $record = new stdClass();
3185         $record->id            = SITEID;
3186         $record->{$this->name} = $data;
3187         $record->timemodified  = time();
3188         // update $SITE
3189         $SITE->{$this->name} = $data;
3190         return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3191     }
3194 /**
3195  * Special text editor for site description.
3196  *
3197  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3198  */
3199 class admin_setting_special_frontpagedesc extends admin_setting {
3200 /**
3201  * Calls parent::__construct with specific arguments
3202  */
3203     public function __construct() {
3204         parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3205         editors_head_setup();
3206     }
3208     /**
3209      * Return the current setting
3210      * @return string The current setting
3211      */
3212     public function get_setting() {
3213         $site = get_site();
3214         return $site->{$this->name};
3215     }
3217     /**
3218      * Save the new setting
3219      *
3220      * @param string $data The new value to save
3221      * @return string empty or error message
3222      */
3223     public function write_setting($data) {
3224         global $DB, $SITE;
3225         $record = new stdClass();
3226         $record->id            = SITEID;
3227         $record->{$this->name} = $data;
3228         $record->timemodified  = time();
3229         $SITE->{$this->name} = $data;
3230         return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3231     }
3233     /**
3234      * Returns XHTML for the field plus wrapping div
3235      *
3236      * @param string $data The current value
3237      * @param string $query
3238      * @return string The XHTML output
3239      */
3240     public function output_html($data, $query='') {
3241         global $CFG;
3243         $CFG->adminusehtmleditor = can_use_html_editor();
3244         $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3246         return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3247     }
3250 /**
3251  * Administration interface for emoticon_manager settings.
3252  *
3253  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3254  */
3255 class admin_setting_emoticons extends admin_setting {
3257 /**
3258  * Calls parent::__construct with specific args
3259  */
3260     public function __construct() {
3261         global $CFG;
3263         $manager = get_emoticon_manager();
3264         $defaults = $this->prepare_form_data($manager->default_emoticons());
3265         parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3266     }
3268     /**
3269      * Return the current setting(s)
3270      *
3271      * @return array Current settings array
3272      */
3273     public function get_setting() {
3274         global $CFG;
3276         $manager = get_emoticon_manager();
3278         $config = $this->config_read($this->name);
3279         if (is_null($config)) {
3280             return null;
3281         }
3283         $config = $manager->decode_stored_config($config);
3284         if (is_null($config)) {
3285             return null;
3286         }
3288         return $this->prepare_form_data($config);
3289     }
3291     /**
3292      * Save selected settings
3293      *
3294      * @param array $data Array of settings to save
3295      * @return bool
3296      */
3297     public function write_setting($data) {
3299         $manager = get_emoticon_manager();
3300         $emoticons = $this->process_form_data($data);
3302         if ($emoticons === false) {
3303             return false;
3304         }
3306         if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3307             return ''; // success
3308         } else {
3309             return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3310         }
3311     }
3313     /**
3314      * Return XHTML field(s) for options
3315      *
3316      * @param array $data Array of options to set in HTML
3317      * @return string XHTML string for the fields and wrapping div(s)
3318      */
3319     public function output_html($data, $query='') {
3320         global $OUTPUT;
3322         $out  = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3323         $out .= html_writer::start_tag('thead');
3324         $out .= html_writer::start_tag('tr');
3325         $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3326         $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3327         $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3328         $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3329         $out .= html_writer::tag('th', '');
3330         $out .= html_writer::end_tag('tr');
3331         $out .= html_writer::end_tag('thead');
3332         $out .= html_writer::start_tag('tbody');
3333         $i = 0;
3334         foreach($data as $field => $value) {
3335             switch ($i) {
3336             case 0:
3337                 $out .= html_writer::start_tag('tr');
3338                 $current_text = $value;
3339                 $current_filename = '';
3340                 $current_imagecomponent = '';
3341                 $current_altidentifier = '';
3342                 $current_altcomponent = '';
3343             case 1:
3344                 $current_filename = $value;
3345             case 2:
3346                 $current_imagecomponent = $value;
3347             case 3:
3348                 $current_altidentifier = $value;
3349             case 4:
3350                 $current_altcomponent = $value;
3351             }
3353             $out .= html_writer::tag('td',
3354                 html_writer::empty_tag('input',
3355                     array(
3356                         'type'  => 'text',
3357                         'class' => 'form-text',
3358                         'name'  => $this->get_full_name().'['.$field.']',
3359                         'value' => $value,
3360                     )
3361                 ), array('class' => 'c'.$i)
3362             );
3364             if ($i == 4) {
3365                 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3366                     $alt = get_string($current_altidentifier, $current_altcomponent);
3367                 } else {
3368                     $alt = $current_text;
3369                 }
3370                 if ($current_filename) {
3371                     $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3372                 } else {
3373                     $out .= html_writer::tag('td', '');
3374                 }
3375                 $out .= html_writer::end_tag('tr');
3376                 $i = 0;
3377             } else {
3378                 $i++;
3379             }
3381         }
3382         $out .= html_writer::end_tag('tbody');
3383         $out .= html_writer::end_tag('table');
3384         $out  = html_writer::tag('div', $out, array('class' => 'form-group'));
3385         $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3387         return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3388     }
3390     /**
3391      * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3392      *
3393      * @see self::process_form_data()
3394      * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3395      * @return array of form fields and their values
3396      */
3397     protected function prepare_form_data(array $emoticons) {
3399         $form = array();
3400         $i = 0;
3401         foreach ($emoticons as $emoticon) {
3402             $form['text'.$i]            = $emoticon->text;
3403             $form['imagename'.$i]       = $emoticon->imagename;
3404             $form['imagecomponent'.$i]  = $emoticon->imagecomponent;
3405             $form['altidentifier'.$i]   = $emoticon->altidentifier;
3406             $form['altcomponent'.$i]    = $emoticon->altcomponent;
3407             $i++;
3408         }
3409         // add one more blank field set for new object
3410         $form['text'.$i]            = '';
3411         $form['imagename'.$i]       = '';
3412         $form['imagecomponent'.$i]  = '';
3413         $form['altidentifier'.$i]   = '';
3414         $form['altcomponent'.$i]    = '';
3416         return $form;
3417     }
3419     /**
3420      * Converts the data from admin settings form into an array of emoticon objects
3421      *
3422      * @see self::prepare_form_data()
3423      * @param array $data array of admin form fields and values
3424      * @return false|array of emoticon objects
3425      */
3426     protected function process_form_data(array $form) {
3428         $count = count($form); // number of form field values
3430         if ($count % 5) {
3431             // we must get five fields per emoticon object
3432             return false;
3433         }
3435         $emoticons = array();
3436         for ($i = 0; $i < $count / 5; $i++) {
3437             $emoticon                   = new stdClass();
3438             $emoticon->text             = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3439             $emoticon->imagename        = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3440             $emoticon->imagecomponent   = clean_param(trim($form['imagecomponent'.$i]), PARAM_SAFEDIR);
3441             $emoticon->altidentifier    = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3442             $emoticon->altcomponent     = clean_param(trim($form['altcomponent'.$i]), PARAM_SAFEDIR);
3444             if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3445                 // prevent from breaking http://url.addresses by accident
3446                 $emoticon->text = '';
3447             }
3449             if (strlen($emoticon->text) < 2) {
3450                 // do not allow single character emoticons
3451                 $emoticon->text = '';
3452             }
3454             if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3455                 // emoticon text must contain some non-alphanumeric character to prevent
3456                 // breaking HTML tags
3457                 $emoticon->text = '';
3458             }
3460             if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3461                 $emoticons[] = $emoticon;
3462             }
3463         }
3464         return $emoticons;
3465     }
3468 /**
3469  * Special setting for limiting of the list of available languages.
3470  *
3471  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3472  */
3473 class admin_setting_langlist extends admin_setting_configtext {
3474 /**
3475  * Calls parent::__construct with specific arguments
3476  */
3477     public function __construct() {
3478         parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3479     }
3481     /**
3482      * Save the new setting
3483      *
3484      * @param string $data The new setting
3485      * @return bool
3486      */
3487     public function write_setting($data) {
3488         $return = parent::write_setting($data);
3489         get_string_manager()->reset_caches();
3490         return $return;
3491     }
3494 /**
3495  * Selection of one of the recognised countries using the list
3496  * returned by {@link get_list_of_countries()}.
3497  *
3498  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3499  */
3500 class admin_settings_country_select extends admin_setting_configselect {
3501     protected $includeall;
3502     public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3503         $this->includeall = $includeall;
3504         parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3505     }
3507     /**
3508      * Lazy-load the available choices for the select box
3509      */
3510     public function load_choices() {
3511         global $CFG;
3512         if (is_array($this->choices)) {
3513             return true;
3514         }
3515         $this->choices = array_merge(
3516                 array('0' => get_string('choosedots')),
3517                 get_string_manager()->get_list_of_countries($this->includeall));
3518         return true;
3519     }
3522 /**
3523  * Course category selection
3524  *
3525  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3526  */
3527 class admin_settings_coursecat_select extends admin_setting_configselect {
3528 /**
3529  * Calls parent::__construct with specific arguments
3530  */
3531     public function __construct($name, $visiblename, $description, $defaultsetting) {
3532         parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3533     }
3535     /**
3536      * Load the available choices for the select box
3537      *
3538      * @return bool
3539      */
3540     public function load_choices() {
3541         global $CFG;
3542         require_once($CFG->dirroot.'/course/lib.php');
3543         if (is_array($this->choices)) {
3544             return true;
3545         }
3546         $this->choices = make_categories_options();
3547         return true;
3548     }
3551 /**
3552  * Special control for selecting days to backup
3553  *
3554  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3555  */
3556 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3557 /**
3558  * Calls parent::__construct with specific arguments
3559  */
3560     public function __construct() {
3561         parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3562         $this->plugin = 'backup';
3563     }
3564     /**
3565      * Load the available choices for the select box
3566      *
3567      * @return bool Always returns true
3568      */
3569     public function load_choices() {
3570         if (is_array($this->choices)) {
3571             return true;
3572         }
3573         $this->choices = array();
3574         $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3575         foreach ($days as $day) {
3576             $this->choices[$day] = get_string($day, 'calendar');
3577         }
3578         return true;
3579     }
3582 /**
3583  * Special debug setting
3584  *
3585  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3586  */
3587 class admin_setting_special_debug extends admin_setting_configselect {
3588 /**
3589  * Calls parent::__construct with specific arguments
3590  */
3591     public function __construct() {
3592         parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3593     }
3595     /**
3596      * Load the available choices for the select box
3597      *
3598      * @return bool
3599      */
3600     public function load_choices() {
3601         if (is_array($this->choices)) {
3602             return true;
3603         }
3604         $this->choices = array(DEBUG_NONE      => get_string('debugnone', 'admin'),
3605             DEBUG_MINIMAL   => get_string('debugminimal', 'admin'),
3606             DEBUG_NORMAL    => get_string('debugnormal', 'admin'),
3607             DEBUG_ALL       => get_string('debugall', 'admin'),
3608             DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3609         return true;
3610     }
3613 /**
3614  * Special admin control
3615  *
3616  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3617  */
3618 class admin_setting_special_calendar_weekend extends admin_setting {
3619 /**
3620  * Calls parent::__construct with specific arguments
3621  */
3622     public function __construct() {
3623         $name = 'calendar_weekend';
3624         $visiblename = get_string('calendar_weekend', 'admin');
3625         $description = get_string('helpweekenddays', 'admin');
3626         $default = array ('0', '6'); // Saturdays and Sundays
3627         parent::__construct($name, $visiblename, $description, $default);
3628     }
3629     /**
3630      * Gets the current settings as an array
3631      *
3632      * @return mixed Null if none, else array of settings
3633      */
3634     public function get_setting() {
3635         $result = $this->config_read($this->name);
3636         if (is_null($result)) {
3637             return NULL;
3638         }
3639         if ($result === '') {
3640             return array();
3641         }
3642         $settings = array();
3643         for ($i=0; $i<7; $i++) {
3644             if ($result & (1 << $i)) {
3645                 $settings[] = $i;
3646             }
3647         }
3648         return $settings;
3649     }
3651     /**
3652      * Save the new settings
3653      *
3654      * @param array $data Array of new settings
3655      * @return bool
3656      */
3657     public function write_setting($data) {
3658         if (!is_array($data)) {
3659             return '';
3660         }
3661         unset($data['xxxxx']);
3662         $result = 0;
3663         foreach($data as $index) {
3664             $result |= 1 << $index;
3665         }
3666         return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3667     }
3669     /**
3670      * Return XHTML to display the control
3671      *
3672      * @param array $data array of selected days
3673      * @param string $query
3674      * @return string XHTML for display (field + wrapping div(s)
3675      */
3676     public function output_html($data, $query='') {
3677     // The order matters very much because of the implied numeric keys
3678         $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3679         $return = '<table><thead><tr>';
3680       &nb