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