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