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