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