MDL-27639 restore of attempt data from 2.0 - first attempt.
[moodle.git] / lib / adminlib.php
blobf69425b35ce796fe4a7d1e8891b089cfe0e174b3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
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
123 function uninstall_plugin($type, $name) {
124 global $CFG, $DB, $OUTPUT;
126 // recursively uninstall all module subplugins first
127 if ($type === 'mod') {
128 if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
129 $subplugins = array();
130 include("$CFG->dirroot/mod/$name/db/subplugins.php");
131 foreach ($subplugins as $subplugintype=>$dir) {
132 $instances = get_plugin_list($subplugintype);
133 foreach ($instances as $subpluginname => $notusedpluginpath) {
134 uninstall_plugin($subplugintype, $subpluginname);
141 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
143 if ($type === 'mod') {
144 $pluginname = $name; // eg. 'forum'
145 if (get_string_manager()->string_exists('modulename', $component)) {
146 $strpluginname = get_string('modulename', $component);
147 } else {
148 $strpluginname = $component;
151 } else {
152 $pluginname = $component;
153 if (get_string_manager()->string_exists('pluginname', $component)) {
154 $strpluginname = get_string('pluginname', $component);
155 } else {
156 $strpluginname = $component;
160 echo $OUTPUT->heading($pluginname);
162 $plugindirectory = get_plugin_directory($type, $name);
163 $uninstalllib = $plugindirectory . '/db/uninstall.php';
164 if (file_exists($uninstalllib)) {
165 require_once($uninstalllib);
166 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
167 if (function_exists($uninstallfunction)) {
168 if (!$uninstallfunction()) {
169 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
174 if ($type === 'mod') {
175 // perform cleanup tasks specific for activity modules
177 if (!$module = $DB->get_record('modules', array('name' => $name))) {
178 print_error('moduledoesnotexist', 'error');
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");
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));
198 // delete all the course module records
199 $DB->delete_records('course_modules', array('module' => $module->id));
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");
210 // delete the module entry itself
211 $DB->delete_records('modules', array('name' => $module->name));
213 // cleanup the gradebook
214 require_once($CFG->libdir.'/gradelib.php');
215 grade_uninstalled_module($module->name);
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);
223 if (!$uninstallfunction()) {
224 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
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));
250 // perform clean-up task common for all the plugin/subplugin types
252 // delete calendar events
253 $DB->delete_records('event', array('modulename' => $pluginname));
255 // delete all the logs
256 $DB->delete_records('log', array('module' => $pluginname));
258 // delete log_display information
259 $DB->delete_records('log_display', array('component' => $component));
261 // delete the module configuration records
262 unset_all_config_for_plugin($pluginname);
264 // delete message provider
265 message_provider_uninstall($component);
267 // delete message processor
268 if ($type === 'message') {
269 message_processor_uninstall($name);
272 // delete the plugin tables
273 $xmldbfilepath = $plugindirectory . '/db/install.xml';
274 drop_plugin_tables($pluginname, $xmldbfilepath, false);
276 // delete the capabilities that were defined by this module
277 capabilities_cleanup($component);
279 // remove event handlers and dequeue pending events
280 events_uninstall($component);
282 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
286 * Returns the version of installed component
288 * @param string $component component name
289 * @param string $source either 'disk' or 'installed' - where to get the version information from
290 * @return string|bool version number or false if the component is not found
292 function get_component_version($component, $source='installed') {
293 global $CFG, $DB;
295 list($type, $name) = normalize_component($component);
297 // moodle core or a core subsystem
298 if ($type === 'core') {
299 if ($source === 'installed') {
300 if (empty($CFG->version)) {
301 return false;
302 } else {
303 return $CFG->version;
305 } else {
306 if (!is_readable($CFG->dirroot.'/version.php')) {
307 return false;
308 } else {
309 $version = null; //initialize variable for IDEs
310 include($CFG->dirroot.'/version.php');
311 return $version;
316 // activity module
317 if ($type === 'mod') {
318 if ($source === 'installed') {
319 return $DB->get_field('modules', 'version', array('name'=>$name));
320 } else {
321 $mods = get_plugin_list('mod');
322 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
323 return false;
324 } else {
325 $module = new stdclass();
326 include($mods[$name].'/version.php');
327 return $module->version;
332 // block
333 if ($type === 'block') {
334 if ($source === 'installed') {
335 return $DB->get_field('block', 'version', array('name'=>$name));
336 } else {
337 $blocks = get_plugin_list('block');
338 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
339 return false;
340 } else {
341 $plugin = new stdclass();
342 include($blocks[$name].'/version.php');
343 return $plugin->version;
348 // all other plugin types
349 if ($source === 'installed') {
350 return get_config($type.'_'.$name, 'version');
351 } else {
352 $plugins = get_plugin_list($type);
353 if (empty($plugins[$name])) {
354 return false;
355 } else {
356 $plugin = new stdclass();
357 include($plugins[$name].'/version.php');
358 return $plugin->version;
364 * Delete all plugin tables
366 * @param string $name Name of plugin, used as table prefix
367 * @param string $file Path to install.xml file
368 * @param bool $feedback defaults to true
369 * @return bool Always returns true
371 function drop_plugin_tables($name, $file, $feedback=true) {
372 global $CFG, $DB;
374 // first try normal delete
375 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
376 return true;
379 // then try to find all tables that start with name and are not in any xml file
380 $used_tables = get_used_table_names();
382 $tables = $DB->get_tables();
384 /// Iterate over, fixing id fields as necessary
385 foreach ($tables as $table) {
386 if (in_array($table, $used_tables)) {
387 continue;
390 if (strpos($table, $name) !== 0) {
391 continue;
394 // found orphan table --> delete it
395 if ($DB->get_manager()->table_exists($table)) {
396 $xmldb_table = new xmldb_table($table);
397 $DB->get_manager()->drop_table($xmldb_table);
401 return true;
405 * Returns names of all known tables == tables that moodle knows about.
407 * @return array Array of lowercase table names
409 function get_used_table_names() {
410 $table_names = array();
411 $dbdirs = get_db_directories();
413 foreach ($dbdirs as $dbdir) {
414 $file = $dbdir.'/install.xml';
416 $xmldb_file = new xmldb_file($file);
418 if (!$xmldb_file->fileExists()) {
419 continue;
422 $loaded = $xmldb_file->loadXMLStructure();
423 $structure = $xmldb_file->getStructure();
425 if ($loaded and $tables = $structure->getTables()) {
426 foreach($tables as $table) {
427 $table_names[] = strtolower($table->name);
432 return $table_names;
436 * Returns list of all directories where we expect install.xml files
437 * @return array Array of paths
439 function get_db_directories() {
440 global $CFG;
442 $dbdirs = array();
444 /// First, the main one (lib/db)
445 $dbdirs[] = $CFG->libdir.'/db';
447 /// Then, all the ones defined by get_plugin_types()
448 $plugintypes = get_plugin_types();
449 foreach ($plugintypes as $plugintype => $pluginbasedir) {
450 if ($plugins = get_plugin_list($plugintype)) {
451 foreach ($plugins as $plugin => $plugindir) {
452 $dbdirs[] = $plugindir.'/db';
457 return $dbdirs;
461 * Try to obtain or release the cron lock.
462 * @param string $name name of lock
463 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
464 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
465 * @return bool true if lock obtained
467 function set_cron_lock($name, $until, $ignorecurrent=false) {
468 global $DB;
469 if (empty($name)) {
470 debugging("Tried to get a cron lock for a null fieldname");
471 return false;
474 // remove lock by force == remove from config table
475 if (is_null($until)) {
476 set_config($name, null);
477 return true;
480 if (!$ignorecurrent) {
481 // read value from db - other processes might have changed it
482 $value = $DB->get_field('config', 'value', array('name'=>$name));
484 if ($value and $value > time()) {
485 //lock active
486 return false;
490 set_config($name, $until);
491 return true;
495 * Test if and critical warnings are present
496 * @return bool
498 function admin_critical_warnings_present() {
499 global $SESSION;
501 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
502 return 0;
505 if (!isset($SESSION->admin_critical_warning)) {
506 $SESSION->admin_critical_warning = 0;
507 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
508 $SESSION->admin_critical_warning = 1;
512 return $SESSION->admin_critical_warning;
516 * Detects if float supports at least 10 decimal digits
518 * Detects if float supports at least 10 decimal digits
519 * and also if float-->string conversion works as expected.
521 * @return bool true if problem found
523 function is_float_problem() {
524 $num1 = 2009010200.01;
525 $num2 = 2009010200.02;
527 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
531 * Try to verify that dataroot is not accessible from web.
533 * Try to verify that dataroot is not accessible from web.
534 * It is not 100% correct but might help to reduce number of vulnerable sites.
535 * Protection from httpd.conf and .htaccess is not detected properly.
537 * @uses INSECURE_DATAROOT_WARNING
538 * @uses INSECURE_DATAROOT_ERROR
539 * @param bool $fetchtest try to test public access by fetching file, default false
540 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
542 function is_dataroot_insecure($fetchtest=false) {
543 global $CFG;
545 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
547 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
548 $rp = strrev(trim($rp, '/'));
549 $rp = explode('/', $rp);
550 foreach($rp as $r) {
551 if (strpos($siteroot, '/'.$r.'/') === 0) {
552 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
553 } else {
554 break; // probably alias root
558 $siteroot = strrev($siteroot);
559 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
561 if (strpos($dataroot, $siteroot) !== 0) {
562 return false;
565 if (!$fetchtest) {
566 return INSECURE_DATAROOT_WARNING;
569 // now try all methods to fetch a test file using http protocol
571 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
572 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
573 $httpdocroot = $matches[1];
574 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
575 make_upload_directory('diag');
576 $testfile = $CFG->dataroot.'/diag/public.txt';
577 if (!file_exists($testfile)) {
578 file_put_contents($testfile, 'test file, do not delete');
580 $teststr = trim(file_get_contents($testfile));
581 if (empty($teststr)) {
582 // hmm, strange
583 return INSECURE_DATAROOT_WARNING;
586 $testurl = $datarooturl.'/diag/public.txt';
587 if (extension_loaded('curl') and
588 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
589 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
590 ($ch = @curl_init($testurl)) !== false) {
591 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
592 curl_setopt($ch, CURLOPT_HEADER, false);
593 $data = curl_exec($ch);
594 if (!curl_errno($ch)) {
595 $data = trim($data);
596 if ($data === $teststr) {
597 curl_close($ch);
598 return INSECURE_DATAROOT_ERROR;
601 curl_close($ch);
604 if ($data = @file_get_contents($testurl)) {
605 $data = trim($data);
606 if ($data === $teststr) {
607 return INSECURE_DATAROOT_ERROR;
611 preg_match('|https?://([^/]+)|i', $testurl, $matches);
612 $sitename = $matches[1];
613 $error = 0;
614 if ($fp = @fsockopen($sitename, 80, $error)) {
615 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
616 $localurl = $matches[1];
617 $out = "GET $localurl HTTP/1.1\r\n";
618 $out .= "Host: $sitename\r\n";
619 $out .= "Connection: Close\r\n\r\n";
620 fwrite($fp, $out);
621 $data = '';
622 $incoming = false;
623 while (!feof($fp)) {
624 if ($incoming) {
625 $data .= fgets($fp, 1024);
626 } else if (@fgets($fp, 1024) === "\r\n") {
627 $incoming = true;
630 fclose($fp);
631 $data = trim($data);
632 if ($data === $teststr) {
633 return INSECURE_DATAROOT_ERROR;
637 return INSECURE_DATAROOT_WARNING;
640 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
644 * Interface for anything appearing in the admin tree
646 * The interface that is implemented by anything that appears in the admin tree
647 * block. It forces inheriting classes to define a method for checking user permissions
648 * and methods for finding something in the admin tree.
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 interface part_of_admin_tree {
655 * Finds a named part_of_admin_tree.
657 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
658 * and not parentable_part_of_admin_tree, then this function should only check if
659 * $this->name matches $name. If it does, it should return a reference to $this,
660 * otherwise, it should return a reference to NULL.
662 * If a class inherits parentable_part_of_admin_tree, this method should be called
663 * recursively on all child objects (assuming, of course, the parent object's name
664 * doesn't match the search criterion).
666 * @param string $name The internal name of the part_of_admin_tree we're searching for.
667 * @return mixed An object reference or a NULL reference.
669 public function locate($name);
672 * Removes named part_of_admin_tree.
674 * @param string $name The internal name of the part_of_admin_tree we want to remove.
675 * @return bool success.
677 public function prune($name);
680 * Search using query
681 * @param string $query
682 * @return mixed array-object structure of found settings and pages
684 public function search($query);
687 * Verifies current user's access to this part_of_admin_tree.
689 * Used to check if the current user has access to this part of the admin tree or
690 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
691 * then this method is usually just a call to has_capability() in the site context.
693 * If a class inherits parentable_part_of_admin_tree, this method should return the
694 * logical OR of the return of check_access() on all child objects.
696 * @return bool True if the user has access, false if she doesn't.
698 public function check_access();
701 * Mostly useful for removing of some parts of the tree in admin tree block.
703 * @return True is hidden from normal list view
705 public function is_hidden();
708 * Show we display Save button at the page bottom?
709 * @return bool
711 public function show_save();
716 * Interface implemented by any part_of_admin_tree that has children.
718 * The interface implemented by any part_of_admin_tree that can be a parent
719 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
720 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
721 * include an add method for adding other part_of_admin_tree objects as children.
723 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
725 interface parentable_part_of_admin_tree extends part_of_admin_tree {
728 * Adds a part_of_admin_tree object to the admin tree.
730 * Used to add a part_of_admin_tree object to this object or a child of this
731 * object. $something should only be added if $destinationname matches
732 * $this->name. If it doesn't, add should be called on child objects that are
733 * also parentable_part_of_admin_tree's.
735 * @param string $destinationname The internal name of the new parent for $something.
736 * @param part_of_admin_tree $something The object to be added.
737 * @return bool True on success, false on failure.
739 public function add($destinationname, $something);
745 * The object used to represent folders (a.k.a. categories) in the admin tree block.
747 * Each admin_category object contains a number of part_of_admin_tree objects.
749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
751 class admin_category implements parentable_part_of_admin_tree {
753 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
754 public $children;
755 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
756 public $name;
757 /** @var string The displayed name for this category. Usually obtained through get_string() */
758 public $visiblename;
759 /** @var bool Should this category be hidden in admin tree block? */
760 public $hidden;
761 /** @var mixed Either a string or an array or strings */
762 public $path;
763 /** @var mixed Either a string or an array or strings */
764 public $visiblepath;
766 /** @var array fast lookup category cache, all categories of one tree point to one cache */
767 protected $category_cache;
770 * Constructor for an empty admin category
772 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
773 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
774 * @param bool $hidden hide category in admin tree block, defaults to false
776 public function __construct($name, $visiblename, $hidden=false) {
777 $this->children = array();
778 $this->name = $name;
779 $this->visiblename = $visiblename;
780 $this->hidden = $hidden;
784 * Returns a reference to the part_of_admin_tree object with internal name $name.
786 * @param string $name The internal name of the object we want.
787 * @param bool $findpath initialize path and visiblepath arrays
788 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
789 * defaults to false
791 public function locate($name, $findpath=false) {
792 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
793 // somebody much have purged the cache
794 $this->category_cache[$this->name] = $this;
797 if ($this->name == $name) {
798 if ($findpath) {
799 $this->visiblepath[] = $this->visiblename;
800 $this->path[] = $this->name;
802 return $this;
805 // quick category lookup
806 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
807 return $this->category_cache[$name];
810 $return = NULL;
811 foreach($this->children as $childid=>$unused) {
812 if ($return = $this->children[$childid]->locate($name, $findpath)) {
813 break;
817 if (!is_null($return) and $findpath) {
818 $return->visiblepath[] = $this->visiblename;
819 $return->path[] = $this->name;
822 return $return;
826 * Search using query
828 * @param string query
829 * @return mixed array-object structure of found settings and pages
831 public function search($query) {
832 $result = array();
833 foreach ($this->children as $child) {
834 $subsearch = $child->search($query);
835 if (!is_array($subsearch)) {
836 debugging('Incorrect search result from '.$child->name);
837 continue;
839 $result = array_merge($result, $subsearch);
841 return $result;
845 * Removes part_of_admin_tree object with internal name $name.
847 * @param string $name The internal name of the object we want to remove.
848 * @return bool success
850 public function prune($name) {
852 if ($this->name == $name) {
853 return false; //can not remove itself
856 foreach($this->children as $precedence => $child) {
857 if ($child->name == $name) {
858 // clear cache and delete self
859 if (is_array($this->category_cache)) {
860 while($this->category_cache) {
861 // delete the cache, but keep the original array address
862 array_pop($this->category_cache);
865 unset($this->children[$precedence]);
866 return true;
867 } else if ($this->children[$precedence]->prune($name)) {
868 return true;
871 return false;
875 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
877 * @param string $destinationame The internal name of the immediate parent that we want for $something.
878 * @param mixed $something A part_of_admin_tree or setting instance to be added.
879 * @return bool True if successfully added, false if $something can not be added.
881 public function add($parentname, $something) {
882 $parent = $this->locate($parentname);
883 if (is_null($parent)) {
884 debugging('parent does not exist!');
885 return false;
888 if ($something instanceof part_of_admin_tree) {
889 if (!($parent instanceof parentable_part_of_admin_tree)) {
890 debugging('error - parts of tree can be inserted only into parentable parts');
891 return false;
893 $parent->children[] = $something;
894 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
895 if (isset($this->category_cache[$something->name])) {
896 debugging('Duplicate admin category name: '.$something->name);
897 } else {
898 $this->category_cache[$something->name] = $something;
899 $something->category_cache =& $this->category_cache;
900 foreach ($something->children as $child) {
901 // just in case somebody already added subcategories
902 if ($child instanceof admin_category) {
903 if (isset($this->category_cache[$child->name])) {
904 debugging('Duplicate admin category name: '.$child->name);
905 } else {
906 $this->category_cache[$child->name] = $child;
907 $child->category_cache =& $this->category_cache;
913 return true;
915 } else {
916 debugging('error - can not add this element');
917 return false;
923 * Checks if the user has access to anything in this category.
925 * @return bool True if the user has access to at least one child in this category, false otherwise.
927 public function check_access() {
928 foreach ($this->children as $child) {
929 if ($child->check_access()) {
930 return true;
933 return false;
937 * Is this category hidden in admin tree block?
939 * @return bool True if hidden
941 public function is_hidden() {
942 return $this->hidden;
946 * Show we display Save button at the page bottom?
947 * @return bool
949 public function show_save() {
950 foreach ($this->children as $child) {
951 if ($child->show_save()) {
952 return true;
955 return false;
961 * Root of admin settings tree, does not have any parent.
963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
965 class admin_root extends admin_category {
966 /** @var array List of errors */
967 public $errors;
968 /** @var string search query */
969 public $search;
970 /** @var bool full tree flag - true means all settings required, false only pages required */
971 public $fulltree;
972 /** @var bool flag indicating loaded tree */
973 public $loaded;
974 /** @var mixed site custom defaults overriding defaults in settings files*/
975 public $custom_defaults;
978 * @param bool $fulltree true means all settings required,
979 * false only pages required
981 public function __construct($fulltree) {
982 global $CFG;
984 parent::__construct('root', get_string('administration'), false);
985 $this->errors = array();
986 $this->search = '';
987 $this->fulltree = $fulltree;
988 $this->loaded = false;
990 $this->category_cache = array();
992 // load custom defaults if found
993 $this->custom_defaults = null;
994 $defaultsfile = "$CFG->dirroot/local/defaults.php";
995 if (is_readable($defaultsfile)) {
996 $defaults = array();
997 include($defaultsfile);
998 if (is_array($defaults) and count($defaults)) {
999 $this->custom_defaults = $defaults;
1005 * Empties children array, and sets loaded to false
1007 * @param bool $requirefulltree
1009 public function purge_children($requirefulltree) {
1010 $this->children = array();
1011 $this->fulltree = ($requirefulltree || $this->fulltree);
1012 $this->loaded = false;
1013 //break circular dependencies - this helps PHP 5.2
1014 while($this->category_cache) {
1015 array_pop($this->category_cache);
1017 $this->category_cache = array();
1023 * Links external PHP pages into the admin tree.
1025 * See detailed usage example at the top of this document (adminlib.php)
1027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1029 class admin_externalpage implements part_of_admin_tree {
1031 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1032 public $name;
1034 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1035 public $visiblename;
1037 /** @var string The external URL that we should link to when someone requests this external page. */
1038 public $url;
1040 /** @var string The role capability/permission a user must have to access this external page. */
1041 public $req_capability;
1043 /** @var object The context in which capability/permission should be checked, default is site context. */
1044 public $context;
1046 /** @var bool hidden in admin tree block. */
1047 public $hidden;
1049 /** @var mixed either string or array of string */
1050 public $path;
1052 /** @var array list of visible names of page parents */
1053 public $visiblepath;
1056 * Constructor for adding an external page into the admin tree.
1058 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1059 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1060 * @param string $url The external URL that we should link to when someone requests this external page.
1061 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1062 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1063 * @param stdClass $context The context the page relates to. Not sure what happens
1064 * if you specify something other than system or front page. Defaults to system.
1066 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1067 $this->name = $name;
1068 $this->visiblename = $visiblename;
1069 $this->url = $url;
1070 if (is_array($req_capability)) {
1071 $this->req_capability = $req_capability;
1072 } else {
1073 $this->req_capability = array($req_capability);
1075 $this->hidden = $hidden;
1076 $this->context = $context;
1080 * Returns a reference to the part_of_admin_tree object with internal name $name.
1082 * @param string $name The internal name of the object we want.
1083 * @param bool $findpath defaults to false
1084 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1086 public function locate($name, $findpath=false) {
1087 if ($this->name == $name) {
1088 if ($findpath) {
1089 $this->visiblepath = array($this->visiblename);
1090 $this->path = array($this->name);
1092 return $this;
1093 } else {
1094 $return = NULL;
1095 return $return;
1100 * This function always returns false, required function by interface
1102 * @param string $name
1103 * @return false
1105 public function prune($name) {
1106 return false;
1110 * Search using query
1112 * @param string $query
1113 * @return mixed array-object structure of found settings and pages
1115 public function search($query) {
1116 $textlib = textlib_get_instance();
1118 $found = false;
1119 if (strpos(strtolower($this->name), $query) !== false) {
1120 $found = true;
1121 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1122 $found = true;
1124 if ($found) {
1125 $result = new stdClass();
1126 $result->page = $this;
1127 $result->settings = array();
1128 return array($this->name => $result);
1129 } else {
1130 return array();
1135 * Determines if the current user has access to this external page based on $this->req_capability.
1137 * @return bool True if user has access, false otherwise.
1139 public function check_access() {
1140 global $CFG;
1141 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1142 foreach($this->req_capability as $cap) {
1143 if (has_capability($cap, $context)) {
1144 return true;
1147 return false;
1151 * Is this external page hidden in admin tree block?
1153 * @return bool True if hidden
1155 public function is_hidden() {
1156 return $this->hidden;
1160 * Show we display Save button at the page bottom?
1161 * @return bool
1163 public function show_save() {
1164 return false;
1170 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1174 class admin_settingpage implements part_of_admin_tree {
1176 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1177 public $name;
1179 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1180 public $visiblename;
1182 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1183 public $settings;
1185 /** @var string The role capability/permission a user must have to access this external page. */
1186 public $req_capability;
1188 /** @var object The context in which capability/permission should be checked, default is site context. */
1189 public $context;
1191 /** @var bool hidden in admin tree block. */
1192 public $hidden;
1194 /** @var mixed string of paths or array of strings of paths */
1195 public $path;
1197 /** @var array list of visible names of page parents */
1198 public $visiblepath;
1201 * see admin_settingpage for details of this function
1203 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1204 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1205 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1206 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1207 * @param stdClass $context The context the page relates to. Not sure what happens
1208 * if you specify something other than system or front page. Defaults to system.
1210 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1211 $this->settings = new stdClass();
1212 $this->name = $name;
1213 $this->visiblename = $visiblename;
1214 if (is_array($req_capability)) {
1215 $this->req_capability = $req_capability;
1216 } else {
1217 $this->req_capability = array($req_capability);
1219 $this->hidden = $hidden;
1220 $this->context = $context;
1224 * see admin_category
1226 * @param string $name
1227 * @param bool $findpath
1228 * @return mixed Object (this) if name == this->name, else returns null
1230 public function locate($name, $findpath=false) {
1231 if ($this->name == $name) {
1232 if ($findpath) {
1233 $this->visiblepath = array($this->visiblename);
1234 $this->path = array($this->name);
1236 return $this;
1237 } else {
1238 $return = NULL;
1239 return $return;
1244 * Search string in settings page.
1246 * @param string $query
1247 * @return array
1249 public function search($query) {
1250 $found = array();
1252 foreach ($this->settings as $setting) {
1253 if ($setting->is_related($query)) {
1254 $found[] = $setting;
1258 if ($found) {
1259 $result = new stdClass();
1260 $result->page = $this;
1261 $result->settings = $found;
1262 return array($this->name => $result);
1265 $textlib = textlib_get_instance();
1267 $found = false;
1268 if (strpos(strtolower($this->name), $query) !== false) {
1269 $found = true;
1270 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1271 $found = true;
1273 if ($found) {
1274 $result = new stdClass();
1275 $result->page = $this;
1276 $result->settings = array();
1277 return array($this->name => $result);
1278 } else {
1279 return array();
1284 * This function always returns false, required by interface
1286 * @param string $name
1287 * @return bool Always false
1289 public function prune($name) {
1290 return false;
1294 * adds an admin_setting to this admin_settingpage
1296 * 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
1297 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1299 * @param object $setting is the admin_setting object you want to add
1300 * @return bool true if successful, false if not
1302 public function add($setting) {
1303 if (!($setting instanceof admin_setting)) {
1304 debugging('error - not a setting instance');
1305 return false;
1308 $this->settings->{$setting->name} = $setting;
1309 return true;
1313 * see admin_externalpage
1315 * @return bool Returns true for yes false for no
1317 public function check_access() {
1318 global $CFG;
1319 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1320 foreach($this->req_capability as $cap) {
1321 if (has_capability($cap, $context)) {
1322 return true;
1325 return false;
1329 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1330 * @return string Returns an XHTML string
1332 public function output_html() {
1333 $adminroot = admin_get_root();
1334 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1335 foreach($this->settings as $setting) {
1336 $fullname = $setting->get_full_name();
1337 if (array_key_exists($fullname, $adminroot->errors)) {
1338 $data = $adminroot->errors[$fullname]->data;
1339 } else {
1340 $data = $setting->get_setting();
1341 // do not use defaults if settings not available - upgrade settings handles the defaults!
1343 $return .= $setting->output_html($data);
1345 $return .= '</fieldset>';
1346 return $return;
1350 * Is this settings page hidden in admin tree block?
1352 * @return bool True if hidden
1354 public function is_hidden() {
1355 return $this->hidden;
1359 * Show we display Save button at the page bottom?
1360 * @return bool
1362 public function show_save() {
1363 foreach($this->settings as $setting) {
1364 if (empty($setting->nosave)) {
1365 return true;
1368 return false;
1374 * Admin settings class. Only exists on setting pages.
1375 * Read & write happens at this level; no authentication.
1377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1379 abstract class admin_setting {
1380 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1381 public $name;
1382 /** @var string localised name */
1383 public $visiblename;
1384 /** @var string localised long description in Markdown format */
1385 public $description;
1386 /** @var mixed Can be string or array of string */
1387 public $defaultsetting;
1388 /** @var string */
1389 public $updatedcallback;
1390 /** @var mixed can be String or Null. Null means main config table */
1391 public $plugin; // null means main config table
1392 /** @var bool true indicates this setting does not actually save anything, just information */
1393 public $nosave = false;
1394 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1395 public $affectsmodinfo = false;
1398 * Constructor
1399 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1400 * or 'myplugin/mysetting' for ones in config_plugins.
1401 * @param string $visiblename localised name
1402 * @param string $description localised long description
1403 * @param mixed $defaultsetting string or array depending on implementation
1405 public function __construct($name, $visiblename, $description, $defaultsetting) {
1406 $this->parse_setting_name($name);
1407 $this->visiblename = $visiblename;
1408 $this->description = $description;
1409 $this->defaultsetting = $defaultsetting;
1413 * Set up $this->name and potentially $this->plugin
1415 * Set up $this->name and possibly $this->plugin based on whether $name looks
1416 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1417 * on the names, that is, output a developer debug warning if the name
1418 * contains anything other than [a-zA-Z0-9_]+.
1420 * @param string $name the setting name passed in to the constructor.
1422 private function parse_setting_name($name) {
1423 $bits = explode('/', $name);
1424 if (count($bits) > 2) {
1425 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1427 $this->name = array_pop($bits);
1428 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1429 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1431 if (!empty($bits)) {
1432 $this->plugin = array_pop($bits);
1433 if ($this->plugin === 'moodle') {
1434 $this->plugin = null;
1435 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1436 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1442 * Returns the fullname prefixed by the plugin
1443 * @return string
1445 public function get_full_name() {
1446 return 's_'.$this->plugin.'_'.$this->name;
1450 * Returns the ID string based on plugin and name
1451 * @return string
1453 public function get_id() {
1454 return 'id_s_'.$this->plugin.'_'.$this->name;
1458 * @param bool $affectsmodinfo If true, changes to this setting will
1459 * cause the course cache to be rebuilt
1461 public function set_affects_modinfo($affectsmodinfo) {
1462 $this->affectsmodinfo = $affectsmodinfo;
1466 * Returns the config if possible
1468 * @return mixed returns config if successful else null
1470 public function config_read($name) {
1471 global $CFG;
1472 if (!empty($this->plugin)) {
1473 $value = get_config($this->plugin, $name);
1474 return $value === false ? NULL : $value;
1476 } else {
1477 if (isset($CFG->$name)) {
1478 return $CFG->$name;
1479 } else {
1480 return NULL;
1486 * Used to set a config pair and log change
1488 * @param string $name
1489 * @param mixed $value Gets converted to string if not null
1490 * @return bool Write setting to config table
1492 public function config_write($name, $value) {
1493 global $DB, $USER, $CFG;
1495 if ($this->nosave) {
1496 return true;
1499 // make sure it is a real change
1500 $oldvalue = get_config($this->plugin, $name);
1501 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1502 $value = is_null($value) ? null : (string)$value;
1504 if ($oldvalue === $value) {
1505 return true;
1508 // store change
1509 set_config($name, $value, $this->plugin);
1511 // Some admin settings affect course modinfo
1512 if ($this->affectsmodinfo) {
1513 // Clear course cache for all courses
1514 rebuild_course_cache(0, true);
1517 // log change
1518 $log = new stdClass();
1519 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1520 $log->timemodified = time();
1521 $log->plugin = $this->plugin;
1522 $log->name = $name;
1523 $log->value = $value;
1524 $log->oldvalue = $oldvalue;
1525 $DB->insert_record('config_log', $log);
1527 return true; // BC only
1531 * Returns current value of this setting
1532 * @return mixed array or string depending on instance, NULL means not set yet
1534 public abstract function get_setting();
1537 * Returns default setting if exists
1538 * @return mixed array or string depending on instance; NULL means no default, user must supply
1540 public function get_defaultsetting() {
1541 $adminroot = admin_get_root(false, false);
1542 if (!empty($adminroot->custom_defaults)) {
1543 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1544 if (isset($adminroot->custom_defaults[$plugin])) {
1545 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1546 return $adminroot->custom_defaults[$plugin][$this->name];
1550 return $this->defaultsetting;
1554 * Store new setting
1556 * @param mixed $data string or array, must not be NULL
1557 * @return string empty string if ok, string error message otherwise
1559 public abstract function write_setting($data);
1562 * Return part of form with setting
1563 * This function should always be overwritten
1565 * @param mixed $data array or string depending on setting
1566 * @param string $query
1567 * @return string
1569 public function output_html($data, $query='') {
1570 // should be overridden
1571 return;
1575 * Function called if setting updated - cleanup, cache reset, etc.
1576 * @param string $functionname Sets the function name
1577 * @return void
1579 public function set_updatedcallback($functionname) {
1580 $this->updatedcallback = $functionname;
1584 * Is setting related to query text - used when searching
1585 * @param string $query
1586 * @return bool
1588 public function is_related($query) {
1589 if (strpos(strtolower($this->name), $query) !== false) {
1590 return true;
1592 $textlib = textlib_get_instance();
1593 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1594 return true;
1596 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1597 return true;
1599 $current = $this->get_setting();
1600 if (!is_null($current)) {
1601 if (is_string($current)) {
1602 if (strpos($textlib->strtolower($current), $query) !== false) {
1603 return true;
1607 $default = $this->get_defaultsetting();
1608 if (!is_null($default)) {
1609 if (is_string($default)) {
1610 if (strpos($textlib->strtolower($default), $query) !== false) {
1611 return true;
1615 return false;
1621 * No setting - just heading and text.
1623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1625 class admin_setting_heading extends admin_setting {
1628 * not a setting, just text
1629 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1630 * @param string $heading heading
1631 * @param string $information text in box
1633 public function __construct($name, $heading, $information) {
1634 $this->nosave = true;
1635 parent::__construct($name, $heading, $information, '');
1639 * Always returns true
1640 * @return bool Always returns true
1642 public function get_setting() {
1643 return true;
1647 * Always returns true
1648 * @return bool Always returns true
1650 public function get_defaultsetting() {
1651 return true;
1655 * Never write settings
1656 * @return string Always returns an empty string
1658 public function write_setting($data) {
1659 // do not write any setting
1660 return '';
1664 * Returns an HTML string
1665 * @return string Returns an HTML string
1667 public function output_html($data, $query='') {
1668 global $OUTPUT;
1669 $return = '';
1670 if ($this->visiblename != '') {
1671 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1673 if ($this->description != '') {
1674 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1676 return $return;
1682 * The most flexibly setting, user is typing text
1684 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1686 class admin_setting_configtext extends admin_setting {
1688 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1689 public $paramtype;
1690 /** @var int default field size */
1691 public $size;
1694 * Config text constructor
1696 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1697 * @param string $visiblename localised
1698 * @param string $description long localised info
1699 * @param string $defaultsetting
1700 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1701 * @param int $size default field size
1703 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1704 $this->paramtype = $paramtype;
1705 if (!is_null($size)) {
1706 $this->size = $size;
1707 } else {
1708 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1710 parent::__construct($name, $visiblename, $description, $defaultsetting);
1714 * Return the setting
1716 * @return mixed returns config if successful else null
1718 public function get_setting() {
1719 return $this->config_read($this->name);
1722 public function write_setting($data) {
1723 if ($this->paramtype === PARAM_INT and $data === '') {
1724 // do not complain if '' used instead of 0
1725 $data = 0;
1727 // $data is a string
1728 $validated = $this->validate($data);
1729 if ($validated !== true) {
1730 return $validated;
1732 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1736 * Validate data before storage
1737 * @param string data
1738 * @return mixed true if ok string if error found
1740 public function validate($data) {
1741 // allow paramtype to be a custom regex if it is the form of /pattern/
1742 if (preg_match('#^/.*/$#', $this->paramtype)) {
1743 if (preg_match($this->paramtype, $data)) {
1744 return true;
1745 } else {
1746 return get_string('validateerror', 'admin');
1749 } else if ($this->paramtype === PARAM_RAW) {
1750 return true;
1752 } else {
1753 $cleaned = clean_param($data, $this->paramtype);
1754 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1755 return true;
1756 } else {
1757 return get_string('validateerror', 'admin');
1763 * Return an XHTML string for the setting
1764 * @return string Returns an XHTML string
1766 public function output_html($data, $query='') {
1767 $default = $this->get_defaultsetting();
1769 return format_admin_setting($this, $this->visiblename,
1770 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1771 $this->description, true, '', $default, $query);
1777 * General text area without html editor.
1779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1781 class admin_setting_configtextarea extends admin_setting_configtext {
1782 private $rows;
1783 private $cols;
1786 * @param string $name
1787 * @param string $visiblename
1788 * @param string $description
1789 * @param mixed $defaultsetting string or array
1790 * @param mixed $paramtype
1791 * @param string $cols The number of columns to make the editor
1792 * @param string $rows The number of rows to make the editor
1794 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1795 $this->rows = $rows;
1796 $this->cols = $cols;
1797 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1801 * Returns an XHTML string for the editor
1803 * @param string $data
1804 * @param string $query
1805 * @return string XHTML string for the editor
1807 public function output_html($data, $query='') {
1808 $default = $this->get_defaultsetting();
1810 $defaultinfo = $default;
1811 if (!is_null($default) and $default !== '') {
1812 $defaultinfo = "\n".$default;
1815 return format_admin_setting($this, $this->visiblename,
1816 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1817 $this->description, true, '', $defaultinfo, $query);
1823 * General text area with html editor.
1825 class admin_setting_confightmleditor extends admin_setting_configtext {
1826 private $rows;
1827 private $cols;
1830 * @param string $name
1831 * @param string $visiblename
1832 * @param string $description
1833 * @param mixed $defaultsetting string or array
1834 * @param mixed $paramtype
1836 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1837 $this->rows = $rows;
1838 $this->cols = $cols;
1839 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1840 editors_head_setup();
1844 * Returns an XHTML string for the editor
1846 * @param string $data
1847 * @param string $query
1848 * @return string XHTML string for the editor
1850 public function output_html($data, $query='') {
1851 $default = $this->get_defaultsetting();
1853 $defaultinfo = $default;
1854 if (!is_null($default) and $default !== '') {
1855 $defaultinfo = "\n".$default;
1858 $editor = editors_get_preferred_editor(FORMAT_HTML);
1859 $editor->use_editor($this->get_id(), array('noclean'=>true));
1861 return format_admin_setting($this, $this->visiblename,
1862 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1863 $this->description, true, '', $defaultinfo, $query);
1869 * Password field, allows unmasking of password
1871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1873 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1875 * Constructor
1876 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1877 * @param string $visiblename localised
1878 * @param string $description long localised info
1879 * @param string $defaultsetting default password
1881 public function __construct($name, $visiblename, $description, $defaultsetting) {
1882 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1886 * Returns XHTML for the field
1887 * Writes Javascript into the HTML below right before the last div
1889 * @todo Make javascript available through newer methods if possible
1890 * @param string $data Value for the field
1891 * @param string $query Passed as final argument for format_admin_setting
1892 * @return string XHTML field
1894 public function output_html($data, $query='') {
1895 $id = $this->get_id();
1896 $unmask = get_string('unmaskpassword', 'form');
1897 $unmaskjs = '<script type="text/javascript">
1898 //<![CDATA[
1899 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1901 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1903 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1905 var unmaskchb = document.createElement("input");
1906 unmaskchb.setAttribute("type", "checkbox");
1907 unmaskchb.setAttribute("id", "'.$id.'unmask");
1908 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1909 unmaskdiv.appendChild(unmaskchb);
1911 var unmasklbl = document.createElement("label");
1912 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1913 if (is_ie) {
1914 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1915 } else {
1916 unmasklbl.setAttribute("for", "'.$id.'unmask");
1918 unmaskdiv.appendChild(unmasklbl);
1920 if (is_ie) {
1921 // ugly hack to work around the famous onchange IE bug
1922 unmaskchb.onclick = function() {this.blur();};
1923 unmaskdiv.onclick = function() {this.blur();};
1925 //]]>
1926 </script>';
1927 return format_admin_setting($this, $this->visiblename,
1928 '<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>',
1929 $this->description, true, '', NULL, $query);
1935 * Path to directory
1937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1939 class admin_setting_configfile extends admin_setting_configtext {
1941 * Constructor
1942 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1943 * @param string $visiblename localised
1944 * @param string $description long localised info
1945 * @param string $defaultdirectory default directory location
1947 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1948 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1952 * Returns XHTML for the field
1954 * Returns XHTML for the field and also checks whether the file
1955 * specified in $data exists using file_exists()
1957 * @param string $data File name and path to use in value attr
1958 * @param string $query
1959 * @return string XHTML field
1961 public function output_html($data, $query='') {
1962 $default = $this->get_defaultsetting();
1964 if ($data) {
1965 if (file_exists($data)) {
1966 $executable = '<span class="pathok">&#x2714;</span>';
1967 } else {
1968 $executable = '<span class="patherror">&#x2718;</span>';
1970 } else {
1971 $executable = '';
1974 return format_admin_setting($this, $this->visiblename,
1975 '<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>',
1976 $this->description, true, '', $default, $query);
1982 * Path to executable file
1984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1986 class admin_setting_configexecutable extends admin_setting_configfile {
1989 * Returns an XHTML field
1991 * @param string $data This is the value for the field
1992 * @param string $query
1993 * @return string XHTML field
1995 public function output_html($data, $query='') {
1996 $default = $this->get_defaultsetting();
1998 if ($data) {
1999 if (file_exists($data) and is_executable($data)) {
2000 $executable = '<span class="pathok">&#x2714;</span>';
2001 } else {
2002 $executable = '<span class="patherror">&#x2718;</span>';
2004 } else {
2005 $executable = '';
2008 return format_admin_setting($this, $this->visiblename,
2009 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2010 $this->description, true, '', $default, $query);
2016 * Path to directory
2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2020 class admin_setting_configdirectory extends admin_setting_configfile {
2023 * Returns an XHTML field
2025 * @param string $data This is the value for the field
2026 * @param string $query
2027 * @return string XHTML
2029 public function output_html($data, $query='') {
2030 $default = $this->get_defaultsetting();
2032 if ($data) {
2033 if (file_exists($data) and is_dir($data)) {
2034 $executable = '<span class="pathok">&#x2714;</span>';
2035 } else {
2036 $executable = '<span class="patherror">&#x2718;</span>';
2038 } else {
2039 $executable = '';
2042 return format_admin_setting($this, $this->visiblename,
2043 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2044 $this->description, true, '', $default, $query);
2050 * Checkbox
2052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2054 class admin_setting_configcheckbox extends admin_setting {
2055 /** @var string Value used when checked */
2056 public $yes;
2057 /** @var string Value used when not checked */
2058 public $no;
2061 * Constructor
2062 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2063 * @param string $visiblename localised
2064 * @param string $description long localised info
2065 * @param string $defaultsetting
2066 * @param string $yes value used when checked
2067 * @param string $no value used when not checked
2069 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2070 parent::__construct($name, $visiblename, $description, $defaultsetting);
2071 $this->yes = (string)$yes;
2072 $this->no = (string)$no;
2076 * Retrieves the current setting using the objects name
2078 * @return string
2080 public function get_setting() {
2081 return $this->config_read($this->name);
2085 * Sets the value for the setting
2087 * Sets the value for the setting to either the yes or no values
2088 * of the object by comparing $data to yes
2090 * @param mixed $data Gets converted to str for comparison against yes value
2091 * @return string empty string or error
2093 public function write_setting($data) {
2094 if ((string)$data === $this->yes) { // convert to strings before comparison
2095 $data = $this->yes;
2096 } else {
2097 $data = $this->no;
2099 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2103 * Returns an XHTML checkbox field
2105 * @param string $data If $data matches yes then checkbox is checked
2106 * @param string $query
2107 * @return string XHTML field
2109 public function output_html($data, $query='') {
2110 $default = $this->get_defaultsetting();
2112 if (!is_null($default)) {
2113 if ((string)$default === $this->yes) {
2114 $defaultinfo = get_string('checkboxyes', 'admin');
2115 } else {
2116 $defaultinfo = get_string('checkboxno', 'admin');
2118 } else {
2119 $defaultinfo = NULL;
2122 if ((string)$data === $this->yes) { // convert to strings before comparison
2123 $checked = 'checked="checked"';
2124 } else {
2125 $checked = '';
2128 return format_admin_setting($this, $this->visiblename,
2129 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2130 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2131 $this->description, true, '', $defaultinfo, $query);
2137 * Multiple checkboxes, each represents different value, stored in csv format
2139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2141 class admin_setting_configmulticheckbox extends admin_setting {
2142 /** @var array Array of choices value=>label */
2143 public $choices;
2146 * Constructor: uses parent::__construct
2148 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2149 * @param string $visiblename localised
2150 * @param string $description long localised info
2151 * @param array $defaultsetting array of selected
2152 * @param array $choices array of $value=>$label for each checkbox
2154 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2155 $this->choices = $choices;
2156 parent::__construct($name, $visiblename, $description, $defaultsetting);
2160 * This public function may be used in ancestors for lazy loading of choices
2162 * @todo Check if this function is still required content commented out only returns true
2163 * @return bool true if loaded, false if error
2165 public function load_choices() {
2167 if (is_array($this->choices)) {
2168 return true;
2170 .... load choices here
2172 return true;
2176 * Is setting related to query text - used when searching
2178 * @param string $query
2179 * @return bool true on related, false on not or failure
2181 public function is_related($query) {
2182 if (!$this->load_choices() or empty($this->choices)) {
2183 return false;
2185 if (parent::is_related($query)) {
2186 return true;
2189 $textlib = textlib_get_instance();
2190 foreach ($this->choices as $desc) {
2191 if (strpos($textlib->strtolower($desc), $query) !== false) {
2192 return true;
2195 return false;
2199 * Returns the current setting if it is set
2201 * @return mixed null if null, else an array
2203 public function get_setting() {
2204 $result = $this->config_read($this->name);
2206 if (is_null($result)) {
2207 return NULL;
2209 if ($result === '') {
2210 return array();
2212 $enabled = explode(',', $result);
2213 $setting = array();
2214 foreach ($enabled as $option) {
2215 $setting[$option] = 1;
2217 return $setting;
2221 * Saves the setting(s) provided in $data
2223 * @param array $data An array of data, if not array returns empty str
2224 * @return mixed empty string on useless data or bool true=success, false=failed
2226 public function write_setting($data) {
2227 if (!is_array($data)) {
2228 return ''; // ignore it
2230 if (!$this->load_choices() or empty($this->choices)) {
2231 return '';
2233 unset($data['xxxxx']);
2234 $result = array();
2235 foreach ($data as $key => $value) {
2236 if ($value and array_key_exists($key, $this->choices)) {
2237 $result[] = $key;
2240 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2244 * Returns XHTML field(s) as required by choices
2246 * Relies on data being an array should data ever be another valid vartype with
2247 * acceptable value this may cause a warning/error
2248 * if (!is_array($data)) would fix the problem
2250 * @todo Add vartype handling to ensure $data is an array
2252 * @param array $data An array of checked values
2253 * @param string $query
2254 * @return string XHTML field
2256 public function output_html($data, $query='') {
2257 if (!$this->load_choices() or empty($this->choices)) {
2258 return '';
2260 $default = $this->get_defaultsetting();
2261 if (is_null($default)) {
2262 $default = array();
2264 if (is_null($data)) {
2265 $data = array();
2267 $options = array();
2268 $defaults = array();
2269 foreach ($this->choices as $key=>$description) {
2270 if (!empty($data[$key])) {
2271 $checked = 'checked="checked"';
2272 } else {
2273 $checked = '';
2275 if (!empty($default[$key])) {
2276 $defaults[] = $description;
2279 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2280 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2283 if (is_null($default)) {
2284 $defaultinfo = NULL;
2285 } else if (!empty($defaults)) {
2286 $defaultinfo = implode(', ', $defaults);
2287 } else {
2288 $defaultinfo = get_string('none');
2291 $return = '<div class="form-multicheckbox">';
2292 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2293 if ($options) {
2294 $return .= '<ul>';
2295 foreach ($options as $option) {
2296 $return .= '<li>'.$option.'</li>';
2298 $return .= '</ul>';
2300 $return .= '</div>';
2302 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2309 * Multiple checkboxes 2, value stored as string 00101011
2311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2313 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2316 * Returns the setting if set
2318 * @return mixed null if not set, else an array of set settings
2320 public function get_setting() {
2321 $result = $this->config_read($this->name);
2322 if (is_null($result)) {
2323 return NULL;
2325 if (!$this->load_choices()) {
2326 return NULL;
2328 $result = str_pad($result, count($this->choices), '0');
2329 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2330 $setting = array();
2331 foreach ($this->choices as $key=>$unused) {
2332 $value = array_shift($result);
2333 if ($value) {
2334 $setting[$key] = 1;
2337 return $setting;
2341 * Save setting(s) provided in $data param
2343 * @param array $data An array of settings to save
2344 * @return mixed empty string for bad data or bool true=>success, false=>error
2346 public function write_setting($data) {
2347 if (!is_array($data)) {
2348 return ''; // ignore it
2350 if (!$this->load_choices() or empty($this->choices)) {
2351 return '';
2353 $result = '';
2354 foreach ($this->choices as $key=>$unused) {
2355 if (!empty($data[$key])) {
2356 $result .= '1';
2357 } else {
2358 $result .= '0';
2361 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2367 * Select one value from list
2369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2371 class admin_setting_configselect extends admin_setting {
2372 /** @var array Array of choices value=>label */
2373 public $choices;
2376 * Constructor
2377 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2378 * @param string $visiblename localised
2379 * @param string $description long localised info
2380 * @param string|int $defaultsetting
2381 * @param array $choices array of $value=>$label for each selection
2383 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2384 $this->choices = $choices;
2385 parent::__construct($name, $visiblename, $description, $defaultsetting);
2389 * This function may be used in ancestors for lazy loading of choices
2391 * Override this method if loading of choices is expensive, such
2392 * as when it requires multiple db requests.
2394 * @return bool true if loaded, false if error
2396 public function load_choices() {
2398 if (is_array($this->choices)) {
2399 return true;
2401 .... load choices here
2403 return true;
2407 * Check if this is $query is related to a choice
2409 * @param string $query
2410 * @return bool true if related, false if not
2412 public function is_related($query) {
2413 if (parent::is_related($query)) {
2414 return true;
2416 if (!$this->load_choices()) {
2417 return false;
2419 $textlib = textlib_get_instance();
2420 foreach ($this->choices as $key=>$value) {
2421 if (strpos($textlib->strtolower($key), $query) !== false) {
2422 return true;
2424 if (strpos($textlib->strtolower($value), $query) !== false) {
2425 return true;
2428 return false;
2432 * Return the setting
2434 * @return mixed returns config if successful else null
2436 public function get_setting() {
2437 return $this->config_read($this->name);
2441 * Save a setting
2443 * @param string $data
2444 * @return string empty of error string
2446 public function write_setting($data) {
2447 if (!$this->load_choices() or empty($this->choices)) {
2448 return '';
2450 if (!array_key_exists($data, $this->choices)) {
2451 return ''; // ignore it
2454 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2458 * Returns XHTML select field
2460 * Ensure the options are loaded, and generate the XHTML for the select
2461 * element and any warning message. Separating this out from output_html
2462 * makes it easier to subclass this class.
2464 * @param string $data the option to show as selected.
2465 * @param string $current the currently selected option in the database, null if none.
2466 * @param string $default the default selected option.
2467 * @return array the HTML for the select element, and a warning message.
2469 public function output_select_html($data, $current, $default, $extraname = '') {
2470 if (!$this->load_choices() or empty($this->choices)) {
2471 return array('', '');
2474 $warning = '';
2475 if (is_null($current)) {
2476 // first run
2477 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2478 // no warning
2479 } else if (!array_key_exists($current, $this->choices)) {
2480 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2481 if (!is_null($default) and $data == $current) {
2482 $data = $default; // use default instead of first value when showing the form
2486 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2487 foreach ($this->choices as $key => $value) {
2488 // the string cast is needed because key may be integer - 0 is equal to most strings!
2489 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2491 $selecthtml .= '</select>';
2492 return array($selecthtml, $warning);
2496 * Returns XHTML select field and wrapping div(s)
2498 * @see output_select_html()
2500 * @param string $data the option to show as selected
2501 * @param string $query
2502 * @return string XHTML field and wrapping div
2504 public function output_html($data, $query='') {
2505 $default = $this->get_defaultsetting();
2506 $current = $this->get_setting();
2508 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2509 if (!$selecthtml) {
2510 return '';
2513 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2514 $defaultinfo = $this->choices[$default];
2515 } else {
2516 $defaultinfo = NULL;
2519 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2521 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2527 * Select multiple items from list
2529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 class admin_setting_configmultiselect extends admin_setting_configselect {
2533 * Constructor
2534 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2535 * @param string $visiblename localised
2536 * @param string $description long localised info
2537 * @param array $defaultsetting array of selected items
2538 * @param array $choices array of $value=>$label for each list item
2540 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2541 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2545 * Returns the select setting(s)
2547 * @return mixed null or array. Null if no settings else array of setting(s)
2549 public function get_setting() {
2550 $result = $this->config_read($this->name);
2551 if (is_null($result)) {
2552 return NULL;
2554 if ($result === '') {
2555 return array();
2557 return explode(',', $result);
2561 * Saves setting(s) provided through $data
2563 * Potential bug in the works should anyone call with this function
2564 * using a vartype that is not an array
2566 * @param array $data
2568 public function write_setting($data) {
2569 if (!is_array($data)) {
2570 return ''; //ignore it
2572 if (!$this->load_choices() or empty($this->choices)) {
2573 return '';
2576 unset($data['xxxxx']);
2578 $save = array();
2579 foreach ($data as $value) {
2580 if (!array_key_exists($value, $this->choices)) {
2581 continue; // ignore it
2583 $save[] = $value;
2586 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2590 * Is setting related to query text - used when searching
2592 * @param string $query
2593 * @return bool true if related, false if not
2595 public function is_related($query) {
2596 if (!$this->load_choices() or empty($this->choices)) {
2597 return false;
2599 if (parent::is_related($query)) {
2600 return true;
2603 $textlib = textlib_get_instance();
2604 foreach ($this->choices as $desc) {
2605 if (strpos($textlib->strtolower($desc), $query) !== false) {
2606 return true;
2609 return false;
2613 * Returns XHTML multi-select field
2615 * @todo Add vartype handling to ensure $data is an array
2616 * @param array $data Array of values to select by default
2617 * @param string $query
2618 * @return string XHTML multi-select field
2620 public function output_html($data, $query='') {
2621 if (!$this->load_choices() or empty($this->choices)) {
2622 return '';
2624 $choices = $this->choices;
2625 $default = $this->get_defaultsetting();
2626 if (is_null($default)) {
2627 $default = array();
2629 if (is_null($data)) {
2630 $data = array();
2633 $defaults = array();
2634 $size = min(10, count($this->choices));
2635 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2636 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2637 foreach ($this->choices as $key => $description) {
2638 if (in_array($key, $data)) {
2639 $selected = 'selected="selected"';
2640 } else {
2641 $selected = '';
2643 if (in_array($key, $default)) {
2644 $defaults[] = $description;
2647 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2650 if (is_null($default)) {
2651 $defaultinfo = NULL;
2652 } if (!empty($defaults)) {
2653 $defaultinfo = implode(', ', $defaults);
2654 } else {
2655 $defaultinfo = get_string('none');
2658 $return .= '</select></div>';
2659 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2664 * Time selector
2666 * This is a liiitle bit messy. we're using two selects, but we're returning
2667 * them as an array named after $name (so we only use $name2 internally for the setting)
2669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2671 class admin_setting_configtime extends admin_setting {
2672 /** @var string Used for setting second select (minutes) */
2673 public $name2;
2676 * Constructor
2677 * @param string $hoursname setting for hours
2678 * @param string $minutesname setting for hours
2679 * @param string $visiblename localised
2680 * @param string $description long localised info
2681 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2683 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2684 $this->name2 = $minutesname;
2685 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2689 * Get the selected time
2691 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2693 public function get_setting() {
2694 $result1 = $this->config_read($this->name);
2695 $result2 = $this->config_read($this->name2);
2696 if (is_null($result1) or is_null($result2)) {
2697 return NULL;
2700 return array('h' => $result1, 'm' => $result2);
2704 * Store the time (hours and minutes)
2706 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2707 * @return bool true if success, false if not
2709 public function write_setting($data) {
2710 if (!is_array($data)) {
2711 return '';
2714 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2715 return ($result ? '' : get_string('errorsetting', 'admin'));
2719 * Returns XHTML time select fields
2721 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2722 * @param string $query
2723 * @return string XHTML time select fields and wrapping div(s)
2725 public function output_html($data, $query='') {
2726 $default = $this->get_defaultsetting();
2728 if (is_array($default)) {
2729 $defaultinfo = $default['h'].':'.$default['m'];
2730 } else {
2731 $defaultinfo = NULL;
2734 $return = '<div class="form-time defaultsnext">'.
2735 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2736 for ($i = 0; $i < 24; $i++) {
2737 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2739 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2740 for ($i = 0; $i < 60; $i += 5) {
2741 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2743 $return .= '</select></div>';
2744 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2751 * Used to validate a textarea used for ip addresses
2753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2755 class admin_setting_configiplist extends admin_setting_configtextarea {
2758 * Validate the contents of the textarea as IP addresses
2760 * Used to validate a new line separated list of IP addresses collected from
2761 * a textarea control
2763 * @param string $data A list of IP Addresses separated by new lines
2764 * @return mixed bool true for success or string:error on failure
2766 public function validate($data) {
2767 if(!empty($data)) {
2768 $ips = explode("\n", $data);
2769 } else {
2770 return true;
2772 $result = true;
2773 foreach($ips as $ip) {
2774 $ip = trim($ip);
2775 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2776 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2777 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2778 $result = true;
2779 } else {
2780 $result = false;
2781 break;
2784 if($result) {
2785 return true;
2786 } else {
2787 return get_string('validateerror', 'admin');
2794 * An admin setting for selecting one or more users who have a capability
2795 * in the system context
2797 * An admin setting for selecting one or more users, who have a particular capability
2798 * in the system context. Warning, make sure the list will never be too long. There is
2799 * no paging or searching of this list.
2801 * To correctly get a list of users from this config setting, you need to call the
2802 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2804 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2806 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2807 /** @var string The capabilities name */
2808 protected $capability;
2809 /** @var int include admin users too */
2810 protected $includeadmins;
2813 * Constructor.
2815 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2816 * @param string $visiblename localised name
2817 * @param string $description localised long description
2818 * @param array $defaultsetting array of usernames
2819 * @param string $capability string capability name.
2820 * @param bool $includeadmins include administrators
2822 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2823 $this->capability = $capability;
2824 $this->includeadmins = $includeadmins;
2825 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2829 * Load all of the uses who have the capability into choice array
2831 * @return bool Always returns true
2833 function load_choices() {
2834 if (is_array($this->choices)) {
2835 return true;
2837 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2838 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2839 $this->choices = array(
2840 '$@NONE@$' => get_string('nobody'),
2841 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2843 if ($this->includeadmins) {
2844 $admins = get_admins();
2845 foreach ($admins as $user) {
2846 $this->choices[$user->id] = fullname($user);
2849 if (is_array($users)) {
2850 foreach ($users as $user) {
2851 $this->choices[$user->id] = fullname($user);
2854 return true;
2858 * Returns the default setting for class
2860 * @return mixed Array, or string. Empty string if no default
2862 public function get_defaultsetting() {
2863 $this->load_choices();
2864 $defaultsetting = parent::get_defaultsetting();
2865 if (empty($defaultsetting)) {
2866 return array('$@NONE@$');
2867 } else if (array_key_exists($defaultsetting, $this->choices)) {
2868 return $defaultsetting;
2869 } else {
2870 return '';
2875 * Returns the current setting
2877 * @return mixed array or string
2879 public function get_setting() {
2880 $result = parent::get_setting();
2881 if ($result === null) {
2882 // this is necessary for settings upgrade
2883 return null;
2885 if (empty($result)) {
2886 $result = array('$@NONE@$');
2888 return $result;
2892 * Save the chosen setting provided as $data
2894 * @param array $data
2895 * @return mixed string or array
2897 public function write_setting($data) {
2898 // If all is selected, remove any explicit options.
2899 if (in_array('$@ALL@$', $data)) {
2900 $data = array('$@ALL@$');
2902 // None never needs to be written to the DB.
2903 if (in_array('$@NONE@$', $data)) {
2904 unset($data[array_search('$@NONE@$', $data)]);
2906 return parent::write_setting($data);
2912 * Special checkbox for calendar - resets SESSION vars.
2914 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2916 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2918 * Calls the parent::__construct with default values
2920 * name => calendar_adminseesall
2921 * visiblename => get_string('adminseesall', 'admin')
2922 * description => get_string('helpadminseesall', 'admin')
2923 * defaultsetting => 0
2925 public function __construct() {
2926 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2927 get_string('helpadminseesall', 'admin'), '0');
2931 * Stores the setting passed in $data
2933 * @param mixed gets converted to string for comparison
2934 * @return string empty string or error message
2936 public function write_setting($data) {
2937 global $SESSION;
2938 unset($SESSION->cal_courses_shown);
2939 return parent::write_setting($data);
2944 * Special select for settings that are altered in setup.php and can not be altered on the fly
2946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2948 class admin_setting_special_selectsetup extends admin_setting_configselect {
2950 * Reads the setting directly from the database
2952 * @return mixed
2954 public function get_setting() {
2955 // read directly from db!
2956 return get_config(NULL, $this->name);
2960 * Save the setting passed in $data
2962 * @param string $data The setting to save
2963 * @return string empty or error message
2965 public function write_setting($data) {
2966 global $CFG;
2967 // do not change active CFG setting!
2968 $current = $CFG->{$this->name};
2969 $result = parent::write_setting($data);
2970 $CFG->{$this->name} = $current;
2971 return $result;
2977 * Special select for frontpage - stores data in course table
2979 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2981 class admin_setting_sitesetselect extends admin_setting_configselect {
2983 * Returns the site name for the selected site
2985 * @see get_site()
2986 * @return string The site name of the selected site
2988 public function get_setting() {
2989 $site = get_site();
2990 return $site->{$this->name};
2994 * Updates the database and save the setting
2996 * @param string data
2997 * @return string empty or error message
2999 public function write_setting($data) {
3000 global $DB, $SITE;
3001 if (!in_array($data, array_keys($this->choices))) {
3002 return get_string('errorsetting', 'admin');
3004 $record = new stdClass();
3005 $record->id = SITEID;
3006 $temp = $this->name;
3007 $record->$temp = $data;
3008 $record->timemodified = time();
3009 // update $SITE
3010 $SITE->{$this->name} = $data;
3011 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3017 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3018 * block to hidden.
3020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3022 class admin_setting_bloglevel extends admin_setting_configselect {
3024 * Updates the database and save the setting
3026 * @param string data
3027 * @return string empty or error message
3029 public function write_setting($data) {
3030 global $DB, $CFG;
3031 if ($data['bloglevel'] == 0) {
3032 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3033 foreach ($blogblocks as $block) {
3034 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3036 } else {
3037 // reenable all blocks only when switching from disabled blogs
3038 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3039 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3040 foreach ($blogblocks as $block) {
3041 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3045 return parent::write_setting($data);
3051 * Special select - lists on the frontpage - hacky
3053 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3055 class admin_setting_courselist_frontpage extends admin_setting {
3056 /** @var array Array of choices value=>label */
3057 public $choices;
3060 * Construct override, requires one param
3062 * @param bool $loggedin Is the user logged in
3064 public function __construct($loggedin) {
3065 global $CFG;
3066 require_once($CFG->dirroot.'/course/lib.php');
3067 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3068 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3069 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3070 $defaults = array(FRONTPAGECOURSELIST);
3071 parent::__construct($name, $visiblename, $description, $defaults);
3075 * Loads the choices available
3077 * @return bool always returns true
3079 public function load_choices() {
3080 global $DB;
3081 if (is_array($this->choices)) {
3082 return true;
3084 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3085 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3086 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3087 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3088 'none' => get_string('none'));
3089 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3090 unset($this->choices[FRONTPAGECOURSELIST]);
3092 return true;
3096 * Returns the selected settings
3098 * @param mixed array or setting or null
3100 public function get_setting() {
3101 $result = $this->config_read($this->name);
3102 if (is_null($result)) {
3103 return NULL;
3105 if ($result === '') {
3106 return array();
3108 return explode(',', $result);
3112 * Save the selected options
3114 * @param array $data
3115 * @return mixed empty string (data is not an array) or bool true=success false=failure
3117 public function write_setting($data) {
3118 if (!is_array($data)) {
3119 return '';
3121 $this->load_choices();
3122 $save = array();
3123 foreach($data as $datum) {
3124 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3125 continue;
3127 $save[$datum] = $datum; // no duplicates
3129 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3133 * Return XHTML select field and wrapping div
3135 * @todo Add vartype handling to make sure $data is an array
3136 * @param array $data Array of elements to select by default
3137 * @return string XHTML select field and wrapping div
3139 public function output_html($data, $query='') {
3140 $this->load_choices();
3141 $currentsetting = array();
3142 foreach ($data as $key) {
3143 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3144 $currentsetting[] = $key; // already selected first
3148 $return = '<div class="form-group">';
3149 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3150 if (!array_key_exists($i, $currentsetting)) {
3151 $currentsetting[$i] = 'none'; //none
3153 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3154 foreach ($this->choices as $key => $value) {
3155 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3157 $return .= '</select>';
3158 if ($i !== count($this->choices) - 2) {
3159 $return .= '<br />';
3162 $return .= '</div>';
3164 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3170 * Special checkbox for frontpage - stores data in course table
3172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3174 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3176 * Returns the current sites name
3178 * @return string
3180 public function get_setting() {
3181 $site = get_site();
3182 return $site->{$this->name};
3186 * Save the selected setting
3188 * @param string $data The selected site
3189 * @return string empty string or error message
3191 public function write_setting($data) {
3192 global $DB, $SITE;
3193 $record = new stdClass();
3194 $record->id = SITEID;
3195 $record->{$this->name} = ($data == '1' ? 1 : 0);
3196 $record->timemodified = time();
3197 // update $SITE
3198 $SITE->{$this->name} = $data;
3199 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3204 * Special text for frontpage - stores data in course table.
3205 * Empty string means not set here. Manual setting is required.
3207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3209 class admin_setting_sitesettext extends admin_setting_configtext {
3211 * Return the current setting
3213 * @return mixed string or null
3215 public function get_setting() {
3216 $site = get_site();
3217 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3221 * Validate the selected data
3223 * @param string $data The selected value to validate
3224 * @return mixed true or message string
3226 public function validate($data) {
3227 $cleaned = clean_param($data, PARAM_MULTILANG);
3228 if ($cleaned === '') {
3229 return get_string('required');
3231 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3232 return true;
3233 } else {
3234 return get_string('validateerror', 'admin');
3239 * Save the selected setting
3241 * @param string $data The selected value
3242 * @return string empty or error message
3244 public function write_setting($data) {
3245 global $DB, $SITE;
3246 $data = trim($data);
3247 $validated = $this->validate($data);
3248 if ($validated !== true) {
3249 return $validated;
3252 $record = new stdClass();
3253 $record->id = SITEID;
3254 $record->{$this->name} = $data;
3255 $record->timemodified = time();
3256 // update $SITE
3257 $SITE->{$this->name} = $data;
3258 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3264 * Special text editor for site description.
3266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3268 class admin_setting_special_frontpagedesc extends admin_setting {
3270 * Calls parent::__construct with specific arguments
3272 public function __construct() {
3273 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3274 editors_head_setup();
3278 * Return the current setting
3279 * @return string The current setting
3281 public function get_setting() {
3282 $site = get_site();
3283 return $site->{$this->name};
3287 * Save the new setting
3289 * @param string $data The new value to save
3290 * @return string empty or error message
3292 public function write_setting($data) {
3293 global $DB, $SITE;
3294 $record = new stdClass();
3295 $record->id = SITEID;
3296 $record->{$this->name} = $data;
3297 $record->timemodified = time();
3298 $SITE->{$this->name} = $data;
3299 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3303 * Returns XHTML for the field plus wrapping div
3305 * @param string $data The current value
3306 * @param string $query
3307 * @return string The XHTML output
3309 public function output_html($data, $query='') {
3310 global $CFG;
3312 $CFG->adminusehtmleditor = can_use_html_editor();
3313 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3315 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3321 * Administration interface for emoticon_manager settings.
3323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3325 class admin_setting_emoticons extends admin_setting {
3328 * Calls parent::__construct with specific args
3330 public function __construct() {
3331 global $CFG;
3333 $manager = get_emoticon_manager();
3334 $defaults = $this->prepare_form_data($manager->default_emoticons());
3335 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3339 * Return the current setting(s)
3341 * @return array Current settings array
3343 public function get_setting() {
3344 global $CFG;
3346 $manager = get_emoticon_manager();
3348 $config = $this->config_read($this->name);
3349 if (is_null($config)) {
3350 return null;
3353 $config = $manager->decode_stored_config($config);
3354 if (is_null($config)) {
3355 return null;
3358 return $this->prepare_form_data($config);
3362 * Save selected settings
3364 * @param array $data Array of settings to save
3365 * @return bool
3367 public function write_setting($data) {
3369 $manager = get_emoticon_manager();
3370 $emoticons = $this->process_form_data($data);
3372 if ($emoticons === false) {
3373 return false;
3376 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3377 return ''; // success
3378 } else {
3379 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3384 * Return XHTML field(s) for options
3386 * @param array $data Array of options to set in HTML
3387 * @return string XHTML string for the fields and wrapping div(s)
3389 public function output_html($data, $query='') {
3390 global $OUTPUT;
3392 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3393 $out .= html_writer::start_tag('thead');
3394 $out .= html_writer::start_tag('tr');
3395 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3396 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3397 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3398 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3399 $out .= html_writer::tag('th', '');
3400 $out .= html_writer::end_tag('tr');
3401 $out .= html_writer::end_tag('thead');
3402 $out .= html_writer::start_tag('tbody');
3403 $i = 0;
3404 foreach($data as $field => $value) {
3405 switch ($i) {
3406 case 0:
3407 $out .= html_writer::start_tag('tr');
3408 $current_text = $value;
3409 $current_filename = '';
3410 $current_imagecomponent = '';
3411 $current_altidentifier = '';
3412 $current_altcomponent = '';
3413 case 1:
3414 $current_filename = $value;
3415 case 2:
3416 $current_imagecomponent = $value;
3417 case 3:
3418 $current_altidentifier = $value;
3419 case 4:
3420 $current_altcomponent = $value;
3423 $out .= html_writer::tag('td',
3424 html_writer::empty_tag('input',
3425 array(
3426 'type' => 'text',
3427 'class' => 'form-text',
3428 'name' => $this->get_full_name().'['.$field.']',
3429 'value' => $value,
3431 ), array('class' => 'c'.$i)
3434 if ($i == 4) {
3435 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3436 $alt = get_string($current_altidentifier, $current_altcomponent);
3437 } else {
3438 $alt = $current_text;
3440 if ($current_filename) {
3441 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3442 } else {
3443 $out .= html_writer::tag('td', '');
3445 $out .= html_writer::end_tag('tr');
3446 $i = 0;
3447 } else {
3448 $i++;
3452 $out .= html_writer::end_tag('tbody');
3453 $out .= html_writer::end_tag('table');
3454 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3455 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3457 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3461 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3463 * @see self::process_form_data()
3464 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3465 * @return array of form fields and their values
3467 protected function prepare_form_data(array $emoticons) {
3469 $form = array();
3470 $i = 0;
3471 foreach ($emoticons as $emoticon) {
3472 $form['text'.$i] = $emoticon->text;
3473 $form['imagename'.$i] = $emoticon->imagename;
3474 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3475 $form['altidentifier'.$i] = $emoticon->altidentifier;
3476 $form['altcomponent'.$i] = $emoticon->altcomponent;
3477 $i++;
3479 // add one more blank field set for new object
3480 $form['text'.$i] = '';
3481 $form['imagename'.$i] = '';
3482 $form['imagecomponent'.$i] = '';
3483 $form['altidentifier'.$i] = '';
3484 $form['altcomponent'.$i] = '';
3486 return $form;
3490 * Converts the data from admin settings form into an array of emoticon objects
3492 * @see self::prepare_form_data()
3493 * @param array $data array of admin form fields and values
3494 * @return false|array of emoticon objects
3496 protected function process_form_data(array $form) {
3498 $count = count($form); // number of form field values
3500 if ($count % 5) {
3501 // we must get five fields per emoticon object
3502 return false;
3505 $emoticons = array();
3506 for ($i = 0; $i < $count / 5; $i++) {
3507 $emoticon = new stdClass();
3508 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3509 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3510 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_SAFEDIR);
3511 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3512 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_SAFEDIR);
3514 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3515 // prevent from breaking http://url.addresses by accident
3516 $emoticon->text = '';
3519 if (strlen($emoticon->text) < 2) {
3520 // do not allow single character emoticons
3521 $emoticon->text = '';
3524 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3525 // emoticon text must contain some non-alphanumeric character to prevent
3526 // breaking HTML tags
3527 $emoticon->text = '';
3530 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3531 $emoticons[] = $emoticon;
3534 return $emoticons;
3540 * Special setting for limiting of the list of available languages.
3542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3544 class admin_setting_langlist extends admin_setting_configtext {
3546 * Calls parent::__construct with specific arguments
3548 public function __construct() {
3549 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3553 * Save the new setting
3555 * @param string $data The new setting
3556 * @return bool
3558 public function write_setting($data) {
3559 $return = parent::write_setting($data);
3560 get_string_manager()->reset_caches();
3561 return $return;
3567 * Selection of one of the recognised countries using the list
3568 * returned by {@link get_list_of_countries()}.
3570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3572 class admin_settings_country_select extends admin_setting_configselect {
3573 protected $includeall;
3574 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3575 $this->includeall = $includeall;
3576 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3580 * Lazy-load the available choices for the select box
3582 public function load_choices() {
3583 global $CFG;
3584 if (is_array($this->choices)) {
3585 return true;
3587 $this->choices = array_merge(
3588 array('0' => get_string('choosedots')),
3589 get_string_manager()->get_list_of_countries($this->includeall));
3590 return true;
3596 * Course category selection
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 class admin_settings_coursecat_select extends admin_setting_configselect {
3602 * Calls parent::__construct with specific arguments
3604 public function __construct($name, $visiblename, $description, $defaultsetting) {
3605 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3609 * Load the available choices for the select box
3611 * @return bool
3613 public function load_choices() {
3614 global $CFG;
3615 require_once($CFG->dirroot.'/course/lib.php');
3616 if (is_array($this->choices)) {
3617 return true;
3619 $this->choices = make_categories_options();
3620 return true;
3626 * Special control for selecting days to backup
3628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3630 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3632 * Calls parent::__construct with specific arguments
3634 public function __construct() {
3635 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3636 $this->plugin = 'backup';
3640 * Load the available choices for the select box
3642 * @return bool Always returns true
3644 public function load_choices() {
3645 if (is_array($this->choices)) {
3646 return true;
3648 $this->choices = array();
3649 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3650 foreach ($days as $day) {
3651 $this->choices[$day] = get_string($day, 'calendar');
3653 return true;
3659 * Special debug setting
3661 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3663 class admin_setting_special_debug extends admin_setting_configselect {
3665 * Calls parent::__construct with specific arguments
3667 public function __construct() {
3668 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3672 * Load the available choices for the select box
3674 * @return bool
3676 public function load_choices() {
3677 if (is_array($this->choices)) {
3678 return true;
3680 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3681 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3682 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3683 DEBUG_ALL => get_string('debugall', 'admin'),
3684 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3685 return true;
3691 * Special admin control
3693 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3695 class admin_setting_special_calendar_weekend extends admin_setting {
3697 * Calls parent::__construct with specific arguments
3699 public function __construct() {
3700 $name = 'calendar_weekend';
3701 $visiblename = get_string('calendar_weekend', 'admin');
3702 $description = get_string('helpweekenddays', 'admin');
3703 $default = array ('0', '6'); // Saturdays and Sundays
3704 parent::__construct($name, $visiblename, $description, $default);
3708 * Gets the current settings as an array
3710 * @return mixed Null if none, else array of settings
3712 public function get_setting() {
3713 $result = $this->config_read($this->name);
3714 if (is_null($result)) {
3715 return NULL;
3717 if ($result === '') {
3718 return array();
3720 $settings = array();
3721 for ($i=0; $i<7; $i++) {
3722 if ($result & (1 << $i)) {
3723 $settings[] = $i;
3726 return $settings;
3730 * Save the new settings
3732 * @param array $data Array of new settings
3733 * @return bool
3735 public function write_setting($data) {
3736 if (!is_array($data)) {
3737 return '';
3739 unset($data['xxxxx']);
3740 $result = 0;
3741 foreach($data as $index) {
3742 $result |= 1 << $index;
3744 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3748 * Return XHTML to display the control
3750 * @param array $data array of selected days
3751 * @param string $query
3752 * @return string XHTML for display (field + wrapping div(s)
3754 public function output_html($data, $query='') {
3755 // The order matters very much because of the implied numeric keys
3756 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3757 $return = '<table><thead><tr>';
3758 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3759 foreach($days as $index => $day) {
3760 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3762 $return .= '</tr></thead><tbody><tr>';
3763 foreach($days as $index => $day) {
3764 $return .= '<td><input type="checkbox" class="form-checkbox" id="'.$this->get_id().$index.'" name="'.$this->get_full_name().'[]" value="'.$index.'" '.(in_array("$index", $data) ? 'checked="checked"' : '').' /></td>';
3766 $return .= '</tr></tbody></table>';
3768 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3775 * Admin setting that allows a user to pick a behaviour.
3777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3779 class admin_setting_question_behaviour extends admin_setting_configselect {
3781 * @param string $name name of config variable
3782 * @param string $visiblename display name
3783 * @param string $description description
3784 * @param string $default default.
3786 public function __construct($name, $visiblename, $description, $default) {
3787 parent::__construct($name, $visiblename, $description, $default, NULL);
3791 * Load list of behaviours as choices
3792 * @return bool true => success, false => error.
3794 public function load_choices() {
3795 global $CFG;
3796 require_once($CFG->dirroot . '/question/engine/lib.php');
3797 $this->choices = question_engine::get_archetypal_behaviours();
3798 return true;
3804 * Admin setting that allows a user to pick appropriate roles for something.
3806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3808 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
3809 /** @var array Array of capabilities which identify roles */
3810 private $types;
3813 * @param string $name Name of config variable
3814 * @param string $visiblename Display name
3815 * @param string $description Description
3816 * @param array $types Array of archetypes which identify
3817 * roles that will be enabled by default.
3819 public function __construct($name, $visiblename, $description, $types) {
3820 parent::__construct($name, $visiblename, $description, NULL, NULL);
3821 $this->types = $types;
3825 * Load roles as choices
3827 * @return bool true=>success, false=>error
3829 public function load_choices() {
3830 global $CFG, $DB;
3831 if (during_initial_install()) {
3832 return false;
3834 if (is_array($this->choices)) {
3835 return true;
3837 if ($roles = get_all_roles()) {
3838 $this->choices = array();
3839 foreach($roles as $role) {
3840 $this->choices[$role->id] = format_string($role->name);
3842 return true;
3843 } else {
3844 return false;
3849 * Return the default setting for this control
3851 * @return array Array of default settings
3853 public function get_defaultsetting() {
3854 global $CFG;
3856 if (during_initial_install()) {
3857 return null;
3859 $result = array();
3860 foreach($this->types as $archetype) {
3861 if ($caproles = get_archetype_roles($archetype)) {
3862 foreach ($caproles as $caprole) {
3863 $result[$caprole->id] = 1;
3867 return $result;
3873 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
3875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3877 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
3879 * Constructor
3880 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3881 * @param string $visiblename localised
3882 * @param string $description long localised info
3883 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
3884 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
3885 * @param int $size default field size
3887 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
3888 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
3892 * Loads the current setting and returns array
3894 * @return array Returns array value=>xx, __construct=>xx
3896 public function get_setting() {
3897 $value = parent::get_setting();
3898 $adv = $this->config_read($this->name.'_adv');
3899 if (is_null($value) or is_null($adv)) {
3900 return NULL;
3902 return array('value' => $value, 'adv' => $adv);
3906 * Saves the new settings passed in $data
3908 * @todo Add vartype handling to ensure $data is an array
3909 * @param array $data
3910 * @return mixed string or Array
3912 public function write_setting($data) {
3913 $error = parent::write_setting($data['value']);
3914 if (!$error) {
3915 $value = empty($data['adv']) ? 0 : 1;
3916 $this->config_write($this->name.'_adv', $value);
3918 return $error;
3922 * Return XHTML for the control
3924 * @param array $data Default data array
3925 * @param string $query
3926 * @return string XHTML to display control
3928 public function output_html($data, $query='') {
3929 $default = $this->get_defaultsetting();
3930 $defaultinfo = array();
3931 if (isset($default['value'])) {
3932 if ($default['value'] === '') {
3933 $defaultinfo[] = "''";
3934 } else {
3935 $defaultinfo[] = $default['value'];
3938 if (!empty($default['adv'])) {
3939 $defaultinfo[] = get_string('advanced');
3941 $defaultinfo = implode(', ', $defaultinfo);
3943 $adv = !empty($data['adv']);
3944 $return = '<div class="form-text defaultsnext">' .
3945 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
3946 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
3947 ' <input type="checkbox" class="form-checkbox" id="' .
3948 $this->get_id() . '_adv" name="' . $this->get_full_name() .
3949 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
3950 ' <label for="' . $this->get_id() . '_adv">' .
3951 get_string('advanced') . '</label></div>';
3953 return format_admin_setting($this, $this->visiblename, $return,
3954 $this->description, true, '', $defaultinfo, $query);
3960 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
3962 * @copyright 2009 Petr Skoda (http://skodak.org)
3963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3965 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
3968 * Constructor
3969 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3970 * @param string $visiblename localised
3971 * @param string $description long localised info
3972 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
3973 * @param string $yes value used when checked
3974 * @param string $no value used when not checked
3976 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3977 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
3981 * Loads the current setting and returns array
3983 * @return array Returns array value=>xx, adv=>xx
3985 public function get_setting() {
3986 $value = parent::get_setting();
3987 $adv = $this->config_read($this->name.'_adv');
3988 if (is_null($value) or is_null($adv)) {
3989 return NULL;
3991 return array('value' => $value, 'adv' => $adv);
3995 * Sets the value for the setting
3997 * Sets the value for the setting to either the yes or no values
3998 * of the object by comparing $data to yes
4000 * @param mixed $data Gets converted to str for comparison against yes value
4001 * @return string empty string or error
4003 public function write_setting($data) {
4004 $error = parent::write_setting($data['value']);
4005 if (!$error) {
4006 $value = empty($data['adv']) ? 0 : 1;
4007 $this->config_write($this->name.'_adv', $value);
4009 return $error;
4013 * Returns an XHTML checkbox field and with extra advanced cehckbox
4015 * @param string $data If $data matches yes then checkbox is checked
4016 * @param string $query
4017 * @return string XHTML field
4019 public function output_html($data, $query='') {
4020 $defaults = $this->get_defaultsetting();
4021 $defaultinfo = array();
4022 if (!is_null($defaults)) {
4023 if ((string)$defaults['value'] === $this->yes) {
4024 $defaultinfo[] = get_string('checkboxyes', 'admin');
4025 } else {
4026 $defaultinfo[] = get_string('checkboxno', 'admin');
4028 if (!empty($defaults['adv'])) {
4029 $defaultinfo[] = get_string('advanced');
4032 $defaultinfo = implode(', ', $defaultinfo);
4034 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4035 $checked = 'checked="checked"';
4036 } else {
4037 $checked = '';
4039 if (!empty($data['adv'])) {
4040 $advanced = 'checked="checked"';
4041 } else {
4042 $advanced = '';
4045 $fullname = $this->get_full_name();
4046 $novalue = s($this->no);
4047 $yesvalue = s($this->yes);
4048 $id = $this->get_id();
4049 $stradvanced = get_string('advanced');
4050 $return = <<<EOT
4051 <div class="form-checkbox defaultsnext" >
4052 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4053 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4054 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4055 <label for="{$id}_adv">$stradvanced</label>
4056 </div>
4057 EOT;
4058 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4059 true, '', $defaultinfo, $query);
4065 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4067 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4069 * @copyright 2010 Sam Hemelryk
4070 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4072 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4074 * Constructor
4075 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4076 * @param string $visiblename localised
4077 * @param string $description long localised info
4078 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4079 * @param string $yes value used when checked
4080 * @param string $no value used when not checked
4082 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4083 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4087 * Loads the current setting and returns array
4089 * @return array Returns array value=>xx, adv=>xx
4091 public function get_setting() {
4092 $value = parent::get_setting();
4093 $locked = $this->config_read($this->name.'_locked');
4094 if (is_null($value) or is_null($locked)) {
4095 return NULL;
4097 return array('value' => $value, 'locked' => $locked);
4101 * Sets the value for the setting
4103 * Sets the value for the setting to either the yes or no values
4104 * of the object by comparing $data to yes
4106 * @param mixed $data Gets converted to str for comparison against yes value
4107 * @return string empty string or error
4109 public function write_setting($data) {
4110 $error = parent::write_setting($data['value']);
4111 if (!$error) {
4112 $value = empty($data['locked']) ? 0 : 1;
4113 $this->config_write($this->name.'_locked', $value);
4115 return $error;
4119 * Returns an XHTML checkbox field and with extra locked checkbox
4121 * @param string $data If $data matches yes then checkbox is checked
4122 * @param string $query
4123 * @return string XHTML field
4125 public function output_html($data, $query='') {
4126 $defaults = $this->get_defaultsetting();
4127 $defaultinfo = array();
4128 if (!is_null($defaults)) {
4129 if ((string)$defaults['value'] === $this->yes) {
4130 $defaultinfo[] = get_string('checkboxyes', 'admin');
4131 } else {
4132 $defaultinfo[] = get_string('checkboxno', 'admin');
4134 if (!empty($defaults['locked'])) {
4135 $defaultinfo[] = get_string('locked', 'admin');
4138 $defaultinfo = implode(', ', $defaultinfo);
4140 $fullname = $this->get_full_name();
4141 $novalue = s($this->no);
4142 $yesvalue = s($this->yes);
4143 $id = $this->get_id();
4145 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4146 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4147 $checkboxparams['checked'] = 'checked';
4150 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox');
4151 if (!empty($data['locked'])) { // convert to strings before comparison
4152 $lockcheckboxparams['checked'] = 'checked';
4155 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4156 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4157 $return .= html_writer::empty_tag('input', $checkboxparams);
4158 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4159 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4160 $return .= html_writer::end_tag('div');
4161 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4167 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4171 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4173 * Calls parent::__construct with specific arguments
4175 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4176 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4180 * Loads the current setting and returns array
4182 * @return array Returns array value=>xx, adv=>xx
4184 public function get_setting() {
4185 $value = parent::get_setting();
4186 $adv = $this->config_read($this->name.'_adv');
4187 if (is_null($value) or is_null($adv)) {
4188 return NULL;
4190 return array('value' => $value, 'adv' => $adv);
4194 * Saves the new settings passed in $data
4196 * @todo Add vartype handling to ensure $data is an array
4197 * @param array $data
4198 * @return mixed string or Array
4200 public function write_setting($data) {
4201 $error = parent::write_setting($data['value']);
4202 if (!$error) {
4203 $value = empty($data['adv']) ? 0 : 1;
4204 $this->config_write($this->name.'_adv', $value);
4206 return $error;
4210 * Return XHTML for the control
4212 * @param array $data Default data array
4213 * @param string $query
4214 * @return string XHTML to display control
4216 public function output_html($data, $query='') {
4217 $default = $this->get_defaultsetting();
4218 $current = $this->get_setting();
4220 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4221 $current['value'], $default['value'], '[value]');
4222 if (!$selecthtml) {
4223 return '';
4226 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4227 $defaultinfo = array();
4228 if (isset($this->choices[$default['value']])) {
4229 $defaultinfo[] = $this->choices[$default['value']];
4231 if (!empty($default['adv'])) {
4232 $defaultinfo[] = get_string('advanced');
4234 $defaultinfo = implode(', ', $defaultinfo);
4235 } else {
4236 $defaultinfo = '';
4239 $adv = !empty($data['adv']);
4240 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4241 ' <input type="checkbox" class="form-checkbox" id="' .
4242 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4243 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4244 ' <label for="' . $this->get_id() . '_adv">' .
4245 get_string('advanced') . '</label></div>';
4247 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4253 * Graded roles in gradebook
4255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4257 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4259 * Calls parent::__construct with specific arguments
4261 public function __construct() {
4262 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4263 get_string('configgradebookroles', 'admin'),
4264 array('student'));
4271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4273 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4275 * Saves the new settings passed in $data
4277 * @param string $data
4278 * @return mixed string or Array
4280 public function write_setting($data) {
4281 global $CFG, $DB;
4283 $oldvalue = $this->config_read($this->name);
4284 $return = parent::write_setting($data);
4285 $newvalue = $this->config_read($this->name);
4287 if ($oldvalue !== $newvalue) {
4288 // force full regrading
4289 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4292 return $return;
4298 * Which roles to show on course description page
4300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4302 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4304 * Calls parent::__construct with specific arguments
4306 public function __construct() {
4307 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4308 get_string('coursecontact_desc', 'admin'),
4309 array('editingteacher'));
4316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4318 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4320 * Calls parent::__construct with specific arguments
4322 function admin_setting_special_gradelimiting() {
4323 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4324 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4328 * Force site regrading
4330 function regrade_all() {
4331 global $CFG;
4332 require_once("$CFG->libdir/gradelib.php");
4333 grade_force_site_regrading();
4337 * Saves the new settings
4339 * @param mixed $data
4340 * @return string empty string or error message
4342 function write_setting($data) {
4343 $previous = $this->get_setting();
4345 if ($previous === null) {
4346 if ($data) {
4347 $this->regrade_all();
4349 } else {
4350 if ($data != $previous) {
4351 $this->regrade_all();
4354 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4361 * Primary grade export plugin - has state tracking.
4363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4365 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4367 * Calls parent::__construct with specific arguments
4369 public function __construct() {
4370 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4371 get_string('configgradeexport', 'admin'), array(), NULL);
4375 * Load the available choices for the multicheckbox
4377 * @return bool always returns true
4379 public function load_choices() {
4380 if (is_array($this->choices)) {
4381 return true;
4383 $this->choices = array();
4385 if ($plugins = get_plugin_list('gradeexport')) {
4386 foreach($plugins as $plugin => $unused) {
4387 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4390 return true;
4396 * Grade category settings
4398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4400 class admin_setting_gradecat_combo extends admin_setting {
4401 /** @var array Array of choices */
4402 public $choices;
4405 * Sets choices and calls parent::__construct with passed arguments
4406 * @param string $name
4407 * @param string $visiblename
4408 * @param string $description
4409 * @param mixed $defaultsetting string or array depending on implementation
4410 * @param array $choices An array of choices for the control
4412 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4413 $this->choices = $choices;
4414 parent::__construct($name, $visiblename, $description, $defaultsetting);
4418 * Return the current setting(s) array
4420 * @return array Array of value=>xx, forced=>xx, adv=>xx
4422 public function get_setting() {
4423 global $CFG;
4425 $value = $this->config_read($this->name);
4426 $flag = $this->config_read($this->name.'_flag');
4428 if (is_null($value) or is_null($flag)) {
4429 return NULL;
4432 $flag = (int)$flag;
4433 $forced = (boolean)(1 & $flag); // first bit
4434 $adv = (boolean)(2 & $flag); // second bit
4436 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4440 * Save the new settings passed in $data
4442 * @todo Add vartype handling to ensure $data is array
4443 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4444 * @return string empty or error message
4446 public function write_setting($data) {
4447 global $CFG;
4449 $value = $data['value'];
4450 $forced = empty($data['forced']) ? 0 : 1;
4451 $adv = empty($data['adv']) ? 0 : 2;
4452 $flag = ($forced | $adv); //bitwise or
4454 if (!in_array($value, array_keys($this->choices))) {
4455 return 'Error setting ';
4458 $oldvalue = $this->config_read($this->name);
4459 $oldflag = (int)$this->config_read($this->name.'_flag');
4460 $oldforced = (1 & $oldflag); // first bit
4462 $result1 = $this->config_write($this->name, $value);
4463 $result2 = $this->config_write($this->name.'_flag', $flag);
4465 // force regrade if needed
4466 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4467 require_once($CFG->libdir.'/gradelib.php');
4468 grade_category::updated_forced_settings();
4471 if ($result1 and $result2) {
4472 return '';
4473 } else {
4474 return get_string('errorsetting', 'admin');
4479 * Return XHTML to display the field and wrapping div
4481 * @todo Add vartype handling to ensure $data is array
4482 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4483 * @param string $query
4484 * @return string XHTML to display control
4486 public function output_html($data, $query='') {
4487 $value = $data['value'];
4488 $forced = !empty($data['forced']);
4489 $adv = !empty($data['adv']);
4491 $default = $this->get_defaultsetting();
4492 if (!is_null($default)) {
4493 $defaultinfo = array();
4494 if (isset($this->choices[$default['value']])) {
4495 $defaultinfo[] = $this->choices[$default['value']];
4497 if (!empty($default['forced'])) {
4498 $defaultinfo[] = get_string('force');
4500 if (!empty($default['adv'])) {
4501 $defaultinfo[] = get_string('advanced');
4503 $defaultinfo = implode(', ', $defaultinfo);
4505 } else {
4506 $defaultinfo = NULL;
4510 $return = '<div class="form-group">';
4511 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4512 foreach ($this->choices as $key => $val) {
4513 // the string cast is needed because key may be integer - 0 is equal to most strings!
4514 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4516 $return .= '</select>';
4517 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4518 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4519 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4520 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4521 $return .= '</div>';
4523 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4529 * Selection of grade report in user profiles
4531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4533 class admin_setting_grade_profilereport extends admin_setting_configselect {
4535 * Calls parent::__construct with specific arguments
4537 public function __construct() {
4538 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4542 * Loads an array of choices for the configselect control
4544 * @return bool always return true
4546 public function load_choices() {
4547 if (is_array($this->choices)) {
4548 return true;
4550 $this->choices = array();
4552 global $CFG;
4553 require_once($CFG->libdir.'/gradelib.php');
4555 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4556 if (file_exists($plugindir.'/lib.php')) {
4557 require_once($plugindir.'/lib.php');
4558 $functionname = 'grade_report_'.$plugin.'_profilereport';
4559 if (function_exists($functionname)) {
4560 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4564 return true;
4570 * Special class for register auth selection
4572 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4574 class admin_setting_special_registerauth extends admin_setting_configselect {
4576 * Calls parent::__construct with specific arguments
4578 public function __construct() {
4579 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4583 * Returns the default option
4585 * @return string empty or default option
4587 public function get_defaultsetting() {
4588 $this->load_choices();
4589 $defaultsetting = parent::get_defaultsetting();
4590 if (array_key_exists($defaultsetting, $this->choices)) {
4591 return $defaultsetting;
4592 } else {
4593 return '';
4598 * Loads the possible choices for the array
4600 * @return bool always returns true
4602 public function load_choices() {
4603 global $CFG;
4605 if (is_array($this->choices)) {
4606 return true;
4608 $this->choices = array();
4609 $this->choices[''] = get_string('disable');
4611 $authsenabled = get_enabled_auth_plugins(true);
4613 foreach ($authsenabled as $auth) {
4614 $authplugin = get_auth_plugin($auth);
4615 if (!$authplugin->can_signup()) {
4616 continue;
4618 // Get the auth title (from core or own auth lang files)
4619 $authtitle = $authplugin->get_title();
4620 $this->choices[$auth] = $authtitle;
4622 return true;
4628 * General plugins manager
4630 class admin_page_pluginsoverview extends admin_externalpage {
4633 * Sets basic information about the external page
4635 public function __construct() {
4636 global $CFG;
4637 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4638 "$CFG->wwwroot/$CFG->admin/plugins.php");
4643 * Module manage page
4645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4647 class admin_page_managemods extends admin_externalpage {
4649 * Calls parent::__construct with specific arguments
4651 public function __construct() {
4652 global $CFG;
4653 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4657 * Try to find the specified module
4659 * @param string $query The module to search for
4660 * @return array
4662 public function search($query) {
4663 global $CFG, $DB;
4664 if ($result = parent::search($query)) {
4665 return $result;
4668 $found = false;
4669 if ($modules = $DB->get_records('modules')) {
4670 $textlib = textlib_get_instance();
4671 foreach ($modules as $module) {
4672 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4673 continue;
4675 if (strpos($module->name, $query) !== false) {
4676 $found = true;
4677 break;
4679 $strmodulename = get_string('modulename', $module->name);
4680 if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
4681 $found = true;
4682 break;
4686 if ($found) {
4687 $result = new stdClass();
4688 $result->page = $this;
4689 $result->settings = array();
4690 return array($this->name => $result);
4691 } else {
4692 return array();
4699 * Special class for enrol plugins management.
4701 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4704 class admin_setting_manageenrols extends admin_setting {
4706 * Calls parent::__construct with specific arguments
4708 public function __construct() {
4709 $this->nosave = true;
4710 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4714 * Always returns true, does nothing
4716 * @return true
4718 public function get_setting() {
4719 return true;
4723 * Always returns true, does nothing
4725 * @return true
4727 public function get_defaultsetting() {
4728 return true;
4732 * Always returns '', does not write anything
4734 * @return string Always returns ''
4736 public function write_setting($data) {
4737 // do not write any setting
4738 return '';
4742 * Checks if $query is one of the available enrol plugins
4744 * @param string $query The string to search for
4745 * @return bool Returns true if found, false if not
4747 public function is_related($query) {
4748 if (parent::is_related($query)) {
4749 return true;
4752 $textlib = textlib_get_instance();
4753 $query = $textlib->strtolower($query);
4754 $enrols = enrol_get_plugins(false);
4755 foreach ($enrols as $name=>$enrol) {
4756 $localised = get_string('pluginname', 'enrol_'.$name);
4757 if (strpos($textlib->strtolower($name), $query) !== false) {
4758 return true;
4760 if (strpos($textlib->strtolower($localised), $query) !== false) {
4761 return true;
4764 return false;
4768 * Builds the XHTML to display the control
4770 * @param string $data Unused
4771 * @param string $query
4772 * @return string
4774 public function output_html($data, $query='') {
4775 global $CFG, $OUTPUT, $DB;
4777 // display strings
4778 $strup = get_string('up');
4779 $strdown = get_string('down');
4780 $strsettings = get_string('settings');
4781 $strenable = get_string('enable');
4782 $strdisable = get_string('disable');
4783 $struninstall = get_string('uninstallplugin', 'admin');
4784 $strusage = get_string('enrolusage', 'enrol');
4786 $enrols_available = enrol_get_plugins(false);
4787 $active_enrols = enrol_get_plugins(true);
4789 $allenrols = array();
4790 foreach ($active_enrols as $key=>$enrol) {
4791 $allenrols[$key] = true;
4793 foreach ($enrols_available as $key=>$enrol) {
4794 $allenrols[$key] = true;
4796 // now find all borked plugins and at least allow then to uninstall
4797 $borked = array();
4798 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
4799 foreach ($condidates as $candidate) {
4800 if (empty($allenrols[$candidate])) {
4801 $allenrols[$candidate] = true;
4805 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
4806 $return .= $OUTPUT->box_start('generalbox enrolsui');
4808 $table = new html_table();
4809 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
4810 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
4811 $table->width = '90%';
4812 $table->data = array();
4814 // iterate through enrol plugins and add to the display table
4815 $updowncount = 1;
4816 $enrolcount = count($active_enrols);
4817 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
4818 $printed = array();
4819 foreach($allenrols as $enrol => $unused) {
4820 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
4821 $name = get_string('pluginname', 'enrol_'.$enrol);
4822 } else {
4823 $name = $enrol;
4825 //usage
4826 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
4827 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
4828 $usage = "$ci / $cp";
4830 // hide/show link
4831 if (isset($active_enrols[$enrol])) {
4832 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
4833 $hideshow = "<a href=\"$aurl\">";
4834 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
4835 $enabled = true;
4836 $displayname = "<span>$name</span>";
4837 } else if (isset($enrols_available[$enrol])) {
4838 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
4839 $hideshow = "<a href=\"$aurl\">";
4840 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
4841 $enabled = false;
4842 $displayname = "<span class=\"dimmed_text\">$name</span>";
4843 } else {
4844 $hideshow = '';
4845 $enabled = false;
4846 $displayname = '<span class="notifyproblem">'.$name.'</span>';
4849 // up/down link (only if enrol is enabled)
4850 $updown = '';
4851 if ($enabled) {
4852 if ($updowncount > 1) {
4853 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
4854 $updown .= "<a href=\"$aurl\">";
4855 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
4856 } else {
4857 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
4859 if ($updowncount < $enrolcount) {
4860 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
4861 $updown .= "<a href=\"$aurl\">";
4862 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
4863 } else {
4864 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
4866 ++$updowncount;
4869 // settings link
4870 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
4871 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
4872 $settings = "<a href=\"$surl\">$strsettings</a>";
4873 } else {
4874 $settings = '';
4877 // uninstall
4878 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
4879 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
4881 // add a row to the table
4882 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
4884 $printed[$enrol] = true;
4887 $return .= html_writer::table($table);
4888 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
4889 $return .= $OUTPUT->box_end();
4890 return highlight($query, $return);
4896 * Blocks manage page
4898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4900 class admin_page_manageblocks extends admin_externalpage {
4902 * Calls parent::__construct with specific arguments
4904 public function __construct() {
4905 global $CFG;
4906 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
4910 * Search for a specific block
4912 * @param string $query The string to search for
4913 * @return array
4915 public function search($query) {
4916 global $CFG, $DB;
4917 if ($result = parent::search($query)) {
4918 return $result;
4921 $found = false;
4922 if ($blocks = $DB->get_records('block')) {
4923 $textlib = textlib_get_instance();
4924 foreach ($blocks as $block) {
4925 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
4926 continue;
4928 if (strpos($block->name, $query) !== false) {
4929 $found = true;
4930 break;
4932 $strblockname = get_string('pluginname', 'block_'.$block->name);
4933 if (strpos($textlib->strtolower($strblockname), $query) !== false) {
4934 $found = true;
4935 break;
4939 if ($found) {
4940 $result = new stdClass();
4941 $result->page = $this;
4942 $result->settings = array();
4943 return array($this->name => $result);
4944 } else {
4945 return array();
4951 * Message outputs configuration
4953 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4955 class admin_page_managemessageoutputs extends admin_externalpage {
4957 * Calls parent::__construct with specific arguments
4959 public function __construct() {
4960 global $CFG;
4961 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
4965 * Search for a specific message processor
4967 * @param string $query The string to search for
4968 * @return array
4970 public function search($query) {
4971 global $CFG, $DB;
4972 if ($result = parent::search($query)) {
4973 return $result;
4976 $found = false;
4977 if ($processors = get_message_processors()) {
4978 $textlib = textlib_get_instance();
4979 foreach ($processors as $processor) {
4980 if (!$processor->available) {
4981 continue;
4983 if (strpos($processor->name, $query) !== false) {
4984 $found = true;
4985 break;
4987 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
4988 if (strpos($textlib->strtolower($strprocessorname), $query) !== false) {
4989 $found = true;
4990 break;
4994 if ($found) {
4995 $result = new stdClass();
4996 $result->page = $this;
4997 $result->settings = array();
4998 return array($this->name => $result);
4999 } else {
5000 return array();
5006 * Default message outputs configuration
5008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5010 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5012 * Calls parent::__construct with specific arguments
5014 public function __construct() {
5015 global $CFG;
5016 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5021 * Question type manage page
5023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5025 class admin_page_manageqtypes extends admin_externalpage {
5027 * Calls parent::__construct with specific arguments
5029 public function __construct() {
5030 global $CFG;
5031 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5035 * Search question types for the specified string
5037 * @param string $query The string to search for in question types
5038 * @return array
5040 public function search($query) {
5041 global $CFG;
5042 if ($result = parent::search($query)) {
5043 return $result;
5046 $found = false;
5047 $textlib = textlib_get_instance();
5048 require_once($CFG->dirroot . '/question/engine/bank.php');
5049 foreach (question_bank::get_all_qtypes() as $qtype) {
5050 if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
5051 $found = true;
5052 break;
5055 if ($found) {
5056 $result = new stdClass();
5057 $result->page = $this;
5058 $result->settings = array();
5059 return array($this->name => $result);
5060 } else {
5061 return array();
5067 class admin_page_manageportfolios extends admin_externalpage {
5069 * Calls parent::__construct with specific arguments
5071 public function __construct() {
5072 global $CFG;
5073 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5074 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5078 * Searches page for the specified string.
5079 * @param string $query The string to search for
5080 * @return bool True if it is found on this page
5082 public function search($query) {
5083 global $CFG;
5084 if ($result = parent::search($query)) {
5085 return $result;
5088 $found = false;
5089 $textlib = textlib_get_instance();
5090 $portfolios = get_plugin_list('portfolio');
5091 foreach ($portfolios as $p => $dir) {
5092 if (strpos($p, $query) !== false) {
5093 $found = true;
5094 break;
5097 if (!$found) {
5098 foreach (portfolio_instances(false, false) as $instance) {
5099 $title = $instance->get('name');
5100 if (strpos($textlib->strtolower($title), $query) !== false) {
5101 $found = true;
5102 break;
5107 if ($found) {
5108 $result = new stdClass();
5109 $result->page = $this;
5110 $result->settings = array();
5111 return array($this->name => $result);
5112 } else {
5113 return array();
5119 class admin_page_managerepositories extends admin_externalpage {
5121 * Calls parent::__construct with specific arguments
5123 public function __construct() {
5124 global $CFG;
5125 parent::__construct('managerepositories', get_string('manage',
5126 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5130 * Searches page for the specified string.
5131 * @param string $query The string to search for
5132 * @return bool True if it is found on this page
5134 public function search($query) {
5135 global $CFG;
5136 if ($result = parent::search($query)) {
5137 return $result;
5140 $found = false;
5141 $textlib = textlib_get_instance();
5142 $repositories= get_plugin_list('repository');
5143 foreach ($repositories as $p => $dir) {
5144 if (strpos($p, $query) !== false) {
5145 $found = true;
5146 break;
5149 if (!$found) {
5150 foreach (repository::get_types() as $instance) {
5151 $title = $instance->get_typename();
5152 if (strpos($textlib->strtolower($title), $query) !== false) {
5153 $found = true;
5154 break;
5159 if ($found) {
5160 $result = new stdClass();
5161 $result->page = $this;
5162 $result->settings = array();
5163 return array($this->name => $result);
5164 } else {
5165 return array();
5172 * Special class for authentication administration.
5174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5176 class admin_setting_manageauths extends admin_setting {
5178 * Calls parent::__construct with specific arguments
5180 public function __construct() {
5181 $this->nosave = true;
5182 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5186 * Always returns true
5188 * @return true
5190 public function get_setting() {
5191 return true;
5195 * Always returns true
5197 * @return true
5199 public function get_defaultsetting() {
5200 return true;
5204 * Always returns '' and doesn't write anything
5206 * @return string Always returns ''
5208 public function write_setting($data) {
5209 // do not write any setting
5210 return '';
5214 * Search to find if Query is related to auth plugin
5216 * @param string $query The string to search for
5217 * @return bool true for related false for not
5219 public function is_related($query) {
5220 if (parent::is_related($query)) {
5221 return true;
5224 $textlib = textlib_get_instance();
5225 $authsavailable = get_plugin_list('auth');
5226 foreach ($authsavailable as $auth => $dir) {
5227 if (strpos($auth, $query) !== false) {
5228 return true;
5230 $authplugin = get_auth_plugin($auth);
5231 $authtitle = $authplugin->get_title();
5232 if (strpos($textlib->strtolower($authtitle), $query) !== false) {
5233 return true;
5236 return false;
5240 * Return XHTML to display control
5242 * @param mixed $data Unused
5243 * @param string $query
5244 * @return string highlight
5246 public function output_html($data, $query='') {
5247 global $CFG, $OUTPUT;
5250 // display strings
5251 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5252 'settings', 'edit', 'name', 'enable', 'disable',
5253 'up', 'down', 'none'));
5254 $txt->updown = "$txt->up/$txt->down";
5256 $authsavailable = get_plugin_list('auth');
5257 get_enabled_auth_plugins(true); // fix the list of enabled auths
5258 if (empty($CFG->auth)) {
5259 $authsenabled = array();
5260 } else {
5261 $authsenabled = explode(',', $CFG->auth);
5264 // construct the display array, with enabled auth plugins at the top, in order
5265 $displayauths = array();
5266 $registrationauths = array();
5267 $registrationauths[''] = $txt->disable;
5268 foreach ($authsenabled as $auth) {
5269 $authplugin = get_auth_plugin($auth);
5270 /// Get the auth title (from core or own auth lang files)
5271 $authtitle = $authplugin->get_title();
5272 /// Apply titles
5273 $displayauths[$auth] = $authtitle;
5274 if ($authplugin->can_signup()) {
5275 $registrationauths[$auth] = $authtitle;
5279 foreach ($authsavailable as $auth => $dir) {
5280 if (array_key_exists($auth, $displayauths)) {
5281 continue; //already in the list
5283 $authplugin = get_auth_plugin($auth);
5284 /// Get the auth title (from core or own auth lang files)
5285 $authtitle = $authplugin->get_title();
5286 /// Apply titles
5287 $displayauths[$auth] = $authtitle;
5288 if ($authplugin->can_signup()) {
5289 $registrationauths[$auth] = $authtitle;
5293 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5294 $return .= $OUTPUT->box_start('generalbox authsui');
5296 $table = new html_table();
5297 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5298 $table->align = array('left', 'center', 'center', 'center');
5299 $table->data = array();
5300 $table->attributes['class'] = 'manageauthtable generaltable';
5302 //add always enabled plugins first
5303 $displayname = "<span>".$displayauths['manual']."</span>";
5304 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5305 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5306 $table->data[] = array($displayname, '', '', $settings);
5307 $displayname = "<span>".$displayauths['nologin']."</span>";
5308 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5309 $table->data[] = array($displayname, '', '', $settings);
5312 // iterate through auth plugins and add to the display table
5313 $updowncount = 1;
5314 $authcount = count($authsenabled);
5315 $url = "auth.php?sesskey=" . sesskey();
5316 foreach ($displayauths as $auth => $name) {
5317 if ($auth == 'manual' or $auth == 'nologin') {
5318 continue;
5320 // hide/show link
5321 if (in_array($auth, $authsenabled)) {
5322 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5323 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5324 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5325 $enabled = true;
5326 $displayname = "<span>$name</span>";
5328 else {
5329 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5330 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5331 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5332 $enabled = false;
5333 $displayname = "<span class=\"dimmed_text\">$name</span>";
5336 // up/down link (only if auth is enabled)
5337 $updown = '';
5338 if ($enabled) {
5339 if ($updowncount > 1) {
5340 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5341 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5343 else {
5344 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5346 if ($updowncount < $authcount) {
5347 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5348 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5350 else {
5351 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5353 ++ $updowncount;
5356 // settings link
5357 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5358 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5359 } else {
5360 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5363 // add a row to the table
5364 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5366 $return .= html_writer::table($table);
5367 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5368 $return .= $OUTPUT->box_end();
5369 return highlight($query, $return);
5375 * Special class for authentication administration.
5377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5379 class admin_setting_manageeditors extends admin_setting {
5381 * Calls parent::__construct with specific arguments
5383 public function __construct() {
5384 $this->nosave = true;
5385 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5389 * Always returns true, does nothing
5391 * @return true
5393 public function get_setting() {
5394 return true;
5398 * Always returns true, does nothing
5400 * @return true
5402 public function get_defaultsetting() {
5403 return true;
5407 * Always returns '', does not write anything
5409 * @return string Always returns ''
5411 public function write_setting($data) {
5412 // do not write any setting
5413 return '';
5417 * Checks if $query is one of the available editors
5419 * @param string $query The string to search for
5420 * @return bool Returns true if found, false if not
5422 public function is_related($query) {
5423 if (parent::is_related($query)) {
5424 return true;
5427 $textlib = textlib_get_instance();
5428 $editors_available = editors_get_available();
5429 foreach ($editors_available as $editor=>$editorstr) {
5430 if (strpos($editor, $query) !== false) {
5431 return true;
5433 if (strpos($textlib->strtolower($editorstr), $query) !== false) {
5434 return true;
5437 return false;
5441 * Builds the XHTML to display the control
5443 * @param string $data Unused
5444 * @param string $query
5445 * @return string
5447 public function output_html($data, $query='') {
5448 global $CFG, $OUTPUT;
5450 // display strings
5451 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5452 'up', 'down', 'none'));
5453 $txt->updown = "$txt->up/$txt->down";
5455 $editors_available = editors_get_available();
5456 $active_editors = explode(',', $CFG->texteditors);
5458 $active_editors = array_reverse($active_editors);
5459 foreach ($active_editors as $key=>$editor) {
5460 if (empty($editors_available[$editor])) {
5461 unset($active_editors[$key]);
5462 } else {
5463 $name = $editors_available[$editor];
5464 unset($editors_available[$editor]);
5465 $editors_available[$editor] = $name;
5468 if (empty($active_editors)) {
5469 //$active_editors = array('textarea');
5471 $editors_available = array_reverse($editors_available, true);
5472 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5473 $return .= $OUTPUT->box_start('generalbox editorsui');
5475 $table = new html_table();
5476 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5477 $table->align = array('left', 'center', 'center', 'center');
5478 $table->width = '90%';
5479 $table->data = array();
5481 // iterate through auth plugins and add to the display table
5482 $updowncount = 1;
5483 $editorcount = count($active_editors);
5484 $url = "editors.php?sesskey=" . sesskey();
5485 foreach ($editors_available as $editor => $name) {
5486 // hide/show link
5487 if (in_array($editor, $active_editors)) {
5488 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5489 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5490 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5491 $enabled = true;
5492 $displayname = "<span>$name</span>";
5494 else {
5495 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5496 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5497 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5498 $enabled = false;
5499 $displayname = "<span class=\"dimmed_text\">$name</span>";
5502 // up/down link (only if auth is enabled)
5503 $updown = '';
5504 if ($enabled) {
5505 if ($updowncount > 1) {
5506 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5507 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5509 else {
5510 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5512 if ($updowncount < $editorcount) {
5513 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5514 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5516 else {
5517 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5519 ++ $updowncount;
5522 // settings link
5523 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5524 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5525 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5526 } else {
5527 $settings = '';
5530 // add a row to the table
5531 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5533 $return .= html_writer::table($table);
5534 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5535 $return .= $OUTPUT->box_end();
5536 return highlight($query, $return);
5542 * Special class for license administration.
5544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5546 class admin_setting_managelicenses extends admin_setting {
5548 * Calls parent::__construct with specific arguments
5550 public function __construct() {
5551 $this->nosave = true;
5552 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5556 * Always returns true, does nothing
5558 * @return true
5560 public function get_setting() {
5561 return true;
5565 * Always returns true, does nothing
5567 * @return true
5569 public function get_defaultsetting() {
5570 return true;
5574 * Always returns '', does not write anything
5576 * @return string Always returns ''
5578 public function write_setting($data) {
5579 // do not write any setting
5580 return '';
5584 * Builds the XHTML to display the control
5586 * @param string $data Unused
5587 * @param string $query
5588 * @return string
5590 public function output_html($data, $query='') {
5591 global $CFG, $OUTPUT;
5592 require_once($CFG->libdir . '/licenselib.php');
5593 $url = "licenses.php?sesskey=" . sesskey();
5595 // display strings
5596 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5597 $licenses = license_manager::get_licenses();
5599 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5601 $return .= $OUTPUT->box_start('generalbox editorsui');
5603 $table = new html_table();
5604 $table->head = array($txt->name, $txt->enable);
5605 $table->align = array('left', 'center');
5606 $table->width = '100%';
5607 $table->data = array();
5609 foreach ($licenses as $value) {
5610 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5612 if ($value->enabled == 1) {
5613 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5614 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5615 } else {
5616 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5617 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5620 if ($value->shortname == $CFG->sitedefaultlicense) {
5621 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5622 $hideshow = '';
5625 $enabled = true;
5627 $table->data[] =array($displayname, $hideshow);
5629 $return .= html_writer::table($table);
5630 $return .= $OUTPUT->box_end();
5631 return highlight($query, $return);
5637 * Special class for filter administration.
5639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5641 class admin_page_managefilters extends admin_externalpage {
5643 * Calls parent::__construct with specific arguments
5645 public function __construct() {
5646 global $CFG;
5647 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5651 * Searches all installed filters for specified filter
5653 * @param string $query The filter(string) to search for
5654 * @param string $query
5656 public function search($query) {
5657 global $CFG;
5658 if ($result = parent::search($query)) {
5659 return $result;
5662 $found = false;
5663 $filternames = filter_get_all_installed();
5664 $textlib = textlib_get_instance();
5665 foreach ($filternames as $path => $strfiltername) {
5666 if (strpos($textlib->strtolower($strfiltername), $query) !== false) {
5667 $found = true;
5668 break;
5670 list($type, $filter) = explode('/', $path);
5671 if (strpos($filter, $query) !== false) {
5672 $found = true;
5673 break;
5677 if ($found) {
5678 $result = new stdClass;
5679 $result->page = $this;
5680 $result->settings = array();
5681 return array($this->name => $result);
5682 } else {
5683 return array();
5690 * Initialise admin page - this function does require login and permission
5691 * checks specified in page definition.
5693 * This function must be called on each admin page before other code.
5695 * @global moodle_page $PAGE
5697 * @param string $section name of page
5698 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5699 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5700 * added to the turn blocks editing on/off form, so this page reloads correctly.
5701 * @param string $actualurl if the actual page being viewed is not the normal one for this
5702 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5703 * @param array $options Additional options that can be specified for page setup.
5704 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5706 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5707 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5709 $PAGE->set_context(null); // hack - set context to something, by default to system context
5711 $site = get_site();
5712 require_login();
5714 $adminroot = admin_get_root(false, false); // settings not required for external pages
5715 $extpage = $adminroot->locate($section, true);
5717 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5718 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5719 die;
5722 // this eliminates our need to authenticate on the actual pages
5723 if (!$extpage->check_access()) {
5724 print_error('accessdenied', 'admin');
5725 die;
5728 if (!empty($options['pagelayout'])) {
5729 // A specific page layout has been requested.
5730 $PAGE->set_pagelayout($options['pagelayout']);
5731 } else if ($section === 'upgradesettings') {
5732 $PAGE->set_pagelayout('maintenance');
5733 } else {
5734 $PAGE->set_pagelayout('admin');
5737 // $PAGE->set_extra_button($extrabutton); TODO
5739 if (!$actualurl) {
5740 $actualurl = $extpage->url;
5743 $PAGE->set_url($actualurl, $extraurlparams);
5744 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5745 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
5748 if (empty($SITE->fullname) || empty($SITE->shortname)) {
5749 // During initial install.
5750 $strinstallation = get_string('installation', 'install');
5751 $strsettings = get_string('settings');
5752 $PAGE->navbar->add($strsettings);
5753 $PAGE->set_title($strinstallation);
5754 $PAGE->set_heading($strinstallation);
5755 $PAGE->set_cacheable(false);
5756 return;
5759 // Locate the current item on the navigation and make it active when found.
5760 $path = $extpage->path;
5761 $node = $PAGE->settingsnav;
5762 while ($node && count($path) > 0) {
5763 $node = $node->get(array_pop($path));
5765 if ($node) {
5766 $node->make_active();
5769 // Normal case.
5770 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
5771 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
5772 $USER->editing = $adminediting;
5775 $visiblepathtosection = array_reverse($extpage->visiblepath);
5777 if ($PAGE->user_allowed_editing()) {
5778 if ($PAGE->user_is_editing()) {
5779 $caption = get_string('blockseditoff');
5780 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
5781 } else {
5782 $caption = get_string('blocksediton');
5783 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
5785 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
5788 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
5789 $PAGE->set_heading($SITE->fullname);
5791 // prevent caching in nav block
5792 $PAGE->navigation->clear_cache();
5796 * Returns the reference to admin tree root
5798 * @return object admin_root object
5800 function admin_get_root($reload=false, $requirefulltree=true) {
5801 global $CFG, $DB, $OUTPUT;
5803 static $ADMIN = NULL;
5805 if (is_null($ADMIN)) {
5806 // create the admin tree!
5807 $ADMIN = new admin_root($requirefulltree);
5810 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
5811 $ADMIN->purge_children($requirefulltree);
5814 if (!$ADMIN->loaded) {
5815 // we process this file first to create categories first and in correct order
5816 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
5818 // now we process all other files in admin/settings to build the admin tree
5819 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
5820 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
5821 continue;
5823 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
5824 // plugins are loaded last - they may insert pages anywhere
5825 continue;
5827 require($file);
5829 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
5831 $ADMIN->loaded = true;
5834 return $ADMIN;
5837 /// settings utility functions
5840 * This function applies default settings.
5842 * @param object $node, NULL means complete tree, null by default
5843 * @param bool $unconditional if true overrides all values with defaults, null buy default
5845 function admin_apply_default_settings($node=NULL, $unconditional=true) {
5846 global $CFG;
5848 if (is_null($node)) {
5849 $node = admin_get_root(true, true);
5852 if ($node instanceof admin_category) {
5853 $entries = array_keys($node->children);
5854 foreach ($entries as $entry) {
5855 admin_apply_default_settings($node->children[$entry], $unconditional);
5858 } else if ($node instanceof admin_settingpage) {
5859 foreach ($node->settings as $setting) {
5860 if (!$unconditional and !is_null($setting->get_setting())) {
5861 //do not override existing defaults
5862 continue;
5864 $defaultsetting = $setting->get_defaultsetting();
5865 if (is_null($defaultsetting)) {
5866 // no value yet - default maybe applied after admin user creation or in upgradesettings
5867 continue;
5869 $setting->write_setting($defaultsetting);
5875 * Store changed settings, this function updates the errors variable in $ADMIN
5877 * @param object $formdata from form
5878 * @return int number of changed settings
5880 function admin_write_settings($formdata) {
5881 global $CFG, $SITE, $DB;
5883 $olddbsessions = !empty($CFG->dbsessions);
5884 $formdata = (array)$formdata;
5886 $data = array();
5887 foreach ($formdata as $fullname=>$value) {
5888 if (strpos($fullname, 's_') !== 0) {
5889 continue; // not a config value
5891 $data[$fullname] = $value;
5894 $adminroot = admin_get_root();
5895 $settings = admin_find_write_settings($adminroot, $data);
5897 $count = 0;
5898 foreach ($settings as $fullname=>$setting) {
5899 $original = serialize($setting->get_setting()); // comparison must work for arrays too
5900 $error = $setting->write_setting($data[$fullname]);
5901 if ($error !== '') {
5902 $adminroot->errors[$fullname] = new stdClass();
5903 $adminroot->errors[$fullname]->data = $data[$fullname];
5904 $adminroot->errors[$fullname]->id = $setting->get_id();
5905 $adminroot->errors[$fullname]->error = $error;
5907 if ($original !== serialize($setting->get_setting())) {
5908 $count++;
5909 $callbackfunction = $setting->updatedcallback;
5910 if (function_exists($callbackfunction)) {
5911 $callbackfunction($fullname);
5916 if ($olddbsessions != !empty($CFG->dbsessions)) {
5917 require_logout();
5920 // Now update $SITE - just update the fields, in case other people have a
5921 // a reference to it (e.g. $PAGE, $COURSE).
5922 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
5923 foreach (get_object_vars($newsite) as $field => $value) {
5924 $SITE->$field = $value;
5927 // now reload all settings - some of them might depend on the changed
5928 admin_get_root(true);
5929 return $count;
5933 * Internal recursive function - finds all settings from submitted form
5935 * @param object $node Instance of admin_category, or admin_settingpage
5936 * @param array $data
5937 * @return array
5939 function admin_find_write_settings($node, $data) {
5940 $return = array();
5942 if (empty($data)) {
5943 return $return;
5946 if ($node instanceof admin_category) {
5947 $entries = array_keys($node->children);
5948 foreach ($entries as $entry) {
5949 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
5952 } else if ($node instanceof admin_settingpage) {
5953 foreach ($node->settings as $setting) {
5954 $fullname = $setting->get_full_name();
5955 if (array_key_exists($fullname, $data)) {
5956 $return[$fullname] = $setting;
5962 return $return;
5966 * Internal function - prints the search results
5968 * @param string $query String to search for
5969 * @return string empty or XHTML
5971 function admin_search_settings_html($query) {
5972 global $CFG, $OUTPUT;
5974 $textlib = textlib_get_instance();
5975 if ($textlib->strlen($query) < 2) {
5976 return '';
5978 $query = $textlib->strtolower($query);
5980 $adminroot = admin_get_root();
5981 $findings = $adminroot->search($query);
5982 $return = '';
5983 $savebutton = false;
5985 foreach ($findings as $found) {
5986 $page = $found->page;
5987 $settings = $found->settings;
5988 if ($page->is_hidden()) {
5989 // hidden pages are not displayed in search results
5990 continue;
5992 if ($page instanceof admin_externalpage) {
5993 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
5994 } else if ($page instanceof admin_settingpage) {
5995 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/settings.php?section='.$page->name.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
5996 } else {
5997 continue;
5999 if (!empty($settings)) {
6000 $return .= '<fieldset class="adminsettings">'."\n";
6001 foreach ($settings as $setting) {
6002 if (empty($setting->nosave)) {
6003 $savebutton = true;
6005 $return .= '<div class="clearer"><!-- --></div>'."\n";
6006 $fullname = $setting->get_full_name();
6007 if (array_key_exists($fullname, $adminroot->errors)) {
6008 $data = $adminroot->errors[$fullname]->data;
6009 } else {
6010 $data = $setting->get_setting();
6011 // do not use defaults if settings not available - upgradesettings handles the defaults!
6013 $return .= $setting->output_html($data, $query);
6015 $return .= '</fieldset>';
6019 if ($savebutton) {
6020 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6023 return $return;
6027 * Internal function - returns arrays of html pages with uninitialised settings
6029 * @param object $node Instance of admin_category or admin_settingpage
6030 * @return array
6032 function admin_output_new_settings_by_page($node) {
6033 global $OUTPUT;
6034 $return = array();
6036 if ($node instanceof admin_category) {
6037 $entries = array_keys($node->children);
6038 foreach ($entries as $entry) {
6039 $return += admin_output_new_settings_by_page($node->children[$entry]);
6042 } else if ($node instanceof admin_settingpage) {
6043 $newsettings = array();
6044 foreach ($node->settings as $setting) {
6045 if (is_null($setting->get_setting())) {
6046 $newsettings[] = $setting;
6049 if (count($newsettings) > 0) {
6050 $adminroot = admin_get_root();
6051 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6052 $page .= '<fieldset class="adminsettings">'."\n";
6053 foreach ($newsettings as $setting) {
6054 $fullname = $setting->get_full_name();
6055 if (array_key_exists($fullname, $adminroot->errors)) {
6056 $data = $adminroot->errors[$fullname]->data;
6057 } else {
6058 $data = $setting->get_setting();
6059 if (is_null($data)) {
6060 $data = $setting->get_defaultsetting();
6063 $page .= '<div class="clearer"><!-- --></div>'."\n";
6064 $page .= $setting->output_html($data);
6066 $page .= '</fieldset>';
6067 $return[$node->name] = $page;
6071 return $return;
6075 * Format admin settings
6077 * @param object $setting
6078 * @param string $title label element
6079 * @param string $form form fragment, html code - not highlighted automatically
6080 * @param string $description
6081 * @param bool $label link label to id, true by default
6082 * @param string $warning warning text
6083 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6084 * @param string $query search query to be highlighted
6085 * @return string XHTML
6087 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6088 global $CFG;
6090 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6091 $fullname = $setting->get_full_name();
6093 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6094 if ($label) {
6095 $labelfor = 'for = "'.$setting->get_id().'"';
6096 } else {
6097 $labelfor = '';
6100 $override = '';
6101 if (empty($setting->plugin)) {
6102 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6103 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6105 } else {
6106 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6107 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6111 if ($warning !== '') {
6112 $warning = '<div class="form-warning">'.$warning.'</div>';
6115 if (is_null($defaultinfo)) {
6116 $defaultinfo = '';
6117 } else {
6118 if ($defaultinfo === '') {
6119 $defaultinfo = get_string('emptysettingvalue', 'admin');
6121 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6122 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6126 $str = '
6127 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6128 <div class="form-label">
6129 <label '.$labelfor.'>'.highlightfast($query, $title).'<span class="form-shortname">'.highlightfast($query, $name).'</span>
6130 '.$override.$warning.'
6131 </label>
6132 </div>
6133 <div class="form-setting">'.$form.$defaultinfo.'</div>
6134 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6135 </div>';
6137 $adminroot = admin_get_root();
6138 if (array_key_exists($fullname, $adminroot->errors)) {
6139 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6142 return $str;
6146 * Based on find_new_settings{@link ()} in upgradesettings.php
6147 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6149 * @param object $node Instance of admin_category, or admin_settingpage
6150 * @return boolean true if any settings haven't been initialised, false if they all have
6152 function any_new_admin_settings($node) {
6154 if ($node instanceof admin_category) {
6155 $entries = array_keys($node->children);
6156 foreach ($entries as $entry) {
6157 if (any_new_admin_settings($node->children[$entry])) {
6158 return true;
6162 } else if ($node instanceof admin_settingpage) {
6163 foreach ($node->settings as $setting) {
6164 if ($setting->get_setting() === NULL) {
6165 return true;
6170 return false;
6174 * Moved from admin/replace.php so that we can use this in cron
6176 * @param string $search string to look for
6177 * @param string $replace string to replace
6178 * @return bool success or fail
6180 function db_replace($search, $replace) {
6181 global $DB, $CFG, $OUTPUT;
6183 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6184 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6185 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6186 'block_instances', 'block_pinned_old', 'block_instance_old', '');
6188 // Turn off time limits, sometimes upgrades can be slow.
6189 @set_time_limit(0);
6191 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6192 return false;
6194 foreach ($tables as $table) {
6196 if (in_array($table, $skiptables)) { // Don't process these
6197 continue;
6200 if ($columns = $DB->get_columns($table)) {
6201 $DB->set_debug(true);
6202 foreach ($columns as $column => $data) {
6203 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6204 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6205 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6208 $DB->set_debug(false);
6212 // delete modinfo caches
6213 rebuild_course_cache(0, true);
6215 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6216 $blocks = get_plugin_list('block');
6217 foreach ($blocks as $blockname=>$fullblock) {
6218 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6219 continue;
6222 if (!is_readable($fullblock.'/lib.php')) {
6223 continue;
6226 $function = 'block_'.$blockname.'_global_db_replace';
6227 include_once($fullblock.'/lib.php');
6228 if (!function_exists($function)) {
6229 continue;
6232 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6233 $function($search, $replace);
6234 echo $OUTPUT->notification("...finished", 'notifysuccess');
6237 return true;
6241 * Manage repository settings
6243 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6245 class admin_setting_managerepository extends admin_setting {
6246 /** @var string */
6247 private $baseurl;
6250 * calls parent::__construct with specific arguments
6252 public function __construct() {
6253 global $CFG;
6254 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6255 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6259 * Always returns true, does nothing
6261 * @return true
6263 public function get_setting() {
6264 return true;
6268 * Always returns true does nothing
6270 * @return true
6272 public function get_defaultsetting() {
6273 return true;
6277 * Always returns s_managerepository
6279 * @return string Always return 's_managerepository'
6281 public function get_full_name() {
6282 return 's_managerepository';
6286 * Always returns '' doesn't do anything
6288 public function write_setting($data) {
6289 $url = $this->baseurl . '&amp;new=' . $data;
6290 return '';
6291 // TODO
6292 // Should not use redirect and exit here
6293 // Find a better way to do this.
6294 // redirect($url);
6295 // exit;
6299 * Searches repository plugins for one that matches $query
6301 * @param string $query The string to search for
6302 * @return bool true if found, false if not
6304 public function is_related($query) {
6305 if (parent::is_related($query)) {
6306 return true;
6309 $textlib = textlib_get_instance();
6310 $repositories= get_plugin_list('repository');
6311 foreach ($repositories as $p => $dir) {
6312 if (strpos($p, $query) !== false) {
6313 return true;
6316 foreach (repository::get_types() as $instance) {
6317 $title = $instance->get_typename();
6318 if (strpos($textlib->strtolower($title), $query) !== false) {
6319 return true;
6322 return false;
6326 * Helper function that generates a moodle_url object
6327 * relevant to the repository
6330 function repository_action_url($repository) {
6331 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6335 * Builds XHTML to display the control
6337 * @param string $data Unused
6338 * @param string $query
6339 * @return string XHTML
6341 public function output_html($data, $query='') {
6342 global $CFG, $USER, $OUTPUT;
6344 // Get strings that are used
6345 $strshow = get_string('on', 'repository');
6346 $strhide = get_string('off', 'repository');
6347 $strdelete = get_string('disabled', 'repository');
6349 $actionchoicesforexisting = array(
6350 'show' => $strshow,
6351 'hide' => $strhide,
6352 'delete' => $strdelete
6355 $actionchoicesfornew = array(
6356 'newon' => $strshow,
6357 'newoff' => $strhide,
6358 'delete' => $strdelete
6361 $return = '';
6362 $return .= $OUTPUT->box_start('generalbox');
6364 // Set strings that are used multiple times
6365 $settingsstr = get_string('settings');
6366 $disablestr = get_string('disable');
6368 // Table to list plug-ins
6369 $table = new html_table();
6370 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6371 $table->align = array('left', 'center', 'center', 'center', 'center');
6372 $table->data = array();
6374 // Get list of used plug-ins
6375 $instances = repository::get_types();
6376 if (!empty($instances)) {
6377 // Array to store plugins being used
6378 $alreadyplugins = array();
6379 $totalinstances = count($instances);
6380 $updowncount = 1;
6381 foreach ($instances as $i) {
6382 $settings = '';
6383 $typename = $i->get_typename();
6384 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6385 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6386 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6388 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6389 // Calculate number of instances in order to display them for the Moodle administrator
6390 if (!empty($instanceoptionnames)) {
6391 $params = array();
6392 $params['context'] = array(get_system_context());
6393 $params['onlyvisible'] = false;
6394 $params['type'] = $typename;
6395 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6396 // site instances
6397 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6398 $params['context'] = array();
6399 $instances = repository::static_function($typename, 'get_instances', $params);
6400 $courseinstances = array();
6401 $userinstances = array();
6403 foreach ($instances as $instance) {
6404 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6405 $courseinstances[] = $instance;
6406 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6407 $userinstances[] = $instance;
6410 // course instances
6411 $instancenumber = count($courseinstances);
6412 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6414 // user private instances
6415 $instancenumber = count($userinstances);
6416 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6417 } else {
6418 $admininstancenumbertext = "";
6419 $courseinstancenumbertext = "";
6420 $userinstancenumbertext = "";
6423 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6425 $settings .= $OUTPUT->container_start('mdl-left');
6426 $settings .= '<br/>';
6427 $settings .= $admininstancenumbertext;
6428 $settings .= '<br/>';
6429 $settings .= $courseinstancenumbertext;
6430 $settings .= '<br/>';
6431 $settings .= $userinstancenumbertext;
6432 $settings .= $OUTPUT->container_end();
6434 // Get the current visibility
6435 if ($i->get_visible()) {
6436 $currentaction = 'show';
6437 } else {
6438 $currentaction = 'hide';
6441 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6443 // Display up/down link
6444 $updown = '';
6445 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6447 if ($updowncount > 1) {
6448 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6449 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6451 else {
6452 $updown .= $spacer;
6454 if ($updowncount < $totalinstances) {
6455 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6456 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6458 else {
6459 $updown .= $spacer;
6462 $updowncount++;
6464 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6466 if (!in_array($typename, $alreadyplugins)) {
6467 $alreadyplugins[] = $typename;
6472 // Get all the plugins that exist on disk
6473 $plugins = get_plugin_list('repository');
6474 if (!empty($plugins)) {
6475 foreach ($plugins as $plugin => $dir) {
6476 // Check that it has not already been listed
6477 if (!in_array($plugin, $alreadyplugins)) {
6478 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6479 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6484 $return .= html_writer::table($table);
6485 $return .= $OUTPUT->box_end();
6486 return highlight($query, $return);
6491 * Special checkbox for enable mobile web service
6492 * If enable then we store the service id of the mobile service into config table
6493 * If disable then we unstore the service id from the config table
6495 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6497 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6500 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6501 * @return boolean
6503 private function is_xmlrpc_cap_allowed() {
6504 global $DB, $CFG;
6506 //if the $this->xmlrpcuse variable is not set, it needs to be set
6507 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6508 $params = array();
6509 $params['permission'] = CAP_ALLOW;
6510 $params['roleid'] = $CFG->defaultuserroleid;
6511 $params['capability'] = 'webservice/xmlrpc:use';
6512 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6515 return $this->xmlrpcuse;
6519 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6520 * @param type $status true to allow, false to not set
6522 private function set_xmlrpc_cap($status) {
6523 global $CFG;
6524 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6525 //need to allow the cap
6526 $permission = CAP_ALLOW;
6527 $assign = true;
6528 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6529 //need to disallow the cap
6530 $permission = CAP_INHERIT;
6531 $assign = true;
6533 if (!empty($assign)) {
6534 $systemcontext = get_system_context();
6535 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6540 * Builds XHTML to display the control.
6541 * The main purpose of this overloading is to display a warning when https
6542 * is not supported by the server
6543 * @param string $data Unused
6544 * @param string $query
6545 * @return string XHTML
6547 public function output_html($data, $query='') {
6548 global $CFG, $OUTPUT;
6549 $html = parent::output_html($data, $query);
6551 if ((string)$data === $this->yes) {
6552 require_once($CFG->dirroot . "/lib/filelib.php");
6553 $curl = new curl();
6554 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6555 $curl->head($httpswwwroot . "/login/index.php");
6556 $info = $curl->get_info();
6557 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6558 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6562 return $html;
6566 * Retrieves the current setting using the objects name
6568 * @return string
6570 public function get_setting() {
6571 global $CFG;
6573 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6574 // Or if web services aren't enabled this can't be,
6575 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6576 return 0;
6579 require_once($CFG->dirroot . '/webservice/lib.php');
6580 $webservicemanager = new webservice();
6581 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6582 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6583 return $this->config_read($this->name); //same as returning 1
6584 } else {
6585 return 0;
6590 * Save the selected setting
6592 * @param string $data The selected site
6593 * @return string empty string or error message
6595 public function write_setting($data) {
6596 global $DB, $CFG;
6598 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6599 if (empty($CFG->defaultuserroleid)) {
6600 return '';
6603 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6605 require_once($CFG->dirroot . '/webservice/lib.php');
6606 $webservicemanager = new webservice();
6608 if ((string)$data === $this->yes) {
6609 //code run when enable mobile web service
6610 //enable web service systeme if necessary
6611 set_config('enablewebservices', true);
6613 //enable mobile service
6614 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6615 $mobileservice->enabled = 1;
6616 $webservicemanager->update_external_service($mobileservice);
6618 //enable xml-rpc server
6619 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6621 if (!in_array('xmlrpc', $activeprotocols)) {
6622 $activeprotocols[] = 'xmlrpc';
6623 set_config('webserviceprotocols', implode(',', $activeprotocols));
6626 //allow xml-rpc:use capability for authenticated user
6627 $this->set_xmlrpc_cap(true);
6629 } else {
6630 //disable web service system if no other services are enabled
6631 $otherenabledservices = $DB->get_records_select('external_services',
6632 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6633 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6634 if (empty($otherenabledservices)) {
6635 set_config('enablewebservices', false);
6637 //also disable xml-rpc server
6638 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6639 $protocolkey = array_search('xmlrpc', $activeprotocols);
6640 if ($protocolkey !== false) {
6641 unset($activeprotocols[$protocolkey]);
6642 set_config('webserviceprotocols', implode(',', $activeprotocols));
6645 //disallow xml-rpc:use capability for authenticated user
6646 $this->set_xmlrpc_cap(false);
6649 //disable the mobile service
6650 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6651 $mobileservice->enabled = 0;
6652 $webservicemanager->update_external_service($mobileservice);
6655 return (parent::write_setting($data));
6660 * Special class for management of external services
6662 * @author Petr Skoda (skodak)
6664 class admin_setting_manageexternalservices extends admin_setting {
6666 * Calls parent::__construct with specific arguments
6668 public function __construct() {
6669 $this->nosave = true;
6670 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6674 * Always returns true, does nothing
6676 * @return true
6678 public function get_setting() {
6679 return true;
6683 * Always returns true, does nothing
6685 * @return true
6687 public function get_defaultsetting() {
6688 return true;
6692 * Always returns '', does not write anything
6694 * @return string Always returns ''
6696 public function write_setting($data) {
6697 // do not write any setting
6698 return '';
6702 * Checks if $query is one of the available external services
6704 * @param string $query The string to search for
6705 * @return bool Returns true if found, false if not
6707 public function is_related($query) {
6708 global $DB;
6710 if (parent::is_related($query)) {
6711 return true;
6714 $textlib = textlib_get_instance();
6715 $services = $DB->get_records('external_services', array(), 'id, name');
6716 foreach ($services as $service) {
6717 if (strpos($textlib->strtolower($service->name), $query) !== false) {
6718 return true;
6721 return false;
6725 * Builds the XHTML to display the control
6727 * @param string $data Unused
6728 * @param string $query
6729 * @return string
6731 public function output_html($data, $query='') {
6732 global $CFG, $OUTPUT, $DB;
6734 // display strings
6735 $stradministration = get_string('administration');
6736 $stredit = get_string('edit');
6737 $strservice = get_string('externalservice', 'webservice');
6738 $strdelete = get_string('delete');
6739 $strplugin = get_string('plugin', 'admin');
6740 $stradd = get_string('add');
6741 $strfunctions = get_string('functions', 'webservice');
6742 $strusers = get_string('users');
6743 $strserviceusers = get_string('serviceusers', 'webservice');
6745 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6746 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6747 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6749 // built in services
6750 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6751 $return = "";
6752 if (!empty($services)) {
6753 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
6757 $table = new html_table();
6758 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
6759 $table->align = array('left', 'left', 'center', 'center', 'center');
6760 $table->size = array('30%', '20%', '20%', '20%', '10%');
6761 $table->width = '100%';
6762 $table->data = array();
6764 // iterate through auth plugins and add to the display table
6765 foreach ($services as $service) {
6766 $name = $service->name;
6768 // hide/show link
6769 if ($service->enabled) {
6770 $displayname = "<span>$name</span>";
6771 } else {
6772 $displayname = "<span class=\"dimmed_text\">$name</span>";
6775 $plugin = $service->component;
6777 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6779 if ($service->restrictedusers) {
6780 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6781 } else {
6782 $users = get_string('allusers', 'webservice');
6785 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6787 // add a row to the table
6788 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
6790 $return .= html_writer::table($table);
6793 // Custom services
6794 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
6795 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
6797 $table = new html_table();
6798 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
6799 $table->align = array('left', 'center', 'center', 'center', 'center');
6800 $table->size = array('30%', '20%', '20%', '20%', '10%');
6801 $table->width = '100%';
6802 $table->data = array();
6804 // iterate through auth plugins and add to the display table
6805 foreach ($services as $service) {
6806 $name = $service->name;
6808 // hide/show link
6809 if ($service->enabled) {
6810 $displayname = "<span>$name</span>";
6811 } else {
6812 $displayname = "<span class=\"dimmed_text\">$name</span>";
6815 // delete link
6816 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
6818 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6820 if ($service->restrictedusers) {
6821 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6822 } else {
6823 $users = get_string('allusers', 'webservice');
6826 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6828 // add a row to the table
6829 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
6831 // add new custom service option
6832 $return .= html_writer::table($table);
6834 $return .= '<br />';
6835 // add a token to the table
6836 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
6838 return highlight($query, $return);
6844 * Special class for plagiarism administration.
6846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6848 class admin_setting_manageplagiarism extends admin_setting {
6850 * Calls parent::__construct with specific arguments
6852 public function __construct() {
6853 $this->nosave = true;
6854 parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
6858 * Always returns true
6860 * @return true
6862 public function get_setting() {
6863 return true;
6867 * Always returns true
6869 * @return true
6871 public function get_defaultsetting() {
6872 return true;
6876 * Always returns '' and doesn't write anything
6878 * @return string Always returns ''
6880 public function write_setting($data) {
6881 // do not write any setting
6882 return '';
6886 * Return XHTML to display control
6888 * @param mixed $data Unused
6889 * @param string $query
6890 * @return string highlight
6892 public function output_html($data, $query='') {
6893 global $CFG, $OUTPUT;
6895 // display strings
6896 $txt = get_strings(array('settings', 'name'));
6898 $plagiarismplugins = get_plugin_list('plagiarism');
6899 if (empty($plagiarismplugins)) {
6900 return get_string('nopluginsinstalled', 'plagiarism');
6903 $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
6904 $return .= $OUTPUT->box_start('generalbox authsui');
6906 $table = new html_table();
6907 $table->head = array($txt->name, $txt->settings);
6908 $table->align = array('left', 'center');
6909 $table->data = array();
6910 $table->attributes['class'] = 'manageplagiarismtable generaltable';
6912 // iterate through auth plugins and add to the display table
6913 $authcount = count($plagiarismplugins);
6914 foreach ($plagiarismplugins as $plugin => $dir) {
6915 if (file_exists($dir.'/settings.php')) {
6916 $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
6917 // settings link
6918 $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
6919 // add a row to the table
6920 $table->data[] =array($displayname, $settings);
6923 $return .= html_writer::table($table);
6924 $return .= get_string('configplagiarismplugins', 'plagiarism');
6925 $return .= $OUTPUT->box_end();
6926 return highlight($query, $return);
6932 * Special class for overview of external services
6934 * @author Jerome Mouneyrac
6936 class admin_setting_webservicesoverview extends admin_setting {
6939 * Calls parent::__construct with specific arguments
6941 public function __construct() {
6942 $this->nosave = true;
6943 parent::__construct('webservicesoverviewui',
6944 get_string('webservicesoverview', 'webservice'), '', '');
6948 * Always returns true, does nothing
6950 * @return true
6952 public function get_setting() {
6953 return true;
6957 * Always returns true, does nothing
6959 * @return true
6961 public function get_defaultsetting() {
6962 return true;
6966 * Always returns '', does not write anything
6968 * @return string Always returns ''
6970 public function write_setting($data) {
6971 // do not write any setting
6972 return '';
6976 * Builds the XHTML to display the control
6978 * @param string $data Unused
6979 * @param string $query
6980 * @return string
6982 public function output_html($data, $query='') {
6983 global $CFG, $OUTPUT;
6985 $return = "";
6987 /// One system controlling Moodle with Token
6988 $brtag = html_writer::empty_tag('br');
6990 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
6991 $table = new html_table();
6992 $table->head = array(get_string('step', 'webservice'), get_string('status'),
6993 get_string('description'));
6994 $table->size = array('30%', '10%', '60%');
6995 $table->align = array('left', 'left', 'left');
6996 $table->width = '90%';
6997 $table->data = array();
6999 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7000 . $brtag . $brtag;
7002 /// 1. Enable Web Services
7003 $row = array();
7004 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7005 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7006 array('href' => $url));
7007 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7008 if ($CFG->enablewebservices) {
7009 $status = get_string('yes');
7011 $row[1] = $status;
7012 $row[2] = get_string('enablewsdescription', 'webservice');
7013 $table->data[] = $row;
7015 /// 2. Enable protocols
7016 $row = array();
7017 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7018 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7019 array('href' => $url));
7020 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7021 //retrieve activated protocol
7022 $active_protocols = empty($CFG->webserviceprotocols) ?
7023 array() : explode(',', $CFG->webserviceprotocols);
7024 if (!empty($active_protocols)) {
7025 $status = "";
7026 foreach ($active_protocols as $protocol) {
7027 $status .= $protocol . $brtag;
7030 $row[1] = $status;
7031 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7032 $table->data[] = $row;
7034 /// 3. Create user account
7035 $row = array();
7036 $url = new moodle_url("/user/editadvanced.php?id=-1");
7037 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7038 array('href' => $url));
7039 $row[1] = "";
7040 $row[2] = get_string('createuserdescription', 'webservice');
7041 $table->data[] = $row;
7043 /// 4. Add capability to users
7044 $row = array();
7045 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7046 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7047 array('href' => $url));
7048 $row[1] = "";
7049 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7050 $table->data[] = $row;
7052 /// 5. Select a web service
7053 $row = array();
7054 $url = new moodle_url("/admin/settings.php?section=externalservices");
7055 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7056 array('href' => $url));
7057 $row[1] = "";
7058 $row[2] = get_string('createservicedescription', 'webservice');
7059 $table->data[] = $row;
7061 /// 6. Add functions
7062 $row = array();
7063 $url = new moodle_url("/admin/settings.php?section=externalservices");
7064 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7065 array('href' => $url));
7066 $row[1] = "";
7067 $row[2] = get_string('addfunctionsdescription', 'webservice');
7068 $table->data[] = $row;
7070 /// 7. Add the specific user
7071 $row = array();
7072 $url = new moodle_url("/admin/settings.php?section=externalservices");
7073 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7074 array('href' => $url));
7075 $row[1] = "";
7076 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7077 $table->data[] = $row;
7079 /// 8. Create token for the specific user
7080 $row = array();
7081 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7082 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7083 array('href' => $url));
7084 $row[1] = "";
7085 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7086 $table->data[] = $row;
7088 /// 9. Enable the documentation
7089 $row = array();
7090 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7091 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7092 array('href' => $url));
7093 $status = '<span class="warning">' . get_string('no') . '</span>';
7094 if ($CFG->enablewsdocumentation) {
7095 $status = get_string('yes');
7097 $row[1] = $status;
7098 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7099 $table->data[] = $row;
7101 /// 10. Test the service
7102 $row = array();
7103 $url = new moodle_url("/admin/webservice/testclient.php");
7104 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7105 array('href' => $url));
7106 $row[1] = "";
7107 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7108 $table->data[] = $row;
7110 $return .= html_writer::table($table);
7112 /// Users as clients with token
7113 $return .= $brtag . $brtag . $brtag;
7114 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7115 $table = new html_table();
7116 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7117 get_string('description'));
7118 $table->size = array('30%', '10%', '60%');
7119 $table->align = array('left', 'left', 'left');
7120 $table->width = '90%';
7121 $table->data = array();
7123 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7124 $brtag . $brtag;
7126 /// 1. Enable Web Services
7127 $row = array();
7128 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7129 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7130 array('href' => $url));
7131 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7132 if ($CFG->enablewebservices) {
7133 $status = get_string('yes');
7135 $row[1] = $status;
7136 $row[2] = get_string('enablewsdescription', 'webservice');
7137 $table->data[] = $row;
7139 /// 2. Enable protocols
7140 $row = array();
7141 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7142 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7143 array('href' => $url));
7144 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7145 //retrieve activated protocol
7146 $active_protocols = empty($CFG->webserviceprotocols) ?
7147 array() : explode(',', $CFG->webserviceprotocols);
7148 if (!empty($active_protocols)) {
7149 $status = "";
7150 foreach ($active_protocols as $protocol) {
7151 $status .= $protocol . $brtag;
7154 $row[1] = $status;
7155 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7156 $table->data[] = $row;
7159 /// 3. Select a web service
7160 $row = array();
7161 $url = new moodle_url("/admin/settings.php?section=externalservices");
7162 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7163 array('href' => $url));
7164 $row[1] = "";
7165 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7166 $table->data[] = $row;
7168 /// 4. Add functions
7169 $row = array();
7170 $url = new moodle_url("/admin/settings.php?section=externalservices");
7171 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7172 array('href' => $url));
7173 $row[1] = "";
7174 $row[2] = get_string('addfunctionsdescription', 'webservice');
7175 $table->data[] = $row;
7177 /// 5. Add capability to users
7178 $row = array();
7179 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7180 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7181 array('href' => $url));
7182 $row[1] = "";
7183 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7184 $table->data[] = $row;
7186 /// 6. Test the service
7187 $row = array();
7188 $url = new moodle_url("/admin/webservice/testclient.php");
7189 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7190 array('href' => $url));
7191 $row[1] = "";
7192 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7193 $table->data[] = $row;
7195 $return .= html_writer::table($table);
7197 return highlight($query, $return);
7204 * Special class for web service protocol administration.
7206 * @author Petr Skoda (skodak)
7208 class admin_setting_managewebserviceprotocols extends admin_setting {
7211 * Calls parent::__construct with specific arguments
7213 public function __construct() {
7214 $this->nosave = true;
7215 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7219 * Always returns true, does nothing
7221 * @return true
7223 public function get_setting() {
7224 return true;
7228 * Always returns true, does nothing
7230 * @return true
7232 public function get_defaultsetting() {
7233 return true;
7237 * Always returns '', does not write anything
7239 * @return string Always returns ''
7241 public function write_setting($data) {
7242 // do not write any setting
7243 return '';
7247 * Checks if $query is one of the available webservices
7249 * @param string $query The string to search for
7250 * @return bool Returns true if found, false if not
7252 public function is_related($query) {
7253 if (parent::is_related($query)) {
7254 return true;
7257 $textlib = textlib_get_instance();
7258 $protocols = get_plugin_list('webservice');
7259 foreach ($protocols as $protocol=>$location) {
7260 if (strpos($protocol, $query) !== false) {
7261 return true;
7263 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7264 if (strpos($textlib->strtolower($protocolstr), $query) !== false) {
7265 return true;
7268 return false;
7272 * Builds the XHTML to display the control
7274 * @param string $data Unused
7275 * @param string $query
7276 * @return string
7278 public function output_html($data, $query='') {
7279 global $CFG, $OUTPUT;
7281 // display strings
7282 $stradministration = get_string('administration');
7283 $strsettings = get_string('settings');
7284 $stredit = get_string('edit');
7285 $strprotocol = get_string('protocol', 'webservice');
7286 $strenable = get_string('enable');
7287 $strdisable = get_string('disable');
7288 $strversion = get_string('version');
7289 $struninstall = get_string('uninstallplugin', 'admin');
7291 $protocols_available = get_plugin_list('webservice');
7292 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7293 ksort($protocols_available);
7295 foreach ($active_protocols as $key=>$protocol) {
7296 if (empty($protocols_available[$protocol])) {
7297 unset($active_protocols[$key]);
7301 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7302 $return .= $OUTPUT->box_start('generalbox webservicesui');
7304 $table = new html_table();
7305 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7306 $table->align = array('left', 'center', 'center', 'center', 'center');
7307 $table->width = '100%';
7308 $table->data = array();
7310 // iterate through auth plugins and add to the display table
7311 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7312 foreach ($protocols_available as $protocol => $location) {
7313 $name = get_string('pluginname', 'webservice_'.$protocol);
7315 $plugin = new stdClass();
7316 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7317 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7319 $version = isset($plugin->version) ? $plugin->version : '';
7321 // hide/show link
7322 if (in_array($protocol, $active_protocols)) {
7323 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7324 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
7325 $displayname = "<span>$name</span>";
7326 } else {
7327 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7328 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
7329 $displayname = "<span class=\"dimmed_text\">$name</span>";
7332 // delete link
7333 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7335 // settings link
7336 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7337 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7338 } else {
7339 $settings = '';
7342 // add a row to the table
7343 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7345 $return .= html_writer::table($table);
7346 $return .= get_string('configwebserviceplugins', 'webservice');
7347 $return .= $OUTPUT->box_end();
7349 return highlight($query, $return);
7355 * Special class for web service token administration.
7357 * @author Jerome Mouneyrac
7359 class admin_setting_managewebservicetokens extends admin_setting {
7362 * Calls parent::__construct with specific arguments
7364 public function __construct() {
7365 $this->nosave = true;
7366 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7370 * Always returns true, does nothing
7372 * @return true
7374 public function get_setting() {
7375 return true;
7379 * Always returns true, does nothing
7381 * @return true
7383 public function get_defaultsetting() {
7384 return true;
7388 * Always returns '', does not write anything
7390 * @return string Always returns ''
7392 public function write_setting($data) {
7393 // do not write any setting
7394 return '';
7398 * Builds the XHTML to display the control
7400 * @param string $data Unused
7401 * @param string $query
7402 * @return string
7404 public function output_html($data, $query='') {
7405 global $CFG, $OUTPUT, $DB, $USER;
7407 // display strings
7408 $stroperation = get_string('operation', 'webservice');
7409 $strtoken = get_string('token', 'webservice');
7410 $strservice = get_string('service', 'webservice');
7411 $struser = get_string('user');
7412 $strcontext = get_string('context', 'webservice');
7413 $strvaliduntil = get_string('validuntil', 'webservice');
7414 $striprestriction = get_string('iprestriction', 'webservice');
7416 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7418 $table = new html_table();
7419 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7420 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7421 $table->width = '100%';
7422 $table->data = array();
7424 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7426 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7428 //here retrieve token list (including linked users firstname/lastname and linked services name)
7429 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.validuntil, s.id AS serviceid
7430 FROM {external_tokens} t, {user} u, {external_services} s
7431 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7432 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7433 if (!empty($tokens)) {
7434 foreach ($tokens as $token) {
7435 //TODO: retrieve context
7437 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7438 $delete .= get_string('delete')."</a>";
7440 $validuntil = '';
7441 if (!empty($token->validuntil)) {
7442 $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
7445 $iprestriction = '';
7446 if (!empty($token->iprestriction)) {
7447 $iprestriction = $token->iprestriction;
7450 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7451 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7452 $useratag .= $token->firstname." ".$token->lastname;
7453 $useratag .= html_writer::end_tag('a');
7455 //check user missing capabilities
7456 require_once($CFG->dirroot . '/webservice/lib.php');
7457 $webservicemanager = new webservice();
7458 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7459 array(array('id' => $token->userid)), $token->serviceid);
7461 if (!is_siteadmin($token->userid) and
7462 key_exists($token->userid, $usermissingcaps)) {
7463 $missingcapabilities = implode(',',
7464 $usermissingcaps[$token->userid]);
7465 if (!empty($missingcapabilities)) {
7466 $useratag .= html_writer::tag('div',
7467 get_string('usermissingcaps', 'webservice',
7468 $missingcapabilities)
7469 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7470 array('class' => 'missingcaps'));
7474 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7477 $return .= html_writer::table($table);
7478 } else {
7479 $return .= get_string('notoken', 'webservice');
7482 $return .= $OUTPUT->box_end();
7483 // add a token to the table
7484 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7485 $return .= get_string('add')."</a>";
7487 return highlight($query, $return);
7493 * Colour picker
7495 * @copyright 2010 Sam Hemelryk
7496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7498 class admin_setting_configcolourpicker extends admin_setting {
7501 * Information for previewing the colour
7503 * @var array|null
7505 protected $previewconfig = null;
7509 * @param string $name
7510 * @param string $visiblename
7511 * @param string $description
7512 * @param string $defaultsetting
7513 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7515 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7516 $this->previewconfig = $previewconfig;
7517 parent::__construct($name, $visiblename, $description, $defaultsetting);
7521 * Return the setting
7523 * @return mixed returns config if successful else null
7525 public function get_setting() {
7526 return $this->config_read($this->name);
7530 * Saves the setting
7532 * @param string $data
7533 * @return bool
7535 public function write_setting($data) {
7536 $data = $this->validate($data);
7537 if ($data === false) {
7538 return get_string('validateerror', 'admin');
7540 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7544 * Validates the colour that was entered by the user
7546 * @param string $data
7547 * @return string|false
7549 protected function validate($data) {
7550 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7551 if (strpos($data, '#')!==0) {
7552 $data = '#'.$data;
7554 return $data;
7555 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7556 return $data;
7557 } else if (empty($data)) {
7558 return $this->defaultsetting;
7559 } else {
7560 return false;
7565 * Generates the HTML for the setting
7567 * @global moodle_page $PAGE
7568 * @global core_renderer $OUTPUT
7569 * @param string $data
7570 * @param string $query
7572 public function output_html($data, $query = '') {
7573 global $PAGE, $OUTPUT;
7574 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7575 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7576 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7577 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
7578 if (!empty($this->previewconfig)) {
7579 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7581 $content .= html_writer::end_tag('div');
7582 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7587 * Administration interface for user specified regular expressions for device detection.
7589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7591 class admin_setting_devicedetectregex extends admin_setting {
7594 * Calls parent::__construct with specific args
7596 * @param string $name
7597 * @param string $visiblename
7598 * @param string $description
7599 * @param mixed $defaultsetting
7601 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7602 global $CFG;
7603 parent::__construct($name, $visiblename, $description, $defaultsetting);
7607 * Return the current setting(s)
7609 * @return array Current settings array
7611 public function get_setting() {
7612 global $CFG;
7614 $config = $this->config_read($this->name);
7615 if (is_null($config)) {
7616 return null;
7619 return $this->prepare_form_data($config);
7623 * Save selected settings
7625 * @param array $data Array of settings to save
7626 * @return bool
7628 public function write_setting($data) {
7629 if (empty($data)) {
7630 $data = array();
7633 if ($this->config_write($this->name, $this->process_form_data($data))) {
7634 return ''; // success
7635 } else {
7636 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
7641 * Return XHTML field(s) for regexes
7643 * @param array $data Array of options to set in HTML
7644 * @return string XHTML string for the fields and wrapping div(s)
7646 public function output_html($data, $query='') {
7647 global $OUTPUT;
7649 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
7650 $out .= html_writer::start_tag('thead');
7651 $out .= html_writer::start_tag('tr');
7652 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
7653 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
7654 $out .= html_writer::end_tag('tr');
7655 $out .= html_writer::end_tag('thead');
7656 $out .= html_writer::start_tag('tbody');
7658 if (empty($data)) {
7659 $looplimit = 1;
7660 } else {
7661 $looplimit = (count($data)/2)+1;
7664 for ($i=0; $i<$looplimit; $i++) {
7665 $out .= html_writer::start_tag('tr');
7667 $expressionname = 'expression'.$i;
7669 if (!empty($data[$expressionname])){
7670 $expression = $data[$expressionname];
7671 } else {
7672 $expression = '';
7675 $out .= html_writer::tag('td',
7676 html_writer::empty_tag('input',
7677 array(
7678 'type' => 'text',
7679 'class' => 'form-text',
7680 'name' => $this->get_full_name().'[expression'.$i.']',
7681 'value' => $expression,
7683 ), array('class' => 'c'.$i)
7686 $valuename = 'value'.$i;
7688 if (!empty($data[$valuename])){
7689 $value = $data[$valuename];
7690 } else {
7691 $value= '';
7694 $out .= html_writer::tag('td',
7695 html_writer::empty_tag('input',
7696 array(
7697 'type' => 'text',
7698 'class' => 'form-text',
7699 'name' => $this->get_full_name().'[value'.$i.']',
7700 'value' => $value,
7702 ), array('class' => 'c'.$i)
7705 $out .= html_writer::end_tag('tr');
7708 $out .= html_writer::end_tag('tbody');
7709 $out .= html_writer::end_tag('table');
7711 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
7715 * Converts the string of regexes
7717 * @see self::process_form_data()
7718 * @param $regexes string of regexes
7719 * @return array of form fields and their values
7721 protected function prepare_form_data($regexes) {
7723 $regexes = json_decode($regexes);
7725 $form = array();
7727 $i = 0;
7729 foreach ($regexes as $value => $regex) {
7730 $expressionname = 'expression'.$i;
7731 $valuename = 'value'.$i;
7733 $form[$expressionname] = $regex;
7734 $form[$valuename] = $value;
7735 $i++;
7738 return $form;
7742 * Converts the data from admin settings form into a string of regexes
7744 * @see self::prepare_form_data()
7745 * @param array $data array of admin form fields and values
7746 * @return false|string of regexes
7748 protected function process_form_data(array $form) {
7750 $count = count($form); // number of form field values
7752 if ($count % 2) {
7753 // we must get five fields per expression
7754 return false;
7757 $regexes = array();
7758 for ($i = 0; $i < $count / 2; $i++) {
7759 $expressionname = "expression".$i;
7760 $valuename = "value".$i;
7762 $expression = trim($form['expression'.$i]);
7763 $value = trim($form['value'.$i]);
7765 if (empty($expression)){
7766 continue;
7769 $regexes[$value] = $expression;
7772 $regexes = json_encode($regexes);
7774 return $regexes;
7779 * Multiselect for current modules
7781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7783 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
7785 * Calls parent::__construct - note array $choices is not required
7787 * @param string $name setting name
7788 * @param string $visiblename localised setting name
7789 * @param string $description setting description
7791 public function __construct($name, $visiblename, $description) {
7792 parent::__construct($name, $visiblename, $description, array(), null);
7796 * Loads an array of current module choices
7798 * @return bool always return true
7800 public function load_choices() {
7801 if (is_array($this->choices)) {
7802 return true;
7804 $this->choices = array();
7806 global $CFG, $DB;
7807 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7808 foreach ($records as $record) {
7809 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7810 $this->choices[$record->id] = $record->name;
7813 return true;