weekly release
[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
cde44edc 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
cde44edc
PS
755 /** @var array fast lookup category cache, all categories of one tree point to one cache */
756 protected $category_cache;
757
6e4dc10f 758 /**
759 * Constructor for an empty admin category
760 *
761 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
762 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
db26acd4 763 * @param bool $hidden hide category in admin tree block, defaults to false
6e4dc10f 764 */
73fa96d5 765 public function __construct($name, $visiblename, $hidden=false) {
220a90c5 766 $this->children = array();
767 $this->name = $name;
6e4dc10f 768 $this->visiblename = $visiblename;
220a90c5 769 $this->hidden = $hidden;
6e4dc10f 770 }
eef868d1 771
6e4dc10f 772 /**
220a90c5 773 * Returns a reference to the part_of_admin_tree object with internal name $name.
6e4dc10f 774 *
220a90c5 775 * @param string $name The internal name of the object we want.
776 * @param bool $findpath initialize path and visiblepath arrays
0c079f19 777 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
db26acd4 778 * defaults to false
6e4dc10f 779 */
73fa96d5 780 public function locate($name, $findpath=false) {
cde44edc
PS
781 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
782 // somebody much have purged the cache
783 $this->category_cache[$this->name] = $this;
784 }
785
6e4dc10f 786 if ($this->name == $name) {
220a90c5 787 if ($findpath) {
788 $this->visiblepath[] = $this->visiblename;
789 $this->path[] = $this->name;
790 }
791 return $this;
6e4dc10f 792 }
eef868d1 793
cde44edc
PS
794 // quick category lookup
795 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
796 return $this->category_cache[$name];
797 }
798
220a90c5 799 $return = NULL;
800 foreach($this->children as $childid=>$unused) {
73fa96d5 801 if ($return = $this->children[$childid]->locate($name, $findpath)) {
220a90c5 802 break;
6e4dc10f 803 }
804 }
eef868d1 805
220a90c5 806 if (!is_null($return) and $findpath) {
807 $return->visiblepath[] = $this->visiblename;
808 $return->path[] = $this->name;
809 }
eef868d1 810
220a90c5 811 return $return;
6e4dc10f 812 }
813
814 /**
220a90c5 815 * Search using query
db26acd4 816 *
817 * @param string query
220a90c5 818 * @return mixed array-object structure of found settings and pages
6e4dc10f 819 */
73fa96d5 820 public function search($query) {
220a90c5 821 $result = array();
822 foreach ($this->children as $child) {
3cea9c55 823 $subsearch = $child->search($query);
824 if (!is_array($subsearch)) {
825 debugging('Incorrect search result from '.$child->name);
826 continue;
827 }
828 $result = array_merge($result, $subsearch);
6e4dc10f 829 }
220a90c5 830 return $result;
6e4dc10f 831 }
832
4672d955 833 /**
834 * Removes part_of_admin_tree object with internal name $name.
835 *
836 * @param string $name The internal name of the object we want to remove.
a8a66c96 837 * @return bool success
4672d955 838 */
73fa96d5 839 public function prune($name) {
4672d955 840
841 if ($this->name == $name) {
842 return false; //can not remove itself
843 }
844
845 foreach($this->children as $precedence => $child) {
846 if ($child->name == $name) {
cde44edc
PS
847 // clear cache and delete self
848 if (is_array($this->category_cache)) {
849 while($this->category_cache) {
850 // delete the cache, but keep the original array address
851 array_pop($this->category_cache);
852 }
853 }
eef868d1 854 unset($this->children[$precedence]);
4672d955 855 return true;
cde44edc 856 } else if ($this->children[$precedence]->prune($name)) {
4672d955 857 return true;
858 }
859 }
860 return false;
861 }
862
6e4dc10f 863 /**
864 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
865 *
220a90c5 866 * @param string $destinationame The internal name of the immediate parent that we want for $something.
875e5f07 867 * @param mixed $something A part_of_admin_tree or setting instance to be added.
220a90c5 868 * @return bool True if successfully added, false if $something can not be added.
6e4dc10f 869 */
73fa96d5 870 public function add($parentname, $something) {
871 $parent = $this->locate($parentname);
220a90c5 872 if (is_null($parent)) {
873 debugging('parent does not exist!');
6e4dc10f 874 return false;
875 }
876
73fa96d5 877 if ($something instanceof part_of_admin_tree) {
878 if (!($parent instanceof parentable_part_of_admin_tree)) {
220a90c5 879 debugging('error - parts of tree can be inserted only into parentable parts');
880 return false;
6e4dc10f 881 }
220a90c5 882 $parent->children[] = $something;
cde44edc
PS
883 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
884 if (isset($this->category_cache[$something->name])) {
885 debugging('Duplicate admin catefory name: '.$something->name);
886 } else {
887 $this->category_cache[$something->name] = $something;
888 $something->category_cache =& $this->category_cache;
889 foreach ($something->children as $child) {
890 // just in case somebody already added subcategories
891 if ($child instanceof admin_category) {
892 if (isset($this->category_cache[$child->name])) {
893 debugging('Duplicate admin catefory name: '.$child->name);
894 } else {
895 $this->category_cache[$child->name] = $child;
896 $child->category_cache =& $this->category_cache;
897 }
898 }
899 }
900 }
901 }
6e4dc10f 902 return true;
eef868d1 903
220a90c5 904 } else {
905 debugging('error - can not add this element');
906 return false;
6e4dc10f 907 }
eef868d1 908
6e4dc10f 909 }
eef868d1 910
6e4dc10f 911 /**
912 * Checks if the user has access to anything in this category.
913 *
875e5f07 914 * @return bool True if the user has access to at least one child in this category, false otherwise.
6e4dc10f 915 */
73fa96d5 916 public function check_access() {
6e4dc10f 917 foreach ($this->children as $child) {
220a90c5 918 if ($child->check_access()) {
919 return true;
920 }
6e4dc10f 921 }
220a90c5 922 return false;
6e4dc10f 923 }
eef868d1 924
a8a66c96 925 /**
926 * Is this category hidden in admin tree block?
927 *
928 * @return bool True if hidden
929 */
73fa96d5 930 public function is_hidden() {
a8a66c96 931 return $this->hidden;
932 }
427649bf
PS
933
934 /**
935 * Show we display Save button at the page bottom?
936 * @return bool
937 */
938 public function show_save() {
939 foreach ($this->children as $child) {
940 if ($child->show_save()) {
941 return true;
942 }
943 }
944 return false;
945 }
6e4dc10f 946}
947
db26acd4 948/**
0c079f19 949 * Root of admin settings tree, does not have any parent.
db26acd4 950 *
951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 952 */
220a90c5 953class admin_root extends admin_category {
9baf6825 954/** @var array List of errors */
73fa96d5 955 public $errors;
0c079f19 956 /** @var string search query */
73fa96d5 957 public $search;
875e5f07 958 /** @var bool full tree flag - true means all settings required, false only pages required */
73fa96d5 959 public $fulltree;
0c079f19 960 /** @var bool flag indicating loaded tree */
73fa96d5 961 public $loaded;
875e5f07 962 /** @var mixed site custom defaults overriding defaults in settings files*/
cd3acbf2 963 public $custom_defaults;
964
db26acd4 965 /**
0c079f19 966 * @param bool $fulltree true means all settings required,
db26acd4 967 * false only pages required
968 */
73fa96d5 969 public function __construct($fulltree) {
cd3acbf2 970 global $CFG;
971
73fa96d5 972 parent::__construct('root', get_string('administration'), false);
220a90c5 973 $this->errors = array();
974 $this->search = '';
73fa96d5 975 $this->fulltree = $fulltree;
976 $this->loaded = false;
cd3acbf2 977
cde44edc
PS
978 $this->category_cache = array();
979
cd3acbf2 980 // load custom defaults if found
981 $this->custom_defaults = null;
982 $defaultsfile = "$CFG->dirroot/local/defaults.php";
983 if (is_readable($defaultsfile)) {
984 $defaults = array();
985 include($defaultsfile);
986 if (is_array($defaults) and count($defaults)) {
987 $this->custom_defaults = $defaults;
988 }
989 }
73fa96d5 990 }
991
db26acd4 992 /**
993 * Empties children array, and sets loaded to false
994 *
995 * @param bool $requirefulltree
996 */
73fa96d5 997 public function purge_children($requirefulltree) {
998 $this->children = array();
999 $this->fulltree = ($requirefulltree || $this->fulltree);
1000 $this->loaded = false;
cde44edc
PS
1001 //break circular dependencies - this helps PHP 5.2
1002 while($this->category_cache) {
1003 array_pop($this->category_cache);
1004 }
1005 $this->category_cache = array();
220a90c5 1006 }
1007}
1008
6e4dc10f 1009/**
1010 * Links external PHP pages into the admin tree.
1011 *
1012 * See detailed usage example at the top of this document (adminlib.php)
1013 *
db26acd4 1014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 1015 */
73fa96d5 1016class admin_externalpage implements part_of_admin_tree {
6e4dc10f 1017
9baf6825 1018/** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
73fa96d5 1019 public $name;
eef868d1 1020
0c079f19 1021 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
73fa96d5 1022 public $visiblename;
eef868d1 1023
0c079f19 1024 /** @var string The external URL that we should link to when someone requests this external page. */
73fa96d5 1025 public $url;
eef868d1 1026
0c079f19 1027 /** @var string The role capability/permission a user must have to access this external page. */
73fa96d5 1028 public $req_capability;
eef868d1 1029
0c079f19 1030 /** @var object The context in which capability/permission should be checked, default is site context. */
73fa96d5 1031 public $context;
84c8ede0 1032
0c079f19 1033 /** @var bool hidden in admin tree block. */
73fa96d5 1034 public $hidden;
a8a66c96 1035
0c079f19 1036 /** @var mixed either string or array of string */
73fa96d5 1037 public $path;
1038 public $visiblepath;
220a90c5 1039
6e4dc10f 1040 /**
1041 * Constructor for adding an external page into the admin tree.
1042 *
1043 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1044 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1045 * @param string $url The external URL that we should link to when someone requests this external page.
38d2d43b 1046 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
92f00846 1047 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
44d8a940 1048 * @param stdClass $context The context the page relates to. Not sure what happens
92f00846 1049 * if you specify something other than system or front page. Defaults to system.
6e4dc10f 1050 */
73fa96d5 1051 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
220a90c5 1052 $this->name = $name;
6e4dc10f 1053 $this->visiblename = $visiblename;
220a90c5 1054 $this->url = $url;
38d2d43b 1055 if (is_array($req_capability)) {
1056 $this->req_capability = $req_capability;
1057 } else {
1058 $this->req_capability = array($req_capability);
1059 }
92f00846 1060 $this->hidden = $hidden;
84c8ede0 1061 $this->context = $context;
6e4dc10f 1062 }
eef868d1 1063
6e4dc10f 1064 /**
1065 * Returns a reference to the part_of_admin_tree object with internal name $name.
1066 *
1067 * @param string $name The internal name of the object we want.
db26acd4 1068 * @param bool $findpath defaults to false
6e4dc10f 1069 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1070 */
73fa96d5 1071 public function locate($name, $findpath=false) {
220a90c5 1072 if ($this->name == $name) {
1073 if ($findpath) {
1074 $this->visiblepath = array($this->visiblename);
1075 $this->path = array($this->name);
1076 }
1077 return $this;
1078 } else {
1079 $return = NULL;
1080 return $return;
1081 }
6e4dc10f 1082 }
4672d955 1083
db26acd4 1084 /**
1085 * This function always returns false, required function by interface
1086 *
1087 * @param string $name
1088 * @return false
1089 */
73fa96d5 1090 public function prune($name) {
4672d955 1091 return false;
1092 }
1093
220a90c5 1094 /**
1095 * Search using query
db26acd4 1096 *
1097 * @param string $query
220a90c5 1098 * @return mixed array-object structure of found settings and pages
1099 */
73fa96d5 1100 public function search($query) {
220a90c5 1101 $textlib = textlib_get_instance();
1102
1103 $found = false;
1104 if (strpos(strtolower($this->name), $query) !== false) {
1105 $found = true;
1106 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
9baf6825 1107 $found = true;
1108 }
220a90c5 1109 if ($found) {
365a5941 1110 $result = new stdClass();
220a90c5 1111 $result->page = $this;
1112 $result->settings = array();
1113 return array($this->name => $result);
1114 } else {
1115 return array();
1116 }
1117 }
1118
6e4dc10f 1119 /**
2ce38b70 1120 * Determines if the current user has access to this external page based on $this->req_capability.
db26acd4 1121 *
6e4dc10f 1122 * @return bool True if user has access, false otherwise.
1123 */
73fa96d5 1124 public function check_access() {
1caea91e 1125 global $CFG;
84c8ede0 1126 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
38d2d43b 1127 foreach($this->req_capability as $cap) {
4f0c2d00 1128 if (has_capability($cap, $context)) {
38d2d43b 1129 return true;
1130 }
1131 }
1132 return false;
6e4dc10f 1133 }
1134
a8a66c96 1135 /**
1136 * Is this external page hidden in admin tree block?
1137 *
1138 * @return bool True if hidden
1139 */
73fa96d5 1140 public function is_hidden() {
a8a66c96 1141 return $this->hidden;
1142 }
1143
427649bf
PS
1144 /**
1145 * Show we display Save button at the page bottom?
1146 * @return bool
1147 */
1148 public function show_save() {
1149 return false;
1150 }
6e4dc10f 1151}
1152
1153/**
1154 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1155 *
db26acd4 1156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6e4dc10f 1157 */
73fa96d5 1158class admin_settingpage implements part_of_admin_tree {
6e4dc10f 1159
9baf6825 1160/** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
73fa96d5 1161 public $name;
eef868d1 1162
0c079f19 1163 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
73fa96d5 1164 public $visiblename;
0c079f19 1165
1166 /** @var mixed An array of admin_setting objects that are part of this setting page. */
73fa96d5 1167 public $settings;
eef868d1 1168
0c079f19 1169 /** @var string The role capability/permission a user must have to access this external page. */
73fa96d5 1170 public $req_capability;
eef868d1 1171
0c079f19 1172 /** @var object The context in which capability/permission should be checked, default is site context. */
73fa96d5 1173 public $context;
84c8ede0 1174
0c079f19 1175 /** @var bool hidden in admin tree block. */
73fa96d5 1176 public $hidden;
a8a66c96 1177
0c079f19 1178 /** @var mixed string of paths or array of strings of paths */
73fa96d5 1179 public $path;
1180 public $visiblepath;
220a90c5 1181
db26acd4 1182 /**
1183 * see admin_settingpage for details of this function
0c079f19 1184 *
db26acd4 1185 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1186 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1187 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1188 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
44d8a940 1189 * @param stdClass $context The context the page relates to. Not sure what happens
db26acd4 1190 * if you specify something other than system or front page. Defaults to system.
1191 */
73fa96d5 1192 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
365a5941 1193 $this->settings = new stdClass();
220a90c5 1194 $this->name = $name;
1195 $this->visiblename = $visiblename;
1196 if (is_array($req_capability)) {
1197 $this->req_capability = $req_capability;
6e4dc10f 1198 } else {
220a90c5 1199 $this->req_capability = array($req_capability);
6e4dc10f 1200 }
220a90c5 1201 $this->hidden = $hidden;
1202 $this->context = $context;
6e4dc10f 1203 }
eef868d1 1204
0c079f19 1205 /**
db26acd4 1206 * see admin_category
1207 *
1208 * @param string $name
1209 * @param bool $findpath
1210 * @return mixed Object (this) if name == this->name, else returns null
1211 */
73fa96d5 1212 public function locate($name, $findpath=false) {
220a90c5 1213 if ($this->name == $name) {
1214 if ($findpath) {
1215 $this->visiblepath = array($this->visiblename);
1216 $this->path = array($this->name);
1217 }
1218 return $this;
1219 } else {
1220 $return = NULL;
1221 return $return;
1222 }
6e4dc10f 1223 }
4672d955 1224
0c079f19 1225 /**
1226 * Search string in settings page.
1227 *
db26acd4 1228 * @param string $query
1229 * @return array
1230 */
73fa96d5 1231 public function search($query) {
220a90c5 1232 $found = array();
4672d955 1233
220a90c5 1234 foreach ($this->settings as $setting) {
1235 if ($setting->is_related($query)) {
1236 $found[] = $setting;
1237 }
1238 }
1239
1240 if ($found) {
365a5941 1241 $result = new stdClass();
220a90c5 1242 $result->page = $this;
1243 $result->settings = $found;
1244 return array($this->name => $result);
1245 }
1246
1247 $textlib = textlib_get_instance();
1248
1249 $found = false;
1250 if (strpos(strtolower($this->name), $query) !== false) {
1251 $found = true;
1252 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
9baf6825 1253 $found = true;
1254 }
220a90c5 1255 if ($found) {
365a5941 1256 $result = new stdClass();
220a90c5 1257 $result->page = $this;
1258 $result->settings = array();
1259 return array($this->name => $result);
38d2d43b 1260 } else {
220a90c5 1261 return array();
38d2d43b 1262 }
6e4dc10f 1263 }
eef868d1 1264
db26acd4 1265 /**
1266 * This function always returns false, required by interface
1267 *
1268 * @param string $name
1269 * @return bool Always false
1270 */
73fa96d5 1271 public function prune($name) {
6e4dc10f 1272 return false;
1273 }
eef868d1 1274
220a90c5 1275 /**
db26acd4 1276 * adds an admin_setting to this admin_settingpage
1277 *
220a90c5 1278 * 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
1279 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
db26acd4 1280 *
220a90c5 1281 * @param object $setting is the admin_setting object you want to add
db26acd4 1282 * @return bool true if successful, false if not
220a90c5 1283 */
73fa96d5 1284 public function add($setting) {
1285 if (!($setting instanceof admin_setting)) {
220a90c5 1286 debugging('error - not a setting instance');
1287 return false;
1288 }
1289
1290 $this->settings->{$setting->name} = $setting;
1291 return true;
1292 }
1293
db26acd4 1294 /**
1295 * see admin_externalpage
1296 *
1297 * @return bool Returns true for yes false for no
1298 */
73fa96d5 1299 public function check_access() {
1caea91e 1300 global $CFG;
84c8ede0 1301 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
38d2d43b 1302 foreach($this->req_capability as $cap) {
4f0c2d00 1303 if (has_capability($cap, $context)) {
38d2d43b 1304 return true;
1305 }
1306 }
1307 return false;
6e4dc10f 1308 }
eef868d1 1309
220a90c5 1310 /**
1311 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
db26acd4 1312 * @return string Returns an XHTML string
220a90c5 1313 */
73fa96d5 1314 public function output_html() {
1315 $adminroot = admin_get_root();
220a90c5 1316 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
6e4dc10f 1317 foreach($this->settings as $setting) {
220a90c5 1318 $fullname = $setting->get_full_name();
1319 if (array_key_exists($fullname, $adminroot->errors)) {
1320 $data = $adminroot->errors[$fullname]->data;
6e4dc10f 1321 } else {
220a90c5 1322 $data = $setting->get_setting();
79698344 1323 // do not use defaults if settings not available - upgrade settings handles the defaults!
6e4dc10f 1324 }
220a90c5 1325 $return .= $setting->output_html($data);
6e4dc10f 1326 }
220a90c5 1327 $return .= '</fieldset>';
6e4dc10f 1328 return $return;
1329 }
1330
a8a66c96 1331 /**
875e5f07 1332 * Is this settings page hidden in admin tree block?
a8a66c96 1333 *
1334 * @return bool True if hidden
1335 */
73fa96d5 1336 public function is_hidden() {
a8a66c96 1337 return $this->hidden;
1338 }
1339
427649bf
PS
1340 /**
1341 * Show we display Save button at the page bottom?
1342 * @return bool
1343 */
1344 public function show_save() {
1345 foreach($this->settings as $setting) {
1346 if (empty($setting->nosave)) {
1347 return true;
1348 }
1349 }
1350 return false;
1351 }
6e4dc10f 1352}
1353
1354
220a90c5 1355/**
1356 * Admin settings class. Only exists on setting pages.
1357 * Read & write happens at this level; no authentication.
db26acd4 1358 *
1359 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1360 */
301bf0b2 1361abstract class admin_setting {
9baf6825 1362/** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
73fa96d5 1363 public $name;
0c079f19 1364 /** @var string localised name */
73fa96d5 1365 public $visiblename;
3fa37159 1366 /** @var string localised long description in Markdown format */
73fa96d5 1367 public $description;
0c079f19 1368 /** @var mixed Can be string or array of string */
73fa96d5 1369 public $defaultsetting;
0c079f19 1370 /** @var string */
73fa96d5 1371 public $updatedcallback;
0c079f19 1372 /** @var mixed can be String or Null. Null means main config table */
73fa96d5 1373 public $plugin; // null means main config table
427649bf
PS
1374 /** @var bool true indicates this setting does not actually save anything, just information */
1375 public $nosave = false;
6e4dc10f 1376
220a90c5 1377 /**
1378 * Constructor
0c079f19 1379 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
db26acd4 1380 * or 'myplugin/mysetting' for ones in config_plugins.
1a41e806 1381 * @param string $visiblename localised name
1382 * @param string $description localised long description
220a90c5 1383 * @param mixed $defaultsetting string or array depending on implementation
1384 */
73fa96d5 1385 public function __construct($name, $visiblename, $description, $defaultsetting) {
7fb0303d 1386 $this->parse_setting_name($name);
220a90c5 1387 $this->visiblename = $visiblename;
8dbe233a 1388 $this->description = $description;
6e4dc10f 1389 $this->defaultsetting = $defaultsetting;
1390 }
eef868d1 1391
7fb0303d 1392 /**
db26acd4 1393 * Set up $this->name and potentially $this->plugin
1394 *
7fb0303d 1395 * Set up $this->name and possibly $this->plugin based on whether $name looks
1396 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1397 * on the names, that is, output a developer debug warning if the name
1398 * contains anything other than [a-zA-Z0-9_]+.
1399 *
1400 * @param string $name the setting name passed in to the constructor.
1401 */
1402 private function parse_setting_name($name) {
1403 $bits = explode('/', $name);
1404 if (count($bits) > 2) {
1405 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1406 }
1407 $this->name = array_pop($bits);
1408 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1409 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1410 }
1411 if (!empty($bits)) {
1412 $this->plugin = array_pop($bits);
cd3acbf2 1413 if ($this->plugin === 'moodle') {
1414 $this->plugin = null;
1415 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
9baf6825 1416 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1417 }
7fb0303d 1418 }
1419 }
1420
db26acd4 1421 /**
1422 * Returns the fullname prefixed by the plugin
1423 * @return string
1424 */
73fa96d5 1425 public function get_full_name() {
220a90c5 1426 return 's_'.$this->plugin.'_'.$this->name;
1427 }
1428
db26acd4 1429 /**
1430 * Returns the ID string based on plugin and name
1431 * @return string
1432 */
73fa96d5 1433 public function get_id() {
220a90c5 1434 return 'id_s_'.$this->plugin.'_'.$this->name;
1435 }
1436
db26acd4 1437 /**
1438 * Returns the config if possible
1439 *
db26acd4 1440 * @return mixed returns config if successfull else null
1441 */
73fa96d5 1442 public function config_read($name) {
220a90c5 1443 global $CFG;
eb6a973c 1444 if (!empty($this->plugin)) {
220a90c5 1445 $value = get_config($this->plugin, $name);
1446 return $value === false ? NULL : $value;
1447
1448 } else {
1449 if (isset($CFG->$name)) {
1450 return $CFG->$name;
1451 } else {
1452 return NULL;
1453 }
1454 }
1455 }
1456
301bf0b2 1457 /**
db26acd4 1458 * Used to set a config pair and log change
301bf0b2 1459 *
db26acd4 1460 * @param string $name
1461 * @param mixed $value Gets converted to string if not null
875e5f07 1462 * @return bool Write setting to config table
301bf0b2 1463 */
73fa96d5 1464 public function config_write($name, $value) {
301bf0b2 1465 global $DB, $USER, $CFG;
1466
427649bf
PS
1467 if ($this->nosave) {
1468 return true;
1469 }
1470
301bf0b2 1471 // make sure it is a real change
1472 $oldvalue = get_config($this->plugin, $name);
1473 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1474 $value = is_null($value) ? null : (string)$value;
1475
1476 if ($oldvalue === $value) {
1477 return true;
1478 }
1479
1480 // store change
1481 set_config($name, $value, $this->plugin);
1482
301bf0b2 1483 // log change
365a5941 1484 $log = new stdClass();
31a99877 1485 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
301bf0b2 1486 $log->timemodified = time();
1487 $log->plugin = $this->plugin;
1488 $log->name = $name;
1489 $log->value = $value;
1490 $log->oldvalue = $oldvalue;
1491 $DB->insert_record('config_log', $log);
1492
1493 return true; // BC only
220a90c5 1494 }
1495
1496 /**
1497 * Returns current value of this setting
1498 * @return mixed array or string depending on instance, NULL means not set yet
1499 */
301bf0b2 1500 public abstract function get_setting();
eef868d1 1501
220a90c5 1502 /**
1503 * Returns default setting if exists
1504 * @return mixed array or string depending on instance; NULL means no default, user must supply
1505 */
73fa96d5 1506 public function get_defaultsetting() {
cd3acbf2 1507 $adminroot = admin_get_root(false, false);
1508 if (!empty($adminroot->custom_defaults)) {
1509 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1510 if (isset($adminroot->custom_defaults[$plugin])) {
875e5f07 1511 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
cd3acbf2 1512 return $adminroot->custom_defaults[$plugin][$this->name];
1513 }
1514 }
1515 }
8e5da17a 1516 return $this->defaultsetting;
1517 }
1518
220a90c5 1519 /**
1520 * Store new setting
db26acd4 1521 *
1522 * @param mixed $data string or array, must not be NULL
1523 * @return string empty string if ok, string error message otherwise
220a90c5 1524 */
301bf0b2 1525 public abstract function write_setting($data);
eef868d1 1526
220a90c5 1527 /**
1528 * Return part of form with setting
db26acd4 1529 * This function should always be overwritten
1530 *
1531 * @param mixed $data array or string depending on setting
1532 * @param string $query
220a90c5 1533 * @return string
1534 */
73fa96d5 1535 public function output_html($data, $query='') {
9baf6825 1536 // should be overridden
220a90c5 1537 return;
1538 }
1539
1540 /**
db26acd4 1541 * Function called if setting updated - cleanup, cache reset, etc.
1542 * @param string $functionname Sets the function name
220a90c5 1543 */
73fa96d5 1544 public function set_updatedcallback($functionname) {
220a90c5 1545 $this->updatedcallback = $functionname;
1546 }
1547
1548 /**
1549 * Is setting related to query text - used when searching
1550 * @param string $query
1551 * @return bool
1552 */
73fa96d5 1553 public function is_related($query) {
220a90c5 1554 if (strpos(strtolower($this->name), $query) !== false) {
1555 return true;
1556 }
1557 $textlib = textlib_get_instance();
1558 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1559 return true;
1560 }
1561 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1562 return true;
1563 }
587c7040 1564 $current = $this->get_setting();
1565 if (!is_null($current)) {
1566 if (is_string($current)) {
1567 if (strpos($textlib->strtolower($current), $query) !== false) {
1568 return true;
1569 }
1570 }
1571 }
1572 $default = $this->get_defaultsetting();
1573 if (!is_null($default)) {
1574 if (is_string($default)) {
1575 if (strpos($textlib->strtolower($default), $query) !== false) {
1576 return true;
1577 }
1578 }
1579 }
220a90c5 1580 return false;
6e4dc10f 1581 }
220a90c5 1582}
eef868d1 1583
220a90c5 1584/**
1585 * No setting - just heading and text.
db26acd4 1586 *
1587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1588 */
1589class admin_setting_heading extends admin_setting {
9baf6825 1590/**
1591 * not a setting, just text
1592 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1593 * @param string $heading heading
1594 * @param string $information text in box
1595 */
73fa96d5 1596 public function __construct($name, $heading, $information) {
427649bf 1597 $this->nosave = true;
73fa96d5 1598 parent::__construct($name, $heading, $information, '');
220a90c5 1599 }
1600
db26acd4 1601 /**
1602 * Always returns true
1603 * @return bool Always returns true
1604 */
73fa96d5 1605 public function get_setting() {
220a90c5 1606 return true;
1607 }
1608
db26acd4 1609 /**
1610 * Always returns true
1611 * @return bool Always returns true
1612 */
73fa96d5 1613 public function get_defaultsetting() {
220a90c5 1614 return true;
1615 }
1616
db26acd4 1617 /**
1618 * Never write settings
1619 * @return string Always returns an empty string
1620 */
73fa96d5 1621 public function write_setting($data) {
9baf6825 1622 // do not write any setting
220a90c5 1623 return '';
1624 }
0c079f19 1625
db26acd4 1626 /**
1627 * Returns an HTML string
1628 * @return string Returns an HTML string
1629 */
73fa96d5 1630 public function output_html($data, $query='') {
3c159385 1631 global $OUTPUT;
220a90c5 1632 $return = '';
1633 if ($this->visiblename != '') {
206dd861 1634 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
220a90c5 1635 }
1636 if ($this->description != '') {
8dbe233a 1637 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
220a90c5 1638 }
1639 return $return;
1640 }
1641}
6e4dc10f 1642
220a90c5 1643/**
1644 * The most flexibly setting, user is typing text
db26acd4 1645 *
1646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1647 */
6e4dc10f 1648class admin_setting_configtext extends admin_setting {
1649
9baf6825 1650/** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
73fa96d5 1651 public $paramtype;
0c079f19 1652 /** @var int default field size */
73fa96d5 1653 public $size;
6e4dc10f 1654
220a90c5 1655 /**
875e5f07 1656 * Config text constructor
db26acd4 1657 *
1a41e806 1658 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 1659 * @param string $visiblename localised
1660 * @param string $description long localised info
1661 * @param string $defaultsetting
1662 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
f7633b0f 1663 * @param int $size default field size
220a90c5 1664 */
73fa96d5 1665 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
6e4dc10f 1666 $this->paramtype = $paramtype;
f7633b0f 1667 if (!is_null($size)) {
1668 $this->size = $size;
1669 } else {
40ea93a4 1670 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
f7633b0f 1671 }
73fa96d5 1672 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 1673 }
1674
db26acd4 1675 /**
1676 * Return the setting
1677 *
875e5f07 1678 * @return mixed returns config if successful else null
db26acd4 1679 */
73fa96d5 1680 public function get_setting() {
220a90c5 1681 return $this->config_read($this->name);
6e4dc10f 1682 }
eef868d1 1683
73fa96d5 1684 public function write_setting($data) {
8cad6cca 1685 if ($this->paramtype === PARAM_INT and $data === '') {
9baf6825 1686 // do not complain if '' used instead of 0
8cad6cca 1687 $data = 0;
1688 }
220a90c5 1689 // $data is a string
c5d2d0dd 1690 $validated = $this->validate($data);
e33fbf87 1691 if ($validated !== true) {
1692 return $validated;
c235598d 1693 }
220a90c5 1694 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 1695 }
1696
e33fbf87 1697 /**
1698 * Validate data before storage
1699 * @param string data
1700 * @return mixed true if ok string if error found
1701 */
73fa96d5 1702 public function validate($data) {
58aaa8e9 1703 // allow paramtype to be a custom regex if it is the form of /pattern/
1704 if (preg_match('#^/.*/$#', $this->paramtype)) {
e33fbf87 1705 if (preg_match($this->paramtype, $data)) {
1706 return true;
1707 } else {
1708 return get_string('validateerror', 'admin');
1709 }
1710
9e24fbd1 1711 } else if ($this->paramtype === PARAM_RAW) {
4ea56b3f 1712 return true;
9baf6825 1713
4ea56b3f 1714 } else {
1715 $cleaned = clean_param($data, $this->paramtype);
40ea93a4 1716 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
4ea56b3f 1717 return true;
e33fbf87 1718 } else {
4ea56b3f 1719 return get_string('validateerror', 'admin');
e33fbf87 1720 }
4ea56b3f 1721 }
c235598d 1722 }
1723
db26acd4 1724 /**
1725 * Return an XHTML string for the setting
1726 * @return string Returns an XHTML string
1727 */
73fa96d5 1728 public function output_html($data, $query='') {
220a90c5 1729 $default = $this->get_defaultsetting();
1730
220a90c5 1731 return format_admin_setting($this, $this->visiblename,
9baf6825 1732 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1733 $this->description, true, '', $default, $query);
6e4dc10f 1734 }
6e4dc10f 1735}
1736
220a90c5 1737/**
1738 * General text area without html editor.
db26acd4 1739 *
1740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1741 */
1742class admin_setting_configtextarea extends admin_setting_configtext {
4fe2250a 1743 private $rows;
1744 private $cols;
eba8cd63 1745
db26acd4 1746 /**
1747 * @param string $name
1748 * @param string $visiblename
1749 * @param string $description
1750 * @param mixed $defaultsetting string or array
1751 * @param mixed $paramtype
1752 * @param string $cols The number of columns to make the editor
1753 * @param string $rows The number of rows to make the editor
1754 */
73fa96d5 1755 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
220a90c5 1756 $this->rows = $rows;
1757 $this->cols = $cols;
73fa96d5 1758 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
eba8cd63 1759 }
db26acd4 1760 /**
1761 * Returns an XHTML string for the editor
1762 *
1763 * @param string $data
1764 * @param string $query
1765 * @return string XHTML string for the editor
1766 */
73fa96d5 1767 public function output_html($data, $query='') {
220a90c5 1768 $default = $this->get_defaultsetting();
1769
587c7040 1770 $defaultinfo = $default;
1771 if (!is_null($default) and $default !== '') {
1772 $defaultinfo = "\n".$default;
c5d2d0dd 1773 }
220a90c5 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);
4fe2250a 1778 }
1779}
1780
1781/**
1782 * General text area with html editor.
1783 */
1784class admin_setting_confightmleditor extends admin_setting_configtext {
1785 private $rows;
1786 private $cols;
0c079f19 1787
4fe2250a 1788 /**
1789 * @param string $name
1790 * @param string $visiblename
1791 * @param string $description
1792 * @param mixed $defaultsetting string or array
1793 * @param mixed $paramtype
1794 */
1795 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1796 $this->rows = $rows;
1797 $this->cols = $cols;
1798 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
ff5fe311 1799 editors_head_setup();
4fe2250a 1800 }
1801 /**
1802 * Returns an XHTML string for the editor
1803 *
1804 * @param string $data
1805 * @param string $query
1806 * @return string XHTML string for the editor
1807 */
1808 public function output_html($data, $query='') {
1809 $default = $this->get_defaultsetting();
1810
1811 $defaultinfo = $default;
1812 if (!is_null($default) and $default !== '') {
1813 $defaultinfo = "\n".$default;
1814 }
1815
20e5da7d 1816 $editor = editors_get_preferred_editor(FORMAT_HTML);
69429650 1817 $editor->use_editor($this->get_id(), array('noclean'=>true));
4fe2250a 1818
1819 return format_admin_setting($this, $this->visiblename,
9baf6825 1820 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1821 $this->description, true, '', $defaultinfo, $query);
220a90c5 1822 }
1823}
1824
1825/**
1826 * Password field, allows unmasking of password
db26acd4 1827 *
1828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1829 */
1830class admin_setting_configpasswordunmask extends admin_setting_configtext {
9baf6825 1831/**
1832 * Constructor
1833 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1834 * @param string $visiblename localised
1835 * @param string $description long localised info
1836 * @param string $defaultsetting default password
1837 */
73fa96d5 1838 public function __construct($name, $visiblename, $description, $defaultsetting) {
1839 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
220a90c5 1840 }
0c079f19 1841
db26acd4 1842 /**
1843 * Returns XHTML for the field
1844 * Writes Javascript into the HTML below right before the last div
1845 *
1846 * @todo Make javascript available through newer methods if possible
1847 * @param string $data Value for the field
1848 * @param string $query Passed as final argument for format_admin_setting
1849 * @return string XHTML field
1850 */
73fa96d5 1851 public function output_html($data, $query='') {
220a90c5 1852 $id = $this->get_id();
1853 $unmask = get_string('unmaskpassword', 'form');
1854 $unmaskjs = '<script type="text/javascript">
eba8cd63 1855//<![CDATA[
633239f6 1856var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1857
1858document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1859
1860var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1861
1862var unmaskchb = document.createElement("input");
1863unmaskchb.setAttribute("type", "checkbox");
1864unmaskchb.setAttribute("id", "'.$id.'unmask");
1865unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1866unmaskdiv.appendChild(unmaskchb);
1867
1868var unmasklbl = document.createElement("label");
1869unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1870if (is_ie) {
1871 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1872} else {
1873 unmasklbl.setAttribute("for", "'.$id.'unmask");
1874}
1875unmaskdiv.appendChild(unmasklbl);
1876
1877if (is_ie) {
1878 // ugly hack to work around the famous onchange IE bug
1879 unmaskchb.onclick = function() {this.blur();};
1880 unmaskdiv.onclick = function() {this.blur();};
1881}
eba8cd63 1882//]]>
1883</script>';
220a90c5 1884 return format_admin_setting($this, $this->visiblename,
9baf6825 1885 '<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>',
1886 $this->description, true, '', NULL, $query);
220a90c5 1887 }
1888}
1889
1890/**
e9c0fa35 1891 * Path to directory
db26acd4 1892 *
1893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1894 */
e9c0fa35 1895class admin_setting_configfile extends admin_setting_configtext {
9baf6825 1896/**
1897 * Constructor
1898 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1899 * @param string $visiblename localised
1900 * @param string $description long localised info
1901 * @param string $defaultdirectory default directory location
1902 */
73fa96d5 1903 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1904 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
220a90c5 1905 }
1906
db26acd4 1907 /**
1908 * Returns XHTML for the field
0c079f19 1909 *
db26acd4 1910 * Returns XHTML for the field and also checks whether the file
1911 * specified in $data exists using file_exists()
1912 *
1913 * @param string $data File name and path to use in value attr
1914 * @param string $query
1915 * @return string XHTML field
1916 */
73fa96d5 1917 public function output_html($data, $query='') {
220a90c5 1918 $default = $this->get_defaultsetting();
1919
220a90c5 1920 if ($data) {
e9c0fa35 1921 if (file_exists($data)) {
220a90c5 1922 $executable = '<span class="pathok">&#x2714;</span>';
1923 } else {
1924 $executable = '<span class="patherror">&#x2718;</span>';
1925 }
1926 } else {
1927 $executable = '';
1928 }
1929
1930 return format_admin_setting($this, $this->visiblename,
9baf6825 1931 '<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>',
1932 $this->description, true, '', $default, $query);
eba8cd63 1933 }
220a90c5 1934}
1935
1936/**
e9c0fa35 1937 * Path to executable file
db26acd4 1938 *
1939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 1940 */
e9c0fa35 1941class admin_setting_configexecutable extends admin_setting_configfile {
1942
9baf6825 1943/**
1944 * Returns an XHTML field
1945 *
1946 * @param string $data This is the value for the field
1947 * @param string $query
1948 * @return string XHTML field
1949 */
73fa96d5 1950 public function output_html($data, $query='') {
e9c0fa35 1951 $default = $this->get_defaultsetting();
1952
1953 if ($data) {
1954 if (file_exists($data) and is_executable($data)) {
1955 $executable = '<span class="pathok">&#x2714;</span>';
1956 } else {
1957 $executable = '<span class="patherror">&#x2718;</span>';
1958 }
1959 } else {
1960 $executable = '';
1961 }
1962
1963 return format_admin_setting($this, $this->visiblename,
9baf6825 1964 '<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>',
1965 $this->description, true, '', $default, $query);
220a90c5 1966 }
e9c0fa35 1967}
220a90c5 1968
e9c0fa35 1969/**
1970 * Path to directory
db26acd4 1971 *
1972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e9c0fa35 1973 */
1974class admin_setting_configdirectory extends admin_setting_configfile {
db26acd4 1975
9baf6825 1976/**
1977 * Returns an XHTML field
1978 *
1979 * @param string $data This is the value for the field
1980 * @param string $query
1981 * @return string XHTML
1982 */
73fa96d5 1983 public function output_html($data, $query='') {
220a90c5 1984 $default = $this->get_defaultsetting();
1985
220a90c5 1986 if ($data) {
1987 if (file_exists($data) and is_dir($data)) {
1988 $executable = '<span class="pathok">&#x2714;</span>';
1989 } else {
1990 $executable = '<span class="patherror">&#x2718;</span>';
1991 }
1992 } else {
1993 $executable = '';
1994 }
9ba38673 1995
220a90c5 1996 return format_admin_setting($this, $this->visiblename,
9baf6825 1997 '<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>',
1998 $this->description, true, '', $default, $query);
220a90c5 1999 }
eba8cd63 2000}
2001
220a90c5 2002/**
2003 * Checkbox
db26acd4 2004 *
2005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2006 */
6e4dc10f 2007class admin_setting_configcheckbox extends admin_setting {
9baf6825 2008/** @var string Value used when checked */
73fa96d5 2009 public $yes;
0c079f19 2010 /** @var string Value used when not checked */
73fa96d5 2011 public $no;
6e4dc10f 2012
220a90c5 2013 /**
2014 * Constructor
1a41e806 2015 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2016 * @param string $visiblename localised
2017 * @param string $description long localised info
2018 * @param string $defaultsetting
2019 * @param string $yes value used when checked
2020 * @param string $no value used when not checked
2021 */
73fa96d5 2022 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2023 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2024 $this->yes = (string)$yes;
2025 $this->no = (string)$no;
6e4dc10f 2026 }
2027
db26acd4 2028 /**
2029 * Retrieves the current setting using the objects name
2030 *
2031 * @return string
2032 */
73fa96d5 2033 public function get_setting() {
220a90c5 2034 return $this->config_read($this->name);
6e4dc10f 2035 }
eef868d1 2036
db26acd4 2037 /**
2038 * Sets the value for the setting
2039 *
2040 * Sets the value for the setting to either the yes or no values
2041 * of the object by comparing $data to yes
2042 *
2043 * @param mixed $data Gets converted to str for comparison against yes value
2044 * @return string empty string or error
2045 */
73fa96d5 2046 public function write_setting($data) {
220a90c5 2047 if ((string)$data === $this->yes) { // convert to strings before comparison
2048 $data = $this->yes;
6e4dc10f 2049 } else {
220a90c5 2050 $data = $this->no;
6e4dc10f 2051 }
220a90c5 2052 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2053 }
2054
db26acd4 2055 /**
2056 * Returns an XHTML checkbox field
2057 *
2058 * @param string $data If $data matches yes then checkbox is checked
2059 * @param string $query
2060 * @return string XHTML field
2061 */
73fa96d5 2062 public function output_html($data, $query='') {
220a90c5 2063 $default = $this->get_defaultsetting();
2064
2065 if (!is_null($default)) {
2066 if ((string)$default === $this->yes) {
587c7040 2067 $defaultinfo = get_string('checkboxyes', 'admin');
220a90c5 2068 } else {
587c7040 2069 $defaultinfo = get_string('checkboxno', 'admin');
220a90c5 2070 }
c8218a42 2071 } else {
587c7040 2072 $defaultinfo = NULL;
c8218a42 2073 }
220a90c5 2074
2075 if ((string)$data === $this->yes) { // convert to strings before comparison
2076 $checked = 'checked="checked"';
2077 } else {
2078 $checked = '';
2079 }
2080
2081 return format_admin_setting($this, $this->visiblename,
9baf6825 2082 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2083 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2084 $this->description, true, '', $defaultinfo, $query);
6e4dc10f 2085 }
6e4dc10f 2086}
2087
220a90c5 2088/**
2089 * Multiple checkboxes, each represents different value, stored in csv format
db26acd4 2090 *
2091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2092 */
2093class admin_setting_configmulticheckbox extends admin_setting {
9baf6825 2094/** @var array Array of choices value=>label */
73fa96d5 2095 public $choices;
eef868d1 2096
220a90c5 2097 /**
db26acd4 2098 * Constructor: uses parent::__construct
2099 *
1a41e806 2100 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2101 * @param string $visiblename localised
2102 * @param string $description long localised info
2103 * @param array $defaultsetting array of selected
2104 * @param array $choices array of $value=>$label for each checkbox
2105 */
73fa96d5 2106 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6e4dc10f 2107 $this->choices = $choices;
73fa96d5 2108 parent::__construct($name, $visiblename, $description, $defaultsetting);
6e4dc10f 2109 }
2110
0a784551 2111 /**
73fa96d5 2112 * This public function may be used in ancestors for lazy loading of choices
db26acd4 2113 *
2114 * @todo Check if this function is still required content commented out only returns true
2115 * @return bool true if loaded, false if error
0a784551 2116 */
73fa96d5 2117 public function load_choices() {
0a784551 2118 /*
220a90c5 2119 if (is_array($this->choices)) {
2120 return true;
0a784551 2121 }
2122 .... load choices here
2123 */
220a90c5 2124 return true;
2125 }
2126
2127 /**
2128 * Is setting related to query text - used when searching
db26acd4 2129 *
220a90c5 2130 * @param string $query
db26acd4 2131 * @return bool true on related, false on not or failure
220a90c5 2132 */
73fa96d5 2133 public function is_related($query) {
220a90c5 2134 if (!$this->load_choices() or empty($this->choices)) {
2135 return false;
2136 }
2137 if (parent::is_related($query)) {
2138 return true;
2139 }
2140
2141 $textlib = textlib_get_instance();
2142 foreach ($this->choices as $desc) {
2143 if (strpos($textlib->strtolower($desc), $query) !== false) {
2144 return true;
2145 }
2146 }
2147 return false;
0a784551 2148 }
2149
db26acd4 2150 /**
2151 * Returns the current setting if it is set
2152 *
2153 * @return mixed null if null, else an array
2154 */
73fa96d5 2155 public function get_setting() {
220a90c5 2156 $result = $this->config_read($this->name);
10f19c49 2157
220a90c5 2158 if (is_null($result)) {
2159 return NULL;
2160 }
2161 if ($result === '') {
2162 return array();
2163 }
10f19c49 2164 $enabled = explode(',', $result);
2165 $setting = array();
2166 foreach ($enabled as $option) {
2167 $setting[$option] = 1;
2168 }
2169 return $setting;
6e4dc10f 2170 }
eef868d1 2171
db26acd4 2172 /**
2173 * Saves the setting(s) provided in $data
2174 *
2175 * @param array $data An array of data, if not array returns empty str
2176 * @return mixed empty string on useless data or bool true=success, false=failed
2177 */
73fa96d5 2178 public function write_setting($data) {
220a90c5 2179 if (!is_array($data)) {
2180 return ''; // ignore it
2181 }
2182 if (!$this->load_choices() or empty($this->choices)) {
2183 return '';
2184 }
2185 unset($data['xxxxx']);
2186 $result = array();
2187 foreach ($data as $key => $value) {
2188 if ($value and array_key_exists($key, $this->choices)) {
2189 $result[] = $key;
2190 }
2191 }
2192 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
6e4dc10f 2193 }
0c079f19 2194
db26acd4 2195 /**
2196 * Returns XHTML field(s) as required by choices
2197 *
2198 * Relies on data being an array should data ever be another valid vartype with
2199 * acceptable value this may cause a warning/error
2200 * if (!is_array($data)) would fix the problem
2201 *
2202 * @todo Add vartype handling to ensure $data is an array
2203 *
2204 * @param array $data An array of checked values
2205 * @param string $query
2206 * @return string XHTML field
2207 */
73fa96d5 2208 public function output_html($data, $query='') {
220a90c5 2209 if (!$this->load_choices() or empty($this->choices)) {
2210 return '';
2211 }
2212 $default = $this->get_defaultsetting();
2213 if (is_null($default)) {
2214 $default = array();
2215 }
2216 if (is_null($data)) {
775f811a 2217 $data = array();
220a90c5 2218 }
220a90c5 2219 $options = array();
2220 $defaults = array();
10f19c49 2221 foreach ($this->choices as $key=>$description) {
2222 if (!empty($data[$key])) {
220a90c5 2223 $checked = 'checked="checked"';
2224 } else {
2225 $checked = '';
2226 }
10f19c49 2227 if (!empty($default[$key])) {
220a90c5 2228 $defaults[] = $description;
2229 }
2230
2231 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
9baf6825 2232 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
220a90c5 2233 }
2234
587c7040 2235 if (is_null($default)) {
2236 $defaultinfo = NULL;
2237 } else if (!empty($defaults)) {
9baf6825 2238 $defaultinfo = implode(', ', $defaults);
2239 } else {
2240 $defaultinfo = get_string('none');
2241 }
220a90c5 2242
2243 $return = '<div class="form-multicheckbox">';
2244 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2245 if ($options) {
2246 $return .= '<ul>';
2247 foreach ($options as $option) {
2248 $return .= '<li>'.$option.'</li>';
2249 }
2250 $return .= '</ul>';
6e4dc10f 2251 }
587c7040 2252 $return .= '</div>';
6153cf58 2253
587c7040 2254 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
c5d2d0dd 2255
6e4dc10f 2256 }
6e4dc10f 2257}
2258
220a90c5 2259/**
2260 * Multiple checkboxes 2, value stored as string 00101011
db26acd4 2261 *
2262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2263 */
2264class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
db26acd4 2265
9baf6825 2266/**
2267 * Returns the setting if set
2268 *
2269 * @return mixed null if not set, else an array of set settings
2270 */
73fa96d5 2271 public function get_setting() {
220a90c5 2272 $result = $this->config_read($this->name);
2273 if (is_null($result)) {
2274 return NULL;
2275 }
2276 if (!$this->load_choices()) {
2277 return NULL;
2278 }
2279 $result = str_pad($result, count($this->choices), '0');
2280 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2281 $setting = array();
2282 foreach ($this->choices as $key=>$unused) {
2283 $value = array_shift($result);
2284 if ($value) {
10f19c49 2285 $setting[$key] = 1;
220a90c5 2286 }
2287 }
2288 return $setting;
2289 }
6e4dc10f 2290
db26acd4 2291 /**
2292 * Save setting(s) provided in $data param
2293 *
2294 * @param array $data An array of settings to save
2295 * @return mixed empty string for bad data or bool true=>success, false=>error
2296 */
73fa96d5 2297 public function write_setting($data) {
220a90c5 2298 if (!is_array($data)) {
2299 return ''; // ignore it
2300 }
2301 if (!$this->load_choices() or empty($this->choices)) {
2302 return '';
2303 }
2304 $result = '';
2305 foreach ($this->choices as $key=>$unused) {
2306 if (!empty($data[$key])) {
2307 $result .= '1';
2308 } else {
2309 $result .= '0';
2310 }
2311 }
2312 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2313 }
2314}
2315
2316/**
2317 * Select one value from list
db26acd4 2318 *
2319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2320 */
2321class admin_setting_configselect extends admin_setting {
9baf6825 2322/** @var array Array of choices value=>label */
73fa96d5 2323 public $choices;
6e4dc10f 2324
220a90c5 2325 /**
2326 * Constructor
1a41e806 2327 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
220a90c5 2328 * @param string $visiblename localised
2329 * @param string $description long localised info
eab8ed9f 2330 * @param string|int $defaultsetting
220a90c5 2331 * @param array $choices array of $value=>$label for each selection
2332 */
73fa96d5 2333 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
220a90c5 2334 $this->choices = $choices;
73fa96d5 2335 parent::__construct($name, $visiblename, $description, $defaultsetting);
220a90c5 2336 }
2337
2338 /**
2339 * This function may be used in ancestors for lazy loading of choices
db26acd4 2340 *
0c079f19 2341 * Override this method if loading of choices is expensive, such
2342 * as when it requires multiple db requests.
2343 *
db26acd4 2344 * @return bool true if loaded, false if error
220a90c5 2345 */
73fa96d5 2346 public function load_choices() {
220a90c5 2347 /*
2348 if (is_array($this->choices)) {
2349 return true;
6e4dc10f 2350 }
220a90c5 2351 .... load choices here
2352 */
2353 return true;
6e4dc10f 2354 }
2355
db26acd4 2356 /**
2357 * Check if this is $query is related to a choice
2358 *
2359 * @param string $query
2360 * @return bool true if related, false if not
2361 */
73fa96d5 2362 public function is_related($query) {
407d8134 2363 if (parent::is_related($query)) {
2364 return true;
2365 }
2366 if (!$this->load_choices()) {
2367 return false;
2368 }
2369 $textlib = textlib_get_instance();
2370 foreach ($this->choices as $key=>$value) {
2371 if (strpos($textlib->strtolower($key), $query) !== false) {
2372 return true;
2373 }
2374 if (strpos($textlib->strtolower($value), $query) !== false) {
2375 return true;
2376 }
c5d2d0dd 2377 }
407d8134 2378 return false;
2379 }
2380
db26acd4 2381 /**
2382 * Return the setting
0c079f19 2383 *
875e5f07 2384 * @return mixed returns config if successful else null
db26acd4 2385 */
73fa96d5 2386 public function get_setting() {
220a90c5 2387 return $this->config_read($this->name);
6e4dc10f 2388 }
eef868d1 2389
db26acd4 2390 /**
2391 * Save a setting
2392 *
2393 * @param string $data
2394 * @return string empty of error string
2395 */
73fa96d5 2396 public function write_setting($data) {
220a90c5 2397 if (!$this->load_choices() or empty($this->choices)) {
2398 return '';
2399 }
2400 if (!array_key_exists($data, $this->choices)) {
2401 return ''; // ignore it
2402 }
eef868d1 2403
220a90c5 2404 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2405 }
eef868d1 2406
e2249afe 2407 /**
db26acd4 2408 * Returns XHTML select field
2409 *
2410 * Ensure the options are loaded, and generate the XHTML for the select
e2249afe 2411 * element and any warning message. Separating this out from output_html
2412 * makes it easier to subclass this class.
2413 *
2414 * @param string $data the option to show as selected.
2415 * @param string $current the currently selected option in the database, null if none.
2416 * @param string $default the default selected option.
2417 * @return array the HTML for the select element, and a warning message.
2418 */
73fa96d5 2419 public function output_select_html($data, $current, $default, $extraname = '') {
220a90c5 2420 if (!$this->load_choices() or empty($this->choices)) {
e2249afe 2421 return array('', '');
6e4dc10f 2422 }
220a90c5 2423
9c305ba1 2424 $warning = '';
2425 if (is_null($current)) {
9baf6825 2426 // first run
9c305ba1 2427 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2428 // no warning
9baf6825 2429 } else if (!array_key_exists($current, $this->choices)) {
2430 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2431 if (!is_null($default) and $data == $current) {
2432 $data = $default; // use default instead of first value when showing the form
2433 }
2434 }
9c305ba1 2435
e2249afe 2436 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
6e4dc10f 2437 foreach ($this->choices as $key => $value) {
9baf6825 2438 // the string cast is needed because key may be integer - 0 is equal to most strings!
e2249afe 2439 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
eef868d1 2440 }
e2249afe 2441 $selecthtml .= '</select>';
2442 return array($selecthtml, $warning);
2443 }
2444
db26acd4 2445 /**
2446 * Returns XHTML select field and wrapping div(s)
2447 *
2448 * @see output_select_html()
0c079f19 2449 *
db26acd4 2450 * @param string $data the option to show as selected
2451 * @param string $query
2452 * @return string XHTML field and wrapping div
2453 */
73fa96d5 2454 public function output_html($data, $query='') {
e2249afe 2455 $default = $this->get_defaultsetting();
2456 $current = $this->get_setting();
2457
2458 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2459 if (!$selecthtml) {
2460 return '';
2461 }
2462
2463 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2464 $defaultinfo = $this->choices[$default];
2465 } else {
2466 $defaultinfo = NULL;
2467 }
2468
2469 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
220a90c5 2470
587c7040 2471 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
6e4dc10f 2472 }
6e4dc10f 2473}
2474
220a90c5 2475/**
2476 * Select multiple items from list
db26acd4 2477 *
2478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2479 */
6e4dc10f 2480class admin_setting_configmultiselect extends admin_setting_configselect {
9baf6825 2481/**
2482 * Constructor
2483 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2484 * @param string $visiblename localised
2485 * @param string $description long localised info
2486 * @param array $defaultsetting array of selected items
2487 * @param array $choices array of $value=>$label for each list item
2488 */
73fa96d5 2489 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2490 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
6e4dc10f 2491 }
2492
db26acd4 2493 /**
2494 * Returns the select setting(s)
2495 *
2496 * @return mixed null or array. Null if no settings else array of setting(s)
2497 */
73fa96d5 2498 public function get_setting() {
220a90c5 2499 $result = $this->config_read($this->name);
2500 if (is_null($result)) {
d7933a55 2501 return NULL;
2502 }
220a90c5 2503 if ($result === '') {
2504 return array();
2505 }
2506 return explode(',', $result);
6e4dc10f 2507 }
eef868d1 2508
db26acd4 2509 /**
2510 * Saves setting(s) provided through $data
2511 *
2512 * Potential bug in the works should anyone call with this function
2513 * using a vartype that is not an array
2514 *
2515 * @todo Add vartype handling to ensure $data is an array
2516 * @param array $data
2517 */
73fa96d5 2518 public function write_setting($data) {
220a90c5 2519 if (!is_array($data)) {
2520 return ''; //ignore it
2521 }
2522 if (!$this->load_choices() or empty($this->choices)) {
2523 return '';
2524 }
2525
a7ad48fd 2526 unset($data['xxxxx']);
2527
220a90c5 2528 $save = array();
2529 foreach ($data as $value) {
2530 if (!array_key_exists($value, $this->choices)) {
2531 continue; // ignore it
2532 }
2533 $save[] = $value;
2534 }
2535
2536 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2537 }
2538
2539 /**
2540 * Is setting related to query text - used when searching
db26acd4 2541 *
220a90c5 2542 * @param string $query
db26acd4 2543 * @return bool true if related, false if not
220a90c5 2544 */
73fa96d5 2545 public function is_related($query) {
220a90c5 2546 if (!$this->load_choices() or empty($this->choices)) {
2547 return false;
2548 }
2549 if (parent::is_related($query)) {
2550 return true;
2551 }
2552
2553 $textlib = textlib_get_instance();
2554 foreach ($this->choices as $desc) {
2555 if (strpos($textlib->strtolower($desc), $query) !== false) {
2556 return true;
2557 }
2558 }
2559 return false;
2560 }
2561
db26acd4 2562 /**
2563 * Returns XHTML multi-select field
2564 *
2565 * @todo Add vartype handling to ensure $data is an array
2566 * @param array $data Array of values to select by default
2567 * @param string $query
2568 * @return string XHTML multi-select field
2569 */
73fa96d5 2570 public function output_html($data, $query='') {
220a90c5 2571 if (!$this->load_choices() or empty($this->choices)) {
2572 return '';
2573 }
2574 $choices = $this->choices;
2575 $default = $this->get_defaultsetting();
2576 if (is_null($default)) {
2577 $default = array();
2578 }
2579 if (is_null($data)) {
d7933a55 2580 $data = array();
2581 }
220a90c5 2582
2583 $defaults = array();
4413941f 2584 $size = min(10, count($this->choices));
a7ad48fd 2585 $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 2586 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
220a90c5 2587 foreach ($this->choices as $key => $description) {
2588 if (in_array($key, $data)) {
2589 $selected = 'selected="selected"';
2590 } else {
2591 $selected = '';
2592 }
2593 if (in_array($key, $default)) {
2594 $defaults[] = $description;
6e4dc10f 2595 }
220a90c5 2596
2597 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2598 }
2599
587c7040 2600 if (is_null($default)) {
2601 $defaultinfo = NULL;
2602 } if (!empty($defaults)) {
2603 $defaultinfo = implode(', ', $defaults);
220a90c5 2604 } else {
587c7040 2605 $defaultinfo = get_string('none');
6e4dc10f 2606 }
eef868d1 2607
587c7040 2608 $return .= '</select></div>';
2609 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
6e4dc10f 2610 }
220a90c5 2611}
eef868d1 2612
220a90c5 2613/**
2614 * Time selector
db26acd4 2615 *
2616 * This is a liiitle bit messy. we're using two selects, but we're returning
220a90c5 2617 * them as an array named after $name (so we only use $name2 internally for the setting)
db26acd4 2618 *
2619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2620 */
2621class admin_setting_configtime extends admin_setting {
9baf6825 2622/** @var string Used for setting second select (minutes) */
73fa96d5 2623 public $name2;
220a90c5 2624
2625 /**
2626 * Constructor
2627 * @param string $hoursname setting for hours
2628 * @param string $minutesname setting for hours
2629 * @param string $visiblename localised
2630 * @param string $description long localised info
2631 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2632 */
73fa96d5 2633 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
220a90c5 2634 $this->name2 = $minutesname;
73fa96d5 2635 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
220a90c5 2636 }
2637
db26acd4 2638 /**
2639 * Get the selected time
0c079f19 2640 *
db26acd4 2641 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2642 */
73fa96d5 2643 public function get_setting() {
220a90c5 2644 $result1 = $this->config_read($this->name);
2645 $result2 = $this->config_read($this->name2);
2646 if (is_null($result1) or is_null($result2)) {
2647 return NULL;
2648 }
2649
2650 return array('h' => $result1, 'm' => $result2);
2651 }
2652
db26acd4 2653 /**
2654 * Store the time (hours and minutes)
0c079f19 2655 *
db26acd4 2656 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2657 * @return bool true if success, false if not
2658 */
73fa96d5 2659 public function write_setting($data) {
220a90c5 2660 if (!is_array($data)) {
2661 return '';
2662 }
2663
2664 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2665 return ($result ? '' : get_string('errorsetting', 'admin'));
2666 }
2667
db26acd4 2668 /**
2669 * Returns XHTML time select fields
2670 *
2671 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2672 * @param string $query
2673 * @return string XHTML time select fields and wrapping div(s)
2674 */
73fa96d5 2675 public function output_html($data, $query='') {
220a90c5 2676 $default = $this->get_defaultsetting();
2677
2678 if (is_array($default)) {
587c7040 2679 $defaultinfo = $default['h'].':'.$default['m'];
cc73de71 2680 } else {
587c7040 2681 $defaultinfo = NULL;
6e4dc10f 2682 }
220a90c5 2683
587c7040 2684 $return = '<div class="form-time defaultsnext">'.
9baf6825 2685 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
220a90c5 2686 for ($i = 0; $i < 24; $i++) {
2687 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
6e4dc10f 2688 }
220a90c5 2689 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2690 for ($i = 0; $i < 60; $i += 5) {
2691 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2692 }
587c7040 2693 $return .= '</select></div>';
2694 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
6e4dc10f 2695 }
2696
2697}
2698
db26acd4 2699/**
2700 * Used to validate a textarea used for ip addresses
2701 *
2702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 2703 */
4e639121 2704class admin_setting_configiplist extends admin_setting_configtextarea {
db26acd4 2705
9baf6825 2706/**
2707 * Validate the contents of the textarea as IP addresses
2708 *
875e5f07 2709 * Used to validate a new line separated list of IP addresses collected from
9baf6825 2710 * a textarea control
2711 *
875e5f07 2712 * @param string $data A list of IP Addresses separated by new lines
9baf6825 2713 * @return mixed bool true for success or string:error on failure
2714 */
73fa96d5 2715 public function validate($data) {
4e639121 2716 if(!empty($data)) {
c5d2d0dd 2717 $ips = explode("\n", $data);
4e639121 2718 } else {
2719 return true;
2720 }
2721 $result = true;
2722 foreach($ips as $ip) {
2723 $ip = trim($ip);
2724 if(preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
9baf6825 2725 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2726 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4e639121 2727 $result = true;
2728 } else {
2729 $result = false;
2730 break;
2731 }
2732 }
9baf6825 2733 if($result) {
4e639121 2734 return true;
2735 } else {
2736 return get_string('validateerror', 'admin');
2737 }
2738 }
2739}
2740
4413941f 2741/**
db26acd4 2742 * An admin setting for selecting one or more users who have a capability
2743 * in the system context
2744 *
4413941f 2745 * An admin setting for selecting one or more users, who have a particular capability
2746 * in the system context. Warning, make sure the list will never be too long. There is
2747 * no paging or searching of this list.
2748 *
2749 * To correctly get a list of users from this config setting, you need to call the
2750 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
db26acd4 2751 *
2752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4413941f 2753 */
2754class admin_setting_users_with_capability extends admin_setting_configmultiselect {
adf176d7 2755 /** @var string The capabilities name */
4413941f 2756 protected $capability;
adf176d7
PS
2757 /** @var int include admin users too */
2758 protected $includeadmins;
4413941f 2759
2760 /**
2761 * Constructor.
2762 *
2763 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2764 * @param string $visiblename localised name
2765 * @param string $description localised long description
2766 * @param array $defaultsetting array of usernames
2767 * @param string $capability string capability name.
875e5f07 2768 * @param bool $includeadmins include administrators
4413941f 2769 */
adf176d7
PS
2770 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2771 $this->capability = $capability;
2772 $this->includeadmins = $includeadmins;
fb073f60 2773 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2774 }
2775
db26acd4 2776 /**
2777 * Load all of the uses who have the capability into choice array
2778 *
2779 * @return bool Always returns true
2780 */
fb073f60 2781 function load_choices() {
2782 if (is_array($this->choices)) {
2783 return true;
2784 }
4413941f 2785 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
9baf6825 2786 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
fb073f60 2787 $this->choices = array(
4413941f 2788 '$@NONE@$' => get_string('nobody'),
fb073f60 2789 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4413941f 2790 );
adf176d7
PS
2791 if ($this->includeadmins) {
2792 $admins = get_admins();
2793 foreach ($admins as $user) {
2794 $this->choices[$user->id] = fullname($user);
2795 }
2796 }
9cc0de51
DM
2797 if (is_array($users)) {
2798 foreach ($users as $user) {
2799 $this->choices[$user->id] = fullname($user);
2800 }
4413941f 2801 }
fb073f60 2802 return true;
4413941f 2803 }
2804
db26acd4 2805 /**
2806 * Returns the default setting for class
2807 *
2808 * @return mixed Array, or string. Empty string if no default
2809 */
73fa96d5 2810 public function get_defaultsetting() {
4413941f 2811 $this->load_choices();
cd3acbf2 2812 $defaultsetting = parent::get_defaultsetting();
2813 if (empty($defaultsetting)) {
4413941f 2814 return array('$@NONE@$');
cd3acbf2 2815 } else if (array_key_exists($defaultsetting, $this->choices)) {
9baf6825 2816 return $defaultsetting;
2817 } else {
2818 return '';
2819 }
4413941f 2820 }
2821
db26acd4 2822 /**
2823 * Returns the current setting
2824 *
2825 * @return mixed array or string
2826 */
73fa96d5 2827 public function get_setting() {
4413941f 2828 $result = parent::get_setting();
adf176d7
PS
2829 if ($result === null) {
2830 // this is necessary for settings upgrade
2831 return null;
2832 }
4413941f 2833 if (empty($result)) {
2834 $result = array('$@NONE@$');
2835 }
2836 return $result;
2837 }
2838
db26acd4 2839 /**
2840 * Save the chosen setting provided as $data
2841 *
2842 * @param array $data
2843 * @return mixed string or array
2844 */
73fa96d5 2845 public function write_setting($data) {
9baf6825 2846 // If all is selected, remove any explicit options.
4413941f 2847 if (in_array('$@ALL@$', $data)) {
2848 $data = array('$@ALL@$');
2849 }
875e5f07 2850 // None never needs to be written to the DB.
4413941f 2851 if (in_array('$@NONE@$', $data)) {
2852 unset($data[array_search('$@NONE@$', $data)]);
2853 }
2854 return parent::write_setting($data);
2855 }
2856}
2857
220a90c5 2858/**
2859 * Special checkbox for calendar - resets SESSION vars.
db26acd4 2860 *
2861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2862 */
6e4dc10f 2863class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
9baf6825 2864/**
2865 * Calls the parent::__construct with default values
2866 *
2867 * name => calendar_adminseesall
2868 * visiblename => get_string('adminseesall', 'admin')
2869 * description => get_string('helpadminseesall', 'admin')
2870 * defaultsetting => 0
2871 */
73fa96d5 2872 public function __construct() {
2873 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
9baf6825 2874 get_string('helpadminseesall', 'admin'), '0');
6e4dc10f 2875 }
2876
db26acd4 2877 /**
2878 * Stores the setting passed in $data
2879 *
db26acd4 2880 * @param mixed gets converted to string for comparison
2881 * @return string empty string or error message
2882 */
73fa96d5 2883 public function write_setting($data) {
6e4dc10f 2884 global $SESSION;
2885 unset($SESSION->cal_courses_shown);
220a90c5 2886 return parent::write_setting($data);
6e4dc10f 2887 }
2888}
2889
392e7363 2890/**
2891 * Special select for settings that are altered in setup.php and can not be altered on the fly
db26acd4 2892 *
2893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
392e7363 2894 */
2895class admin_setting_special_selectsetup extends admin_setting_configselect {
9baf6825 2896/**
2897 * Reads the setting directly from the database
2898 *
2899 * @return mixed
2900 */
73fa96d5 2901 public function get_setting() {
9baf6825 2902 // read directly from db!
392e7363 2903 return get_config(NULL, $this->name);
2904 }
2905
db26acd4 2906 /**
2907 * Save the setting passed in $data
2908 *
db26acd4 2909 * @param string $data The setting to save
2910 * @return string empty or error message
2911 */
73fa96d5 2912 public function write_setting($data) {
392e7363 2913 global $CFG;
2914 // do not change active CFG setting!
2915 $current = $CFG->{$this->name};
2916 $result = parent::write_setting($data);
2917 $CFG->{$this->name} = $current;
2918 return $result;
2919 }
2920}
2921
220a90c5 2922/**
2923 * Special select for frontpage - stores data in course table
db26acd4 2924 *
2925 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2926 */
6e4dc10f 2927class admin_setting_sitesetselect extends admin_setting_configselect {
9baf6825 2928/**
2929 * Returns the site name for the selected site
2930 *
2931 * @see get_site()
2932 * @return string The site name of the selected site
2933 */
73fa96d5 2934 public function get_setting() {
b2bf016e 2935 $site = get_site();
2936 return $site->{$this->name};
6e4dc10f 2937 }
db26acd4 2938 /**
2939 * Updates the database and save the setting
2940 *
db26acd4 2941 * @param string data
2942 * @return string empty or error message
2943 */
73fa96d5 2944 public function write_setting($data) {
b2bf016e 2945 global $DB, $SITE;
6e4dc10f 2946 if (!in_array($data, array_keys($this->choices))) {
220a90c5 2947 return get_string('errorsetting', 'admin');
6e4dc10f 2948 }
2949 $record = new stdClass();
220a90c5 2950 $record->id = SITEID;
2951 $temp = $this->name;
2952 $record->$temp = $data;
6e4dc10f 2953 $record->timemodified = time();
b2bf016e 2954 // update $SITE
2955 $SITE->{$this->name} = $data;
f33e1ed4 2956 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 2957 }
6e4dc10f 2958}
2959
ca497f4f 2960/**
2961 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
2962 * block to hidden.
2963 *
2964 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2965 */
2966class admin_setting_bloglevel extends admin_setting_configselect {
2967 /**
2968 * Updates the database and save the setting
2969 *
2970 * @param string data
2971 * @return string empty or error message
2972 */
2973 public function write_setting($data) {
2974 global $DB;
2975 if ($data['bloglevel'] == 0) {
2976 $DB->set_field('block', 'visible', 0, array('name' => 'blog_menu'));
2977 } else {
2978 $DB->set_field('block', 'visible', 1, array('name' => 'blog_menu'));
2979 }
2980 return parent::write_setting($data);
2981 }
2982}
2983
220a90c5 2984/**
2985 * Special select - lists on the frontpage - hacky
db26acd4 2986 *
2987 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 2988 */
2989class admin_setting_courselist_frontpage extends admin_setting {
9baf6825 2990/** @var array Array of choices value=>label */
73fa96d5 2991 public $choices;
6e4dc10f 2992
db26acd4 2993 /**
2994 * Construct override, requires one param
2995 *
db26acd4 2996 * @param bool $loggedin Is the user logged in
2997 */
73fa96d5 2998 public function __construct($loggedin) {
6e4dc10f 2999 global $CFG;
220a90c5 3000 require_once($CFG->dirroot.'/course/lib.php');
3001 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3002 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3003 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3004 $defaults = array(FRONTPAGECOURSELIST);
73fa96d5 3005 parent::__construct($name, $visiblename, $description, $defaults);
6e4dc10f 3006 }
eef868d1 3007
db26acd4 3008 /**
3009 * Loads the choices available
3010 *
db26acd4 3011 * @return bool always returns true
3012 */
73fa96d5 3013 public function load_choices() {
c7da4357 3014 global $DB;
220a90c5 3015 if (is_array($this->choices)) {
3016 return true;
3017 }
3018 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
9baf6825 3019 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3020 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3021 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3022 'none' => get_string('none'));
c7da4357 3023 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
220a90c5 3024 unset($this->choices[FRONTPAGECOURSELIST]);
3025 }
3026 return true;
3027 }
db26acd4 3028 /**
3029 * Returns the selected settings
3030 *
3031 * @param mixed array or setting or null
3032 */
73fa96d5 3033 public function get_setting() {
220a90c5 3034 $result = $this->config_read($this->name);
3035 if (is_null($result)) {
3036 return NULL;
3037 }
3038 if ($result === '') {
3039 return array();
3040 }
3041 return explode(',', $result);
6e4dc10f 3042 }
eef868d1 3043
db26acd4 3044 /**
3045 * Save the selected options
3046 *
3047 * @param array $data
3048 * @return mixed empty string (data is not an array) or bool true=success false=failure
3049 */
73fa96d5 3050 public function write_setting($data) {
220a90c5 3051 if (!is_array($data)) {
3052 return '';
6e4dc10f 3053 }
220a90c5 3054 $this->load_choices();
3055 $save = array();
6e4dc10f 3056 foreach($data as $datum) {
220a90c5 3057 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3058 continue;
6e4dc10f 3059 }
220a90c5 3060 $save[$datum] = $datum; // no duplicates
6e4dc10f 3061 }
220a90c5 3062 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 3063 }
eef868d1 3064
db26acd4 3065 /**
3066 * Return XHTML select field and wrapping div
3067 *
3068 * @todo Add vartype handling to make sure $data is an array
3069 * @param array $data Array of elements to select by default
3070 * @return string XHTML select field and wrapping div
3071 */
73fa96d5 3072 public function output_html($data, $query='') {
220a90c5 3073 $this->load_choices();
3074 $currentsetting = array();
3075 foreach ($data as $key) {
3076 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3077 $currentsetting[] = $key; // already selected first
6e4dc10f 3078 }
3079 }
220a90c5 3080
0a7e84c3 3081 $return = '<div class="form-group">';
6e4dc10f 3082 for ($i = 0; $i < count($this->choices) - 1; $i++) {
220a90c5 3083 if (!array_key_exists($i, $currentsetting)) {
3084 $currentsetting[$i] = 'none'; //none
3085 }
3086 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
6e4dc10f 3087 foreach ($this->choices as $key => $value) {
220a90c5 3088 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
6e4dc10f 3089 }
3090 $return .= '</select>';
3091 if ($i !== count($this->choices) - 2) {
975211bb 3092 $return .= '<br />';
6e4dc10f 3093 }
3094 }
0a7e84c3 3095 $return .= '</div>';
3096
587c7040 3097 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
6e4dc10f 3098 }
3099}
3100
220a90c5 3101/**
3102 * Special checkbox for frontpage - stores data in course table
db26acd4 3103 *
3104 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 3105 */
6e4dc10f 3106class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
9baf6825 3107/**
3108 * Returns the current sites name
3109 *
3110 * @return string
3111 */
73fa96d5 3112 public function get_setting() {
b2bf016e 3113 $site = get_site();
3114 return $site->{$this->name};
6e4dc10f 3115 }
eef868d1 3116
db26acd4 3117 /**
3118 * Save the selected setting
3119 *
db26acd4 3120 * @param string $data The selected site
3121 * @return string empty string or error message
3122 */
73fa96d5 3123 public function write_setting($data) {
b2bf016e 3124 global $DB, $SITE;
365a5941 3125 $record = new stdClass();
220a90c5 3126 $record->id = SITEID;
3127 $record->{$this->name} = ($data == '1' ? 1 : 0);
3128 $record->timemodified = time();
b2bf016e 3129 // update $SITE
3130 $SITE->{$this->name} = $data;
f33e1ed4 3131 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 3132 }
6e4dc10f 3133}
3134
220a90c5 3135/**
3136 * Special text for frontpage - stores data in course table.
3137 * Empty string means not set here. Manual setting is required.
db26acd4 3138 *
3139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 3140 */
6e4dc10f 3141class admin_setting_sitesettext extends admin_setting_configtext {
9baf6825 3142/**
3143 * Return the current setting
3144 *
3145 * @return mixed string or null
3146 */
73fa96d5 3147 public function get_setting() {
b2bf016e 3148 $site = get_site();
a7747679 3149 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
6e4dc10f 3150 }
90cfbd0a 3151
db26acd4 3152 /**
3153 * Validate the selected data
3154 *
3155 * @param string $data The selected value to validate
3156 * @return mixed true or message string
3157 */
73fa96d5 3158 public function validate($data) {
294ce987 3159 $cleaned = clean_param($data, PARAM_MULTILANG);
e33fbf87 3160 if ($cleaned === '') {
3161 return get_string('required');
3162 }
3163 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3164 return true;
3165 } else {
3166 return get_string('validateerror', 'admin');
b89639f9 3167 }
b89639f9 3168 }
3169
db26acd4 3170 /**
3171 * Save the selected setting
3172 *
db26acd4 3173 * @param string $data The selected value
875e5f07 3174 * @return string empty or error message
db26acd4 3175 */
73fa96d5 3176 public function write_setting($data) {
b2bf016e 3177 global $DB, $SITE;
b89639f9 3178 $data = trim($data);
c5d2d0dd 3179 $validated = $this->validate($data);
e33fbf87 3180 if ($validated !== true) {
3181 return $validated;
90cfbd0a 3182 }
eef868d1 3183
365a5941 3184 $record = new stdClass();
220a90c5 3185 $record->id = SITEID;
f33e1ed4 3186 $record->{$this->name} = $data;
220a90c5 3187 $record->timemodified = time();
b2bf016e 3188 // update $SITE
3189 $SITE->{$this->name} = $data;
f33e1ed4 3190 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
6e4dc10f 3191 }
6e4dc10f 3192}
3193
220a90c5 3194/**
3195 * Special text editor for site description.
db26acd4 3196 *
3197 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
220a90c5 3198 */
6e4dc10f 3199class admin_setting_special_frontpagedesc extends admin_setting {
9baf6825 3200/**
3201 * Calls parent::__construct with specific arguments
3202 */
73fa96d5 3203 public function __construct() {
3204 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
ff5fe311 3205 editors_head_setup();
6e4dc10f 3206 }
eef868d1 3207
db26acd4 3208 /**
3209 * Return the current setting
3210 * @return string The current setting
3211 */
73fa96d5 3212 public function get_setting() {
b2bf016e 3213 $site = get_site();
3214 return $site->{$this->name};
c626c2f4 3215 }
eef868d1 3216
db26acd4 3217 /**
3218 * Save the new setting
3219 *
db26acd4 3220 * @param string $data The new value to save
3221 * @return string empty or error message
3222 */
73fa96d5 3223 public function write_setting($data) {
b2bf016e 3224 global $DB, $SITE;
365a5941 3225 $record = new stdClass();
220a90c5 3226 $record->id = SITEID;
f33e1ed4 3227 $record->{$this->name} = $data;
c626c2f4 3228 $record->timemodified = time();
b2bf016e 3229 $SITE->{$this->name} = $data;
7719860b 3230 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
6e4dc10f 3231 }
3232
db26acd4 3233 /**
3234 * Returns XHTML for the field plus wrapping div
3235 *
db26acd4 3236 * @param string $data The current value
3237 * @param string $query
3238 * @return string The XHTML output
3239 */
73fa96d5 3240 public function output_html($data, $query='') {
cb6c02c4 3241 global $CFG;
6e4dc10f 3242
220a90c5 3243 $CFG->adminusehtmleditor = can_use_html_editor();
8c37106d 3244 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
220a90c5 3245
587c7040 3246 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
220a90c5 3247 }
3248}
6e4dc10f 3249
db26acd4 3250/**
7680da6c 3251 * Administration interface for emoticon_manager settings.
db26acd4 3252 *
3253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
db26acd4 3254 */
93c61c18 3255class admin_setting_emoticons extends admin_setting {
3256
9baf6825 3257/**
3258 * Calls parent::__construct with specific args
3259 */
73fa96d5 3260 public function __construct() {
93c61c18 3261 global $CFG;
7680da6c
DM
3262
3263 $manager = get_emoticon_manager();
3264 $defaults = $this->prepare_form_data($manager->default_emoticons());
3265 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
93c61c18 3266 }
0c079f19 3267
db26acd4 3268 /**
3269 * Return the current setting(s)
3270 *
db26acd4 3271 * @return array Current settings array
3272 */
73fa96d5 3273 public function get_setting() {
93c61c18 3274 global $CFG;
7680da6c
DM
3275
3276 $manager = get_emoticon_manager();
f8392c81 3277
7680da6c 3278 $config = $this->config_read($this->name);
f8392c81
DM
3279 if (is_null($config)) {
3280 return null;
3281 }
7680da6c 3282
f8392c81 3283 $config = $manager->decode_stored_config($config);
7680da6c
DM
3284 if (is_null($config)) {
3285 return null;
220a90c5 3286 }
7680da6c