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