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