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