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