weekly release 2.7dev
[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
b8b50d04 1663 add_to_config_log($name, $oldvalue, $value, $this->plugin);
301bf0b2 1664
1665 return true; // BC only
220a90c5 1666 }
1667
1668 /**
1669 * Returns current value of this setting
1670 * @return mixed array or string depending on instance, NULL means not set yet
1671 */
301bf0b2 1672 public abstract function get_setting();
eef868d1 1673
220a90c5 1674 /**
1675 * Returns default setting if exists
1676 * @return mixed array or string depending on instance; NULL means no default, user must supply
1677 */
73fa96d5 1678 public function get_defaultsetting() {
cd3acbf2 1679 $adminroot = admin_get_root(false, false);
1680 if (!empty($adminroot->custom_defaults)) {
1681 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1682 if (isset($adminroot->custom_defaults[$plugin])) {
875e5f07 1683 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
cd3acbf2 1684 return $adminroot->custom_defaults[$plugin][$this->name];
1685 }
1686 }
1687 }
8e5da17a 1688 return $this->defaultsetting;
1689 }
1690
220a90c5 1691 /**
1692 * Store new setting
db26acd4 1693 *
1694 * @param mixed $data string or array, must not be NULL
1695 * @return string empty string if ok, string error message otherwise
220a90c5 1696 */
301bf0b2 1697 public abstract function write_setting($data);
eef868d1 1698
220a90c5 1699 /**
1700 * Return part of form with setting
db26acd4 1701 * This function should always be overwritten
1702 *
1703 * @param mixed $data array or string depending on setting
1704 * @param string $query
220a90c5 1705 * @return string
1706 */
73fa96d5 1707 public function output_html($data, $query='') {
9baf6825 1708 // should be overridden
220a90c5 1709 return;
1710 }
1711
1712 /**
db26acd4 1713 * Function called if setting updated - cleanup, cache reset, etc.
1714 * @param string $functionname Sets the function name
3e7069e7 1715 * @return void
220a90c5 1716 */
73fa96d5 1717 public function set_updatedcallback($functionname) {
220a90c5 1718 $this->updatedcallback = $functionname;
1719 }
1720
6ddc9278
PS
1721 /**
1722 * Execute postupdatecallback if necessary.
1723 * @param mixed $original original value before write_setting()
1724 * @return bool true if changed, false if not.
1725 */
1726 public function post_write_settings($original) {
1727 // Comparison must work for arrays too.
1728 if (serialize($original) === serialize($this->get_setting())) {
1729 return false;
1730 }
1731
1732 $callbackfunction = $this->updatedcallback;
1733 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1734 $callbackfunction($this->get_full_name());
1735 }
1736 return true;
1737 }
1738
220a90c5 1739 /**
1740 * Is setting related to query text - used when searching
1741 * @param string $query
1742 * @return bool
1743 */
73fa96d5 1744 public function is_related($query) {
220a90c5 1745 if (strpos(strtolower($this->name), $query) !== false) {
1746 return true;
1747 }
2f1e464a 1748 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
220a90c5 1749 return true;
1750 }
2f1e464a 1751 if (strpos(core_text::strtolower($this->description), $query) !== false) {
220a90c5 1752 return true;
1753 }
587c7040 1754 $current = $this->get_setting();
1755 if (!is_null($current)) {
1756 if (is_string($current)) {
2f1e464a 1757 if (strpos(core_text::strtolower($current), $query) !== false) {
587c7040 1758 return true;
1759 }
1760 }
1761 }
1762 $default = $this->get_defaultsetting();
1763 if (!is_null($default)) {
1764 if (is_string($default)) {
2f1e464a 1765 if (strpos(core_text::strtolower($default), $query) !== false) {
587c7040 1766 return true;
1767 }
1768 }
1769 }
220a90c5 1770 return false;
6e4dc10f 1771 }
220a90c5 1772}
eef868d1 1773
3c88a678
DW
1774/**
1775 * An additional option that can be applied to an admin setting.
1776 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1777 *
1778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1779 */
1780class admin_setting_flag {
1781 /** @var bool Flag to indicate if this option can be toggled for this setting */
1782 private $enabled = false;
1783 /** @var bool Flag to indicate if this option defaults to true or false */
1784 private $default = false;
1785 /** @var string Short string used to create setting name - e.g. 'adv' */
1786 private $shortname = '';
1787 /** @var string String used as the label for this flag */
1788 private $displayname = '';
1789 /** @const Checkbox for this flag is displayed in admin page */
1790 const ENABLED = true;
1791 /** @const Checkbox for this flag is not displayed in admin page */
1792 const DISABLED = false;
1793
1794 /**
1795 * Constructor
1796 *
1797 * @param bool $enabled Can this option can be toggled.
1798 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1799 * @param bool $default The default checked state for this setting option.
1800 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1801 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1802 */
1803 public function __construct($enabled, $default, $shortname, $displayname) {
1804 $this->shortname = $shortname;
1805 $this->displayname = $displayname;
1806 $this->set_options($enabled, $default);
1807 }
1808
1809 /**
1810 * Update the values of this setting options class
1811 *
1812 * @param bool $enabled Can this option can be toggled.
1813 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1814 * @param bool $default The default checked state for this setting option.
1815 */
1816 public function set_options($enabled, $default) {
1817 $this->enabled = $enabled;
1818 $this->default = $default;
1819 }
1820
1821 /**
1822 * Should this option appear in the interface and be toggleable?
1823 *
1824 * @return bool Is it enabled?
1825 */
1826 public function is_enabled() {
1827 return $this->enabled;
1828 }
1829
1830 /**
1831 * Should this option be checked by default?
1832 *
1833 * @return bool Is it on by default?
1834 */
1835 public function get_default() {
1836 return $this->default;
1837 }
1838
1839 /**
1840 * Return the short name for this flag. e.g. 'adv' or 'locked'
1841 *
1842 * @return string
1843 */
1844 public function get_shortname() {
1845 return $this->shortname;
1846 }
1847
1848 /**
1849 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1850 *
1851 * @return string
1852 */
1853 public function get_displayname() {
1854 return $this->displayname;
1855 }
1856
1857 /**
1858 * Save the submitted data for this flag - or set it to the default if $data is null.
1859 *
1860 * @param admin_setting $setting - The admin setting for this flag
7e815a6e 1861 * @param array $data - The data submitted from the form or null to set the default value for new installs.
3c88a678
DW
1862 * @return bool
1863 */
1864 public function write_setting_flag(admin_setting $setting, $data) {
1865 $result = true;
1866 if ($this->is_enabled()) {
7e815a6e
DW
1867 if (!isset($data)) {
1868 $value = $this->get_default();
1869 } else {
1870 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
1871 }
3c88a678
DW
1872 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
1873 }
1874
1875 return $result;
1876
1877 }
1878
1879 /**
1880 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
1881 *
1882 * @param admin_setting $setting - The admin setting for this flag
1883 * @return string - The html for the checkbox.
1884 */
1885 public function output_setting_flag(admin_setting $setting) {
1886 $value = $setting->get_setting_flag_value($this);
1887 $output = ' <input type="checkbox" class="form-checkbox" ' .
1888 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
1889 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
1890 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
1891 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
1892 $this->get_displayname() .
1893 ' </label> ';
1894 return $output;
1895 }
1896}
1897
3e7069e7 1898
220a90c5 1899/**
1900 * No setting - just heading and text.
db26acd4 1901 *
1902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1903 */
1904class admin_setting_heading extends admin_setting {
3e7069e7
PS
1905
1906 /**
1907 * not a setting, just text
1908 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1909 * @param string $heading heading
1910 * @param string $information text in box
1911 */
73fa96d5 1912 public function __construct($name, $heading, $information) {
427649bf 1913 $this->nosave = true;
73fa96d5 1914 parent::__construct($name, $heading, $information, '');
220a90c5 1915 }
1916
db26acd4 1917 /**
1918 * Always returns true
1919 * @return bool Always returns true
1920 */
73fa96d5 1921 public function get_setting() {
220a90c5 1922 return true;
1923 }
1924
db26acd4 1925 /**
1926 * Always returns true
1927 * @return bool Always returns true
1928 */
73fa96d5 1929 public function get_defaultsetting() {
220a90c5 1930 return true;
1931 }
1932
db26acd4 1933 /**
1934 * Never write settings
1935 * @return string Always returns an empty string
1936 */
73fa96d5 1937 public function write_setting($data) {
9baf6825 1938 // do not write any setting
220a90c5 1939 return '';
1940 }
0c079f19 1941
db26acd4 1942 /**
1943 * Returns an HTML string
1944 * @return string Returns an HTML string
1945 */
73fa96d5 1946 public function output_html($data, $query='') {
3c159385 1947 global $OUTPUT;
220a90c5 1948 $return = '';
1949 if ($this->visiblename != '') {
206dd861 1950 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
220a90c5 1951 }
1952 if ($this->description != '') {
8dbe233a 1953 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
220a90c5 1954 }
1955 return $return;
1956 }
1957}
6e4dc10f 1958
3e7069e7 1959
220a90c5 1960/**
1961 * The most flexibly setting, user is typing text
db26acd4 1962 *
1963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1964 */
6e4dc10f 1965class admin_setting_configtext extends admin_setting {
1966
3e7069e7 1967 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
73fa96d5 1968 public $paramtype;
0c079f19 1969 /** @var int default field size */
73fa96d5 1970 public $size;
6e4dc10f 1971
220a90c5 1972 /**
875e5f07 1973 * Config text constructor
db26acd4 1974 *
1a41e806 1975 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 1976 * @param string $visiblename localised
1977 * @param string $description long localised info
1978 * @param string $defaultsetting
1979 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
f7633b0f 1980 * @param int $size default field size
220a90c5 1981 */
73fa96d5 1982 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
6e4dc10f 1983 $this->paramtype = $paramtype;
f7633b0f 1984 if (!is_null($size)) {
1985 $this->size = $size;
1986 } else {
40ea93a4 1987 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
f7633b0f 1988 }
73fa96d5 1989 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 1990 }
1991
db26acd4 1992 /**
1993 * Return the setting
1994 *
875e5f07 1995 * @return mixed returns config if successful else null
db26acd4 1996 */
73fa96d5 1997 public function get_setting() {
220a90c5 1998 return $this->config_read($this->name);
6e4dc10f 1999 }
eef868d1 2000
73fa96d5 2001 public function write_setting($data) {
8cad6cca 2002 if ($this->paramtype === PARAM_INT and $data === '') {
9baf6825 2003 // do not complain if '' used instead of 0
8cad6cca 2004 $data = 0;
2005 }
220a90c5 2006 // $data is a string
c5d2d0dd 2007 $validated = $this->validate($data);
e33fbf87 2008 if ($validated !== true) {
2009 return $validated;
c235598d 2010 }
220a90c5 2011 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2012 }
2013
e33fbf87 2014 /**
2015 * Validate data before storage
2016 * @param string data
2017 * @return mixed true if ok string if error found
2018 */
73fa96d5 2019 public function validate($data) {
58aaa8e9 2020 // allow paramtype to be a custom regex if it is the form of /pattern/
2021 if (preg_match('#^/.*/$#', $this->paramtype)) {
e33fbf87 2022 if (preg_match($this->paramtype, $data)) {
2023 return true;
2024 } else {
2025 return get_string('validateerror', 'admin');
2026 }
2027
9e24fbd1 2028 } else if ($this->paramtype === PARAM_RAW) {
4ea56b3f 2029 return true;
9baf6825 2030
4ea56b3f 2031 } else {
2032 $cleaned = clean_param($data, $this->paramtype);
40ea93a4 2033 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
4ea56b3f 2034 return true;
e33fbf87 2035 } else {
4ea56b3f 2036 return get_string('validateerror', 'admin');
e33fbf87 2037 }
4ea56b3f 2038 }
c235598d 2039 }
2040
db26acd4 2041 /**
2042 * Return an XHTML string for the setting
2043 * @return string Returns an XHTML string
2044 */
73fa96d5 2045 public function output_html($data, $query='') {
220a90c5 2046 $default = $this->get_defaultsetting();
2047
220a90c5 2048 return format_admin_setting($this, $this->visiblename,
9baf6825 2049 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2050 $this->description, true, '', $default, $query);
6e4dc10f 2051 }
6e4dc10f 2052}
2053
3e7069e7 2054
220a90c5 2055/**
2056 * General text area without html editor.
db26acd4 2057 *
2058 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2059 */
2060class admin_setting_configtextarea extends admin_setting_configtext {
4fe2250a 2061 private $rows;
2062 private $cols;
eba8cd63 2063
db26acd4 2064 /**
2065 * @param string $name
2066 * @param string $visiblename
2067 * @param string $description
2068 * @param mixed $defaultsetting string or array
2069 * @param mixed $paramtype
2070 * @param string $cols The number of columns to make the editor
2071 * @param string $rows The number of rows to make the editor
2072 */
73fa96d5 2073 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
220a90c5 2074 $this->rows = $rows;
2075 $this->cols = $cols;
73fa96d5 2076 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
eba8cd63 2077 }
3e7069e7 2078
db26acd4 2079 /**
2080 * Returns an XHTML string for the editor
2081 *
2082 * @param string $data
2083 * @param string $query
2084 * @return string XHTML string for the editor
2085 */
73fa96d5 2086 public function output_html($data, $query='') {
220a90c5 2087 $default = $this->get_defaultsetting();
2088
587c7040 2089 $defaultinfo = $default;
2090 if (!is_null($default) and $default !== '') {
2091 $defaultinfo = "\n".$default;
c5d2d0dd 2092 }
220a90c5 2093
2094 return format_admin_setting($this, $this->visiblename,
0ac97084 2095 '<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 2096 $this->description, true, '', $defaultinfo, $query);
4fe2250a 2097 }
2098}
2099
3e7069e7 2100
4fe2250a 2101/**
2102 * General text area with html editor.
2103 */
2104class admin_setting_confightmleditor extends admin_setting_configtext {
2105 private $rows;
2106 private $cols;
0c079f19 2107
4fe2250a 2108 /**
2109 * @param string $name
2110 * @param string $visiblename
2111 * @param string $description
2112 * @param mixed $defaultsetting string or array
2113 * @param mixed $paramtype
2114 */
2115 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2116 $this->rows = $rows;
2117 $this->cols = $cols;
2118 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
ff5fe311 2119 editors_head_setup();
4fe2250a 2120 }
3e7069e7 2121
4fe2250a 2122 /**
2123 * Returns an XHTML string for the editor
2124 *
2125 * @param string $data
2126 * @param string $query
2127 * @return string XHTML string for the editor
2128 */
2129 public function output_html($data, $query='') {
2130 $default = $this->get_defaultsetting();
2131
2132 $defaultinfo = $default;
2133 if (!is_null($default) and $default !== '') {
2134 $defaultinfo = "\n".$default;
2135 }
2136
20e5da7d 2137 $editor = editors_get_preferred_editor(FORMAT_HTML);
69429650 2138 $editor->use_editor($this->get_id(), array('noclean'=>true));
4fe2250a 2139
2140 return format_admin_setting($this, $this->visiblename,
0ac97084 2141 '<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 2142 $this->description, true, '', $defaultinfo, $query);
220a90c5 2143 }
2144}
2145
3e7069e7 2146
220a90c5 2147/**
2148 * Password field, allows unmasking of password
db26acd4 2149 *
2150 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2151 */
2152class admin_setting_configpasswordunmask extends admin_setting_configtext {
3e7069e7
PS
2153 /**
2154 * Constructor
2155 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2156 * @param string $visiblename localised
2157 * @param string $description long localised info
2158 * @param string $defaultsetting default password
2159 */
73fa96d5 2160 public function __construct($name, $visiblename, $description, $defaultsetting) {
2161 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
220a90c5 2162 }
0c079f19 2163
db26acd4 2164 /**
2165 * Returns XHTML for the field
2166 * Writes Javascript into the HTML below right before the last div
2167 *
2168 * @todo Make javascript available through newer methods if possible
2169 * @param string $data Value for the field
2170 * @param string $query Passed as final argument for format_admin_setting
2171 * @return string XHTML field
2172 */
73fa96d5 2173 public function output_html($data, $query='') {
220a90c5 2174 $id = $this->get_id();
2175 $unmask = get_string('unmaskpassword', 'form');
2176 $unmaskjs = '<script type="text/javascript">
eba8cd63 2177//<![CDATA[
633239f6 2178var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2179
2180document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2181
2182var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2183
2184var unmaskchb = document.createElement("input");
2185unmaskchb.setAttribute("type", "checkbox");
2186unmaskchb.setAttribute("id", "'.$id.'unmask");
2187unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2188unmaskdiv.appendChild(unmaskchb);
2189
2190var unmasklbl = document.createElement("label");
2191unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2192if (is_ie) {
2193 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2194} else {
2195 unmasklbl.setAttribute("for", "'.$id.'unmask");
2196}
2197unmaskdiv.appendChild(unmasklbl);
2198
2199if (is_ie) {
2200 // ugly hack to work around the famous onchange IE bug
2201 unmaskchb.onclick = function() {this.blur();};
2202 unmaskdiv.onclick = function() {this.blur();};
2203}
eba8cd63 2204//]]>
2205</script>';
220a90c5 2206 return format_admin_setting($this, $this->visiblename,
9baf6825 2207 '<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>',
2208 $this->description, true, '', NULL, $query);
220a90c5 2209 }
2210}
2211
c7cd8d9c
DW
2212/**
2213 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2214 * Note: Only advanced makes sense right now - locked does not.
2215 *
2216 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2217 */
2218class admin_setting_configempty extends admin_setting_configtext {
2219
2220 /**
2221 * @param string $name
2222 * @param string $visiblename
2223 * @param string $description
2224 */
2225 public function __construct($name, $visiblename, $description) {
2226 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2227 }
2228
2229 /**
2230 * Returns an XHTML string for the hidden field
2231 *
2232 * @param string $data
2233 * @param string $query
2234 * @return string XHTML string for the editor
2235 */
2236 public function output_html($data, $query='') {
2237 return format_admin_setting($this,
2238 $this->visiblename,
2239 '<div class="form-empty" >' .
2240 '<input type="hidden"' .
2241 ' id="'. $this->get_id() .'"' .
2242 ' name="'. $this->get_full_name() .'"' .
2243 ' value=""/></div>',
2244 $this->description,
2245 true,
2246 '',
2247 get_string('none'),
2248 $query);
2249 }
2250}
2251
3e7069e7 2252
220a90c5 2253/**
e9c0fa35 2254 * Path to directory
db26acd4 2255 *
2256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2257 */
e9c0fa35 2258class admin_setting_configfile extends admin_setting_configtext {
3e7069e7
PS
2259 /**
2260 * Constructor
2261 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2262 * @param string $visiblename localised
2263 * @param string $description long localised info
2264 * @param string $defaultdirectory default directory location
2265 */
73fa96d5 2266 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2267 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
220a90c5 2268 }
2269
db26acd4 2270 /**
2271 * Returns XHTML for the field
0c079f19 2272 *
db26acd4 2273 * Returns XHTML for the field and also checks whether the file
2274 * specified in $data exists using file_exists()
2275 *
2276 * @param string $data File name and path to use in value attr
2277 * @param string $query
2278 * @return string XHTML field
2279 */
73fa96d5 2280 public function output_html($data, $query='') {
220a90c5 2281 $default = $this->get_defaultsetting();
2282
220a90c5 2283 if ($data) {
e9c0fa35 2284 if (file_exists($data)) {
220a90c5 2285 $executable = '<span class="pathok">&#x2714;</span>';
2286 } else {
2287 $executable = '<span class="patherror">&#x2718;</span>';
2288 }
2289 } else {
2290 $executable = '';
2291 }
2292
2293 return format_admin_setting($this, $this->visiblename,
9baf6825 2294 '<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>',
2295 $this->description, true, '', $default, $query);
eba8cd63 2296 }
9a2b5e0b
HD
2297 /**
2298 * checks if execpatch has been disabled in config.php
2299 */
2300 public function write_setting($data) {
2301 global $CFG;
2302 if (!empty($CFG->preventexecpath)) {
2303 return '';
2304 }
2305 return parent::write_setting($data);
2306 }
220a90c5 2307}
2308
3e7069e7 2309
220a90c5 2310/**
e9c0fa35 2311 * Path to executable file
db26acd4 2312 *
2313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2314 */
e9c0fa35 2315class admin_setting_configexecutable extends admin_setting_configfile {
2316
3e7069e7
PS
2317 /**
2318 * Returns an XHTML field
2319 *
2320 * @param string $data This is the value for the field
2321 * @param string $query
2322 * @return string XHTML field
2323 */
73fa96d5 2324 public function output_html($data, $query='') {
9a2b5e0b 2325 global $CFG;
e9c0fa35 2326 $default = $this->get_defaultsetting();
2327
2328 if ($data) {
2329 if (file_exists($data) and is_executable($data)) {
2330 $executable = '<span class="pathok">&#x2714;</span>';
2331 } else {
2332 $executable = '<span class="patherror">&#x2718;</span>';
2333 }
2334 } else {
2335 $executable = '';
2336 }
9a2b5e0b
HD
2337 if (!empty($CFG->preventexecpath)) {
2338 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2339 }
e9c0fa35 2340
2341 return format_admin_setting($this, $this->visiblename,
9baf6825 2342 '<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>',
2343 $this->description, true, '', $default, $query);
220a90c5 2344 }
e9c0fa35 2345}
220a90c5 2346
3e7069e7 2347
e9c0fa35 2348/**
2349 * Path to directory
db26acd4 2350 *
2351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e9c0fa35 2352 */
2353class admin_setting_configdirectory extends admin_setting_configfile {
db26acd4 2354
3e7069e7
PS
2355 /**
2356 * Returns an XHTML field
2357 *
2358 * @param string $data This is the value for the field
2359 * @param string $query
2360 * @return string XHTML
2361 */
73fa96d5 2362 public function output_html($data, $query='') {
220a90c5 2363 $default = $this->get_defaultsetting();
2364
220a90c5 2365 if ($data) {
2366 if (file_exists($data) and is_dir($data)) {
2367 $executable = '<span class="pathok">&#x2714;</span>';
2368 } else {
2369 $executable = '<span class="patherror">&#x2718;</span>';
2370 }
2371 } else {
2372 $executable = '';
2373 }
9ba38673 2374
220a90c5 2375 return format_admin_setting($this, $this->visiblename,
9baf6825 2376 '<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>',
2377 $this->description, true, '', $default, $query);
220a90c5 2378 }
eba8cd63 2379}
2380
3e7069e7 2381
220a90c5 2382/**
2383 * Checkbox
db26acd4 2384 *
2385 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2386 */
6e4dc10f 2387class admin_setting_configcheckbox extends admin_setting {
3e7069e7 2388 /** @var string Value used when checked */
73fa96d5 2389 public $yes;
0c079f19 2390 /** @var string Value used when not checked */
73fa96d5 2391 public $no;
6e4dc10f 2392
220a90c5 2393 /**
2394 * Constructor
1a41e806 2395 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2396 * @param string $visiblename localised
2397 * @param string $description long localised info
2398 * @param string $defaultsetting
2399 * @param string $yes value used when checked
2400 * @param string $no value used when not checked
2401 */
73fa96d5 2402 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2403 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2404 $this->yes = (string)$yes;
2405 $this->no = (string)$no;
6e4dc10f 2406 }
2407
db26acd4 2408 /**
2409 * Retrieves the current setting using the objects name
2410 *
2411 * @return string
2412 */
73fa96d5 2413 public function get_setting() {
220a90c5 2414 return $this->config_read($this->name);
6e4dc10f 2415 }
eef868d1 2416
db26acd4 2417 /**
2418 * Sets the value for the setting
2419 *
2420 * Sets the value for the setting to either the yes or no values
2421 * of the object by comparing $data to yes
2422 *
2423 * @param mixed $data Gets converted to str for comparison against yes value
2424 * @return string empty string or error
2425 */
73fa96d5 2426 public function write_setting($data) {
220a90c5 2427 if ((string)$data === $this->yes) { // convert to strings before comparison
2428 $data = $this->yes;
6e4dc10f 2429 } else {
220a90c5 2430 $data = $this->no;
6e4dc10f 2431 }
220a90c5 2432 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2433 }
2434
db26acd4 2435 /**
2436 * Returns an XHTML checkbox field
2437 *
2438 * @param string $data If $data matches yes then checkbox is checked
2439 * @param string $query
2440 * @return string XHTML field
2441 */
73fa96d5 2442 public function output_html($data, $query='') {
220a90c5 2443 $default = $this->get_defaultsetting();
2444
2445 if (!is_null($default)) {
2446 if ((string)$default === $this->yes) {
587c7040 2447 $defaultinfo = get_string('checkboxyes', 'admin');
220a90c5 2448 } else {
587c7040 2449 $defaultinfo = get_string('checkboxno', 'admin');
220a90c5 2450 }
c8218a42 2451 } else {
587c7040 2452 $defaultinfo = NULL;
c8218a42 2453 }
220a90c5 2454
2455 if ((string)$data === $this->yes) { // convert to strings before comparison
2456 $checked = 'checked="checked"';
2457 } else {
2458 $checked = '';
2459 }
2460
2461 return format_admin_setting($this, $this->visiblename,
9baf6825 2462 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2463 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2464 $this->description, true, '', $defaultinfo, $query);
6e4dc10f 2465 }
6e4dc10f 2466}
2467
3e7069e7 2468
220a90c5 2469/**
2470 * Multiple checkboxes, each represents different value, stored in csv format
db26acd4 2471 *
2472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2473 */
2474class admin_setting_configmulticheckbox extends admin_setting {
3e7069e7 2475 /** @var array Array of choices value=>label */
73fa96d5 2476 public $choices;
eef868d1 2477
220a90c5 2478 /**
db26acd4 2479 * Constructor: uses parent::__construct
2480 *
1a41e806 2481 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2482 * @param string $visiblename localised
2483 * @param string $description long localised info
2484 * @param array $defaultsetting array of selected
2485 * @param array $choices array of $value=>$label for each checkbox
2486 */
73fa96d5 2487 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6e4dc10f 2488 $this->choices = $choices;
73fa96d5 2489 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 2490 }
2491
0a784551 2492 /**
73fa96d5 2493 * This public function may be used in ancestors for lazy loading of choices
db26acd4 2494 *
2495 * @todo Check if this function is still required content commented out only returns true
2496 * @return bool true if loaded, false if error
0a784551 2497 */
73fa96d5 2498 public function load_choices() {
0a784551 2499 /*
220a90c5 2500 if (is_array($this->choices)) {
2501 return true;
0a784551 2502 }
2503 .... load choices here
2504 */
220a90c5 2505 return true;
2506 }
2507
2508 /**
2509 * Is setting related to query text - used when searching
db26acd4 2510 *
220a90c5 2511 * @param string $query
db26acd4 2512 * @return bool true on related, false on not or failure
220a90c5 2513 */
73fa96d5 2514 public function is_related($query) {
220a90c5 2515 if (!$this->load_choices() or empty($this->choices)) {
2516 return false;
2517 }
2518 if (parent::is_related($query)) {
2519 return true;
2520 }
2521
220a90c5 2522 foreach ($this->choices as $desc) {
2f1e464a 2523 if (strpos(core_text::strtolower($desc), $query) !== false) {
220a90c5 2524 return true;
2525 }
2526 }
2527 return false;
0a784551 2528 }
2529
db26acd4 2530 /**
2531 * Returns the current setting if it is set
2532 *
2533 * @return mixed null if null, else an array
2534 */
73fa96d5 2535 public function get_setting() {
220a90c5 2536 $result = $this->config_read($this->name);
10f19c49 2537
220a90c5 2538 if (is_null($result)) {
2539 return NULL;
2540 }
2541 if ($result === '') {
2542 return array();
2543 }
10f19c49 2544 $enabled = explode(',', $result);
2545 $setting = array();
2546 foreach ($enabled as $option) {
2547 $setting[$option] = 1;
2548 }
2549 return $setting;
6e4dc10f 2550 }
eef868d1 2551
db26acd4 2552 /**
2553 * Saves the setting(s) provided in $data
2554 *
2555 * @param array $data An array of data, if not array returns empty str
2556 * @return mixed empty string on useless data or bool true=success, false=failed
2557 */
73fa96d5 2558 public function write_setting($data) {
220a90c5 2559 if (!is_array($data)) {
2560 return ''; // ignore it
2561 }
2562 if (!$this->load_choices() or empty($this->choices)) {
2563 return '';
2564 }
2565 unset($data['xxxxx']);
2566 $result = array();
2567 foreach ($data as $key => $value) {
2568 if ($value and array_key_exists($key, $this->choices)) {
2569 $result[] = $key;
2570 }
2571 }
2572 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
6e4dc10f 2573 }
0c079f19 2574
db26acd4 2575 /**
2576 * Returns XHTML field(s) as required by choices
2577 *
2578 * Relies on data being an array should data ever be another valid vartype with
2579 * acceptable value this may cause a warning/error
2580 * if (!is_array($data)) would fix the problem
2581 *
2582 * @todo Add vartype handling to ensure $data is an array
2583 *
2584 * @param array $data An array of checked values
2585 * @param string $query
2586 * @return string XHTML field
2587 */
73fa96d5 2588 public function output_html($data, $query='') {
220a90c5 2589 if (!$this->load_choices() or empty($this->choices)) {
2590 return '';
2591 }
2592 $default = $this->get_defaultsetting();
2593 if (is_null($default)) {
2594 $default = array();
2595 }
2596 if (is_null($data)) {
775f811a 2597 $data = array();
220a90c5 2598 }
220a90c5 2599 $options = array();
2600 $defaults = array();
10f19c49 2601 foreach ($this->choices as $key=>$description) {
2602 if (!empty($data[$key])) {
220a90c5 2603 $checked = 'checked="checked"';
2604 } else {
2605 $checked = '';
2606 }
10f19c49 2607 if (!empty($default[$key])) {
220a90c5 2608 $defaults[] = $description;
2609 }
2610
2611 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
9baf6825 2612 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
220a90c5 2613 }
2614
587c7040 2615 if (is_null($default)) {
2616 $defaultinfo = NULL;
2617 } else if (!empty($defaults)) {
9baf6825 2618 $defaultinfo = implode(', ', $defaults);
2619 } else {
2620 $defaultinfo = get_string('none');
2621 }
220a90c5 2622
2623 $return = '<div class="form-multicheckbox">';
2624 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2625 if ($options) {
2626 $return .= '<ul>';
2627 foreach ($options as $option) {
2628 $return .= '<li>'.$option.'</li>';
2629 }
2630 $return .= '</ul>';
6e4dc10f 2631 }
587c7040 2632 $return .= '</div>';
6153cf58 2633
587c7040 2634 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
c5d2d0dd 2635
6e4dc10f 2636 }
6e4dc10f 2637}
2638
3e7069e7 2639
220a90c5 2640/**
2641 * Multiple checkboxes 2, value stored as string 00101011
db26acd4 2642 *
2643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2644 */
2645class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
db26acd4 2646
3e7069e7
PS
2647 /**
2648 * Returns the setting if set
2649 *
2650 * @return mixed null if not set, else an array of set settings
2651 */
73fa96d5 2652 public function get_setting() {
220a90c5 2653 $result = $this->config_read($this->name);
2654 if (is_null($result)) {
2655 return NULL;
2656 }
2657 if (!$this->load_choices()) {
2658 return NULL;
2659 }
2660 $result = str_pad($result, count($this->choices), '0');
2661 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2662 $setting = array();
2663 foreach ($this->choices as $key=>$unused) {
2664 $value = array_shift($result);
2665 if ($value) {
10f19c49 2666 $setting[$key] = 1;
220a90c5 2667 }
2668 }
2669 return $setting;
2670 }
6e4dc10f 2671
db26acd4 2672 /**
2673 * Save setting(s) provided in $data param
2674 *
2675 * @param array $data An array of settings to save
2676 * @return mixed empty string for bad data or bool true=>success, false=>error
2677 */
73fa96d5 2678 public function write_setting($data) {
220a90c5 2679 if (!is_array($data)) {
2680 return ''; // ignore it
2681 }
2682 if (!$this->load_choices() or empty($this->choices)) {
2683 return '';
2684 }
2685 $result = '';
2686 foreach ($this->choices as $key=>$unused) {
2687 if (!empty($data[$key])) {
2688 $result .= '1';
2689 } else {
2690 $result .= '0';
2691 }
2692 }
2693 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2694 }
2695}
2696
3e7069e7 2697
220a90c5 2698/**
2699 * Select one value from list
db26acd4 2700 *
2701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2702 */
2703class admin_setting_configselect extends admin_setting {
3e7069e7 2704 /** @var array Array of choices value=>label */
73fa96d5 2705 public $choices;
6e4dc10f 2706
220a90c5 2707 /**
2708 * Constructor
1a41e806 2709 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2710 * @param string $visiblename localised
2711 * @param string $description long localised info
eab8ed9f 2712 * @param string|int $defaultsetting
220a90c5 2713 * @param array $choices array of $value=>$label for each selection
2714 */
73fa96d5 2715 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
220a90c5 2716 $this->choices = $choices;
73fa96d5 2717 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2718 }
2719
2720 /**
2721 * This function may be used in ancestors for lazy loading of choices
db26acd4 2722 *
0c079f19 2723 * Override this method if loading of choices is expensive, such
2724 * as when it requires multiple db requests.
2725 *
db26acd4 2726 * @return bool true if loaded, false if error
220a90c5 2727 */
73fa96d5 2728 public function load_choices() {
220a90c5 2729 /*
2730 if (is_array($this->choices)) {
2731 return true;
6e4dc10f 2732 }
220a90c5 2733 .... load choices here
2734 */
2735 return true;
6e4dc10f 2736 }
2737
db26acd4 2738 /**
2739 * Check if this is $query is related to a choice
2740 *
2741 * @param string $query
2742 * @return bool true if related, false if not
2743 */
73fa96d5 2744 public function is_related($query) {
407d8134 2745 if (parent::is_related($query)) {
2746 return true;
2747 }
2748 if (!$this->load_choices()) {
2749 return false;
2750 }
407d8134 2751 foreach ($this->choices as $key=>$value) {
2f1e464a 2752 if (strpos(core_text::strtolower($key), $query) !== false) {
407d8134 2753 return true;
2754 }
2f1e464a 2755 if (strpos(core_text::strtolower($value), $query) !== false) {
407d8134 2756 return true;
2757 }
c5d2d0dd 2758 }
407d8134 2759 return false;
2760 }
2761
db26acd4 2762 /**
2763 * Return the setting
0c079f19 2764 *
875e5f07 2765 * @return mixed returns config if successful else null
db26acd4 2766 */
73fa96d5 2767 public function get_setting() {
220a90c5 2768 return $this->config_read($this->name);
6e4dc10f 2769 }
eef868d1 2770
db26acd4 2771 /**
2772 * Save a setting
2773 *
2774 * @param string $data
2775 * @return string empty of error string
2776 */
73fa96d5 2777 public function write_setting($data) {
220a90c5 2778 if (!$this->load_choices() or empty($this->choices)) {
2779 return '';
2780 }
2781 if (!array_key_exists($data, $this->choices)) {
2782 return ''; // ignore it
2783 }
eef868d1 2784
220a90c5 2785 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2786 }
eef868d1 2787
e2249afe 2788 /**
db26acd4 2789 * Returns XHTML select field
2790 *
2791 * Ensure the options are loaded, and generate the XHTML for the select
e2249afe 2792 * element and any warning message. Separating this out from output_html
2793 * makes it easier to subclass this class.
2794 *
2795 * @param string $data the option to show as selected.
2796 * @param string $current the currently selected option in the database, null if none.
2797 * @param string $default the default selected option.
2798 * @return array the HTML for the select element, and a warning message.
2799 */
73fa96d5 2800 public function output_select_html($data, $current, $default, $extraname = '') {
220a90c5 2801 if (!$this->load_choices() or empty($this->choices)) {
e2249afe 2802 return array('', '');
6e4dc10f 2803 }
220a90c5 2804
9c305ba1 2805 $warning = '';
2806 if (is_null($current)) {
9baf6825 2807 // first run
9c305ba1 2808 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2809 // no warning
9baf6825 2810 } else if (!array_key_exists($current, $this->choices)) {
2811 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2812 if (!is_null($default) and $data == $current) {
2813 $data = $default; // use default instead of first value when showing the form
2814 }
2815 }
9c305ba1 2816
e2249afe 2817 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
6e4dc10f 2818 foreach ($this->choices as $key => $value) {
9baf6825 2819 // the string cast is needed because key may be integer - 0 is equal to most strings!
e2249afe 2820 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
eef868d1 2821 }
e2249afe 2822 $selecthtml .= '</select>';
2823 return array($selecthtml, $warning);
2824 }
2825
db26acd4 2826 /**
2827 * Returns XHTML select field and wrapping div(s)
2828 *
2829 * @see output_select_html()
0c079f19 2830 *
db26acd4 2831 * @param string $data the option to show as selected
2832 * @param string $query
2833 * @return string XHTML field and wrapping div
2834 */
73fa96d5 2835 public function output_html($data, $query='') {
e2249afe 2836 $default = $this->get_defaultsetting();
2837 $current = $this->get_setting();
2838
2839 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2840 if (!$selecthtml) {
2841 return '';
2842 }
2843
2844 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2845 $defaultinfo = $this->choices[$default];
2846 } else {
2847 $defaultinfo = NULL;
2848 }
2849
2850 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
220a90c5 2851
587c7040 2852 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
6e4dc10f 2853 }
6e4dc10f 2854}
2855
3e7069e7 2856
220a90c5 2857/**
2858 * Select multiple items from list
db26acd4 2859 *
2860 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2861 */
6e4dc10f 2862class admin_setting_configmultiselect extends admin_setting_configselect {
3e7069e7
PS
2863 /**
2864 * Constructor
2865 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2866 * @param string $visiblename localised
2867 * @param string $description long localised info
2868 * @param array $defaultsetting array of selected items
2869 * @param array $choices array of $value=>$label for each list item
2870 */
73fa96d5 2871 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2872 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
6e4dc10f 2873 }
2874
db26acd4 2875 /**
2876 * Returns the select setting(s)
2877 *
2878 * @return mixed null or array. Null if no settings else array of setting(s)
2879 */
73fa96d5 2880 public function get_setting() {
220a90c5 2881 $result = $this->config_read($this->name);
2882 if (is_null($result)) {
d7933a55 2883 return NULL;
2884 }
220a90c5 2885 if ($result === '') {
2886 return array();
2887 }
2888 return explode(',', $result);
6e4dc10f 2889 }
eef868d1 2890
db26acd4 2891 /**
2892 * Saves setting(s) provided through $data
2893 *
2894 * Potential bug in the works should anyone call with this function
2895 * using a vartype that is not an array
2896 *
db26acd4 2897 * @param array $data
2898 */
73fa96d5 2899 public function write_setting($data) {
220a90c5 2900 if (!is_array($data)) {
2901 return ''; //ignore it
2902 }
2903 if (!$this->load_choices() or empty($this->choices)) {
2904 return '';
2905 }
2906
a7ad48fd 2907 unset($data['xxxxx']);
2908
220a90c5 2909 $save = array();
2910 foreach ($data as $value) {
2911 if (!array_key_exists($value, $this->choices)) {
2912 continue; // ignore it
2913 }
2914 $save[] = $value;
2915 }
2916
2917 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2918 }
2919
2920 /**
2921 * Is setting related to query text - used when searching
db26acd4 2922 *
220a90c5 2923 * @param string $query
db26acd4 2924 * @return bool true if related, false if not
220a90c5 2925 */
73fa96d5 2926 public function is_related($query) {
220a90c5 2927 if (!$this->load_choices() or empty($this->choices)) {
2928 return false;
2929 }
2930 if (parent::is_related($query)) {
2931 return true;
2932 }
2933
220a90c5 2934 foreach ($this->choices as $desc) {
2f1e464a 2935 if (strpos(core_text::strtolower($desc), $query) !== false) {
220a90c5 2936 return true;
2937 }
2938 }
2939 return false;
2940 }
2941
db26acd4 2942 /**
2943 * Returns XHTML multi-select field
2944 *
2945 * @todo Add vartype handling to ensure $data is an array
2946 * @param array $data Array of values to select by default
2947 * @param string $query
2948 * @return string XHTML multi-select field
2949 */
73fa96d5 2950 public function output_html($data, $query='') {
220a90c5 2951 if (!$this->load_choices() or empty($this->choices)) {
2952 return '';
2953 }
2954 $choices = $this->choices;
2955 $default = $this->get_defaultsetting();
2956 if (is_null($default)) {
2957 $default = array();
2958 }
2959 if (is_null($data)) {
d7933a55 2960 $data = array();
2961 }
220a90c5 2962
2963 $defaults = array();
4413941f 2964 $size = min(10, count($this->choices));
a7ad48fd 2965 $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 2966 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
220a90c5 2967 foreach ($this->choices as $key => $description) {
2968 if (in_array($key, $data)) {
2969 $selected = 'selected="selected"';
2970 } else {
2971 $selected = '';
2972 }
2973 if (in_array($key, $default)) {
2974 $defaults[] = $description;
6e4dc10f 2975 }
220a90c5 2976
2977 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2978 }
2979
587c7040 2980 if (is_null($default)) {
2981 $defaultinfo = NULL;
2982 } if (!empty($defaults)) {
2983 $defaultinfo = implode(', ', $defaults);
220a90c5 2984 } else {
587c7040 2985 $defaultinfo = get_string('none');
6e4dc10f 2986 }
eef868d1 2987
587c7040 2988 $return .= '</select></div>';
2989 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
6e4dc10f 2990 }
220a90c5 2991}
eef868d1 2992
220a90c5 2993/**
2994 * Time selector
db26acd4 2995 *
2996 * This is a liiitle bit messy. we're using two selects, but we're returning
220a90c5 2997 * them as an array named after $name (so we only use $name2 internally for the setting)
db26acd4 2998 *
2999 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 3000 */
3001class admin_setting_configtime extends admin_setting {
3e7069e7 3002 /** @var string Used for setting second select (minutes) */
73fa96d5 3003 public $name2;
220a90c5 3004
3005 /**
3006 * Constructor
3007 * @param string $hoursname setting for hours
3008 * @param string $minutesname setting for hours
3009 * @param string $visiblename localised
3010 * @param string $description long localised info
3011 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3012 */
73fa96d5 3013 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
220a90c5 3014 $this->name2 = $minutesname;
73fa96d5 3015 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
220a90c5 3016 }
3017
db26acd4 3018 /**
3019 * Get the selected time
0c079f19 3020 *
db26acd4 3021 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3022 */
73fa96d5 3023 public function get_setting() {
220a90c5 3024 $result1 = $this->config_read($this->name);
3025 $result2 = $this->config_read($this->name2);
3026 if (is_null($result1) or is_null($result2)) {
3027 return NULL;
3028 }
3029
3030 return array('h' => $result1, 'm' => $result2);
3031 }
3032
db26acd4 3033 /**
3034 * Store the time (hours and minutes)
0c079f19 3035 *
db26acd4 3036 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3037 * @return bool true if success, false if not
3038 */
73fa96d5 3039 public function write_setting($data) {
220a90c5 3040 if (!is_array($data)) {
3041 return '';
3042 }
3043
3044 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3045 return ($result ? '' : get_string('errorsetting', 'admin'));
3046 }
3047
db26acd4 3048 /**
3049 * Returns XHTML time select fields
3050 *
3051 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3052 * @param string $query
3053 * @return string XHTML time select fields and wrapping div(s)
3054 */
73fa96d5 3055 public function output_html($data, $query='') {
220a90c5 3056 $default = $this->get_defaultsetting();
3057
3058 if (is_array($default)) {
587c7040 3059 $defaultinfo = $default['h'].':'.$default['m'];
cc73de71 3060 } else {
587c7040 3061 $defaultinfo = NULL;
6e4dc10f 3062 }
220a90c5 3063
587c7040 3064 $return = '<div class="form-time defaultsnext">'.
9baf6825 3065 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
220a90c5 3066 for ($i = 0; $i < 24; $i++) {
3067 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
6e4dc10f 3068 }
220a90c5 3069 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
3070 for ($i = 0; $i < 60; $i += 5) {
3071 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3072 }
587c7040 3073 $return .= '</select></div>';
3074 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
6e4dc10f 3075 }
3076
3077}
3078
3e7069e7 3079
38257347
PS
3080/**
3081 * Seconds duration setting.
3082 *
3083 * @copyright 2012 Petr Skoda (http://skodak.org)
3084 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3085 */
3086class admin_setting_configduration extends admin_setting {
3087
3088 /** @var int default duration unit */
3089 protected $defaultunit;
3090
3091 /**
3092 * Constructor
3093 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3094 * or 'myplugin/mysetting' for ones in config_plugins.
3095 * @param string $visiblename localised name
3096 * @param string $description localised long description
3097 * @param mixed $defaultsetting string or array depending on implementation
3098 * @param int $defaultunit - day, week, etc. (in seconds)
3099 */
3100 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3101 if (is_number($defaultsetting)) {
3102 $defaultsetting = self::parse_seconds($defaultsetting);
3103 }
3104 $units = self::get_units();
3105 if (isset($units[$defaultunit])) {
3106 $this->defaultunit = $defaultunit;
3107 } else {
3108 $this->defaultunit = 86400;
3109 }
3110 parent::__construct($name, $visiblename, $description, $defaultsetting);
3111 }
3112
3113 /**
3114 * Returns selectable units.
3115 * @static
3116 * @return array
3117 */
3118 protected static function get_units() {
3119 return array(
3120 604800 => get_string('weeks'),
3121 86400 => get_string('days'),
3122 3600 => get_string('hours'),
3123 60 => get_string('minutes'),
3124 1 => get_string('seconds'),
3125 );
3126 }
3127
3128 /**
3129 * Converts seconds to some more user friendly string.
3130 * @static
3131 * @param int $seconds
3132 * @return string
3133 */
3134 protected static function get_duration_text($seconds) {
3135 if (empty($seconds)) {
3136 return get_string('none');
3137 }
3138 $data = self::parse_seconds($seconds);
3139 switch ($data['u']) {
444af7c6
EL
3140 case (60*60*24*7):
3141 return get_string('numweeks', '', $data['v']);
3142 case (60*60*24):
3143 return get_string('numdays', '', $data['v']);
3144 case (60*60):
3145 return get_string('numhours', '', $data['v']);
3146 case (60):
3147 return get_string('numminutes', '', $data['v']);
3148 default:
3149 return get_string('numseconds', '', $data['v']*$data['u']);
38257347
PS
3150 }
3151 }
3152
3153 /**
3154 * Finds suitable units for given duration.
3155 * @static
3156 * @param int $seconds
3157 * @return array
3158 */
3159 protected static function parse_seconds($seconds) {
444af7c6 3160 foreach (self::get_units() as $unit => $unused) {
38257347
PS
3161 if ($seconds % $unit === 0) {
3162 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3163 }
3164 }
3165 return array('v'=>(int)$seconds, 'u'=>1);
3166 }
3167
3168 /**
3169 * Get the selected duration as array.
3170 *
3171 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3172 */
3173 public function get_setting() {
3174 $seconds = $this->config_read($this->name);
3175 if (is_null($seconds)) {
3176 return null;
3177 }
3178
3179 return self::parse_seconds($seconds);
3180 }
3181
3182 /**
3183 * Store the duration as seconds.
3184 *
3185 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3186 * @return bool true if success, false if not
3187 */
3188 public function write_setting($data) {
3189 if (!is_array($data)) {
3190 return '';
3191 }
3192
3193 $seconds = (int)($data['v']*$data['u']);
3194 if ($seconds < 0) {
3195 return get_string('errorsetting', 'admin');
3196 }
3197
3198 $result = $this->config_write($this->name, $seconds);
3199 return ($result ? '' : get_string('errorsetting', 'admin'));
3200 }
3201
3202 /**
3203 * Returns duration text+select fields.
3204 *
3205 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3206 * @param string $query
3207 * @return string duration text+select fields and wrapping div(s)
3208 */
3209 public function output_html($data, $query='') {
3210 $default = $this->get_defaultsetting();
3211
3212 if (is_number($default)) {
3213 $defaultinfo = self::get_duration_text($default);
3214 } else if (is_array($default)) {
3215 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3216 } else {
3217 $defaultinfo = null;
3218 }
3219
3220 $units = self::get_units();
3221
3222 $return = '<div class="form-duration defaultsnext">';
3223 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3224 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
444af7c6 3225 foreach ($units as $val => $text) {
38257347
PS
3226 $selected = '';
3227 if ($data['v'] == 0) {
3228 if ($val == $this->defaultunit) {
3229 $selected = ' selected="selected"';
3230 }
3231 } else if ($val == $data['u']) {
3232 $selected = ' selected="selected"';
3233 }
3234 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3235 }
3236 $return .= '</select></div>';
3237 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3238 }
3239}
3240
3241
db26acd4 3242/**
3243 * Used to validate a textarea used for ip addresses
3244 *
3245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 3246 */
4e639121 3247class admin_setting_configiplist extends admin_setting_configtextarea {
db26acd4 3248
3e7069e7
PS
3249 /**
3250 * Validate the contents of the textarea as IP addresses
3251 *
3252 * Used to validate a new line separated list of IP addresses collected from
3253 * a textarea control
3254 *
3255 * @param string $data A list of IP Addresses separated by new lines
3256 * @return mixed bool true for success or string:error on failure
3257 */
73fa96d5 3258 public function validate($data) {
4e639121 3259 if(!empty($data)) {
c5d2d0dd 3260 $ips = explode("\n", $data);
4e639121 3261 } else {
3262 return true;
3263 }
3264 $result = true;
3265 foreach($ips as $ip) {
3266 $ip = trim($ip);
3e7069e7 3267 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
9baf6825 3268 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3269 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4e639121 3270 $result = true;
3271 } else {
3272 $result = false;
3273 break;
3274 }
3275 }
9baf6825 3276 if($result) {
4e639121 3277 return true;
3278 } else {
3279 return get_string('validateerror', 'admin');
3280 }
3281 }
3282}
3283
3e7069e7 3284
4413941f 3285/**
db26acd4 3286 * An admin setting for selecting one or more users who have a capability
3287 * in the system context
3288 *
4413941f 3289 * An admin setting for selecting one or more users, who have a particular capability
3290 * in the system context. Warning, make sure the list will never be too long. There is
3291 * no paging or searching of this list.
3292 *
3293 * To correctly get a list of users from this config setting, you need to call the
3294 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
db26acd4 3295 *
3296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4413941f 3297 */
3298class admin_setting_users_with_capability extends admin_setting_configmultiselect {
adf176d7 3299 /** @var string The capabilities name */
4413941f 3300 protected $capability;
adf176d7
PS
3301 /** @var int include admin users too */
3302 protected $includeadmins;
4413941f 3303
3304 /**
3305 * Constructor.
3306 *
3307 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3308 * @param string $visiblename localised name
3309 * @param string $description localised long description
3310 * @param array $defaultsetting array of usernames
3311 * @param string $capability string capability name.
875e5f07 3312 * @param bool $includeadmins include administrators
4413941f 3313 */
adf176d7
PS
3314 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3315 $this->capability = $capability;
3316 $this->includeadmins = $includeadmins;
fb073f60 3317 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3318 }
3319
db26acd4 3320 /**
3321 * Load all of the uses who have the capability into choice array
3322 *
3323 * @return bool Always returns true
3324 */
fb073f60 3325 function load_choices() {
3326 if (is_array($this->choices)) {
3327 return true;
3328 }
9695ff81
TH
3329 list($sort, $sortparams) = users_order_by_sql('u');
3330 if (!empty($sortparams)) {
3331 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3332 'This is unexpected, and a problem because there is no way to pass these ' .
3333 'parameters to get_users_by_capability. See MDL-34657.');
3334 }
4d83abd0
AG
3335 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3336 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
fb073f60 3337 $this->choices = array(
4413941f 3338 '$@NONE@$' => get_string('nobody'),
fb073f60 3339 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4413941f 3340 );
adf176d7
PS
3341 if ($this->includeadmins) {
3342 $admins = get_admins();
3343 foreach ($admins as $user) {
3344 $this->choices[$user->id] = fullname($user);
3345 }