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