MDL-43646 "disapprove" changed to "undo approval"
[moodle.git] / lib / adminlib.php
CommitLineData
db26acd4 1<?php
0c079f19 2// This file is part of Moodle - http://moodle.org/
3//
db26acd4 4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
0c079f19 13//
db26acd4 14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
88a7228a 16
17/**
0c079f19 18 * Functions and classes used during installation, upgrades and for admin settings.
db26acd4 19 *
0c079f19 20 * ADMIN SETTINGS TREE INTRODUCTION
db26acd4 21 *
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
61ef8f9f 25 * -it defines the admin_externalpage_setup()
db26acd4 26 *
27 * ADMIN_SETTING OBJECTS
28 *
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
32 *
33 * ADMIN_SETTINGPAGE OBJECTS
34 *
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
38 *
39 * ADMIN_EXTERNALPAGE OBJECTS
40 *
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
45 *
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
55 *
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
4d553cb2 58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
db26acd4 59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
4d553cb2 62 * echo $OUTPUT->header();
db26acd4 63 * // your HTML goes here
4d553cb2 64 * echo $OUTPUT->footer();
db26acd4 65 * </code>
66 *
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
01a2ce80 69 * It also configures all $PAGE properties needed for navigation.
db26acd4 70 *
71 * ADMIN_CATEGORY OBJECTS
72 *
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
76 *
77 * OTHER NOTES
78 *
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
83 *
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
88 *
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
91 *
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
95 *
0c079f19 96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
db26acd4 98 *
78bfb562
PS
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
88a7228a 103 */
104
78bfb562
PS
105defined('MOODLE_INTERNAL') || die();
106
598b38f7 107/// Add libraries
108require_once($CFG->libdir.'/ddllib.php');
b1f93b15 109require_once($CFG->libdir.'/xmlize.php');
3bcbd80e 110require_once($CFG->libdir.'/messagelib.php');
b1f93b15 111
bba0beae 112define('INSECURE_DATAROOT_WARNING', 1);
113define('INSECURE_DATAROOT_ERROR', 2);
0c079f19 114
ed996ede 115/**
116 * Automatically clean-up all plugin data and remove the plugin DB tables
117 *
2f87bb03
PS
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
119 *
ed996ede 120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
124 */
125function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
127
3db309dc 128 // This may take a long time.
3ef7279f 129 core_php_time_limit::raise();
3db309dc 130
3601c5f0
PS
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
c57fc98b 135 if (file_exists("$base/db/subplugins.php")) {
846e4e17 136 $subplugins = array();
c57fc98b 137 include("$base/db/subplugins.php");
846e4e17 138 foreach ($subplugins as $subplugintype=>$dir) {
3601c5f0 139 $instances = core_component::get_plugin_list($subplugintype);
846e4e17
PS
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
142 }
ed996ede 143 }
144 }
846e4e17 145
ed996ede 146 }
147
2138244c 148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
149
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
70d35fe6
PS
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
156 }
df997f84 157
2138244c 158 } else {
9baf6825 159 $pluginname = $component;
70d35fe6
PS
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
164 }
2138244c 165 }
df997f84 166
ed996ede 167 echo $OUTPUT->heading($pluginname);
168
effff2a4 169 // Custom plugin uninstall.
1c74b260 170 $plugindirectory = core_component::get_plugin_directory($type, $name);
ed996ede 171 $uninstalllib = $plugindirectory . '/db/uninstall.php';
172 if (file_exists($uninstalllib)) {
173 require_once($uninstalllib);
2138244c 174 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
ed996ede 175 if (function_exists($uninstallfunction)) {
effff2a4
PS
176 // Do not verify result, let plugin complain if necessary.
177 $uninstallfunction();
ed996ede 178 }
179 }
180
a31e0b40 181 // Specific plugin type cleanup.
e87214bd 182 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
a31e0b40
PS
183 if ($plugininfo) {
184 $plugininfo->uninstall_cleanup();
e87214bd 185 core_plugin_manager::reset_caches();
a31e0b40
PS
186 }
187 $plugininfo = null;
188
70d35fe6 189 // perform clean-up task common for all the plugin/subplugin types
ed996ede 190
bc81eadb
JM
191 //delete the web service functions and pre-built services
192 require_once($CFG->dirroot.'/lib/externallib.php');
193 external_delete_descriptions($component);
194
ed996ede 195 // delete calendar events
2138244c 196 $DB->delete_records('event', array('modulename' => $pluginname));
ed996ede 197
198 // delete all the logs
2138244c 199 $DB->delete_records('log', array('module' => $pluginname));
ed996ede 200
201 // delete log_display information
c6d75bff 202 $DB->delete_records('log_display', array('component' => $component));
ed996ede 203
204 // delete the module configuration records
bde002b8
PS
205 unset_all_config_for_plugin($component);
206 if ($type === 'mod') {
207 unset_all_config_for_plugin($pluginname);
208 }
ed996ede 209
3bcbd80e 210 // delete message provider
8e265315
RK
211 message_provider_uninstall($component);
212
ed996ede 213 // delete the plugin tables
214 $xmldbfilepath = $plugindirectory . '/db/install.xml';
54483279
PS
215 drop_plugin_tables($component, $xmldbfilepath, false);
216 if ($type === 'mod' or $type === 'block') {
217 // non-frankenstyle table prefixes
218 drop_plugin_tables($name, $xmldbfilepath, false);
219 }
ed996ede 220
ed996ede 221 // delete the capabilities that were defined by this module
222 capabilities_cleanup($component);
223
875e5f07 224 // remove event handlers and dequeue pending events
ed996ede 225 events_uninstall($component);
226
546b8864
DM
227 // Delete all remaining files in the filepool owned by the component.
228 $fs = get_file_storage();
229 $fs->delete_component_files($component);
230
5718a123
DM
231 // Finally purge all caches.
232 purge_all_caches();
233
82b1cf00
PS
234 // Invalidate the hash used for upgrade detections.
235 set_config('allversionshash', '');
236
ed996ede 237 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
238}
239
e243c8c4
DM
240/**
241 * Returns the version of installed component
242 *
243 * @param string $component component name
244 * @param string $source either 'disk' or 'installed' - where to get the version information from
245 * @return string|bool version number or false if the component is not found
246 */
247function get_component_version($component, $source='installed') {
248 global $CFG, $DB;
249
56da374e 250 list($type, $name) = core_component::normalize_component($component);
e243c8c4
DM
251
252 // moodle core or a core subsystem
253 if ($type === 'core') {
254 if ($source === 'installed') {
255 if (empty($CFG->version)) {
256 return false;
257 } else {
258 return $CFG->version;
259 }
260 } else {
261 if (!is_readable($CFG->dirroot.'/version.php')) {
262 return false;
263 } else {
9a8abf13 264 $version = null; //initialize variable for IDEs
e243c8c4
DM
265 include($CFG->dirroot.'/version.php');
266 return $version;
267 }
268 }
269 }
270
271 // activity module
272 if ($type === 'mod') {
273 if ($source === 'installed') {
5f8012d4
PS
274 if ($CFG->version < 2013092001.02) {
275 return $DB->get_field('modules', 'version', array('name'=>$name));
276 } else {
277 return get_config('mod_'.$name, 'version');
278 }
279
e243c8c4 280 } else {
bd3b3bba 281 $mods = core_component::get_plugin_list('mod');
d361c804 282 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
e243c8c4
DM
283 return false;
284 } else {
bde002b8
PS
285 $plugin = new stdClass();
286 $plugin->version = null;
287 $module = $plugin;
d361c804 288 include($mods[$name].'/version.php');
bde002b8 289 return $plugin->version;
e243c8c4
DM
290 }
291 }
292 }
293
294 // block
295 if ($type === 'block') {
296 if ($source === 'installed') {
c66b839a
PS
297 if ($CFG->version < 2013092001.02) {
298 return $DB->get_field('block', 'version', array('name'=>$name));
299 } else {
300 return get_config('block_'.$name, 'version');
301 }
e243c8c4 302 } else {
bd3b3bba 303 $blocks = core_component::get_plugin_list('block');
e243c8c4
DM
304 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
305 return false;
306 } else {
307 $plugin = new stdclass();
308 include($blocks[$name].'/version.php');
309 return $plugin->version;
310 }
311 }
312 }
313
314 // all other plugin types
315 if ($source === 'installed') {
316 return get_config($type.'_'.$name, 'version');
317 } else {
bd3b3bba 318 $plugins = core_component::get_plugin_list($type);
e243c8c4
DM
319 if (empty($plugins[$name])) {
320 return false;
321 } else {
322 $plugin = new stdclass();
323 include($plugins[$name].'/version.php');
324 return $plugin->version;
325 }
326 }
327}
328
b1f93b15 329/**
330 * Delete all plugin tables
db26acd4 331 *
db26acd4 332 * @param string $name Name of plugin, used as table prefix
333 * @param string $file Path to install.xml file
334 * @param bool $feedback defaults to true
0c079f19 335 * @return bool Always returns true
b1f93b15 336 */
337function drop_plugin_tables($name, $file, $feedback=true) {
338 global $CFG, $DB;
339
340 // first try normal delete
8b4ca8f7 341 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
b1f93b15 342 return true;
343 }
344
345 // then try to find all tables that start with name and are not in any xml file
346 $used_tables = get_used_table_names();
347
348 $tables = $DB->get_tables();
349
350 /// Iterate over, fixing id fields as necessary
351 foreach ($tables as $table) {
352 if (in_array($table, $used_tables)) {
353 continue;
354 }
355
8b4ca8f7 356 if (strpos($table, $name) !== 0) {
357 continue;
358 }
359
b1f93b15 360 // found orphan table --> delete it
361 if ($DB->get_manager()->table_exists($table)) {
362 $xmldb_table = new xmldb_table($table);
eee5d9bb 363 $DB->get_manager()->drop_table($xmldb_table);
b1f93b15 364 }
365 }
366
367 return true;
368}
369
370/**
875e5f07 371 * Returns names of all known tables == tables that moodle knows about.
db26acd4 372 *
373 * @return array Array of lowercase table names
b1f93b15 374 */
375function get_used_table_names() {
376 $table_names = array();
377 $dbdirs = get_db_directories();
378
379 foreach ($dbdirs as $dbdir) {
380 $file = $dbdir.'/install.xml';
381
382 $xmldb_file = new xmldb_file($file);
383
384 if (!$xmldb_file->fileExists()) {
385 continue;
386 }
387
388 $loaded = $xmldb_file->loadXMLStructure();
73fa96d5 389 $structure = $xmldb_file->getStructure();
b1f93b15 390
391 if ($loaded and $tables = $structure->getTables()) {
392 foreach($tables as $table) {
afe1cf72 393 $table_names[] = strtolower($table->getName());
b1f93b15 394 }
395 }
396 }
397
398 return $table_names;
399}
400
401/**
402 * Returns list of all directories where we expect install.xml files
db26acd4 403 * @return array Array of paths
b1f93b15 404 */
405function get_db_directories() {
406 global $CFG;
407
408 $dbdirs = array();
409
9baf6825 410 /// First, the main one (lib/db)
b1f93b15 411 $dbdirs[] = $CFG->libdir.'/db';
412
46f6f7f2
PS
413 /// Then, all the ones defined by core_component::get_plugin_types()
414 $plugintypes = core_component::get_plugin_types();
17da2e6f 415 foreach ($plugintypes as $plugintype => $pluginbasedir) {
bd3b3bba 416 if ($plugins = core_component::get_plugin_list($plugintype)) {
17da2e6f 417 foreach ($plugins as $plugin => $plugindir) {
418 $dbdirs[] = $plugindir.'/db';
76b6c644 419 }
b91b274b 420 }
7cdd8b22 421 }
b1f93b15 422
b1f93b15 423 return $dbdirs;
424}
425
eef868d1 426/**
61460dd6 427 * Try to obtain or release the cron lock.
61460dd6 428 * @param string $name name of lock
875e5f07
PS
429 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
430 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
61460dd6 431 * @return bool true if lock obtained
f3221af9 432 */
61460dd6 433function set_cron_lock($name, $until, $ignorecurrent=false) {
f33e1ed4 434 global $DB;
f3221af9 435 if (empty($name)) {
61460dd6 436 debugging("Tried to get a cron lock for a null fieldname");
f3221af9 437 return false;
438 }
439
61460dd6 440 // remove lock by force == remove from config table
441 if (is_null($until)) {
442 set_config($name, null);
f3221af9 443 return true;
444 }
445
61460dd6 446 if (!$ignorecurrent) {
3e7069e7 447 // read value from db - other processes might have changed it
f33e1ed4 448 $value = $DB->get_field('config', 'value', array('name'=>$name));
61460dd6 449
450 if ($value and $value > time()) {
3e7069e7 451 //lock active
61460dd6 452 return false;
f3221af9 453 }
454 }
61460dd6 455
456 set_config($name, $until);
f3221af9 457 return true;
458}
a597f8a8 459
bba0beae 460/**
461 * Test if and critical warnings are present
462 * @return bool
463 */
464function admin_critical_warnings_present() {
465 global $SESSION;
466
b0c6dc1c 467 if (!has_capability('moodle/site:config', context_system::instance())) {
bba0beae 468 return 0;
469 }
470
471 if (!isset($SESSION->admin_critical_warning)) {
472 $SESSION->admin_critical_warning = 0;
fbf2c91e 473 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
bba0beae 474 $SESSION->admin_critical_warning = 1;
475 }
476 }
477
478 return $SESSION->admin_critical_warning;
479}
480
61f9c4b4 481/**
db26acd4 482 * Detects if float supports at least 10 decimal digits
483 *
875e5f07 484 * Detects if float supports at least 10 decimal digits
61f9c4b4 485 * and also if float-->string conversion works as expected.
db26acd4 486 *
61f9c4b4 487 * @return bool true if problem found
488 */
489function is_float_problem() {
490 $num1 = 2009010200.01;
491 $num2 = 2009010200.02;
492
493 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
494}
495
57e35f32 496/**
497 * Try to verify that dataroot is not accessible from web.
57e35f32 498 *
db26acd4 499 * Try to verify that dataroot is not accessible from web.
500 * It is not 100% correct but might help to reduce number of vulnerable sites.
57e35f32 501 * Protection from httpd.conf and .htaccess is not detected properly.
0c079f19 502 *
db26acd4 503 * @uses INSECURE_DATAROOT_WARNING
504 * @uses INSECURE_DATAROOT_ERROR
505 * @param bool $fetchtest try to test public access by fetching file, default false
875e5f07 506 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
57e35f32 507 */
bba0beae 508function is_dataroot_insecure($fetchtest=false) {
57e35f32 509 global $CFG;
510
511 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
512
513 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
514 $rp = strrev(trim($rp, '/'));
515 $rp = explode('/', $rp);
516 foreach($rp as $r) {
517 if (strpos($siteroot, '/'.$r.'/') === 0) {
518 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
519 } else {
520 break; // probably alias root
521 }
522 }
523
524 $siteroot = strrev($siteroot);
525 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
526
bba0beae 527 if (strpos($dataroot, $siteroot) !== 0) {
528 return false;
529 }
530
531 if (!$fetchtest) {
532 return INSECURE_DATAROOT_WARNING;
533 }
534
535 // now try all methods to fetch a test file using http protocol
536
537 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
538 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
539 $httpdocroot = $matches[1];
540 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
71904f4d 541 make_upload_directory('diag');
bba0beae 542 $testfile = $CFG->dataroot.'/diag/public.txt';
543 if (!file_exists($testfile)) {
544 file_put_contents($testfile, 'test file, do not delete');
eb459f71 545 @chmod($testfile, $CFG->filepermissions);
bba0beae 546 }
547 $teststr = trim(file_get_contents($testfile));
548 if (empty($teststr)) {
9baf6825 549 // hmm, strange
bba0beae 550 return INSECURE_DATAROOT_WARNING;
551 }
552
553 $testurl = $datarooturl.'/diag/public.txt';
041a4b0f 554 if (extension_loaded('curl') and
555 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
556 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
557 ($ch = @curl_init($testurl)) !== false) {
bba0beae 558 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
559 curl_setopt($ch, CURLOPT_HEADER, false);
560 $data = curl_exec($ch);
561 if (!curl_errno($ch)) {
562 $data = trim($data);
563 if ($data === $teststr) {
564 curl_close($ch);
565 return INSECURE_DATAROOT_ERROR;
566 }
567 }
568 curl_close($ch);
569 }
570
571 if ($data = @file_get_contents($testurl)) {
572 $data = trim($data);
573 if ($data === $teststr) {
574 return INSECURE_DATAROOT_ERROR;
575 }
576 }
577
578 preg_match('|https?://([^/]+)|i', $testurl, $matches);
579 $sitename = $matches[1];
580 $error = 0;
581 if ($fp = @fsockopen($sitename, 80, $error)) {
582 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
583 $localurl = $matches[1];
584 $out = "GET $localurl HTTP/1.1\r\n";
585 $out .= "Host: $sitename\r\n";
586 $out .= "Connection: Close\r\n\r\n";
587 fwrite($fp, $out);
588 $data = '';
589 $incoming = false;
590 while (!feof($fp)) {
591 if ($incoming) {
592 $data .= fgets($fp, 1024);
593 } else if (@fgets($fp, 1024) === "\r\n") {
9baf6825 594 $incoming = true;
595 }
bba0beae 596 }
597 fclose($fp);
598 $data = trim($data);
599 if ($data === $teststr) {
600 return INSECURE_DATAROOT_ERROR;
601 }
57e35f32 602 }
bba0beae 603
604 return INSECURE_DATAROOT_WARNING;
57e35f32 605}
6e4dc10f 606
48e114a5
PS
607/**
608 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
609 */
610function enable_cli_maintenance_mode() {
611 global $CFG;
612
613 if (file_exists("$CFG->dataroot/climaintenance.html")) {
614 unlink("$CFG->dataroot/climaintenance.html");
615 }
616
617 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
618 $data = $CFG->maintenance_message;
619 $data = bootstrap_renderer::early_error_content($data, null, null, null);
620 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
621
622 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
623 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
624
625 } else {
626 $data = get_string('sitemaintenance', 'admin');
627 $data = bootstrap_renderer::early_error_content($data, null, null, null);
628 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
629 }
630
631 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
632 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
633}
634
6e4dc10f 635/// CLASS DEFINITIONS /////////////////////////////////////////////////////////
636
3e7069e7 637
6e4dc10f 638/**
875e5f07 639 * Interface for anything appearing in the admin tree
6e4dc10f 640 *
875e5f07 641 * The interface that is implemented by anything that appears in the admin tree
6e4dc10f 642 * block. It forces inheriting classes to define a method for checking user permissions
643 * and methods for finding something in the admin tree.
644 *
db26acd4 645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 646 */
73fa96d5 647interface part_of_admin_tree {
6e4dc10f 648
9baf6825 649/**
650 * Finds a named part_of_admin_tree.
651 *
652 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
653 * and not parentable_part_of_admin_tree, then this function should only check if
654 * $this->name matches $name. If it does, it should return a reference to $this,
655 * otherwise, it should return a reference to NULL.
656 *
657 * If a class inherits parentable_part_of_admin_tree, this method should be called
658 * recursively on all child objects (assuming, of course, the parent object's name
659 * doesn't match the search criterion).
660 *
661 * @param string $name The internal name of the part_of_admin_tree we're searching for.
662 * @return mixed An object reference or a NULL reference.
663 */
73fa96d5 664 public function locate($name);
4672d955 665
666 /**
667 * Removes named part_of_admin_tree.
668 *
669 * @param string $name The internal name of the part_of_admin_tree we want to remove.
a8a66c96 670 * @return bool success.
4672d955 671 */
73fa96d5 672 public function prune($name);
4672d955 673
220a90c5 674 /**
675 * Search using query
db26acd4 676 * @param string $query
220a90c5 677 * @return mixed array-object structure of found settings and pages
678 */
73fa96d5 679 public function search($query);
220a90c5 680
6e4dc10f 681 /**
682 * Verifies current user's access to this part_of_admin_tree.
683 *
684 * Used to check if the current user has access to this part of the admin tree or
685 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
686 * then this method is usually just a call to has_capability() in the site context.
687 *
688 * If a class inherits parentable_part_of_admin_tree, this method should return the
689 * logical OR of the return of check_access() on all child objects.
690 *
691 * @return bool True if the user has access, false if she doesn't.
692 */
73fa96d5 693 public function check_access();
eef868d1 694
a8a66c96 695 /**
875e5f07 696 * Mostly useful for removing of some parts of the tree in admin tree block.
a8a66c96 697 *
698 * @return True is hidden from normal list view
699 */
73fa96d5 700 public function is_hidden();
427649bf
PS
701
702 /**
703 * Show we display Save button at the page bottom?
704 * @return bool
705 */
706 public function show_save();
6e4dc10f 707}
708
3e7069e7 709
6e4dc10f 710/**
875e5f07 711 * Interface implemented by any part_of_admin_tree that has children.
6e4dc10f 712 *
875e5f07 713 * The interface implemented by any part_of_admin_tree that can be a parent
6e4dc10f 714 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
eef868d1 715 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
6e4dc10f 716 * include an add method for adding other part_of_admin_tree objects as children.
717 *
db26acd4 718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 719 */
73fa96d5 720interface parentable_part_of_admin_tree extends part_of_admin_tree {
eef868d1 721
9baf6825 722/**
723 * Adds a part_of_admin_tree object to the admin tree.
724 *
725 * Used to add a part_of_admin_tree object to this object or a child of this
726 * object. $something should only be added if $destinationname matches
727 * $this->name. If it doesn't, add should be called on child objects that are
728 * also parentable_part_of_admin_tree's.
729 *
f6e85ab0
DM
730 * $something should be appended as the last child in the $destinationname. If the
731 * $beforesibling is specified, $something should be prepended to it. If the given
732 * sibling is not found, $something should be appended to the end of $destinationname
733 * and a developer debugging message should be displayed.
734 *
9baf6825 735 * @param string $destinationname The internal name of the new parent for $something.
736 * @param part_of_admin_tree $something The object to be added.
737 * @return bool True on success, false on failure.
738 */
f6e85ab0 739 public function add($destinationname, $something, $beforesibling = null);
eef868d1 740
6e4dc10f 741}
742
3e7069e7 743
6e4dc10f 744/**
745 * The object used to represent folders (a.k.a. categories) in the admin tree block.
eef868d1 746 *
6e4dc10f 747 * Each admin_category object contains a number of part_of_admin_tree objects.
748 *
db26acd4 749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 750 */
73fa96d5 751class admin_category implements parentable_part_of_admin_tree {
6e4dc10f 752
cde44edc 753 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
73fa96d5 754 public $children;
0c079f19 755 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
73fa96d5 756 public $name;
0c079f19 757 /** @var string The displayed name for this category. Usually obtained through get_string() */
73fa96d5 758 public $visiblename;
0c079f19 759 /** @var bool Should this category be hidden in admin tree block? */
73fa96d5 760 public $hidden;
0c079f19 761 /** @var mixed Either a string or an array or strings */
73fa96d5 762 public $path;
0c079f19 763 /** @var mixed Either a string or an array or strings */
73fa96d5 764 public $visiblepath;
6e4dc10f 765
cde44edc
PS
766 /** @var array fast lookup category cache, all categories of one tree point to one cache */
767 protected $category_cache;
768
6e4dc10f 769 /**
770 * Constructor for an empty admin category
771 *
772 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
773 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
db26acd4 774 * @param bool $hidden hide category in admin tree block, defaults to false
6e4dc10f 775 */
73fa96d5 776 public function __construct($name, $visiblename, $hidden=false) {
220a90c5 777 $this->children = array();
778 $this->name = $name;
6e4dc10f 779 $this->visiblename = $visiblename;
220a90c5 780 $this->hidden = $hidden;
6e4dc10f 781 }
eef868d1 782
6e4dc10f 783 /**
220a90c5 784 * Returns a reference to the part_of_admin_tree object with internal name $name.
6e4dc10f 785 *
220a90c5 786 * @param string $name The internal name of the object we want.
787 * @param bool $findpath initialize path and visiblepath arrays
0c079f19 788 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
db26acd4 789 * defaults to false
6e4dc10f 790 */
73fa96d5 791 public function locate($name, $findpath=false) {
42b53d46 792 if (!isset($this->category_cache[$this->name])) {
cde44edc
PS
793 // somebody much have purged the cache
794 $this->category_cache[$this->name] = $this;
795 }
796
6e4dc10f 797 if ($this->name == $name) {
220a90c5 798 if ($findpath) {
799 $this->visiblepath[] = $this->visiblename;
800 $this->path[] = $this->name;
801 }
802 return $this;
6e4dc10f 803 }
eef868d1 804
cde44edc 805 // quick category lookup
42b53d46 806 if (!$findpath and isset($this->category_cache[$name])) {
cde44edc
PS
807 return $this->category_cache[$name];
808 }
809
220a90c5 810 $return = NULL;
811 foreach($this->children as $childid=>$unused) {
73fa96d5 812 if ($return = $this->children[$childid]->locate($name, $findpath)) {
220a90c5 813 break;
6e4dc10f 814 }
815 }
eef868d1 816
220a90c5 817 if (!is_null($return) and $findpath) {
818 $return->visiblepath[] = $this->visiblename;
819 $return->path[] = $this->name;
820 }
eef868d1 821
220a90c5 822 return $return;
6e4dc10f 823 }
824
825 /**
220a90c5 826 * Search using query
db26acd4 827 *
828 * @param string query
220a90c5 829 * @return mixed array-object structure of found settings and pages
6e4dc10f 830 */
73fa96d5 831 public function search($query) {
220a90c5 832 $result = array();
833 foreach ($this->children as $child) {
3cea9c55 834 $subsearch = $child->search($query);
835 if (!is_array($subsearch)) {
836 debugging('Incorrect search result from '.$child->name);
837 continue;
838 }
839 $result = array_merge($result, $subsearch);
6e4dc10f 840 }
220a90c5 841 return $result;
6e4dc10f 842 }
843
4672d955 844 /**
845 * Removes part_of_admin_tree object with internal name $name.
846 *
847 * @param string $name The internal name of the object we want to remove.
a8a66c96 848 * @return bool success
4672d955 849 */
73fa96d5 850 public function prune($name) {
4672d955 851
852 if ($this->name == $name) {
853 return false; //can not remove itself
854 }
855
856 foreach($this->children as $precedence => $child) {
857 if ($child->name == $name) {
cde44edc 858 // clear cache and delete self
42b53d46
AN
859 while($this->category_cache) {
860 // delete the cache, but keep the original array address
861 array_pop($this->category_cache);
cde44edc 862 }
eef868d1 863 unset($this->children[$precedence]);
4672d955 864 return true;
cde44edc 865 } else if ($this->children[$precedence]->prune($name)) {
4672d955 866 return true;
867 }
868 }
869 return false;
870 }
871
6e4dc10f 872 /**
873 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
874 *
f6e85ab0
DM
875 * By default the new part of the tree is appended as the last child of the parent. You
876 * can specify a sibling node that the new part should be prepended to. If the given
877 * sibling is not found, the part is appended to the end (as it would be by default) and
878 * a developer debugging message is displayed.
879 *
880 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
220a90c5 881 * @param string $destinationame The internal name of the immediate parent that we want for $something.
875e5f07 882 * @param mixed $something A part_of_admin_tree or setting instance to be added.
f6e85ab0 883 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
220a90c5 884 * @return bool True if successfully added, false if $something can not be added.
6e4dc10f 885 */
f6e85ab0 886 public function add($parentname, $something, $beforesibling = null) {
96f81ea3
PS
887 global $CFG;
888
73fa96d5 889 $parent = $this->locate($parentname);
220a90c5 890 if (is_null($parent)) {
891 debugging('parent does not exist!');
6e4dc10f 892 return false;
893 }
894
73fa96d5 895 if ($something instanceof part_of_admin_tree) {
896 if (!($parent instanceof parentable_part_of_admin_tree)) {
220a90c5 897 debugging('error - parts of tree can be inserted only into parentable parts');
898 return false;
6e4dc10f 899 }
96f81ea3 900 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
97a8eddd
FM
901 // The name of the node is already used, simply warn the developer that this should not happen.
902 // It is intentional to check for the debug level before performing the check.
903 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
904 }
f6e85ab0
DM
905 if (is_null($beforesibling)) {
906 // Append $something as the parent's last child.
907 $parent->children[] = $something;
908 } else {
909 if (!is_string($beforesibling) or trim($beforesibling) === '') {
910 throw new coding_exception('Unexpected value of the beforesibling parameter');
911 }
912 // Try to find the position of the sibling.
913 $siblingposition = null;
914 foreach ($parent->children as $childposition => $child) {
915 if ($child->name === $beforesibling) {
916 $siblingposition = $childposition;
917 break;
918 }
919 }
920 if (is_null($siblingposition)) {
921 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
922 $parent->children[] = $something;
923 } else {
924 $parent->children = array_merge(
925 array_slice($parent->children, 0, $siblingposition),
926 array($something),
927 array_slice($parent->children, $siblingposition)
928 );
929 }
930 }
42b53d46 931 if ($something instanceof admin_category) {
cde44edc 932 if (isset($this->category_cache[$something->name])) {
3e7069e7 933 debugging('Duplicate admin category name: '.$something->name);
cde44edc
PS
934 } else {
935 $this->category_cache[$something->name] = $something;
936 $something->category_cache =& $this->category_cache;
937 foreach ($something->children as $child) {
938 // just in case somebody already added subcategories
939 if ($child instanceof admin_category) {
940 if (isset($this->category_cache[$child->name])) {
3e7069e7 941 debugging('Duplicate admin category name: '.$child->name);
cde44edc
PS
942 } else {
943 $this->category_cache[$child->name] = $child;
944 $child->category_cache =& $this->category_cache;
945 }
946 }
947 }
948 }
949 }
6e4dc10f 950 return true;
eef868d1 951
220a90c5 952 } else {
953 debugging('error - can not add this element');
954 return false;
6e4dc10f 955 }
eef868d1 956
6e4dc10f 957 }
eef868d1 958
6e4dc10f 959 /**
960 * Checks if the user has access to anything in this category.
961 *
875e5f07 962 * @return bool True if the user has access to at least one child in this category, false otherwise.
6e4dc10f 963 */
73fa96d5 964 public function check_access() {
6e4dc10f 965 foreach ($this->children as $child) {
220a90c5 966 if ($child->check_access()) {
967 return true;
968 }
6e4dc10f 969 }
220a90c5 970 return false;
6e4dc10f 971 }
eef868d1 972
a8a66c96 973 /**
974 * Is this category hidden in admin tree block?
975 *
976 * @return bool True if hidden
977 */
73fa96d5 978 public function is_hidden() {
a8a66c96 979 return $this->hidden;
980 }
427649bf
PS
981
982 /**
983 * Show we display Save button at the page bottom?
984 * @return bool
985 */
986 public function show_save() {
987 foreach ($this->children as $child) {
988 if ($child->show_save()) {
989 return true;
990 }
991 }
992 return false;
993 }
6e4dc10f 994}
995
3e7069e7 996
db26acd4 997/**
0c079f19 998 * Root of admin settings tree, does not have any parent.
db26acd4 999 *
1000 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 1001 */
220a90c5 1002class admin_root extends admin_category {
9baf6825 1003/** @var array List of errors */
73fa96d5 1004 public $errors;
0c079f19 1005 /** @var string search query */
73fa96d5 1006 public $search;
875e5f07 1007 /** @var bool full tree flag - true means all settings required, false only pages required */
73fa96d5 1008 public $fulltree;
0c079f19 1009 /** @var bool flag indicating loaded tree */
73fa96d5 1010 public $loaded;
875e5f07 1011 /** @var mixed site custom defaults overriding defaults in settings files*/
cd3acbf2 1012 public $custom_defaults;
1013
db26acd4 1014 /**
0c079f19 1015 * @param bool $fulltree true means all settings required,
db26acd4 1016 * false only pages required
1017 */
73fa96d5 1018 public function __construct($fulltree) {
cd3acbf2 1019 global $CFG;
1020
73fa96d5 1021 parent::__construct('root', get_string('administration'), false);
220a90c5 1022 $this->errors = array();
1023 $this->search = '';
73fa96d5 1024 $this->fulltree = $fulltree;
1025 $this->loaded = false;
cd3acbf2 1026
cde44edc
PS
1027 $this->category_cache = array();
1028
cd3acbf2 1029 // load custom defaults if found
1030 $this->custom_defaults = null;
1031 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1032 if (is_readable($defaultsfile)) {
1033 $defaults = array();
1034 include($defaultsfile);
1035 if (is_array($defaults) and count($defaults)) {
1036 $this->custom_defaults = $defaults;
1037 }
1038 }
73fa96d5 1039 }
1040
db26acd4 1041 /**
1042 * Empties children array, and sets loaded to false
1043 *
1044 * @param bool $requirefulltree
1045 */
73fa96d5 1046 public function purge_children($requirefulltree) {
1047 $this->children = array();
1048 $this->fulltree = ($requirefulltree || $this->fulltree);
1049 $this->loaded = false;
cde44edc
PS
1050 //break circular dependencies - this helps PHP 5.2
1051 while($this->category_cache) {
1052 array_pop($this->category_cache);
1053 }
1054 $this->category_cache = array();
220a90c5 1055 }
1056}
1057
3e7069e7 1058
6e4dc10f 1059/**
1060 * Links external PHP pages into the admin tree.
1061 *
1062 * See detailed usage example at the top of this document (adminlib.php)
1063 *
db26acd4 1064 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 1065 */
73fa96d5 1066class admin_externalpage implements part_of_admin_tree {
6e4dc10f 1067
3e7069e7 1068 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
73fa96d5 1069 public $name;
eef868d1 1070
0c079f19 1071 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
73fa96d5 1072 public $visiblename;
eef868d1 1073
0c079f19 1074 /** @var string The external URL that we should link to when someone requests this external page. */
73fa96d5 1075 public $url;
eef868d1 1076
0c079f19 1077 /** @var string The role capability/permission a user must have to access this external page. */
73fa96d5 1078 public $req_capability;
eef868d1 1079
0c079f19 1080 /** @var object The context in which capability/permission should be checked, default is site context. */
73fa96d5 1081 public $context;
84c8ede0 1082
0c079f19 1083 /** @var bool hidden in admin tree block. */
73fa96d5 1084 public $hidden;
a8a66c96 1085
0c079f19 1086 /** @var mixed either string or array of string */
73fa96d5 1087 public $path;
3e7069e7
PS
1088
1089 /** @var array list of visible names of page parents */
73fa96d5 1090 public $visiblepath;
220a90c5 1091
6e4dc10f 1092 /**
1093 * Constructor for adding an external page into the admin tree.
1094 *
1095 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1096 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1097 * @param string $url The external URL that we should link to when someone requests this external page.
38d2d43b 1098 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
92f00846 1099 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
44d8a940 1100 * @param stdClass $context The context the page relates to. Not sure what happens
92f00846 1101 * if you specify something other than system or front page. Defaults to system.
6e4dc10f 1102 */
73fa96d5 1103 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
220a90c5 1104 $this->name = $name;
6e4dc10f 1105 $this->visiblename = $visiblename;
220a90c5 1106 $this->url = $url;
38d2d43b 1107 if (is_array($req_capability)) {
1108 $this->req_capability = $req_capability;
1109 } else {
1110 $this->req_capability = array($req_capability);
1111 }
92f00846 1112 $this->hidden = $hidden;
84c8ede0 1113 $this->context = $context;
6e4dc10f 1114 }
eef868d1 1115
6e4dc10f 1116 /**
1117 * Returns a reference to the part_of_admin_tree object with internal name $name.
1118 *
1119 * @param string $name The internal name of the object we want.
db26acd4 1120 * @param bool $findpath defaults to false
6e4dc10f 1121 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1122 */
73fa96d5 1123 public function locate($name, $findpath=false) {
220a90c5 1124 if ($this->name == $name) {
1125 if ($findpath) {
1126 $this->visiblepath = array($this->visiblename);
1127 $this->path = array($this->name);
1128 }
1129 return $this;
1130 } else {
1131 $return = NULL;
1132 return $return;
1133 }
6e4dc10f 1134 }
4672d955 1135
db26acd4 1136 /**
1137 * This function always returns false, required function by interface
1138 *
1139 * @param string $name
1140 * @return false
1141 */
73fa96d5 1142 public function prune($name) {
4672d955 1143 return false;
1144 }
1145
220a90c5 1146 /**
1147 * Search using query
db26acd4 1148 *
1149 * @param string $query
220a90c5 1150 * @return mixed array-object structure of found settings and pages
1151 */
73fa96d5 1152 public function search($query) {
220a90c5 1153 $found = false;
1154 if (strpos(strtolower($this->name), $query) !== false) {
1155 $found = true;
2f1e464a 1156 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
9baf6825 1157 $found = true;
1158 }
220a90c5 1159 if ($found) {
365a5941 1160 $result = new stdClass();
220a90c5 1161 $result->page = $this;
1162 $result->settings = array();
1163 return array($this->name => $result);
1164 } else {
1165 return array();
1166 }
1167 }
1168
6e4dc10f 1169 /**
2ce38b70 1170 * Determines if the current user has access to this external page based on $this->req_capability.
db26acd4 1171 *
6e4dc10f 1172 * @return bool True if user has access, false otherwise.
1173 */
73fa96d5 1174 public function check_access() {
1caea91e 1175 global $CFG;
b0c6dc1c 1176 $context = empty($this->context) ? context_system::instance() : $this->context;
38d2d43b 1177 foreach($this->req_capability as $cap) {
4f0c2d00 1178 if (has_capability($cap, $context)) {
38d2d43b 1179 return true;
1180 }
1181 }
1182 return false;
6e4dc10f 1183 }
1184
a8a66c96 1185 /**
1186 * Is this external page hidden in admin tree block?
1187 *
1188 * @return bool True if hidden
1189 */
73fa96d5 1190 public function is_hidden() {
a8a66c96 1191 return $this->hidden;
1192 }
1193
427649bf
PS
1194 /**
1195 * Show we display Save button at the page bottom?
1196 * @return bool
1197 */
1198 public function show_save() {
1199 return false;
1200 }
6e4dc10f 1201}
1202
3e7069e7 1203
6e4dc10f 1204/**
1205 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1206 *
db26acd4 1207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 1208 */
73fa96d5 1209class admin_settingpage implements part_of_admin_tree {
6e4dc10f 1210
3e7069e7 1211 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
73fa96d5 1212 public $name;
eef868d1 1213
0c079f19 1214 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
73fa96d5 1215 public $visiblename;
0c079f19 1216
1217 /** @var mixed An array of admin_setting objects that are part of this setting page. */
73fa96d5 1218 public $settings;
eef868d1 1219
0c079f19 1220 /** @var string The role capability/permission a user must have to access this external page. */
73fa96d5 1221 public $req_capability;
eef868d1 1222
0c079f19 1223 /** @var object The context in which capability/permission should be checked, default is site context. */
73fa96d5 1224 public $context;
84c8ede0 1225
0c079f19 1226 /** @var bool hidden in admin tree block. */
73fa96d5 1227 public $hidden;
a8a66c96 1228
0c079f19 1229 /** @var mixed string of paths or array of strings of paths */
73fa96d5 1230 public $path;
3e7069e7
PS
1231
1232 /** @var array list of visible names of page parents */
73fa96d5 1233 public $visiblepath;
220a90c5 1234
db26acd4 1235 /**
1236 * see admin_settingpage for details of this function
0c079f19 1237 *
db26acd4 1238 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1239 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1240 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1241 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
44d8a940 1242 * @param stdClass $context The context the page relates to. Not sure what happens
db26acd4 1243 * if you specify something other than system or front page. Defaults to system.
1244 */
73fa96d5 1245 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
365a5941 1246 $this->settings = new stdClass();
220a90c5 1247 $this->name = $name;
1248 $this->visiblename = $visiblename;
1249 if (is_array($req_capability)) {
1250 $this->req_capability = $req_capability;
6e4dc10f 1251 } else {
220a90c5 1252 $this->req_capability = array($req_capability);
6e4dc10f 1253 }
220a90c5 1254 $this->hidden = $hidden;
1255 $this->context = $context;
6e4dc10f 1256 }
eef868d1 1257
0c079f19 1258 /**
db26acd4 1259 * see admin_category
1260 *
1261 * @param string $name
1262 * @param bool $findpath
1263 * @return mixed Object (this) if name == this->name, else returns null
1264 */
73fa96d5 1265 public function locate($name, $findpath=false) {
220a90c5 1266 if ($this->name == $name) {
1267 if ($findpath) {
1268 $this->visiblepath = array($this->visiblename);
1269 $this->path = array($this->name);
1270 }
1271 return $this;
1272 } else {
1273 $return = NULL;
1274 return $return;
1275 }
6e4dc10f 1276 }
4672d955 1277
0c079f19 1278 /**
1279 * Search string in settings page.
1280 *
db26acd4 1281 * @param string $query
1282 * @return array
1283 */
73fa96d5 1284 public function search($query) {
220a90c5 1285 $found = array();
4672d955 1286
220a90c5 1287 foreach ($this->settings as $setting) {
1288 if ($setting->is_related($query)) {
1289 $found[] = $setting;
1290 }
1291 }
1292
1293 if ($found) {
365a5941 1294 $result = new stdClass();
220a90c5 1295 $result->page = $this;
1296 $result->settings = $found;
1297 return array($this->name => $result);
1298 }
1299
220a90c5 1300 $found = false;
1301 if (strpos(strtolower($this->name), $query) !== false) {
1302 $found = true;
2f1e464a 1303 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
9baf6825 1304 $found = true;
1305 }
220a90c5 1306 if ($found) {
365a5941 1307 $result = new stdClass();
220a90c5 1308 $result->page = $this;
1309 $result->settings = array();
1310 return array($this->name => $result);
38d2d43b 1311 } else {
220a90c5 1312 return array();
38d2d43b 1313 }
6e4dc10f 1314 }
eef868d1 1315
db26acd4 1316 /**
1317 * This function always returns false, required by interface
1318 *
1319 * @param string $name
1320 * @return bool Always false
1321 */
73fa96d5 1322 public function prune($name) {
6e4dc10f 1323 return false;
1324 }
eef868d1 1325
220a90c5 1326 /**
db26acd4 1327 * adds an admin_setting to this admin_settingpage
1328 *
220a90c5 1329 * 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
1330 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
db26acd4 1331 *
220a90c5 1332 * @param object $setting is the admin_setting object you want to add
db26acd4 1333 * @return bool true if successful, false if not
220a90c5 1334 */
73fa96d5 1335 public function add($setting) {
1336 if (!($setting instanceof admin_setting)) {
220a90c5 1337 debugging('error - not a setting instance');
1338 return false;
1339 }
1340
1341 $this->settings->{$setting->name} = $setting;
1342 return true;
1343 }
1344
db26acd4 1345 /**
1346 * see admin_externalpage
1347 *
1348 * @return bool Returns true for yes false for no
1349 */
73fa96d5 1350 public function check_access() {
1caea91e 1351 global $CFG;
b0c6dc1c 1352 $context = empty($this->context) ? context_system::instance() : $this->context;
38d2d43b 1353 foreach($this->req_capability as $cap) {
4f0c2d00 1354 if (has_capability($cap, $context)) {
38d2d43b 1355 return true;
1356 }
1357 }
1358 return false;
6e4dc10f 1359 }
eef868d1 1360
220a90c5 1361 /**
1362 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
db26acd4 1363 * @return string Returns an XHTML string
220a90c5 1364 */
73fa96d5 1365 public function output_html() {
1366 $adminroot = admin_get_root();
220a90c5 1367 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
6e4dc10f 1368 foreach($this->settings as $setting) {
220a90c5 1369 $fullname = $setting->get_full_name();
1370 if (array_key_exists($fullname, $adminroot->errors)) {
1371 $data = $adminroot->errors[$fullname]->data;
6e4dc10f 1372 } else {
220a90c5 1373 $data = $setting->get_setting();
79698344 1374 // do not use defaults if settings not available - upgrade settings handles the defaults!
6e4dc10f 1375 }
220a90c5 1376 $return .= $setting->output_html($data);
6e4dc10f 1377 }
220a90c5 1378 $return .= '</fieldset>';
6e4dc10f 1379 return $return;
1380 }
1381
a8a66c96 1382 /**
875e5f07 1383 * Is this settings page hidden in admin tree block?
a8a66c96 1384 *
1385 * @return bool True if hidden
1386 */
73fa96d5 1387 public function is_hidden() {
a8a66c96 1388 return $this->hidden;
1389 }
1390
427649bf
PS
1391 /**
1392 * Show we display Save button at the page bottom?
1393 * @return bool
1394 */
1395 public function show_save() {
1396 foreach($this->settings as $setting) {
1397 if (empty($setting->nosave)) {
1398 return true;
1399 }
1400 }
1401 return false;
1402 }
6e4dc10f 1403}
1404
1405
220a90c5 1406/**
1407 * Admin settings class. Only exists on setting pages.
1408 * Read & write happens at this level; no authentication.
db26acd4 1409 *
1410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1411 */
301bf0b2 1412abstract class admin_setting {
3e7069e7 1413 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
73fa96d5 1414 public $name;
0c079f19 1415 /** @var string localised name */
73fa96d5 1416 public $visiblename;
3fa37159 1417 /** @var string localised long description in Markdown format */
73fa96d5 1418 public $description;
0c079f19 1419 /** @var mixed Can be string or array of string */
73fa96d5 1420 public $defaultsetting;
0c079f19 1421 /** @var string */
73fa96d5 1422 public $updatedcallback;
0c079f19 1423 /** @var mixed can be String or Null. Null means main config table */
73fa96d5 1424 public $plugin; // null means main config table
427649bf
PS
1425 /** @var bool true indicates this setting does not actually save anything, just information */
1426 public $nosave = false;
adaeccb6 1427 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1428 public $affectsmodinfo = false;
3c88a678
DW
1429 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1430 private $flags = array();
6e4dc10f 1431
220a90c5 1432 /**
1433 * Constructor
0c079f19 1434 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
db26acd4 1435 * or 'myplugin/mysetting' for ones in config_plugins.
1a41e806 1436 * @param string $visiblename localised name
1437 * @param string $description localised long description
220a90c5 1438 * @param mixed $defaultsetting string or array depending on implementation
1439 */
73fa96d5 1440 public function __construct($name, $visiblename, $description, $defaultsetting) {
7fb0303d 1441 $this->parse_setting_name($name);
220a90c5 1442 $this->visiblename = $visiblename;
8dbe233a 1443 $this->description = $description;
6e4dc10f 1444 $this->defaultsetting = $defaultsetting;
1445 }
eef868d1 1446
3c88a678
DW
1447 /**
1448 * Generic function to add a flag to this admin setting.
1449 *
1450 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1451 * @param bool $default - The default for the flag
1452 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1453 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1454 */
1455 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1456 if (empty($this->flags[$shortname])) {
1457 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1458 } else {
1459 $this->flags[$shortname]->set_options($enabled, $default);
1460 }
1461 }
1462
1463 /**
1464 * Set the enabled options flag on this admin setting.
1465 *
1466 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1467 * @param bool $default - The default for the flag
1468 */
1469 public function set_enabled_flag_options($enabled, $default) {
1470 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1471 }
1472
1473 /**
1474 * Set the advanced options flag on this admin setting.
1475 *
1476 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1477 * @param bool $default - The default for the flag
1478 */
1479 public function set_advanced_flag_options($enabled, $default) {
1480 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1481 }
1482
1483
1484 /**
1485 * Set the locked options flag on this admin setting.
1486 *
1487 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1488 * @param bool $default - The default for the flag
1489 */
1490 public function set_locked_flag_options($enabled, $default) {
1491 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1492 }
1493
1494 /**
1495 * Get the currently saved value for a setting flag
1496 *
1497 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1498 * @return bool
1499 */
1500 public function get_setting_flag_value(admin_setting_flag $flag) {
1501 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1502 if (!isset($value)) {
1503 $value = $flag->get_default();
1504 }
1505
1506 return !empty($value);
1507 }
1508
1509 /**
1510 * Get the list of defaults for the flags on this setting.
1511 *
1512 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1513 */
1514 public function get_setting_flag_defaults(& $defaults) {
1515 foreach ($this->flags as $flag) {
1516 if ($flag->is_enabled() && $flag->get_default()) {
1517 $defaults[] = $flag->get_displayname();
1518 }
1519 }
1520 }
1521
1522 /**
1523 * Output the input fields for the advanced and locked flags on this setting.
1524 *
1525 * @param bool $adv - The current value of the advanced flag.
1526 * @param bool $locked - The current value of the locked flag.
1527 * @return string $output - The html for the flags.
1528 */
1529 public function output_setting_flags() {
1530 $output = '';
1531
1532 foreach ($this->flags as $flag) {
1533 if ($flag->is_enabled()) {
1534 $output .= $flag->output_setting_flag($this);
1535 }
1536 }
1537
459e3c88
DW
1538 if (!empty($output)) {
1539 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1540 }
3c88a678
DW
1541 return $output;
1542 }
1543
1544 /**
1545 * Write the values of the flags for this admin setting.
1546 *
7e815a6e 1547 * @param array $data - The data submitted from the form or null to set the default value for new installs.
3c88a678
DW
1548 * @return bool - true if successful.
1549 */
1550 public function write_setting_flags($data) {
1551 $result = true;
1552 foreach ($this->flags as $flag) {
1553 $result = $result && $flag->write_setting_flag($this, $data);
1554 }
1555 return $result;
1556 }
1557
7fb0303d 1558 /**
db26acd4 1559 * Set up $this->name and potentially $this->plugin
1560 *
7fb0303d 1561 * Set up $this->name and possibly $this->plugin based on whether $name looks
1562 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1563 * on the names, that is, output a developer debug warning if the name
1564 * contains anything other than [a-zA-Z0-9_]+.
1565 *
1566 * @param string $name the setting name passed in to the constructor.
1567 */
1568 private function parse_setting_name($name) {
1569 $bits = explode('/', $name);
1570 if (count($bits) > 2) {
1571 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1572 }
1573 $this->name = array_pop($bits);
1574 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1575 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1576 }
1577 if (!empty($bits)) {
1578 $this->plugin = array_pop($bits);
cd3acbf2 1579 if ($this->plugin === 'moodle') {
1580 $this->plugin = null;
1581 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
9baf6825 1582 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1583 }
7fb0303d 1584 }
1585 }
1586
db26acd4 1587 /**
1588 * Returns the fullname prefixed by the plugin
1589 * @return string
1590 */
73fa96d5 1591 public function get_full_name() {
220a90c5 1592 return 's_'.$this->plugin.'_'.$this->name;
1593 }
1594
db26acd4 1595 /**
1596 * Returns the ID string based on plugin and name
1597 * @return string
1598 */
73fa96d5 1599 public function get_id() {
220a90c5 1600 return 'id_s_'.$this->plugin.'_'.$this->name;
1601 }
1602
adaeccb6 1603 /**
1604 * @param bool $affectsmodinfo If true, changes to this setting will
1605 * cause the course cache to be rebuilt
1606 */
1607 public function set_affects_modinfo($affectsmodinfo) {
1608 $this->affectsmodinfo = $affectsmodinfo;
1609 }
1610
db26acd4 1611 /**
1612 * Returns the config if possible
1613 *
3e7069e7 1614 * @return mixed returns config if successful else null
db26acd4 1615 */
73fa96d5 1616 public function config_read($name) {
220a90c5 1617 global $CFG;
eb6a973c 1618 if (!empty($this->plugin)) {
220a90c5 1619 $value = get_config($this->plugin, $name);
1620 return $value === false ? NULL : $value;
1621
1622 } else {
1623 if (isset($CFG->$name)) {
1624 return $CFG->$name;
1625 } else {
1626 return NULL;
1627 }
1628 }
1629 }
1630
301bf0b2 1631 /**
db26acd4 1632 * Used to set a config pair and log change
301bf0b2 1633 *
db26acd4 1634 * @param string $name
1635 * @param mixed $value Gets converted to string if not null
875e5f07 1636 * @return bool Write setting to config table
301bf0b2 1637 */
73fa96d5 1638 public function config_write($name, $value) {
301bf0b2 1639 global $DB, $USER, $CFG;
1640
427649bf
PS
1641 if ($this->nosave) {
1642 return true;
1643 }
1644
301bf0b2 1645 // make sure it is a real change
1646 $oldvalue = get_config($this->plugin, $name);
1647 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1648 $value = is_null($value) ? null : (string)$value;
1649
1650 if ($oldvalue === $value) {
1651 return true;
1652 }
1653
1654 // store change
1655 set_config($name, $value, $this->plugin);
1656
adaeccb6 1657 // Some admin settings affect course modinfo
1658 if ($this->affectsmodinfo) {
1659 // Clear course cache for all courses
1660 rebuild_course_cache(0, true);
1661 }
1662
914499a3 1663 $this->add_to_config_log($name, $oldvalue, $value);
301bf0b2 1664
1665 return true; // BC only
220a90c5 1666 }
1667
914499a3
PS
1668 /**
1669 * Log config changes if necessary.
1670 * @param string $name
1671 * @param string $oldvalue
1672 * @param string $value
1673 */
1674 protected function add_to_config_log($name, $oldvalue, $value) {
1675 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1676 }
1677
220a90c5 1678 /**
1679 * Returns current value of this setting
1680 * @return mixed array or string depending on instance, NULL means not set yet
1681 */
301bf0b2 1682 public abstract function get_setting();
eef868d1 1683
220a90c5 1684 /**
1685 * Returns default setting if exists
1686 * @return mixed array or string depending on instance; NULL means no default, user must supply
1687 */
73fa96d5 1688 public function get_defaultsetting() {
cd3acbf2 1689 $adminroot = admin_get_root(false, false);
1690 if (!empty($adminroot->custom_defaults)) {
1691 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1692 if (isset($adminroot->custom_defaults[$plugin])) {
875e5f07 1693 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
cd3acbf2 1694 return $adminroot->custom_defaults[$plugin][$this->name];
1695 }
1696 }
1697 }
8e5da17a 1698 return $this->defaultsetting;
1699 }
1700
220a90c5 1701 /**
1702 * Store new setting
db26acd4 1703 *
1704 * @param mixed $data string or array, must not be NULL
1705 * @return string empty string if ok, string error message otherwise
220a90c5 1706 */
301bf0b2 1707 public abstract function write_setting($data);
eef868d1 1708
220a90c5 1709 /**
1710 * Return part of form with setting
db26acd4 1711 * This function should always be overwritten
1712 *
1713 * @param mixed $data array or string depending on setting
1714 * @param string $query
220a90c5 1715 * @return string
1716 */
73fa96d5 1717 public function output_html($data, $query='') {
9baf6825 1718 // should be overridden
220a90c5 1719 return;
1720 }
1721
1722 /**
db26acd4 1723 * Function called if setting updated - cleanup, cache reset, etc.
1724 * @param string $functionname Sets the function name
3e7069e7 1725 * @return void
220a90c5 1726 */
73fa96d5 1727 public function set_updatedcallback($functionname) {
220a90c5 1728 $this->updatedcallback = $functionname;
1729 }
1730
6ddc9278
PS
1731 /**
1732 * Execute postupdatecallback if necessary.
1733 * @param mixed $original original value before write_setting()
1734 * @return bool true if changed, false if not.
1735 */
1736 public function post_write_settings($original) {
1737 // Comparison must work for arrays too.
1738 if (serialize($original) === serialize($this->get_setting())) {
1739 return false;
1740 }
1741
1742 $callbackfunction = $this->updatedcallback;
1743 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1744 $callbackfunction($this->get_full_name());
1745 }
1746 return true;
1747 }
1748
220a90c5 1749 /**
1750 * Is setting related to query text - used when searching
1751 * @param string $query
1752 * @return bool
1753 */
73fa96d5 1754 public function is_related($query) {
220a90c5 1755 if (strpos(strtolower($this->name), $query) !== false) {
1756 return true;
1757 }
2f1e464a 1758 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
220a90c5 1759 return true;
1760 }
2f1e464a 1761 if (strpos(core_text::strtolower($this->description), $query) !== false) {
220a90c5 1762 return true;
1763 }
587c7040 1764 $current = $this->get_setting();
1765 if (!is_null($current)) {
1766 if (is_string($current)) {
2f1e464a 1767 if (strpos(core_text::strtolower($current), $query) !== false) {
587c7040 1768 return true;
1769 }
1770 }
1771 }
1772 $default = $this->get_defaultsetting();
1773 if (!is_null($default)) {
1774 if (is_string($default)) {
2f1e464a 1775 if (strpos(core_text::strtolower($default), $query) !== false) {
587c7040 1776 return true;
1777 }
1778 }
1779 }
220a90c5 1780 return false;
6e4dc10f 1781 }
220a90c5 1782}
eef868d1 1783
3c88a678
DW
1784/**
1785 * An additional option that can be applied to an admin setting.
1786 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1787 *
1788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1789 */
1790class admin_setting_flag {
1791 /** @var bool Flag to indicate if this option can be toggled for this setting */
1792 private $enabled = false;
1793 /** @var bool Flag to indicate if this option defaults to true or false */
1794 private $default = false;
1795 /** @var string Short string used to create setting name - e.g. 'adv' */
1796 private $shortname = '';
1797 /** @var string String used as the label for this flag */
1798 private $displayname = '';
1799 /** @const Checkbox for this flag is displayed in admin page */
1800 const ENABLED = true;
1801 /** @const Checkbox for this flag is not displayed in admin page */
1802 const DISABLED = false;
1803
1804 /**
1805 * Constructor
1806 *
1807 * @param bool $enabled Can this option can be toggled.
1808 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1809 * @param bool $default The default checked state for this setting option.
1810 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1811 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1812 */
1813 public function __construct($enabled, $default, $shortname, $displayname) {
1814 $this->shortname = $shortname;
1815 $this->displayname = $displayname;
1816 $this->set_options($enabled, $default);
1817 }
1818
1819 /**
1820 * Update the values of this setting options class
1821 *
1822 * @param bool $enabled Can this option can be toggled.
1823 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1824 * @param bool $default The default checked state for this setting option.
1825 */
1826 public function set_options($enabled, $default) {
1827 $this->enabled = $enabled;
1828 $this->default = $default;
1829 }
1830
1831 /**
1832 * Should this option appear in the interface and be toggleable?
1833 *
1834 * @return bool Is it enabled?
1835 */
1836 public function is_enabled() {
1837 return $this->enabled;
1838 }
1839
1840 /**
1841 * Should this option be checked by default?
1842 *
1843 * @return bool Is it on by default?
1844 */
1845 public function get_default() {
1846 return $this->default;
1847 }
1848
1849 /**
1850 * Return the short name for this flag. e.g. 'adv' or 'locked'
1851 *
1852 * @return string
1853 */
1854 public function get_shortname() {
1855 return $this->shortname;
1856 }
1857
1858 /**
1859 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1860 *
1861 * @return string
1862 */
1863 public function get_displayname() {
1864 return $this->displayname;
1865 }
1866
1867 /**
1868 * Save the submitted data for this flag - or set it to the default if $data is null.
1869 *
1870 * @param admin_setting $setting - The admin setting for this flag
7e815a6e 1871 * @param array $data - The data submitted from the form or null to set the default value for new installs.
3c88a678
DW
1872 * @return bool
1873 */
1874 public function write_setting_flag(admin_setting $setting, $data) {
1875 $result = true;
1876 if ($this->is_enabled()) {
7e815a6e
DW
1877 if (!isset($data)) {
1878 $value = $this->get_default();
1879 } else {
1880 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
1881 }
3c88a678
DW
1882 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
1883 }
1884
1885 return $result;
1886
1887 }
1888
1889 /**
1890 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
1891 *
1892 * @param admin_setting $setting - The admin setting for this flag
1893 * @return string - The html for the checkbox.
1894 */
1895 public function output_setting_flag(admin_setting $setting) {
1896 $value = $setting->get_setting_flag_value($this);
1897 $output = ' <input type="checkbox" class="form-checkbox" ' .
1898 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
1899 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
1900 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
1901 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
1902 $this->get_displayname() .
1903 ' </label> ';
1904 return $output;
1905 }
1906}
1907
3e7069e7 1908
220a90c5 1909/**
1910 * No setting - just heading and text.
db26acd4 1911 *
1912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1913 */
1914class admin_setting_heading extends admin_setting {
3e7069e7
PS
1915
1916 /**
1917 * not a setting, just text
1918 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1919 * @param string $heading heading
1920 * @param string $information text in box
1921 */
73fa96d5 1922 public function __construct($name, $heading, $information) {
427649bf 1923 $this->nosave = true;
73fa96d5 1924 parent::__construct($name, $heading, $information, '');
220a90c5 1925 }
1926
db26acd4 1927 /**
1928 * Always returns true
1929 * @return bool Always returns true
1930 */
73fa96d5 1931 public function get_setting() {
220a90c5 1932 return true;
1933 }
1934
db26acd4 1935 /**
1936 * Always returns true
1937 * @return bool Always returns true
1938 */
73fa96d5 1939 public function get_defaultsetting() {
220a90c5 1940 return true;
1941 }
1942
db26acd4 1943 /**
1944 * Never write settings
1945 * @return string Always returns an empty string
1946 */
73fa96d5 1947 public function write_setting($data) {
9baf6825 1948 // do not write any setting
220a90c5 1949 return '';
1950 }
0c079f19 1951
db26acd4 1952 /**
1953 * Returns an HTML string
1954 * @return string Returns an HTML string
1955 */
73fa96d5 1956 public function output_html($data, $query='') {
3c159385 1957 global $OUTPUT;
220a90c5 1958 $return = '';
1959 if ($this->visiblename != '') {
206dd861 1960 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
220a90c5 1961 }
1962 if ($this->description != '') {
8dbe233a 1963 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
220a90c5 1964 }
1965 return $return;
1966 }
1967}
6e4dc10f 1968
3e7069e7 1969
220a90c5 1970/**
1971 * The most flexibly setting, user is typing text
db26acd4 1972 *
1973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1974 */
6e4dc10f 1975class admin_setting_configtext extends admin_setting {
1976
3e7069e7 1977 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
73fa96d5 1978 public $paramtype;
0c079f19 1979 /** @var int default field size */
73fa96d5 1980 public $size;
6e4dc10f 1981
220a90c5 1982 /**
875e5f07 1983 * Config text constructor
db26acd4 1984 *
1a41e806 1985 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 1986 * @param string $visiblename localised
1987 * @param string $description long localised info
1988 * @param string $defaultsetting
1989 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
f7633b0f 1990 * @param int $size default field size
220a90c5 1991 */
73fa96d5 1992 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
6e4dc10f 1993 $this->paramtype = $paramtype;
f7633b0f 1994 if (!is_null($size)) {
1995 $this->size = $size;
1996 } else {
40ea93a4 1997 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
f7633b0f 1998 }
73fa96d5 1999 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 2000 }
2001
db26acd4 2002 /**
2003 * Return the setting
2004 *
875e5f07 2005 * @return mixed returns config if successful else null
db26acd4 2006 */
73fa96d5 2007 public function get_setting() {
220a90c5 2008 return $this->config_read($this->name);
6e4dc10f 2009 }
eef868d1 2010
73fa96d5 2011 public function write_setting($data) {
8cad6cca 2012 if ($this->paramtype === PARAM_INT and $data === '') {
9baf6825 2013 // do not complain if '' used instead of 0
8cad6cca 2014 $data = 0;
2015 }
220a90c5 2016 // $data is a string
c5d2d0dd 2017 $validated = $this->validate($data);
e33fbf87 2018 if ($validated !== true) {
2019 return $validated;
c235598d 2020 }
220a90c5 2021 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2022 }
2023
e33fbf87 2024 /**
2025 * Validate data before storage
2026 * @param string data
2027 * @return mixed true if ok string if error found
2028 */
73fa96d5 2029 public function validate($data) {
58aaa8e9 2030 // allow paramtype to be a custom regex if it is the form of /pattern/
2031 if (preg_match('#^/.*/$#', $this->paramtype)) {
e33fbf87 2032 if (preg_match($this->paramtype, $data)) {
2033 return true;
2034 } else {
2035 return get_string('validateerror', 'admin');
2036 }
2037
9e24fbd1 2038 } else if ($this->paramtype === PARAM_RAW) {
4ea56b3f 2039 return true;
9baf6825 2040
4ea56b3f 2041 } else {
2042 $cleaned = clean_param($data, $this->paramtype);
40ea93a4 2043 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
4ea56b3f 2044 return true;
e33fbf87 2045 } else {
4ea56b3f 2046 return get_string('validateerror', 'admin');
e33fbf87 2047 }
4ea56b3f 2048 }
c235598d 2049 }
2050
db26acd4 2051 /**
2052 * Return an XHTML string for the setting
2053 * @return string Returns an XHTML string
2054 */
73fa96d5 2055 public function output_html($data, $query='') {
220a90c5 2056 $default = $this->get_defaultsetting();
2057
220a90c5 2058 return format_admin_setting($this, $this->visiblename,
9baf6825 2059 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2060 $this->description, true, '', $default, $query);
6e4dc10f 2061 }
6e4dc10f 2062}
2063
3e7069e7 2064
220a90c5 2065/**
2066 * General text area without html editor.
db26acd4 2067 *
2068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2069 */
2070class admin_setting_configtextarea extends admin_setting_configtext {
4fe2250a 2071 private $rows;
2072 private $cols;
eba8cd63 2073
db26acd4 2074 /**
2075 * @param string $name
2076 * @param string $visiblename
2077 * @param string $description
2078 * @param mixed $defaultsetting string or array
2079 * @param mixed $paramtype
2080 * @param string $cols The number of columns to make the editor
2081 * @param string $rows The number of rows to make the editor
2082 */
73fa96d5 2083 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
220a90c5 2084 $this->rows = $rows;
2085 $this->cols = $cols;
73fa96d5 2086 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
eba8cd63 2087 }
3e7069e7 2088
db26acd4 2089 /**
2090 * Returns an XHTML string for the editor
2091 *
2092 * @param string $data
2093 * @param string $query
2094 * @return string XHTML string for the editor
2095 */
73fa96d5 2096 public function output_html($data, $query='') {
220a90c5 2097 $default = $this->get_defaultsetting();
2098
587c7040 2099 $defaultinfo = $default;
2100 if (!is_null($default) and $default !== '') {
2101 $defaultinfo = "\n".$default;
c5d2d0dd 2102 }
220a90c5 2103
2104 return format_admin_setting($this, $this->visiblename,
0ac97084 2105 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
9baf6825 2106 $this->description, true, '', $defaultinfo, $query);
4fe2250a 2107 }
2108}
2109
3e7069e7 2110
4fe2250a 2111/**
2112 * General text area with html editor.
2113 */
2114class admin_setting_confightmleditor extends admin_setting_configtext {
2115 private $rows;
2116 private $cols;
0c079f19 2117
4fe2250a 2118 /**
2119 * @param string $name
2120 * @param string $visiblename
2121 * @param string $description
2122 * @param mixed $defaultsetting string or array
2123 * @param mixed $paramtype
2124 */
2125 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2126 $this->rows = $rows;
2127 $this->cols = $cols;
2128 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
ff5fe311 2129 editors_head_setup();
4fe2250a 2130 }
3e7069e7 2131
4fe2250a 2132 /**
2133 * Returns an XHTML string for the editor
2134 *
2135 * @param string $data
2136 * @param string $query
2137 * @return string XHTML string for the editor
2138 */
2139 public function output_html($data, $query='') {
2140 $default = $this->get_defaultsetting();
2141
2142 $defaultinfo = $default;
2143 if (!is_null($default) and $default !== '') {
2144 $defaultinfo = "\n".$default;
2145 }
2146
20e5da7d 2147 $editor = editors_get_preferred_editor(FORMAT_HTML);
69429650 2148 $editor->use_editor($this->get_id(), array('noclean'=>true));
4fe2250a 2149
2150 return format_admin_setting($this, $this->visiblename,
0ac97084 2151 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
9baf6825 2152 $this->description, true, '', $defaultinfo, $query);
220a90c5 2153 }
2154}
2155
3e7069e7 2156
220a90c5 2157/**
2158 * Password field, allows unmasking of password
db26acd4 2159 *
2160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2161 */
2162class admin_setting_configpasswordunmask extends admin_setting_configtext {
3e7069e7
PS
2163 /**
2164 * Constructor
2165 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2166 * @param string $visiblename localised
2167 * @param string $description long localised info
2168 * @param string $defaultsetting default password
2169 */
73fa96d5 2170 public function __construct($name, $visiblename, $description, $defaultsetting) {
2171 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
220a90c5 2172 }
0c079f19 2173
914499a3
PS
2174 /**
2175 * Log config changes if necessary.
2176 * @param string $name
2177 * @param string $oldvalue
2178 * @param string $value
2179 */
2180 protected function add_to_config_log($name, $oldvalue, $value) {
2181 if ($value !== '') {
2182 $value = '********';
2183 }
2184 if ($oldvalue !== '' and $oldvalue !== null) {
2185 $oldvalue = '********';
2186 }
2187 parent::add_to_config_log($name, $oldvalue, $value);
2188 }
2189
db26acd4 2190 /**
2191 * Returns XHTML for the field
2192 * Writes Javascript into the HTML below right before the last div
2193 *
2194 * @todo Make javascript available through newer methods if possible
2195 * @param string $data Value for the field
2196 * @param string $query Passed as final argument for format_admin_setting
2197 * @return string XHTML field
2198 */
73fa96d5 2199 public function output_html($data, $query='') {
220a90c5 2200 $id = $this->get_id();
2201 $unmask = get_string('unmaskpassword', 'form');
2202 $unmaskjs = '<script type="text/javascript">
eba8cd63 2203//<![CDATA[
633239f6 2204var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2205
2206document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2207
2208var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2209
2210var unmaskchb = document.createElement("input");
2211unmaskchb.setAttribute("type", "checkbox");
2212unmaskchb.setAttribute("id", "'.$id.'unmask");
2213unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2214unmaskdiv.appendChild(unmaskchb);
2215
2216var unmasklbl = document.createElement("label");
2217unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2218if (is_ie) {
2219 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2220} else {
2221 unmasklbl.setAttribute("for", "'.$id.'unmask");
2222}
2223unmaskdiv.appendChild(unmasklbl);
2224
2225if (is_ie) {
2226 // ugly hack to work around the famous onchange IE bug
2227 unmaskchb.onclick = function() {this.blur();};
2228 unmaskdiv.onclick = function() {this.blur();};
2229}
eba8cd63 2230//]]>
2231</script>';
220a90c5 2232 return format_admin_setting($this, $this->visiblename,
9baf6825 2233 '<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>',
2234 $this->description, true, '', NULL, $query);
220a90c5 2235 }
2236}
2237
c7cd8d9c
DW
2238/**
2239 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2240 * Note: Only advanced makes sense right now - locked does not.
2241 *
2242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2243 */
2244class admin_setting_configempty extends admin_setting_configtext {
2245
2246 /**
2247 * @param string $name
2248 * @param string $visiblename
2249 * @param string $description
2250 */
2251 public function __construct($name, $visiblename, $description) {
2252 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2253 }
2254
2255 /**
2256 * Returns an XHTML string for the hidden field
2257 *
2258 * @param string $data
2259 * @param string $query
2260 * @return string XHTML string for the editor
2261 */
2262 public function output_html($data, $query='') {
2263 return format_admin_setting($this,
2264 $this->visiblename,
2265 '<div class="form-empty" >' .
2266 '<input type="hidden"' .
2267 ' id="'. $this->get_id() .'"' .
2268 ' name="'. $this->get_full_name() .'"' .
2269 ' value=""/></div>',
2270 $this->description,
2271 true,
2272 '',
2273 get_string('none'),
2274 $query);
2275 }
2276}
2277
3e7069e7 2278
220a90c5 2279/**
e9c0fa35 2280 * Path to directory
db26acd4 2281 *
2282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2283 */
e9c0fa35 2284class admin_setting_configfile extends admin_setting_configtext {
3e7069e7
PS
2285 /**
2286 * Constructor
2287 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2288 * @param string $visiblename localised
2289 * @param string $description long localised info
2290 * @param string $defaultdirectory default directory location
2291 */
73fa96d5 2292 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2293 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
220a90c5 2294 }
2295
db26acd4 2296 /**
2297 * Returns XHTML for the field
0c079f19 2298 *
db26acd4 2299 * Returns XHTML for the field and also checks whether the file
2300 * specified in $data exists using file_exists()
2301 *
2302 * @param string $data File name and path to use in value attr
2303 * @param string $query
2304 * @return string XHTML field
2305 */
73fa96d5 2306 public function output_html($data, $query='') {
220a90c5 2307 $default = $this->get_defaultsetting();
2308
220a90c5 2309 if ($data) {
e9c0fa35 2310 if (file_exists($data)) {
220a90c5 2311 $executable = '<span class="pathok">&#x2714;</span>';
2312 } else {
2313 $executable = '<span class="patherror">&#x2718;</span>';
2314 }
2315 } else {
2316 $executable = '';
2317 }
2318
2319 return format_admin_setting($this, $this->visiblename,
9baf6825 2320 '<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>',
2321 $this->description, true, '', $default, $query);
eba8cd63 2322 }
9a2b5e0b
HD
2323 /**
2324 * checks if execpatch has been disabled in config.php
2325 */
2326 public function write_setting($data) {
2327 global $CFG;
2328 if (!empty($CFG->preventexecpath)) {
2329 return '';
2330 }
2331 return parent::write_setting($data);
2332 }
220a90c5 2333}
2334
3e7069e7 2335
220a90c5 2336/**
e9c0fa35 2337 * Path to executable file
db26acd4 2338 *
2339 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2340 */
e9c0fa35 2341class admin_setting_configexecutable extends admin_setting_configfile {
2342
3e7069e7
PS
2343 /**
2344 * Returns an XHTML field
2345 *
2346 * @param string $data This is the value for the field
2347 * @param string $query
2348 * @return string XHTML field
2349 */
73fa96d5 2350 public function output_html($data, $query='') {
9a2b5e0b 2351 global $CFG;
e9c0fa35 2352 $default = $this->get_defaultsetting();
2353
2354 if ($data) {
2355 if (file_exists($data) and is_executable($data)) {
2356 $executable = '<span class="pathok">&#x2714;</span>';
2357 } else {
2358 $executable = '<span class="patherror">&#x2718;</span>';
2359 }
2360 } else {
2361 $executable = '';
2362 }
9a2b5e0b
HD
2363 if (!empty($CFG->preventexecpath)) {
2364 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2365 }
e9c0fa35 2366
2367 return format_admin_setting($this, $this->visiblename,
9baf6825 2368 '<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>',
2369 $this->description, true, '', $default, $query);
220a90c5 2370 }
e9c0fa35 2371}
220a90c5 2372
3e7069e7 2373
e9c0fa35 2374/**
2375 * Path to directory
db26acd4 2376 *
2377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e9c0fa35 2378 */
2379class admin_setting_configdirectory extends admin_setting_configfile {
db26acd4 2380
3e7069e7
PS
2381 /**
2382 * Returns an XHTML field
2383 *
2384 * @param string $data This is the value for the field
2385 * @param string $query
2386 * @return string XHTML
2387 */
73fa96d5 2388 public function output_html($data, $query='') {
220a90c5 2389 $default = $this->get_defaultsetting();
2390
220a90c5 2391 if ($data) {
2392 if (file_exists($data) and is_dir($data)) {
2393 $executable = '<span class="pathok">&#x2714;</span>';
2394 } else {
2395 $executable = '<span class="patherror">&#x2718;</span>';
2396 }
2397 } else {
2398 $executable = '';
2399 }
9ba38673 2400
220a90c5 2401 return format_admin_setting($this, $this->visiblename,
9baf6825 2402 '<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>',
2403 $this->description, true, '', $default, $query);
220a90c5 2404 }
eba8cd63 2405}
2406
3e7069e7 2407
220a90c5 2408/**
2409 * Checkbox
db26acd4 2410 *
2411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2412 */
6e4dc10f 2413class admin_setting_configcheckbox extends admin_setting {
3e7069e7 2414 /** @var string Value used when checked */
73fa96d5 2415 public $yes;
0c079f19 2416 /** @var string Value used when not checked */
73fa96d5 2417 public $no;
6e4dc10f 2418
220a90c5 2419 /**
2420 * Constructor
1a41e806 2421 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2422 * @param string $visiblename localised
2423 * @param string $description long localised info
2424 * @param string $defaultsetting
2425 * @param string $yes value used when checked
2426 * @param string $no value used when not checked
2427 */
73fa96d5 2428 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2429 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2430 $this->yes = (string)$yes;
2431 $this->no = (string)$no;
6e4dc10f 2432 }
2433
db26acd4 2434 /**
2435 * Retrieves the current setting using the objects name
2436 *
2437 * @return string
2438 */
73fa96d5 2439 public function get_setting() {
220a90c5 2440 return $this->config_read($this->name);
6e4dc10f 2441 }
eef868d1 2442
db26acd4 2443 /**
2444 * Sets the value for the setting
2445 *
2446 * Sets the value for the setting to either the yes or no values
2447 * of the object by comparing $data to yes
2448 *
2449 * @param mixed $data Gets converted to str for comparison against yes value
2450 * @return string empty string or error
2451 */
73fa96d5 2452 public function write_setting($data) {
220a90c5 2453 if ((string)$data === $this->yes) { // convert to strings before comparison
2454 $data = $this->yes;
6e4dc10f 2455 } else {
220a90c5 2456 $data = $this->no;
6e4dc10f 2457 }
220a90c5 2458 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2459 }
2460
db26acd4 2461 /**
2462 * Returns an XHTML checkbox field
2463 *
2464 * @param string $data If $data matches yes then checkbox is checked
2465 * @param string $query
2466 * @return string XHTML field
2467 */
73fa96d5 2468 public function output_html($data, $query='') {
220a90c5 2469 $default = $this->get_defaultsetting();
2470
2471 if (!is_null($default)) {
2472 if ((string)$default === $this->yes) {
587c7040 2473 $defaultinfo = get_string('checkboxyes', 'admin');
220a90c5 2474 } else {
587c7040 2475 $defaultinfo = get_string('checkboxno', 'admin');
220a90c5 2476 }
c8218a42 2477 } else {
587c7040 2478 $defaultinfo = NULL;
c8218a42 2479 }
220a90c5 2480
2481 if ((string)$data === $this->yes) { // convert to strings before comparison
2482 $checked = 'checked="checked"';
2483 } else {
2484 $checked = '';
2485 }
2486
2487 return format_admin_setting($this, $this->visiblename,
9baf6825 2488 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2489 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2490 $this->description, true, '', $defaultinfo, $query);
6e4dc10f 2491 }
6e4dc10f 2492}
2493
3e7069e7 2494
220a90c5 2495/**
2496 * Multiple checkboxes, each represents different value, stored in csv format
db26acd4 2497 *
2498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2499 */
2500class admin_setting_configmulticheckbox extends admin_setting {
3e7069e7 2501 /** @var array Array of choices value=>label */
73fa96d5 2502 public $choices;
eef868d1 2503
220a90c5 2504 /**
db26acd4 2505 * Constructor: uses parent::__construct
2506 *
1a41e806 2507 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2508 * @param string $visiblename localised
2509 * @param string $description long localised info
2510 * @param array $defaultsetting array of selected
2511 * @param array $choices array of $value=>$label for each checkbox
2512 */
73fa96d5 2513 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6e4dc10f 2514 $this->choices = $choices;
73fa96d5 2515 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 2516 }
2517
0a784551 2518 /**
73fa96d5 2519 * This public function may be used in ancestors for lazy loading of choices
db26acd4 2520 *
2521 * @todo Check if this function is still required content commented out only returns true
2522 * @return bool true if loaded, false if error
0a784551 2523 */
73fa96d5 2524 public function load_choices() {
0a784551 2525 /*
220a90c5 2526 if (is_array($this->choices)) {
2527 return true;
0a784551 2528 }
2529 .... load choices here
2530 */
220a90c5 2531 return true;
2532 }
2533
2534 /**
2535 * Is setting related to query text - used when searching
db26acd4 2536 *
220a90c5 2537 * @param string $query
db26acd4 2538 * @return bool true on related, false on not or failure
220a90c5 2539 */
73fa96d5 2540 public function is_related($query) {
220a90c5 2541 if (!$this->load_choices() or empty($this->choices)) {
2542 return false;
2543 }
2544 if (parent::is_related($query)) {
2545 return true;
2546 }
2547
220a90c5 2548 foreach ($this->choices as $desc) {
2f1e464a 2549 if (strpos(core_text::strtolower($desc), $query) !== false) {
220a90c5 2550 return true;
2551 }
2552 }
2553 return false;
0a784551 2554 }
2555
db26acd4 2556 /**
2557 * Returns the current setting if it is set
2558 *
2559 * @return mixed null if null, else an array
2560 */
73fa96d5 2561 public function get_setting() {
220a90c5 2562 $result = $this->config_read($this->name);
10f19c49 2563
220a90c5 2564 if (is_null($result)) {
2565 return NULL;
2566 }
2567 if ($result === '') {
2568 return array();
2569 }
10f19c49 2570 $enabled = explode(',', $result);
2571 $setting = array();
2572 foreach ($enabled as $option) {
2573 $setting[$option] = 1;
2574 }
2575 return $setting;
6e4dc10f 2576 }
eef868d1 2577
db26acd4 2578 /**
2579 * Saves the setting(s) provided in $data
2580 *
2581 * @param array $data An array of data, if not array returns empty str
2582 * @return mixed empty string on useless data or bool true=success, false=failed
2583 */
73fa96d5 2584 public function write_setting($data) {
220a90c5 2585 if (!is_array($data)) {
2586 return ''; // ignore it
2587 }
2588 if (!$this->load_choices() or empty($this->choices)) {
2589 return '';
2590 }
2591 unset($data['xxxxx']);
2592 $result = array();
2593 foreach ($data as $key => $value) {
2594 if ($value and array_key_exists($key, $this->choices)) {
2595 $result[] = $key;
2596 }
2597 }
2598 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
6e4dc10f 2599 }
0c079f19 2600
db26acd4 2601 /**
2602 * Returns XHTML field(s) as required by choices
2603 *
2604 * Relies on data being an array should data ever be another valid vartype with
2605 * acceptable value this may cause a warning/error
2606 * if (!is_array($data)) would fix the problem
2607 *
2608 * @todo Add vartype handling to ensure $data is an array
2609 *
2610 * @param array $data An array of checked values
2611 * @param string $query
2612 * @return string XHTML field
2613 */
73fa96d5 2614 public function output_html($data, $query='') {
220a90c5 2615 if (!$this->load_choices() or empty($this->choices)) {
2616 return '';
2617 }
2618 $default = $this->get_defaultsetting();
2619 if (is_null($default)) {
2620 $default = array();
2621 }
2622 if (is_null($data)) {
775f811a 2623 $data = array();
220a90c5 2624 }
220a90c5 2625 $options = array();
2626 $defaults = array();
10f19c49 2627 foreach ($this->choices as $key=>$description) {
2628 if (!empty($data[$key])) {
220a90c5 2629 $checked = 'checked="checked"';
2630 } else {
2631 $checked = '';
2632 }
10f19c49 2633 if (!empty($default[$key])) {
220a90c5 2634 $defaults[] = $description;
2635 }
2636
2637 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
9baf6825 2638 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
220a90c5 2639 }
2640
587c7040 2641 if (is_null($default)) {
2642 $defaultinfo = NULL;
2643 } else if (!empty($defaults)) {
9baf6825 2644 $defaultinfo = implode(', ', $defaults);
2645 } else {
2646 $defaultinfo = get_string('none');
2647 }
220a90c5 2648
2649 $return = '<div class="form-multicheckbox">';
2650 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2651 if ($options) {
2652 $return .= '<ul>';
2653 foreach ($options as $option) {
2654 $return .= '<li>'.$option.'</li>';
2655 }
2656 $return .= '</ul>';
6e4dc10f 2657 }
587c7040 2658 $return .= '</div>';
6153cf58 2659
587c7040 2660 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
c5d2d0dd 2661
6e4dc10f 2662 }
6e4dc10f 2663}
2664
3e7069e7 2665
220a90c5 2666/**
2667 * Multiple checkboxes 2, value stored as string 00101011
db26acd4 2668 *
2669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2670 */
2671class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
db26acd4 2672
3e7069e7
PS
2673 /**
2674 * Returns the setting if set
2675 *
2676 * @return mixed null if not set, else an array of set settings
2677 */
73fa96d5 2678 public function get_setting() {
220a90c5 2679 $result = $this->config_read($this->name);
2680 if (is_null($result)) {
2681 return NULL;
2682 }
2683 if (!$this->load_choices()) {
2684 return NULL;
2685 }
2686 $result = str_pad($result, count($this->choices), '0');
2687 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2688 $setting = array();
2689 foreach ($this->choices as $key=>$unused) {
2690 $value = array_shift($result);
2691 if ($value) {
10f19c49 2692 $setting[$key] = 1;
220a90c5 2693 }
2694 }
2695 return $setting;
2696 }
6e4dc10f 2697
db26acd4 2698 /**
2699 * Save setting(s) provided in $data param
2700 *
2701 * @param array $data An array of settings to save
2702 * @return mixed empty string for bad data or bool true=>success, false=>error
2703 */
73fa96d5 2704 public function write_setting($data) {
220a90c5 2705 if (!is_array($data)) {
2706 return ''; // ignore it
2707 }
2708 if (!$this->load_choices() or empty($this->choices)) {
2709 return '';
2710 }
2711 $result = '';
2712 foreach ($this->choices as $key=>$unused) {
2713 if (!empty($data[$key])) {
2714 $result .= '1';
2715 } else {
2716 $result .= '0';
2717 }
2718 }
2719 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2720 }
2721}
2722
3e7069e7 2723
220a90c5 2724/**
2725 * Select one value from list
db26acd4 2726 *
2727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2728 */
2729class admin_setting_configselect extends admin_setting {
3e7069e7 2730 /** @var array Array of choices value=>label */
73fa96d5 2731 public $choices;
6e4dc10f 2732
220a90c5 2733 /**
2734 * Constructor
1a41e806 2735 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2736 * @param string $visiblename localised
2737 * @param string $description long localised info
eab8ed9f 2738 * @param string|int $defaultsetting
220a90c5 2739 * @param array $choices array of $value=>$label for each selection
2740 */
73fa96d5 2741 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
220a90c5 2742 $this->choices = $choices;
73fa96d5 2743 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2744 }
2745
2746 /**
2747 * This function may be used in ancestors for lazy loading of choices
db26acd4 2748 *
0c079f19 2749 * Override this method if loading of choices is expensive, such
2750 * as when it requires multiple db requests.
2751 *
db26acd4 2752 * @return bool true if loaded, false if error
220a90c5 2753 */
73fa96d5 2754 public function load_choices() {
220a90c5 2755 /*
2756 if (is_array($this->choices)) {
2757 return true;
6e4dc10f 2758 }
220a90c5 2759 .... load choices here
2760 */
2761 return true;
6e4dc10f 2762 }
2763
db26acd4 2764 /**
2765 * Check if this is $query is related to a choice
2766 *
2767 * @param string $query
2768 * @return bool true if related, false if not
2769 */
73fa96d5 2770 public function is_related($query) {
407d8134 2771 if (parent::is_related($query)) {
2772 return true;
2773 }
2774 if (!$this->load_choices()) {
2775 return false;
2776 }
407d8134 2777 foreach ($this->choices as $key=>$value) {
2f1e464a 2778 if (strpos(core_text::strtolower($key), $query) !== false) {
407d8134 2779 return true;
2780 }
2f1e464a 2781 if (strpos(core_text::strtolower($value), $query) !== false) {
407d8134 2782 return true;
2783 }
c5d2d0dd 2784 }
407d8134 2785 return false;
2786 }
2787
db26acd4 2788 /**
2789 * Return the setting
0c079f19 2790 *
875e5f07 2791 * @return mixed returns config if successful else null
db26acd4 2792 */
73fa96d5 2793 public function get_setting() {
220a90c5 2794 return $this->config_read($this->name);
6e4dc10f 2795 }
eef868d1 2796
db26acd4 2797 /**
2798 * Save a setting
2799 *
2800 * @param string $data
2801 * @return string empty of error string
2802 */
73fa96d5 2803 public function write_setting($data) {
220a90c5 2804 if (!$this->load_choices() or empty($this->choices)) {
2805 return '';
2806 }
2807 if (!array_key_exists($data, $this->choices)) {
2808 return ''; // ignore it
2809 }
eef868d1 2810
220a90c5 2811 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2812 }
eef868d1 2813
e2249afe 2814 /**
db26acd4 2815 * Returns XHTML select field
2816 *
2817 * Ensure the options are loaded, and generate the XHTML for the select
e2249afe 2818 * element and any warning message. Separating this out from output_html
2819 * makes it easier to subclass this class.
2820 *
2821 * @param string $data the option to show as selected.
2822 * @param string $current the currently selected option in the database, null if none.
2823 * @param string $default the default selected option.
2824 * @return array the HTML for the select element, and a warning message.
2825 */
73fa96d5 2826 public function output_select_html($data, $current, $default, $extraname = '') {
220a90c5 2827 if (!$this->load_choices() or empty($this->choices)) {
e2249afe 2828 return array('', '');
6e4dc10f 2829 }
220a90c5 2830
9c305ba1 2831 $warning = '';
2832 if (is_null($current)) {
9baf6825 2833 // first run
9c305ba1 2834 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2835 // no warning
9baf6825 2836 } else if (!array_key_exists($current, $this->choices)) {
2837 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2838 if (!is_null($default) and $data == $current) {
2839 $data = $default; // use default instead of first value when showing the form
2840 }
2841 }
9c305ba1 2842
e2249afe 2843 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
6e4dc10f 2844 foreach ($this->choices as $key => $value) {
9baf6825 2845 // the string cast is needed because key may be integer - 0 is equal to most strings!
e2249afe 2846 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
eef868d1 2847 }
e2249afe 2848 $selecthtml .= '</select>';
2849 return array($selecthtml, $warning);
2850 }
2851
db26acd4 2852 /**
2853 * Returns XHTML select field and wrapping div(s)
2854 *
2855 * @see output_select_html()
0c079f19 2856 *
db26acd4 2857 * @param string $data the option to show as selected
2858 * @param string $query
2859 * @return string XHTML field and wrapping div
2860 */
73fa96d5 2861 public function output_html($data, $query='') {
e2249afe 2862 $default = $this->get_defaultsetting();
2863 $current = $this->get_setting();
2864
2865 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2866 if (!$selecthtml) {
2867 return '';
2868 }
2869
2870 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2871 $defaultinfo = $this->choices[$default];
2872 } else {
2873 $defaultinfo = NULL;
2874 }
2875
2876 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
220a90c5 2877
587c7040 2878 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
6e4dc10f 2879 }
6e4dc10f 2880}
2881
3e7069e7 2882
220a90c5 2883/**
2884 * Select multiple items from list
db26acd4 2885 *
2886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2887 */
6e4dc10f 2888class admin_setting_configmultiselect extends admin_setting_configselect {
3e7069e7
PS
2889 /**
2890 * Constructor
2891 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2892 * @param string $visiblename localised
2893 * @param string $description long localised info
2894 * @param array $defaultsetting array of selected items
2895 * @param array $choices array of $value=>$label for each list item
2896 */
73fa96d5 2897 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2898 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
6e4dc10f 2899 }
2900
db26acd4 2901 /**
2902 * Returns the select setting(s)
2903 *
2904 * @return mixed null or array. Null if no settings else array of setting(s)
2905 */
73fa96d5 2906 public function get_setting() {
220a90c5 2907 $result = $this->config_read($this->name);
2908 if (is_null($result)) {
d7933a55 2909 return NULL;
2910 }
220a90c5 2911 if ($result === '') {
2912 return array();
2913 }
2914 return explode(',', $result);
6e4dc10f 2915 }
eef868d1 2916
db26acd4 2917 /**
2918 * Saves setting(s) provided through $data
2919 *
2920 * Potential bug in the works should anyone call with this function
2921 * using a vartype that is not an array
2922 *
db26acd4 2923 * @param array $data
2924 */
73fa96d5 2925 public function write_setting($data) {
220a90c5 2926 if (!is_array($data)) {
2927 return ''; //ignore it
2928 }
2929 if (!$this->load_choices() or empty($this->choices)) {
2930 return '';
2931 }
2932
a7ad48fd 2933 unset($data['xxxxx']);
2934
220a90c5 2935 $save = array();
2936 foreach ($data as $value) {
2937 if (!array_key_exists($value, $this->choices)) {
2938 continue; // ignore it
2939 }
2940 $save[] = $value;
2941 }
2942
2943 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2944 }
2945
2946 /**
2947 * Is setting related to query text - used when searching
db26acd4 2948 *
220a90c5 2949 * @param string $query
db26acd4 2950 * @return bool true if related, false if not
220a90c5 2951 */
73fa96d5 2952 public function is_related($query) {
220a90c5 2953 if (!$this->load_choices() or empty($this->choices)) {
2954 return false;
2955 }
2956 if (parent::is_related($query)) {
2957 return true;
2958 }
2959
220a90c5 2960 foreach ($this->choices as $desc) {
2f1e464a 2961 if (strpos(core_text::strtolower($desc), $query) !== false) {
220a90c5 2962 return true;
2963 }
2964 }
2965 return false;
2966 }
2967
db26acd4 2968 /**
2969 * Returns XHTML multi-select field
2970 *
2971 * @todo Add vartype handling to ensure $data is an array
2972 * @param array $data Array of values to select by default
2973 * @param string $query
2974 * @return string XHTML multi-select field
2975 */
73fa96d5 2976 public function output_html($data, $query='') {
220a90c5 2977 if (!$this->load_choices() or empty($this->choices)) {
2978 return '';
2979 }
2980 $choices = $this->choices;
2981 $default = $this->get_defaultsetting();
2982 if (is_null($default)) {
2983 $default = array();
2984 }
2985 if (is_null($data)) {
d7933a55 2986 $data = array();
2987 }
220a90c5 2988
2989 $defaults = array();
4413941f 2990 $size = min(10, count($this->choices));
a7ad48fd 2991 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4413941f 2992 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
220a90c5 2993 foreach ($this->choices as $key => $description) {
2994 if (in_array($key, $data)) {
2995 $selected = 'selected="selected"';
2996 } else {
2997 $selected = '';
2998 }
2999 if (in_array($key, $default)) {
3000 $defaults[] = $description;
6e4dc10f 3001 }
220a90c5 3002
3003 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3004 }
3005
587c7040 3006 if (is_null($default)) {
3007 $defaultinfo = NULL;
3008 } if (!empty($defaults)) {
3009 $defaultinfo = implode(', ', $defaults);
220a90c5 3010 } else {
587c7040 3011 $defaultinfo = get_string('none');
6e4dc10f 3012 }
eef868d1 3013
587c7040 3014 $return .= '</select></div>';
3015 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
6e4dc10f 3016 }
220a90c5 3017}
eef868d1 3018
220a90c5 3019/**
3020 * Time selector
db26acd4 3021 *
3022 * This is a liiitle bit messy. we're using two selects, but we're returning
220a90c5 3023 * them as an array named after $name (so we only use $name2 internally for the setting)
db26acd4 3024 *
3025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 3026 */
3027class admin_setting_configtime extends admin_setting {
3e7069e7 3028 /** @var string Used for setting second select (minutes) */
73fa96d5 3029 public $name2;
220a90c5 3030
3031 /**
3032 * Constructor
3033 * @param string $hoursname setting for hours
3034 * @param string $minutesname setting for hours
3035 * @param string $visiblename localised
3036 * @param string $description long localised info
3037 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3038 */
73fa96d5 3039 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
220a90c5 3040 $this->name2 = $minutesname;
73fa96d5 3041 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
220a90c5 3042 }
3043
db26acd4 3044 /**
3045 * Get the selected time
0c079f19 3046 *
db26acd4 3047 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3048 */
73fa96d5 3049 public function get_setting() {
220a90c5 3050 $result1 = $this->config_read($this->name);
3051 $result2 = $this->config_read($this->name2);
3052 if (is_null($result1) or is_null($result2)) {
3053 return NULL;
3054 }
3055
3056 return array('h' => $result1, 'm' => $result2);
3057 }
3058
db26acd4 3059 /**
3060 * Store the time (hours and minutes)
0c079f19 3061 *
db26acd4 3062 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3063 * @return bool true if success, false if not
3064 */
73fa96d5 3065 public function write_setting($data) {
220a90c5 3066 if (!is_array($data)) {
3067 return '';
3068 }
3069
3070 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3071 return ($result ? '' : get_string('errorsetting', 'admin'));
3072 }
3073
db26acd4 3074 /**
3075 * Returns XHTML time select fields
3076 *
3077 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3078 * @param string $query
3079 * @return string XHTML time select fields and wrapping div(s)
3080 */
73fa96d5 3081 public function output_html($data, $query='') {
220a90c5 3082 $default = $this->get_defaultsetting();
3083
3084 if (is_array($default)) {
587c7040 3085 $defaultinfo = $default['h'].':'.$default['m'];
cc73de71 3086 } else {
587c7040 3087 $defaultinfo = NULL;
6e4dc10f 3088 }
220a90c5 3089
587c7040 3090 $return = '<div class="form-time defaultsnext">'.
9baf6825 3091 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
220a90c5 3092 for ($i = 0; $i < 24; $i++) {
3093 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
6e4dc10f 3094 }
220a90c5 3095 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
3096 for ($i = 0; $i < 60; $i += 5) {
3097 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3098 }
587c7040 3099 $return .= '</select></div>';
3100 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
6e4dc10f 3101 }
3102
3103}
3104
3e7069e7 3105
38257347
PS
3106/**
3107 * Seconds duration setting.
3108 *
3109 * @copyright 2012 Petr Skoda (http://skodak.org)
3110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3111 */
3112class admin_setting_configduration extends admin_setting {
3113
3114 /** @var int default duration unit */
3115 protected $defaultunit;
3116
3117 /**
3118 * Constructor
3119 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3120 * or 'myplugin/mysetting' for ones in config_plugins.
3121 * @param string $visiblename localised name
3122 * @param string $description localised long description
3123 * @param mixed $defaultsetting string or array depending on implementation
3124 * @param int $defaultunit - day, week, etc. (in seconds)
3125 */
3126 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3127 if (is_number($defaultsetting)) {
3128 $defaultsetting = self::parse_seconds($defaultsetting);
3129 }
3130 $units = self::get_units();
3131 if (isset($units[$defaultunit])) {
3132 $this->defaultunit = $defaultunit;
3133 } else {
3134 $this->defaultunit = 86400;
3135 }
3136 parent::__construct($name, $visiblename, $description, $defaultsetting);
3137 }
3138
3139 /**
3140 * Returns selectable units.
3141 * @static
3142 * @return array
3143 */
3144 protected static function get_units() {
3145 return array(
3146 604800 => get_string('weeks'),
3147 86400 => get_string('days'),
3148 3600 => get_string('hours'),
3149 60 => get_string('minutes'),
3150 1 => get_string('seconds'),
3151 );
3152 }
3153
3154 /**
3155 * Converts seconds to some more user friendly string.
3156 * @static
3157 * @param int $seconds
3158 * @return string
3159 */
3160 protected static function get_duration_text($seconds) {
3161 if (empty($seconds)) {
3162 return get_string('none');
3163 }
3164 $data = self::parse_seconds($seconds);
3165 switch ($data['u']) {
444af7c6
EL
3166 case (60*60*24*7):
3167 return get_string('numweeks', '', $data['v']);
3168 case (60*60*24):
3169 return get_string('numdays', '', $data['v']);
3170 case (60*60):
3171 return get_string('numhours', '', $data['v']);
3172 case (60):
3173 return get_string('numminutes', '', $data['v']);
3174 default:
3175 return get_string('numseconds', '', $data['v']*$data['u']);
38257347
PS
3176 }
3177 }
3178
3179 /**
3180 * Finds suitable units for given duration.
3181 * @static
3182 * @param int $seconds
3183 * @return array
3184 */
3185 protected static function parse_seconds($seconds) {
444af7c6 3186 foreach (self::get_units() as $unit => $unused) {
38257347
PS
3187 if ($seconds % $unit === 0) {
3188 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3189 }
3190 }
3191 return array('v'=>(int)$seconds, 'u'=>1);
3192 }
3193
3194 /**
3195 * Get the selected duration as array.
3196 *
3197 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3198 */
3199 public function get_setting() {
3200 $seconds = $this->config_read($this->name);
3201 if (is_null($seconds)) {
3202 return null;
3203 }
3204
3205 return self::parse_seconds($seconds);
3206 }
3207
3208 /**
3209 * Store the duration as seconds.
3210 *
3211 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3212 * @return bool true if success, false if not
3213 */
3214 public function write_setting($data) {
3215 if (!is_array($data)) {
3216 return '';
3217 }
3218
3219 $seconds = (int)($data['v']*$data['u']);
3220 if ($seconds < 0) {
3221 return get_string('errorsetting', 'admin');
3222 }
3223
3224 $result = $this->config_write($this->name, $seconds);
3225 return ($result ? '' : get_string('errorsetting', 'admin'));
3226 }
3227
3228 /**
3229 * Returns duration text+select fields.
3230 *
3231 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3232 * @param string $query
3233 * @return string duration text+select fields and wrapping div(s)
3234 */
3235 public function output_html($data, $query='') {
3236 $default = $this->get_defaultsetting();
3237
3238 if (is_number($default)) {
3239 $defaultinfo = self::get_duration_text($default);
3240 } else if (is_array($default)) {
3241 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3242 } else {
3243 $defaultinfo = null;
3244 }
3245
3246 $units = self::get_units();
3247
3248 $return = '<div class="form-duration defaultsnext">';
3249 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3250 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
444af7c6 3251 foreach ($units as $val => $text) {
38257347
PS
3252 $selected = '';
3253 if ($data['v'] == 0) {
3254 if ($val == $this->defaultunit) {
3255 $selected = ' selected="selected"';
3256 }
3257 } else if ($val == $data['u']) {
3258 $selected = ' selected="selected"';
3259 }
3260 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3261 }
3262 $return .= '</select></div>';
3263 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3264 }
3265}
3266
3267
db26acd4 3268/**
3269 * Used to validate a textarea used for ip addresses
3270 *
3271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 3272 */
4e639121 3273class admin_setting_configiplist extends admin_setting_configtextarea {
db26acd4 3274
3e7069e7
PS
3275 /**
3276 * Validate the contents of the textarea as IP addresses
3277 *
3278 * Used to validate a new line separated list of IP addresses collected from
3279 * a textarea control
3280 *
3281 * @param string $data A list of IP Addresses separated by new lines
3282 * @return mixed bool true for success or string:error on failure
3283 */
73fa96d5 3284 public function validate($data) {
4e639121 3285 if(!empty($data)) {
c5d2d0dd 3286 $ips = explode("\n", $data);
4e639121 3287 } else {
3288 return true;
3289 }
3290 $result = true;
3291 foreach($ips as $ip) {
3292 $ip = trim($ip);
3e7069e7 3293 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
9baf6825 3294 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3295 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4e639121 3296 $result = true;
3297 } else {
3298 $result = false;
3299 break;
3300 }
3301 }
9baf6825 3302 if($result) {
4e639121 3303 return true;
3304 } else {
3305 return get_string('validateerror', 'admin');
3306 }
3307 }
3308}
3309
3e7069e7 3310
4413941f 3311/**
db26acd4 3312 * An admin setting for selecting one or more users who have a capability
3313 * in the system context
3314 *
4413941f 3315 * An admin setting for selecting one or more users, who have a particular capability
3316 * in the system context. Warning, make sure the list will never be too long. There is
3317 * no paging or searching of this list.
3318 *
3319 * To correctly get a list of users from this config setting, you need to call the
3320 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
db26acd4 3321 *
3322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4413941f 3323 */
3324class admin_setting_users_with_capability extends admin_setting_configmultiselect {
adf176d7 3325 /** @var string The capabilities name */
4413941f 3326 protected $capability;
adf176d7
PS
3327 /** @var int include admin users too */
3328 protected $includeadmins;
4413941f 3329
3330 /**
3331 * Constructor.
3332 *
3333 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3334 * @param string $visiblename localised name
3335 * @param string $description localised long description
3336 * @param array $defaultsetting array of usernames
3337 * @param string $capability string capability name.
875e5f07 3338 * @param bool $includeadmins include administrators
4413941f 3339 */
adf176d7
PS
3340 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3341 $this->capability = $capability;
3342 $this->includeadmins = $includeadmins;
fb073f60 3343 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3344 }
3345
db26acd4 3346 /**
3347 * Load all of the uses who have the capability into choice array
3348 *
3349 * @return bool Always returns true
3350 */
fb073f60 3351