Merge branch 'wip-MDL-25454-master' of git://github.com/marinaglancy/moodle
[moodle.git] / lib / adminlib.php
blobd4adbe679c13d8cbe0eabb3ebc488a4d332a8cfe
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 return parent::write_setting($data);
2943 * Special select for settings that are altered in setup.php and can not be altered on the fly
2945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2947 class admin_setting_special_selectsetup extends admin_setting_configselect {
2949 * Reads the setting directly from the database
2951 * @return mixed
2953 public function get_setting() {
2954 // read directly from db!
2955 return get_config(NULL, $this->name);
2959 * Save the setting passed in $data
2961 * @param string $data The setting to save
2962 * @return string empty or error message
2964 public function write_setting($data) {
2965 global $CFG;
2966 // do not change active CFG setting!
2967 $current = $CFG->{$this->name};
2968 $result = parent::write_setting($data);
2969 $CFG->{$this->name} = $current;
2970 return $result;
2976 * Special select for frontpage - stores data in course table
2978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2980 class admin_setting_sitesetselect extends admin_setting_configselect {
2982 * Returns the site name for the selected site
2984 * @see get_site()
2985 * @return string The site name of the selected site
2987 public function get_setting() {
2988 $site = get_site();
2989 return $site->{$this->name};
2993 * Updates the database and save the setting
2995 * @param string data
2996 * @return string empty or error message
2998 public function write_setting($data) {
2999 global $DB, $SITE;
3000 if (!in_array($data, array_keys($this->choices))) {
3001 return get_string('errorsetting', 'admin');
3003 $record = new stdClass();
3004 $record->id = SITEID;
3005 $temp = $this->name;
3006 $record->$temp = $data;
3007 $record->timemodified = time();
3008 // update $SITE
3009 $SITE->{$this->name} = $data;
3010 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3016 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3017 * block to hidden.
3019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3021 class admin_setting_bloglevel extends admin_setting_configselect {
3023 * Updates the database and save the setting
3025 * @param string data
3026 * @return string empty or error message
3028 public function write_setting($data) {
3029 global $DB, $CFG;
3030 if ($data['bloglevel'] == 0) {
3031 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3032 foreach ($blogblocks as $block) {
3033 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3035 } else {
3036 // reenable all blocks only when switching from disabled blogs
3037 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3038 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3039 foreach ($blogblocks as $block) {
3040 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3044 return parent::write_setting($data);
3050 * Special select - lists on the frontpage - hacky
3052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3054 class admin_setting_courselist_frontpage extends admin_setting {
3055 /** @var array Array of choices value=>label */
3056 public $choices;
3059 * Construct override, requires one param
3061 * @param bool $loggedin Is the user logged in
3063 public function __construct($loggedin) {
3064 global $CFG;
3065 require_once($CFG->dirroot.'/course/lib.php');
3066 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3067 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3068 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3069 $defaults = array(FRONTPAGECOURSELIST);
3070 parent::__construct($name, $visiblename, $description, $defaults);
3074 * Loads the choices available
3076 * @return bool always returns true
3078 public function load_choices() {
3079 global $DB;
3080 if (is_array($this->choices)) {
3081 return true;
3083 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3084 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3085 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3086 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3087 'none' => get_string('none'));
3088 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3089 unset($this->choices[FRONTPAGECOURSELIST]);
3091 return true;
3095 * Returns the selected settings
3097 * @param mixed array or setting or null
3099 public function get_setting() {
3100 $result = $this->config_read($this->name);
3101 if (is_null($result)) {
3102 return NULL;
3104 if ($result === '') {
3105 return array();
3107 return explode(',', $result);
3111 * Save the selected options
3113 * @param array $data
3114 * @return mixed empty string (data is not an array) or bool true=success false=failure
3116 public function write_setting($data) {
3117 if (!is_array($data)) {
3118 return '';
3120 $this->load_choices();
3121 $save = array();
3122 foreach($data as $datum) {
3123 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3124 continue;
3126 $save[$datum] = $datum; // no duplicates
3128 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3132 * Return XHTML select field and wrapping div
3134 * @todo Add vartype handling to make sure $data is an array
3135 * @param array $data Array of elements to select by default
3136 * @return string XHTML select field and wrapping div
3138 public function output_html($data, $query='') {
3139 $this->load_choices();
3140 $currentsetting = array();
3141 foreach ($data as $key) {
3142 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3143 $currentsetting[] = $key; // already selected first
3147 $return = '<div class="form-group">';
3148 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3149 if (!array_key_exists($i, $currentsetting)) {
3150 $currentsetting[$i] = 'none'; //none
3152 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3153 foreach ($this->choices as $key => $value) {
3154 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3156 $return .= '</select>';
3157 if ($i !== count($this->choices) - 2) {
3158 $return .= '<br />';
3161 $return .= '</div>';
3163 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3169 * Special checkbox for frontpage - stores data in course table
3171 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3173 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3175 * Returns the current sites name
3177 * @return string
3179 public function get_setting() {
3180 $site = get_site();
3181 return $site->{$this->name};
3185 * Save the selected setting
3187 * @param string $data The selected site
3188 * @return string empty string or error message
3190 public function write_setting($data) {
3191 global $DB, $SITE;
3192 $record = new stdClass();
3193 $record->id = SITEID;
3194 $record->{$this->name} = ($data == '1' ? 1 : 0);
3195 $record->timemodified = time();
3196 // update $SITE
3197 $SITE->{$this->name} = $data;
3198 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3203 * Special text for frontpage - stores data in course table.
3204 * Empty string means not set here. Manual setting is required.
3206 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3208 class admin_setting_sitesettext extends admin_setting_configtext {
3210 * Return the current setting
3212 * @return mixed string or null
3214 public function get_setting() {
3215 $site = get_site();
3216 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3220 * Validate the selected data
3222 * @param string $data The selected value to validate
3223 * @return mixed true or message string
3225 public function validate($data) {
3226 $cleaned = clean_param($data, PARAM_MULTILANG);
3227 if ($cleaned === '') {
3228 return get_string('required');
3230 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3231 return true;
3232 } else {
3233 return get_string('validateerror', 'admin');
3238 * Save the selected setting
3240 * @param string $data The selected value
3241 * @return string empty or error message
3243 public function write_setting($data) {
3244 global $DB, $SITE;
3245 $data = trim($data);
3246 $validated = $this->validate($data);
3247 if ($validated !== true) {
3248 return $validated;
3251 $record = new stdClass();
3252 $record->id = SITEID;
3253 $record->{$this->name} = $data;
3254 $record->timemodified = time();
3255 // update $SITE
3256 $SITE->{$this->name} = $data;
3257 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3263 * Special text editor for site description.
3265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3267 class admin_setting_special_frontpagedesc extends admin_setting {
3269 * Calls parent::__construct with specific arguments
3271 public function __construct() {
3272 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3273 editors_head_setup();
3277 * Return the current setting
3278 * @return string The current setting
3280 public function get_setting() {
3281 $site = get_site();
3282 return $site->{$this->name};
3286 * Save the new setting
3288 * @param string $data The new value to save
3289 * @return string empty or error message
3291 public function write_setting($data) {
3292 global $DB, $SITE;
3293 $record = new stdClass();
3294 $record->id = SITEID;
3295 $record->{$this->name} = $data;
3296 $record->timemodified = time();
3297 $SITE->{$this->name} = $data;
3298 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3302 * Returns XHTML for the field plus wrapping div
3304 * @param string $data The current value
3305 * @param string $query
3306 * @return string The XHTML output
3308 public function output_html($data, $query='') {
3309 global $CFG;
3311 $CFG->adminusehtmleditor = can_use_html_editor();
3312 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3314 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3320 * Administration interface for emoticon_manager settings.
3322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3324 class admin_setting_emoticons extends admin_setting {
3327 * Calls parent::__construct with specific args
3329 public function __construct() {
3330 global $CFG;
3332 $manager = get_emoticon_manager();
3333 $defaults = $this->prepare_form_data($manager->default_emoticons());
3334 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3338 * Return the current setting(s)
3340 * @return array Current settings array
3342 public function get_setting() {
3343 global $CFG;
3345 $manager = get_emoticon_manager();
3347 $config = $this->config_read($this->name);
3348 if (is_null($config)) {
3349 return null;
3352 $config = $manager->decode_stored_config($config);
3353 if (is_null($config)) {
3354 return null;
3357 return $this->prepare_form_data($config);
3361 * Save selected settings
3363 * @param array $data Array of settings to save
3364 * @return bool
3366 public function write_setting($data) {
3368 $manager = get_emoticon_manager();
3369 $emoticons = $this->process_form_data($data);
3371 if ($emoticons === false) {
3372 return false;
3375 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3376 return ''; // success
3377 } else {
3378 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3383 * Return XHTML field(s) for options
3385 * @param array $data Array of options to set in HTML
3386 * @return string XHTML string for the fields and wrapping div(s)
3388 public function output_html($data, $query='') {
3389 global $OUTPUT;
3391 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3392 $out .= html_writer::start_tag('thead');
3393 $out .= html_writer::start_tag('tr');
3394 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3395 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3396 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3397 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3398 $out .= html_writer::tag('th', '');
3399 $out .= html_writer::end_tag('tr');
3400 $out .= html_writer::end_tag('thead');
3401 $out .= html_writer::start_tag('tbody');
3402 $i = 0;
3403 foreach($data as $field => $value) {
3404 switch ($i) {
3405 case 0:
3406 $out .= html_writer::start_tag('tr');
3407 $current_text = $value;
3408 $current_filename = '';
3409 $current_imagecomponent = '';
3410 $current_altidentifier = '';
3411 $current_altcomponent = '';
3412 case 1:
3413 $current_filename = $value;
3414 case 2:
3415 $current_imagecomponent = $value;
3416 case 3:
3417 $current_altidentifier = $value;
3418 case 4:
3419 $current_altcomponent = $value;
3422 $out .= html_writer::tag('td',
3423 html_writer::empty_tag('input',
3424 array(
3425 'type' => 'text',
3426 'class' => 'form-text',
3427 'name' => $this->get_full_name().'['.$field.']',
3428 'value' => $value,
3430 ), array('class' => 'c'.$i)
3433 if ($i == 4) {
3434 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3435 $alt = get_string($current_altidentifier, $current_altcomponent);
3436 } else {
3437 $alt = $current_text;
3439 if ($current_filename) {
3440 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3441 } else {
3442 $out .= html_writer::tag('td', '');
3444 $out .= html_writer::end_tag('tr');
3445 $i = 0;
3446 } else {
3447 $i++;
3451 $out .= html_writer::end_tag('tbody');
3452 $out .= html_writer::end_tag('table');
3453 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3454 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3456 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3460 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3462 * @see self::process_form_data()
3463 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3464 * @return array of form fields and their values
3466 protected function prepare_form_data(array $emoticons) {
3468 $form = array();
3469 $i = 0;
3470 foreach ($emoticons as $emoticon) {
3471 $form['text'.$i] = $emoticon->text;
3472 $form['imagename'.$i] = $emoticon->imagename;
3473 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3474 $form['altidentifier'.$i] = $emoticon->altidentifier;
3475 $form['altcomponent'.$i] = $emoticon->altcomponent;
3476 $i++;
3478 // add one more blank field set for new object
3479 $form['text'.$i] = '';
3480 $form['imagename'.$i] = '';
3481 $form['imagecomponent'.$i] = '';
3482 $form['altidentifier'.$i] = '';
3483 $form['altcomponent'.$i] = '';
3485 return $form;
3489 * Converts the data from admin settings form into an array of emoticon objects
3491 * @see self::prepare_form_data()
3492 * @param array $data array of admin form fields and values
3493 * @return false|array of emoticon objects
3495 protected function process_form_data(array $form) {
3497 $count = count($form); // number of form field values
3499 if ($count % 5) {
3500 // we must get five fields per emoticon object
3501 return false;
3504 $emoticons = array();
3505 for ($i = 0; $i < $count / 5; $i++) {
3506 $emoticon = new stdClass();
3507 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3508 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3509 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3510 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3511 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3513 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3514 // prevent from breaking http://url.addresses by accident
3515 $emoticon->text = '';
3518 if (strlen($emoticon->text) < 2) {
3519 // do not allow single character emoticons
3520 $emoticon->text = '';
3523 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3524 // emoticon text must contain some non-alphanumeric character to prevent
3525 // breaking HTML tags
3526 $emoticon->text = '';
3529 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3530 $emoticons[] = $emoticon;
3533 return $emoticons;
3539 * Special setting for limiting of the list of available languages.
3541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3543 class admin_setting_langlist extends admin_setting_configtext {
3545 * Calls parent::__construct with specific arguments
3547 public function __construct() {
3548 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3552 * Save the new setting
3554 * @param string $data The new setting
3555 * @return bool
3557 public function write_setting($data) {
3558 $return = parent::write_setting($data);
3559 get_string_manager()->reset_caches();
3560 return $return;
3566 * Selection of one of the recognised countries using the list
3567 * returned by {@link get_list_of_countries()}.
3569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3571 class admin_settings_country_select extends admin_setting_configselect {
3572 protected $includeall;
3573 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3574 $this->includeall = $includeall;
3575 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3579 * Lazy-load the available choices for the select box
3581 public function load_choices() {
3582 global $CFG;
3583 if (is_array($this->choices)) {
3584 return true;
3586 $this->choices = array_merge(
3587 array('0' => get_string('choosedots')),
3588 get_string_manager()->get_list_of_countries($this->includeall));
3589 return true;
3595 * admin_setting_configselect for the default number of sections in a course,
3596 * simply so we can lazy-load the choices.
3598 * @copyright 2011 The Open University
3599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3601 class admin_settings_num_course_sections extends admin_setting_configselect {
3602 public function __construct($name, $visiblename, $description, $defaultsetting) {
3603 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3606 /** Lazy-load the available choices for the select box */
3607 public function load_choices() {
3608 $max = get_config('moodlecourse', 'maxsections');
3609 if (empty($max)) {
3610 $max = 52;
3612 for ($i = 0; $i <= $max; $i++) {
3613 $this->choices[$i] = "$i";
3615 return true;
3621 * Course category selection
3623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3625 class admin_settings_coursecat_select extends admin_setting_configselect {
3627 * Calls parent::__construct with specific arguments
3629 public function __construct($name, $visiblename, $description, $defaultsetting) {
3630 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3634 * Load the available choices for the select box
3636 * @return bool
3638 public function load_choices() {
3639 global $CFG;
3640 require_once($CFG->dirroot.'/course/lib.php');
3641 if (is_array($this->choices)) {
3642 return true;
3644 $this->choices = make_categories_options();
3645 return true;
3651 * Special control for selecting days to backup
3653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3655 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3657 * Calls parent::__construct with specific arguments
3659 public function __construct() {
3660 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3661 $this->plugin = 'backup';
3665 * Load the available choices for the select box
3667 * @return bool Always returns true
3669 public function load_choices() {
3670 if (is_array($this->choices)) {
3671 return true;
3673 $this->choices = array();
3674 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3675 foreach ($days as $day) {
3676 $this->choices[$day] = get_string($day, 'calendar');
3678 return true;
3684 * Special debug setting
3686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3688 class admin_setting_special_debug extends admin_setting_configselect {
3690 * Calls parent::__construct with specific arguments
3692 public function __construct() {
3693 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3697 * Load the available choices for the select box
3699 * @return bool
3701 public function load_choices() {
3702 if (is_array($this->choices)) {
3703 return true;
3705 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3706 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3707 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3708 DEBUG_ALL => get_string('debugall', 'admin'),
3709 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3710 return true;
3716 * Special admin control
3718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3720 class admin_setting_special_calendar_weekend extends admin_setting {
3722 * Calls parent::__construct with specific arguments
3724 public function __construct() {
3725 $name = 'calendar_weekend';
3726 $visiblename = get_string('calendar_weekend', 'admin');
3727 $description = get_string('helpweekenddays', 'admin');
3728 $default = array ('0', '6'); // Saturdays and Sundays
3729 parent::__construct($name, $visiblename, $description, $default);
3733 * Gets the current settings as an array
3735 * @return mixed Null if none, else array of settings
3737 public function get_setting() {
3738 $result = $this->config_read($this->name);
3739 if (is_null($result)) {
3740 return NULL;
3742 if ($result === '') {
3743 return array();
3745 $settings = array();
3746 for ($i=0; $i<7; $i++) {
3747 if ($result & (1 << $i)) {
3748 $settings[] = $i;
3751 return $settings;
3755 * Save the new settings
3757 * @param array $data Array of new settings
3758 * @return bool
3760 public function write_setting($data) {
3761 if (!is_array($data)) {
3762 return '';
3764 unset($data['xxxxx']);
3765 $result = 0;
3766 foreach($data as $index) {
3767 $result |= 1 << $index;
3769 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3773 * Return XHTML to display the control
3775 * @param array $data array of selected days
3776 * @param string $query
3777 * @return string XHTML for display (field + wrapping div(s)
3779 public function output_html($data, $query='') {
3780 // The order matters very much because of the implied numeric keys
3781 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3782 $return = '<table><thead><tr>';
3783 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3784 foreach($days as $index => $day) {
3785 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3787 $return .= '</tr></thead><tbody><tr>';
3788 foreach($days as $index => $day) {
3789 $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>';
3791 $return .= '</tr></tbody></table>';
3793 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3800 * Admin setting that allows a user to pick a behaviour.
3802 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3804 class admin_setting_question_behaviour extends admin_setting_configselect {
3806 * @param string $name name of config variable
3807 * @param string $visiblename display name
3808 * @param string $description description
3809 * @param string $default default.
3811 public function __construct($name, $visiblename, $description, $default) {
3812 parent::__construct($name, $visiblename, $description, $default, NULL);
3816 * Load list of behaviours as choices
3817 * @return bool true => success, false => error.
3819 public function load_choices() {
3820 global $CFG;
3821 require_once($CFG->dirroot . '/question/engine/lib.php');
3822 $this->choices = question_engine::get_archetypal_behaviours();
3823 return true;
3829 * Admin setting that allows a user to pick appropriate roles for something.
3831 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3833 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
3834 /** @var array Array of capabilities which identify roles */
3835 private $types;
3838 * @param string $name Name of config variable
3839 * @param string $visiblename Display name
3840 * @param string $description Description
3841 * @param array $types Array of archetypes which identify
3842 * roles that will be enabled by default.
3844 public function __construct($name, $visiblename, $description, $types) {
3845 parent::__construct($name, $visiblename, $description, NULL, NULL);
3846 $this->types = $types;
3850 * Load roles as choices
3852 * @return bool true=>success, false=>error
3854 public function load_choices() {
3855 global $CFG, $DB;
3856 if (during_initial_install()) {
3857 return false;
3859 if (is_array($this->choices)) {
3860 return true;
3862 if ($roles = get_all_roles()) {
3863 $this->choices = array();
3864 foreach($roles as $role) {
3865 $this->choices[$role->id] = format_string($role->name);
3867 return true;
3868 } else {
3869 return false;
3874 * Return the default setting for this control
3876 * @return array Array of default settings
3878 public function get_defaultsetting() {
3879 global $CFG;
3881 if (during_initial_install()) {
3882 return null;
3884 $result = array();
3885 foreach($this->types as $archetype) {
3886 if ($caproles = get_archetype_roles($archetype)) {
3887 foreach ($caproles as $caprole) {
3888 $result[$caprole->id] = 1;
3892 return $result;
3898 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
3900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3902 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
3904 * Constructor
3905 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3906 * @param string $visiblename localised
3907 * @param string $description long localised info
3908 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
3909 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
3910 * @param int $size default field size
3912 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
3913 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
3917 * Loads the current setting and returns array
3919 * @return array Returns array value=>xx, __construct=>xx
3921 public function get_setting() {
3922 $value = parent::get_setting();
3923 $adv = $this->config_read($this->name.'_adv');
3924 if (is_null($value) or is_null($adv)) {
3925 return NULL;
3927 return array('value' => $value, 'adv' => $adv);
3931 * Saves the new settings passed in $data
3933 * @todo Add vartype handling to ensure $data is an array
3934 * @param array $data
3935 * @return mixed string or Array
3937 public function write_setting($data) {
3938 $error = parent::write_setting($data['value']);
3939 if (!$error) {
3940 $value = empty($data['adv']) ? 0 : 1;
3941 $this->config_write($this->name.'_adv', $value);
3943 return $error;
3947 * Return XHTML for the control
3949 * @param array $data Default data array
3950 * @param string $query
3951 * @return string XHTML to display control
3953 public function output_html($data, $query='') {
3954 $default = $this->get_defaultsetting();
3955 $defaultinfo = array();
3956 if (isset($default['value'])) {
3957 if ($default['value'] === '') {
3958 $defaultinfo[] = "''";
3959 } else {
3960 $defaultinfo[] = $default['value'];
3963 if (!empty($default['adv'])) {
3964 $defaultinfo[] = get_string('advanced');
3966 $defaultinfo = implode(', ', $defaultinfo);
3968 $adv = !empty($data['adv']);
3969 $return = '<div class="form-text defaultsnext">' .
3970 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
3971 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
3972 ' <input type="checkbox" class="form-checkbox" id="' .
3973 $this->get_id() . '_adv" name="' . $this->get_full_name() .
3974 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
3975 ' <label for="' . $this->get_id() . '_adv">' .
3976 get_string('advanced') . '</label></div>';
3978 return format_admin_setting($this, $this->visiblename, $return,
3979 $this->description, true, '', $defaultinfo, $query);
3985 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
3987 * @copyright 2009 Petr Skoda (http://skodak.org)
3988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3990 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
3993 * Constructor
3994 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3995 * @param string $visiblename localised
3996 * @param string $description long localised info
3997 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
3998 * @param string $yes value used when checked
3999 * @param string $no value used when not checked
4001 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4002 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4006 * Loads the current setting and returns array
4008 * @return array Returns array value=>xx, adv=>xx
4010 public function get_setting() {
4011 $value = parent::get_setting();
4012 $adv = $this->config_read($this->name.'_adv');
4013 if (is_null($value) or is_null($adv)) {
4014 return NULL;
4016 return array('value' => $value, 'adv' => $adv);
4020 * Sets the value for the setting
4022 * Sets the value for the setting to either the yes or no values
4023 * of the object by comparing $data to yes
4025 * @param mixed $data Gets converted to str for comparison against yes value
4026 * @return string empty string or error
4028 public function write_setting($data) {
4029 $error = parent::write_setting($data['value']);
4030 if (!$error) {
4031 $value = empty($data['adv']) ? 0 : 1;
4032 $this->config_write($this->name.'_adv', $value);
4034 return $error;
4038 * Returns an XHTML checkbox field and with extra advanced cehckbox
4040 * @param string $data If $data matches yes then checkbox is checked
4041 * @param string $query
4042 * @return string XHTML field
4044 public function output_html($data, $query='') {
4045 $defaults = $this->get_defaultsetting();
4046 $defaultinfo = array();
4047 if (!is_null($defaults)) {
4048 if ((string)$defaults['value'] === $this->yes) {
4049 $defaultinfo[] = get_string('checkboxyes', 'admin');
4050 } else {
4051 $defaultinfo[] = get_string('checkboxno', 'admin');
4053 if (!empty($defaults['adv'])) {
4054 $defaultinfo[] = get_string('advanced');
4057 $defaultinfo = implode(', ', $defaultinfo);
4059 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4060 $checked = 'checked="checked"';
4061 } else {
4062 $checked = '';
4064 if (!empty($data['adv'])) {
4065 $advanced = 'checked="checked"';
4066 } else {
4067 $advanced = '';
4070 $fullname = $this->get_full_name();
4071 $novalue = s($this->no);
4072 $yesvalue = s($this->yes);
4073 $id = $this->get_id();
4074 $stradvanced = get_string('advanced');
4075 $return = <<<EOT
4076 <div class="form-checkbox defaultsnext" >
4077 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4078 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4079 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4080 <label for="{$id}_adv">$stradvanced</label>
4081 </div>
4082 EOT;
4083 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4084 true, '', $defaultinfo, $query);
4090 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4092 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4094 * @copyright 2010 Sam Hemelryk
4095 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4097 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4099 * Constructor
4100 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4101 * @param string $visiblename localised
4102 * @param string $description long localised info
4103 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4104 * @param string $yes value used when checked
4105 * @param string $no value used when not checked
4107 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4108 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4112 * Loads the current setting and returns array
4114 * @return array Returns array value=>xx, adv=>xx
4116 public function get_setting() {
4117 $value = parent::get_setting();
4118 $locked = $this->config_read($this->name.'_locked');
4119 if (is_null($value) or is_null($locked)) {
4120 return NULL;
4122 return array('value' => $value, 'locked' => $locked);
4126 * Sets the value for the setting
4128 * Sets the value for the setting to either the yes or no values
4129 * of the object by comparing $data to yes
4131 * @param mixed $data Gets converted to str for comparison against yes value
4132 * @return string empty string or error
4134 public function write_setting($data) {
4135 $error = parent::write_setting($data['value']);
4136 if (!$error) {
4137 $value = empty($data['locked']) ? 0 : 1;
4138 $this->config_write($this->name.'_locked', $value);
4140 return $error;
4144 * Returns an XHTML checkbox field and with extra locked checkbox
4146 * @param string $data If $data matches yes then checkbox is checked
4147 * @param string $query
4148 * @return string XHTML field
4150 public function output_html($data, $query='') {
4151 $defaults = $this->get_defaultsetting();
4152 $defaultinfo = array();
4153 if (!is_null($defaults)) {
4154 if ((string)$defaults['value'] === $this->yes) {
4155 $defaultinfo[] = get_string('checkboxyes', 'admin');
4156 } else {
4157 $defaultinfo[] = get_string('checkboxno', 'admin');
4159 if (!empty($defaults['locked'])) {
4160 $defaultinfo[] = get_string('locked', 'admin');
4163 $defaultinfo = implode(', ', $defaultinfo);
4165 $fullname = $this->get_full_name();
4166 $novalue = s($this->no);
4167 $yesvalue = s($this->yes);
4168 $id = $this->get_id();
4170 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4171 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4172 $checkboxparams['checked'] = 'checked';
4175 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4176 if (!empty($data['locked'])) { // convert to strings before comparison
4177 $lockcheckboxparams['checked'] = 'checked';
4180 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4181 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4182 $return .= html_writer::empty_tag('input', $checkboxparams);
4183 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4184 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4185 $return .= html_writer::end_tag('div');
4186 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4192 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4194 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4196 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4198 * Calls parent::__construct with specific arguments
4200 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4201 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4205 * Loads the current setting and returns array
4207 * @return array Returns array value=>xx, adv=>xx
4209 public function get_setting() {
4210 $value = parent::get_setting();
4211 $adv = $this->config_read($this->name.'_adv');
4212 if (is_null($value) or is_null($adv)) {
4213 return NULL;
4215 return array('value' => $value, 'adv' => $adv);
4219 * Saves the new settings passed in $data
4221 * @todo Add vartype handling to ensure $data is an array
4222 * @param array $data
4223 * @return mixed string or Array
4225 public function write_setting($data) {
4226 $error = parent::write_setting($data['value']);
4227 if (!$error) {
4228 $value = empty($data['adv']) ? 0 : 1;
4229 $this->config_write($this->name.'_adv', $value);
4231 return $error;
4235 * Return XHTML for the control
4237 * @param array $data Default data array
4238 * @param string $query
4239 * @return string XHTML to display control
4241 public function output_html($data, $query='') {
4242 $default = $this->get_defaultsetting();
4243 $current = $this->get_setting();
4245 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4246 $current['value'], $default['value'], '[value]');
4247 if (!$selecthtml) {
4248 return '';
4251 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4252 $defaultinfo = array();
4253 if (isset($this->choices[$default['value']])) {
4254 $defaultinfo[] = $this->choices[$default['value']];
4256 if (!empty($default['adv'])) {
4257 $defaultinfo[] = get_string('advanced');
4259 $defaultinfo = implode(', ', $defaultinfo);
4260 } else {
4261 $defaultinfo = '';
4264 $adv = !empty($data['adv']);
4265 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4266 ' <input type="checkbox" class="form-checkbox" id="' .
4267 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4268 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4269 ' <label for="' . $this->get_id() . '_adv">' .
4270 get_string('advanced') . '</label></div>';
4272 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4278 * Graded roles in gradebook
4280 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4282 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4284 * Calls parent::__construct with specific arguments
4286 public function __construct() {
4287 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4288 get_string('configgradebookroles', 'admin'),
4289 array('student'));
4296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4298 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4300 * Saves the new settings passed in $data
4302 * @param string $data
4303 * @return mixed string or Array
4305 public function write_setting($data) {
4306 global $CFG, $DB;
4308 $oldvalue = $this->config_read($this->name);
4309 $return = parent::write_setting($data);
4310 $newvalue = $this->config_read($this->name);
4312 if ($oldvalue !== $newvalue) {
4313 // force full regrading
4314 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4317 return $return;
4323 * Which roles to show on course description page
4325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4327 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4329 * Calls parent::__construct with specific arguments
4331 public function __construct() {
4332 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4333 get_string('coursecontact_desc', 'admin'),
4334 array('editingteacher'));
4341 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4343 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4345 * Calls parent::__construct with specific arguments
4347 function admin_setting_special_gradelimiting() {
4348 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4349 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4353 * Force site regrading
4355 function regrade_all() {
4356 global $CFG;
4357 require_once("$CFG->libdir/gradelib.php");
4358 grade_force_site_regrading();
4362 * Saves the new settings
4364 * @param mixed $data
4365 * @return string empty string or error message
4367 function write_setting($data) {
4368 $previous = $this->get_setting();
4370 if ($previous === null) {
4371 if ($data) {
4372 $this->regrade_all();
4374 } else {
4375 if ($data != $previous) {
4376 $this->regrade_all();
4379 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4386 * Primary grade export plugin - has state tracking.
4388 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4390 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4392 * Calls parent::__construct with specific arguments
4394 public function __construct() {
4395 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4396 get_string('configgradeexport', 'admin'), array(), NULL);
4400 * Load the available choices for the multicheckbox
4402 * @return bool always returns true
4404 public function load_choices() {
4405 if (is_array($this->choices)) {
4406 return true;
4408 $this->choices = array();
4410 if ($plugins = get_plugin_list('gradeexport')) {
4411 foreach($plugins as $plugin => $unused) {
4412 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4415 return true;
4421 * Grade category settings
4423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4425 class admin_setting_gradecat_combo extends admin_setting {
4426 /** @var array Array of choices */
4427 public $choices;
4430 * Sets choices and calls parent::__construct with passed arguments
4431 * @param string $name
4432 * @param string $visiblename
4433 * @param string $description
4434 * @param mixed $defaultsetting string or array depending on implementation
4435 * @param array $choices An array of choices for the control
4437 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4438 $this->choices = $choices;
4439 parent::__construct($name, $visiblename, $description, $defaultsetting);
4443 * Return the current setting(s) array
4445 * @return array Array of value=>xx, forced=>xx, adv=>xx
4447 public function get_setting() {
4448 global $CFG;
4450 $value = $this->config_read($this->name);
4451 $flag = $this->config_read($this->name.'_flag');
4453 if (is_null($value) or is_null($flag)) {
4454 return NULL;
4457 $flag = (int)$flag;
4458 $forced = (boolean)(1 & $flag); // first bit
4459 $adv = (boolean)(2 & $flag); // second bit
4461 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4465 * Save the new settings passed in $data
4467 * @todo Add vartype handling to ensure $data is array
4468 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4469 * @return string empty or error message
4471 public function write_setting($data) {
4472 global $CFG;
4474 $value = $data['value'];
4475 $forced = empty($data['forced']) ? 0 : 1;
4476 $adv = empty($data['adv']) ? 0 : 2;
4477 $flag = ($forced | $adv); //bitwise or
4479 if (!in_array($value, array_keys($this->choices))) {
4480 return 'Error setting ';
4483 $oldvalue = $this->config_read($this->name);
4484 $oldflag = (int)$this->config_read($this->name.'_flag');
4485 $oldforced = (1 & $oldflag); // first bit
4487 $result1 = $this->config_write($this->name, $value);
4488 $result2 = $this->config_write($this->name.'_flag', $flag);
4490 // force regrade if needed
4491 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4492 require_once($CFG->libdir.'/gradelib.php');
4493 grade_category::updated_forced_settings();
4496 if ($result1 and $result2) {
4497 return '';
4498 } else {
4499 return get_string('errorsetting', 'admin');
4504 * Return XHTML to display the field and wrapping div
4506 * @todo Add vartype handling to ensure $data is array
4507 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4508 * @param string $query
4509 * @return string XHTML to display control
4511 public function output_html($data, $query='') {
4512 $value = $data['value'];
4513 $forced = !empty($data['forced']);
4514 $adv = !empty($data['adv']);
4516 $default = $this->get_defaultsetting();
4517 if (!is_null($default)) {
4518 $defaultinfo = array();
4519 if (isset($this->choices[$default['value']])) {
4520 $defaultinfo[] = $this->choices[$default['value']];
4522 if (!empty($default['forced'])) {
4523 $defaultinfo[] = get_string('force');
4525 if (!empty($default['adv'])) {
4526 $defaultinfo[] = get_string('advanced');
4528 $defaultinfo = implode(', ', $defaultinfo);
4530 } else {
4531 $defaultinfo = NULL;
4535 $return = '<div class="form-group">';
4536 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4537 foreach ($this->choices as $key => $val) {
4538 // the string cast is needed because key may be integer - 0 is equal to most strings!
4539 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4541 $return .= '</select>';
4542 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4543 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4544 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4545 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4546 $return .= '</div>';
4548 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4554 * Selection of grade report in user profiles
4556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4558 class admin_setting_grade_profilereport extends admin_setting_configselect {
4560 * Calls parent::__construct with specific arguments
4562 public function __construct() {
4563 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4567 * Loads an array of choices for the configselect control
4569 * @return bool always return true
4571 public function load_choices() {
4572 if (is_array($this->choices)) {
4573 return true;
4575 $this->choices = array();
4577 global $CFG;
4578 require_once($CFG->libdir.'/gradelib.php');
4580 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4581 if (file_exists($plugindir.'/lib.php')) {
4582 require_once($plugindir.'/lib.php');
4583 $functionname = 'grade_report_'.$plugin.'_profilereport';
4584 if (function_exists($functionname)) {
4585 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4589 return true;
4595 * Special class for register auth selection
4597 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4599 class admin_setting_special_registerauth extends admin_setting_configselect {
4601 * Calls parent::__construct with specific arguments
4603 public function __construct() {
4604 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4608 * Returns the default option
4610 * @return string empty or default option
4612 public function get_defaultsetting() {
4613 $this->load_choices();
4614 $defaultsetting = parent::get_defaultsetting();
4615 if (array_key_exists($defaultsetting, $this->choices)) {
4616 return $defaultsetting;
4617 } else {
4618 return '';
4623 * Loads the possible choices for the array
4625 * @return bool always returns true
4627 public function load_choices() {
4628 global $CFG;
4630 if (is_array($this->choices)) {
4631 return true;
4633 $this->choices = array();
4634 $this->choices[''] = get_string('disable');
4636 $authsenabled = get_enabled_auth_plugins(true);
4638 foreach ($authsenabled as $auth) {
4639 $authplugin = get_auth_plugin($auth);
4640 if (!$authplugin->can_signup()) {
4641 continue;
4643 // Get the auth title (from core or own auth lang files)
4644 $authtitle = $authplugin->get_title();
4645 $this->choices[$auth] = $authtitle;
4647 return true;
4653 * General plugins manager
4655 class admin_page_pluginsoverview extends admin_externalpage {
4658 * Sets basic information about the external page
4660 public function __construct() {
4661 global $CFG;
4662 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4663 "$CFG->wwwroot/$CFG->admin/plugins.php");
4668 * Module manage page
4670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4672 class admin_page_managemods extends admin_externalpage {
4674 * Calls parent::__construct with specific arguments
4676 public function __construct() {
4677 global $CFG;
4678 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4682 * Try to find the specified module
4684 * @param string $query The module to search for
4685 * @return array
4687 public function search($query) {
4688 global $CFG, $DB;
4689 if ($result = parent::search($query)) {
4690 return $result;
4693 $found = false;
4694 if ($modules = $DB->get_records('modules')) {
4695 $textlib = textlib_get_instance();
4696 foreach ($modules as $module) {
4697 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4698 continue;
4700 if (strpos($module->name, $query) !== false) {
4701 $found = true;
4702 break;
4704 $strmodulename = get_string('modulename', $module->name);
4705 if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
4706 $found = true;
4707 break;
4711 if ($found) {
4712 $result = new stdClass();
4713 $result->page = $this;
4714 $result->settings = array();
4715 return array($this->name => $result);
4716 } else {
4717 return array();
4724 * Special class for enrol plugins management.
4726 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4729 class admin_setting_manageenrols extends admin_setting {
4731 * Calls parent::__construct with specific arguments
4733 public function __construct() {
4734 $this->nosave = true;
4735 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4739 * Always returns true, does nothing
4741 * @return true
4743 public function get_setting() {
4744 return true;
4748 * Always returns true, does nothing
4750 * @return true
4752 public function get_defaultsetting() {
4753 return true;
4757 * Always returns '', does not write anything
4759 * @return string Always returns ''
4761 public function write_setting($data) {
4762 // do not write any setting
4763 return '';
4767 * Checks if $query is one of the available enrol plugins
4769 * @param string $query The string to search for
4770 * @return bool Returns true if found, false if not
4772 public function is_related($query) {
4773 if (parent::is_related($query)) {
4774 return true;
4777 $textlib = textlib_get_instance();
4778 $query = $textlib->strtolower($query);
4779 $enrols = enrol_get_plugins(false);
4780 foreach ($enrols as $name=>$enrol) {
4781 $localised = get_string('pluginname', 'enrol_'.$name);
4782 if (strpos($textlib->strtolower($name), $query) !== false) {
4783 return true;
4785 if (strpos($textlib->strtolower($localised), $query) !== false) {
4786 return true;
4789 return false;
4793 * Builds the XHTML to display the control
4795 * @param string $data Unused
4796 * @param string $query
4797 * @return string
4799 public function output_html($data, $query='') {
4800 global $CFG, $OUTPUT, $DB;
4802 // display strings
4803 $strup = get_string('up');
4804 $strdown = get_string('down');
4805 $strsettings = get_string('settings');
4806 $strenable = get_string('enable');
4807 $strdisable = get_string('disable');
4808 $struninstall = get_string('uninstallplugin', 'admin');
4809 $strusage = get_string('enrolusage', 'enrol');
4811 $enrols_available = enrol_get_plugins(false);
4812 $active_enrols = enrol_get_plugins(true);
4814 $allenrols = array();
4815 foreach ($active_enrols as $key=>$enrol) {
4816 $allenrols[$key] = true;
4818 foreach ($enrols_available as $key=>$enrol) {
4819 $allenrols[$key] = true;
4821 // now find all borked plugins and at least allow then to uninstall
4822 $borked = array();
4823 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
4824 foreach ($condidates as $candidate) {
4825 if (empty($allenrols[$candidate])) {
4826 $allenrols[$candidate] = true;
4830 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
4831 $return .= $OUTPUT->box_start('generalbox enrolsui');
4833 $table = new html_table();
4834 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
4835 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
4836 $table->width = '90%';
4837 $table->data = array();
4839 // iterate through enrol plugins and add to the display table
4840 $updowncount = 1;
4841 $enrolcount = count($active_enrols);
4842 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
4843 $printed = array();
4844 foreach($allenrols as $enrol => $unused) {
4845 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
4846 $name = get_string('pluginname', 'enrol_'.$enrol);
4847 } else {
4848 $name = $enrol;
4850 //usage
4851 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
4852 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
4853 $usage = "$ci / $cp";
4855 // hide/show link
4856 if (isset($active_enrols[$enrol])) {
4857 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
4858 $hideshow = "<a href=\"$aurl\">";
4859 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
4860 $enabled = true;
4861 $displayname = "<span>$name</span>";
4862 } else if (isset($enrols_available[$enrol])) {
4863 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
4864 $hideshow = "<a href=\"$aurl\">";
4865 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
4866 $enabled = false;
4867 $displayname = "<span class=\"dimmed_text\">$name</span>";
4868 } else {
4869 $hideshow = '';
4870 $enabled = false;
4871 $displayname = '<span class="notifyproblem">'.$name.'</span>';
4874 // up/down link (only if enrol is enabled)
4875 $updown = '';
4876 if ($enabled) {
4877 if ($updowncount > 1) {
4878 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
4879 $updown .= "<a href=\"$aurl\">";
4880 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
4881 } else {
4882 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
4884 if ($updowncount < $enrolcount) {
4885 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
4886 $updown .= "<a href=\"$aurl\">";
4887 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
4888 } else {
4889 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
4891 ++$updowncount;
4894 // settings link
4895 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
4896 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
4897 $settings = "<a href=\"$surl\">$strsettings</a>";
4898 } else {
4899 $settings = '';
4902 // uninstall
4903 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
4904 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
4906 // add a row to the table
4907 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
4909 $printed[$enrol] = true;
4912 $return .= html_writer::table($table);
4913 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
4914 $return .= $OUTPUT->box_end();
4915 return highlight($query, $return);
4921 * Blocks manage page
4923 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4925 class admin_page_manageblocks extends admin_externalpage {
4927 * Calls parent::__construct with specific arguments
4929 public function __construct() {
4930 global $CFG;
4931 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
4935 * Search for a specific block
4937 * @param string $query The string to search for
4938 * @return array
4940 public function search($query) {
4941 global $CFG, $DB;
4942 if ($result = parent::search($query)) {
4943 return $result;
4946 $found = false;
4947 if ($blocks = $DB->get_records('block')) {
4948 $textlib = textlib_get_instance();
4949 foreach ($blocks as $block) {
4950 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
4951 continue;
4953 if (strpos($block->name, $query) !== false) {
4954 $found = true;
4955 break;
4957 $strblockname = get_string('pluginname', 'block_'.$block->name);
4958 if (strpos($textlib->strtolower($strblockname), $query) !== false) {
4959 $found = true;
4960 break;
4964 if ($found) {
4965 $result = new stdClass();
4966 $result->page = $this;
4967 $result->settings = array();
4968 return array($this->name => $result);
4969 } else {
4970 return array();
4976 * Message outputs configuration
4978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4980 class admin_page_managemessageoutputs extends admin_externalpage {
4982 * Calls parent::__construct with specific arguments
4984 public function __construct() {
4985 global $CFG;
4986 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
4990 * Search for a specific message processor
4992 * @param string $query The string to search for
4993 * @return array
4995 public function search($query) {
4996 global $CFG, $DB;
4997 if ($result = parent::search($query)) {
4998 return $result;
5001 $found = false;
5002 if ($processors = get_message_processors()) {
5003 $textlib = textlib_get_instance();
5004 foreach ($processors as $processor) {
5005 if (!$processor->available) {
5006 continue;
5008 if (strpos($processor->name, $query) !== false) {
5009 $found = true;
5010 break;
5012 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5013 if (strpos($textlib->strtolower($strprocessorname), $query) !== false) {
5014 $found = true;
5015 break;
5019 if ($found) {
5020 $result = new stdClass();
5021 $result->page = $this;
5022 $result->settings = array();
5023 return array($this->name => $result);
5024 } else {
5025 return array();
5031 * Default message outputs configuration
5033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5035 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5037 * Calls parent::__construct with specific arguments
5039 public function __construct() {
5040 global $CFG;
5041 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5047 * Manage question behaviours page
5049 * @copyright 2011 The Open University
5050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5052 class admin_page_manageqbehaviours extends admin_externalpage {
5054 * Constructor
5056 public function __construct() {
5057 global $CFG;
5058 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5059 new moodle_url('/admin/qbehaviours.php'));
5063 * Search question behaviours for the specified string
5065 * @param string $query The string to search for in question behaviours
5066 * @return array
5068 public function search($query) {
5069 global $CFG;
5070 if ($result = parent::search($query)) {
5071 return $result;
5074 $found = false;
5075 $textlib = textlib_get_instance();
5076 require_once($CFG->dirroot . '/question/engine/lib.php');
5077 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5078 if (strpos($textlib->strtolower(question_engine::get_behaviour_name($behaviour)),
5079 $query) !== false) {
5080 $found = true;
5081 break;
5084 if ($found) {
5085 $result = new stdClass();
5086 $result->page = $this;
5087 $result->settings = array();
5088 return array($this->name => $result);
5089 } else {
5090 return array();
5097 * Question type manage page
5099 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5101 class admin_page_manageqtypes extends admin_externalpage {
5103 * Calls parent::__construct with specific arguments
5105 public function __construct() {
5106 global $CFG;
5107 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5111 * Search question types for the specified string
5113 * @param string $query The string to search for in question types
5114 * @return array
5116 public function search($query) {
5117 global $CFG;
5118 if ($result = parent::search($query)) {
5119 return $result;
5122 $found = false;
5123 $textlib = textlib_get_instance();
5124 require_once($CFG->dirroot . '/question/engine/bank.php');
5125 foreach (question_bank::get_all_qtypes() as $qtype) {
5126 if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
5127 $found = true;
5128 break;
5131 if ($found) {
5132 $result = new stdClass();
5133 $result->page = $this;
5134 $result->settings = array();
5135 return array($this->name => $result);
5136 } else {
5137 return array();
5143 class admin_page_manageportfolios extends admin_externalpage {
5145 * Calls parent::__construct with specific arguments
5147 public function __construct() {
5148 global $CFG;
5149 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5150 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5154 * Searches page for the specified string.
5155 * @param string $query The string to search for
5156 * @return bool True if it is found on this page
5158 public function search($query) {
5159 global $CFG;
5160 if ($result = parent::search($query)) {
5161 return $result;
5164 $found = false;
5165 $textlib = textlib_get_instance();
5166 $portfolios = get_plugin_list('portfolio');
5167 foreach ($portfolios as $p => $dir) {
5168 if (strpos($p, $query) !== false) {
5169 $found = true;
5170 break;
5173 if (!$found) {
5174 foreach (portfolio_instances(false, false) as $instance) {
5175 $title = $instance->get('name');
5176 if (strpos($textlib->strtolower($title), $query) !== false) {
5177 $found = true;
5178 break;
5183 if ($found) {
5184 $result = new stdClass();
5185 $result->page = $this;
5186 $result->settings = array();
5187 return array($this->name => $result);
5188 } else {
5189 return array();
5195 class admin_page_managerepositories extends admin_externalpage {
5197 * Calls parent::__construct with specific arguments
5199 public function __construct() {
5200 global $CFG;
5201 parent::__construct('managerepositories', get_string('manage',
5202 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5206 * Searches page for the specified string.
5207 * @param string $query The string to search for
5208 * @return bool True if it is found on this page
5210 public function search($query) {
5211 global $CFG;
5212 if ($result = parent::search($query)) {
5213 return $result;
5216 $found = false;
5217 $textlib = textlib_get_instance();
5218 $repositories= get_plugin_list('repository');
5219 foreach ($repositories as $p => $dir) {
5220 if (strpos($p, $query) !== false) {
5221 $found = true;
5222 break;
5225 if (!$found) {
5226 foreach (repository::get_types() as $instance) {
5227 $title = $instance->get_typename();
5228 if (strpos($textlib->strtolower($title), $query) !== false) {
5229 $found = true;
5230 break;
5235 if ($found) {
5236 $result = new stdClass();
5237 $result->page = $this;
5238 $result->settings = array();
5239 return array($this->name => $result);
5240 } else {
5241 return array();
5248 * Special class for authentication administration.
5250 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5252 class admin_setting_manageauths extends admin_setting {
5254 * Calls parent::__construct with specific arguments
5256 public function __construct() {
5257 $this->nosave = true;
5258 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5262 * Always returns true
5264 * @return true
5266 public function get_setting() {
5267 return true;
5271 * Always returns true
5273 * @return true
5275 public function get_defaultsetting() {
5276 return true;
5280 * Always returns '' and doesn't write anything
5282 * @return string Always returns ''
5284 public function write_setting($data) {
5285 // do not write any setting
5286 return '';
5290 * Search to find if Query is related to auth plugin
5292 * @param string $query The string to search for
5293 * @return bool true for related false for not
5295 public function is_related($query) {
5296 if (parent::is_related($query)) {
5297 return true;
5300 $textlib = textlib_get_instance();
5301 $authsavailable = get_plugin_list('auth');
5302 foreach ($authsavailable as $auth => $dir) {
5303 if (strpos($auth, $query) !== false) {
5304 return true;
5306 $authplugin = get_auth_plugin($auth);
5307 $authtitle = $authplugin->get_title();
5308 if (strpos($textlib->strtolower($authtitle), $query) !== false) {
5309 return true;
5312 return false;
5316 * Return XHTML to display control
5318 * @param mixed $data Unused
5319 * @param string $query
5320 * @return string highlight
5322 public function output_html($data, $query='') {
5323 global $CFG, $OUTPUT;
5326 // display strings
5327 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5328 'settings', 'edit', 'name', 'enable', 'disable',
5329 'up', 'down', 'none'));
5330 $txt->updown = "$txt->up/$txt->down";
5332 $authsavailable = get_plugin_list('auth');
5333 get_enabled_auth_plugins(true); // fix the list of enabled auths
5334 if (empty($CFG->auth)) {
5335 $authsenabled = array();
5336 } else {
5337 $authsenabled = explode(',', $CFG->auth);
5340 // construct the display array, with enabled auth plugins at the top, in order
5341 $displayauths = array();
5342 $registrationauths = array();
5343 $registrationauths[''] = $txt->disable;
5344 foreach ($authsenabled as $auth) {
5345 $authplugin = get_auth_plugin($auth);
5346 /// Get the auth title (from core or own auth lang files)
5347 $authtitle = $authplugin->get_title();
5348 /// Apply titles
5349 $displayauths[$auth] = $authtitle;
5350 if ($authplugin->can_signup()) {
5351 $registrationauths[$auth] = $authtitle;
5355 foreach ($authsavailable as $auth => $dir) {
5356 if (array_key_exists($auth, $displayauths)) {
5357 continue; //already in the list
5359 $authplugin = get_auth_plugin($auth);
5360 /// Get the auth title (from core or own auth lang files)
5361 $authtitle = $authplugin->get_title();
5362 /// Apply titles
5363 $displayauths[$auth] = $authtitle;
5364 if ($authplugin->can_signup()) {
5365 $registrationauths[$auth] = $authtitle;
5369 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5370 $return .= $OUTPUT->box_start('generalbox authsui');
5372 $table = new html_table();
5373 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5374 $table->align = array('left', 'center', 'center', 'center');
5375 $table->data = array();
5376 $table->attributes['class'] = 'manageauthtable generaltable';
5378 //add always enabled plugins first
5379 $displayname = "<span>".$displayauths['manual']."</span>";
5380 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5381 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5382 $table->data[] = array($displayname, '', '', $settings);
5383 $displayname = "<span>".$displayauths['nologin']."</span>";
5384 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5385 $table->data[] = array($displayname, '', '', $settings);
5388 // iterate through auth plugins and add to the display table
5389 $updowncount = 1;
5390 $authcount = count($authsenabled);
5391 $url = "auth.php?sesskey=" . sesskey();
5392 foreach ($displayauths as $auth => $name) {
5393 if ($auth == 'manual' or $auth == 'nologin') {
5394 continue;
5396 // hide/show link
5397 if (in_array($auth, $authsenabled)) {
5398 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5399 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5400 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5401 $enabled = true;
5402 $displayname = "<span>$name</span>";
5404 else {
5405 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5406 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5407 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5408 $enabled = false;
5409 $displayname = "<span class=\"dimmed_text\">$name</span>";
5412 // up/down link (only if auth is enabled)
5413 $updown = '';
5414 if ($enabled) {
5415 if ($updowncount > 1) {
5416 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5417 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5419 else {
5420 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5422 if ($updowncount < $authcount) {
5423 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5424 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5426 else {
5427 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5429 ++ $updowncount;
5432 // settings link
5433 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5434 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5435 } else {
5436 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5439 // add a row to the table
5440 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5442 $return .= html_writer::table($table);
5443 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5444 $return .= $OUTPUT->box_end();
5445 return highlight($query, $return);
5451 * Special class for authentication administration.
5453 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5455 class admin_setting_manageeditors extends admin_setting {
5457 * Calls parent::__construct with specific arguments
5459 public function __construct() {
5460 $this->nosave = true;
5461 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5465 * Always returns true, does nothing
5467 * @return true
5469 public function get_setting() {
5470 return true;
5474 * Always returns true, does nothing
5476 * @return true
5478 public function get_defaultsetting() {
5479 return true;
5483 * Always returns '', does not write anything
5485 * @return string Always returns ''
5487 public function write_setting($data) {
5488 // do not write any setting
5489 return '';
5493 * Checks if $query is one of the available editors
5495 * @param string $query The string to search for
5496 * @return bool Returns true if found, false if not
5498 public function is_related($query) {
5499 if (parent::is_related($query)) {
5500 return true;
5503 $textlib = textlib_get_instance();
5504 $editors_available = editors_get_available();
5505 foreach ($editors_available as $editor=>$editorstr) {
5506 if (strpos($editor, $query) !== false) {
5507 return true;
5509 if (strpos($textlib->strtolower($editorstr), $query) !== false) {
5510 return true;
5513 return false;
5517 * Builds the XHTML to display the control
5519 * @param string $data Unused
5520 * @param string $query
5521 * @return string
5523 public function output_html($data, $query='') {
5524 global $CFG, $OUTPUT;
5526 // display strings
5527 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5528 'up', 'down', 'none'));
5529 $txt->updown = "$txt->up/$txt->down";
5531 $editors_available = editors_get_available();
5532 $active_editors = explode(',', $CFG->texteditors);
5534 $active_editors = array_reverse($active_editors);
5535 foreach ($active_editors as $key=>$editor) {
5536 if (empty($editors_available[$editor])) {
5537 unset($active_editors[$key]);
5538 } else {
5539 $name = $editors_available[$editor];
5540 unset($editors_available[$editor]);
5541 $editors_available[$editor] = $name;
5544 if (empty($active_editors)) {
5545 //$active_editors = array('textarea');
5547 $editors_available = array_reverse($editors_available, true);
5548 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5549 $return .= $OUTPUT->box_start('generalbox editorsui');
5551 $table = new html_table();
5552 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5553 $table->align = array('left', 'center', 'center', 'center');
5554 $table->width = '90%';
5555 $table->data = array();
5557 // iterate through auth plugins and add to the display table
5558 $updowncount = 1;
5559 $editorcount = count($active_editors);
5560 $url = "editors.php?sesskey=" . sesskey();
5561 foreach ($editors_available as $editor => $name) {
5562 // hide/show link
5563 if (in_array($editor, $active_editors)) {
5564 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5565 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5566 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5567 $enabled = true;
5568 $displayname = "<span>$name</span>";
5570 else {
5571 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5572 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5573 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5574 $enabled = false;
5575 $displayname = "<span class=\"dimmed_text\">$name</span>";
5578 // up/down link (only if auth is enabled)
5579 $updown = '';
5580 if ($enabled) {
5581 if ($updowncount > 1) {
5582 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5583 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5585 else {
5586 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5588 if ($updowncount < $editorcount) {
5589 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5590 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5592 else {
5593 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5595 ++ $updowncount;
5598 // settings link
5599 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5600 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5601 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5602 } else {
5603 $settings = '';
5606 // add a row to the table
5607 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5609 $return .= html_writer::table($table);
5610 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5611 $return .= $OUTPUT->box_end();
5612 return highlight($query, $return);
5618 * Special class for license administration.
5620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5622 class admin_setting_managelicenses extends admin_setting {
5624 * Calls parent::__construct with specific arguments
5626 public function __construct() {
5627 $this->nosave = true;
5628 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5632 * Always returns true, does nothing
5634 * @return true
5636 public function get_setting() {
5637 return true;
5641 * Always returns true, does nothing
5643 * @return true
5645 public function get_defaultsetting() {
5646 return true;
5650 * Always returns '', does not write anything
5652 * @return string Always returns ''
5654 public function write_setting($data) {
5655 // do not write any setting
5656 return '';
5660 * Builds the XHTML to display the control
5662 * @param string $data Unused
5663 * @param string $query
5664 * @return string
5666 public function output_html($data, $query='') {
5667 global $CFG, $OUTPUT;
5668 require_once($CFG->libdir . '/licenselib.php');
5669 $url = "licenses.php?sesskey=" . sesskey();
5671 // display strings
5672 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5673 $licenses = license_manager::get_licenses();
5675 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5677 $return .= $OUTPUT->box_start('generalbox editorsui');
5679 $table = new html_table();
5680 $table->head = array($txt->name, $txt->enable);
5681 $table->align = array('left', 'center');
5682 $table->width = '100%';
5683 $table->data = array();
5685 foreach ($licenses as $value) {
5686 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5688 if ($value->enabled == 1) {
5689 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5690 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5691 } else {
5692 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5693 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5696 if ($value->shortname == $CFG->sitedefaultlicense) {
5697 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5698 $hideshow = '';
5701 $enabled = true;
5703 $table->data[] =array($displayname, $hideshow);
5705 $return .= html_writer::table($table);
5706 $return .= $OUTPUT->box_end();
5707 return highlight($query, $return);
5713 * Special class for filter administration.
5715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5717 class admin_page_managefilters extends admin_externalpage {
5719 * Calls parent::__construct with specific arguments
5721 public function __construct() {
5722 global $CFG;
5723 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5727 * Searches all installed filters for specified filter
5729 * @param string $query The filter(string) to search for
5730 * @param string $query
5732 public function search($query) {
5733 global $CFG;
5734 if ($result = parent::search($query)) {
5735 return $result;
5738 $found = false;
5739 $filternames = filter_get_all_installed();
5740 $textlib = textlib_get_instance();
5741 foreach ($filternames as $path => $strfiltername) {
5742 if (strpos($textlib->strtolower($strfiltername), $query) !== false) {
5743 $found = true;
5744 break;
5746 list($type, $filter) = explode('/', $path);
5747 if (strpos($filter, $query) !== false) {
5748 $found = true;
5749 break;
5753 if ($found) {
5754 $result = new stdClass;
5755 $result->page = $this;
5756 $result->settings = array();
5757 return array($this->name => $result);
5758 } else {
5759 return array();
5766 * Initialise admin page - this function does require login and permission
5767 * checks specified in page definition.
5769 * This function must be called on each admin page before other code.
5771 * @global moodle_page $PAGE
5773 * @param string $section name of page
5774 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5775 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5776 * added to the turn blocks editing on/off form, so this page reloads correctly.
5777 * @param string $actualurl if the actual page being viewed is not the normal one for this
5778 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5779 * @param array $options Additional options that can be specified for page setup.
5780 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5782 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5783 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5785 $PAGE->set_context(null); // hack - set context to something, by default to system context
5787 $site = get_site();
5788 require_login();
5790 $adminroot = admin_get_root(false, false); // settings not required for external pages
5791 $extpage = $adminroot->locate($section, true);
5793 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5794 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5795 die;
5798 // this eliminates our need to authenticate on the actual pages
5799 if (!$extpage->check_access()) {
5800 print_error('accessdenied', 'admin');
5801 die;
5804 if (!empty($options['pagelayout'])) {
5805 // A specific page layout has been requested.
5806 $PAGE->set_pagelayout($options['pagelayout']);
5807 } else if ($section === 'upgradesettings') {
5808 $PAGE->set_pagelayout('maintenance');
5809 } else {
5810 $PAGE->set_pagelayout('admin');
5813 // $PAGE->set_extra_button($extrabutton); TODO
5815 if (!$actualurl) {
5816 $actualurl = $extpage->url;
5819 $PAGE->set_url($actualurl, $extraurlparams);
5820 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5821 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
5824 if (empty($SITE->fullname) || empty($SITE->shortname)) {
5825 // During initial install.
5826 $strinstallation = get_string('installation', 'install');
5827 $strsettings = get_string('settings');
5828 $PAGE->navbar->add($strsettings);
5829 $PAGE->set_title($strinstallation);
5830 $PAGE->set_heading($strinstallation);
5831 $PAGE->set_cacheable(false);
5832 return;
5835 // Locate the current item on the navigation and make it active when found.
5836 $path = $extpage->path;
5837 $node = $PAGE->settingsnav;
5838 while ($node && count($path) > 0) {
5839 $node = $node->get(array_pop($path));
5841 if ($node) {
5842 $node->make_active();
5845 // Normal case.
5846 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
5847 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
5848 $USER->editing = $adminediting;
5851 $visiblepathtosection = array_reverse($extpage->visiblepath);
5853 if ($PAGE->user_allowed_editing()) {
5854 if ($PAGE->user_is_editing()) {
5855 $caption = get_string('blockseditoff');
5856 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
5857 } else {
5858 $caption = get_string('blocksediton');
5859 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
5861 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
5864 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
5865 $PAGE->set_heading($SITE->fullname);
5867 // prevent caching in nav block
5868 $PAGE->navigation->clear_cache();
5872 * Returns the reference to admin tree root
5874 * @return object admin_root object
5876 function admin_get_root($reload=false, $requirefulltree=true) {
5877 global $CFG, $DB, $OUTPUT;
5879 static $ADMIN = NULL;
5881 if (is_null($ADMIN)) {
5882 // create the admin tree!
5883 $ADMIN = new admin_root($requirefulltree);
5886 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
5887 $ADMIN->purge_children($requirefulltree);
5890 if (!$ADMIN->loaded) {
5891 // we process this file first to create categories first and in correct order
5892 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
5894 // now we process all other files in admin/settings to build the admin tree
5895 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
5896 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
5897 continue;
5899 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
5900 // plugins are loaded last - they may insert pages anywhere
5901 continue;
5903 require($file);
5905 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
5907 $ADMIN->loaded = true;
5910 return $ADMIN;
5913 /// settings utility functions
5916 * This function applies default settings.
5918 * @param object $node, NULL means complete tree, null by default
5919 * @param bool $unconditional if true overrides all values with defaults, null buy default
5921 function admin_apply_default_settings($node=NULL, $unconditional=true) {
5922 global $CFG;
5924 if (is_null($node)) {
5925 $node = admin_get_root(true, true);
5928 if ($node instanceof admin_category) {
5929 $entries = array_keys($node->children);
5930 foreach ($entries as $entry) {
5931 admin_apply_default_settings($node->children[$entry], $unconditional);
5934 } else if ($node instanceof admin_settingpage) {
5935 foreach ($node->settings as $setting) {
5936 if (!$unconditional and !is_null($setting->get_setting())) {
5937 //do not override existing defaults
5938 continue;
5940 $defaultsetting = $setting->get_defaultsetting();
5941 if (is_null($defaultsetting)) {
5942 // no value yet - default maybe applied after admin user creation or in upgradesettings
5943 continue;
5945 $setting->write_setting($defaultsetting);
5951 * Store changed settings, this function updates the errors variable in $ADMIN
5953 * @param object $formdata from form
5954 * @return int number of changed settings
5956 function admin_write_settings($formdata) {
5957 global $CFG, $SITE, $DB;
5959 $olddbsessions = !empty($CFG->dbsessions);
5960 $formdata = (array)$formdata;
5962 $data = array();
5963 foreach ($formdata as $fullname=>$value) {
5964 if (strpos($fullname, 's_') !== 0) {
5965 continue; // not a config value
5967 $data[$fullname] = $value;
5970 $adminroot = admin_get_root();
5971 $settings = admin_find_write_settings($adminroot, $data);
5973 $count = 0;
5974 foreach ($settings as $fullname=>$setting) {
5975 $original = serialize($setting->get_setting()); // comparison must work for arrays too
5976 $error = $setting->write_setting($data[$fullname]);
5977 if ($error !== '') {
5978 $adminroot->errors[$fullname] = new stdClass();
5979 $adminroot->errors[$fullname]->data = $data[$fullname];
5980 $adminroot->errors[$fullname]->id = $setting->get_id();
5981 $adminroot->errors[$fullname]->error = $error;
5983 if ($original !== serialize($setting->get_setting())) {
5984 $count++;
5985 $callbackfunction = $setting->updatedcallback;
5986 if (function_exists($callbackfunction)) {
5987 $callbackfunction($fullname);
5992 if ($olddbsessions != !empty($CFG->dbsessions)) {
5993 require_logout();
5996 // Now update $SITE - just update the fields, in case other people have a
5997 // a reference to it (e.g. $PAGE, $COURSE).
5998 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
5999 foreach (get_object_vars($newsite) as $field => $value) {
6000 $SITE->$field = $value;
6003 // now reload all settings - some of them might depend on the changed
6004 admin_get_root(true);
6005 return $count;
6009 * Internal recursive function - finds all settings from submitted form
6011 * @param object $node Instance of admin_category, or admin_settingpage
6012 * @param array $data
6013 * @return array
6015 function admin_find_write_settings($node, $data) {
6016 $return = array();
6018 if (empty($data)) {
6019 return $return;
6022 if ($node instanceof admin_category) {
6023 $entries = array_keys($node->children);
6024 foreach ($entries as $entry) {
6025 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6028 } else if ($node instanceof admin_settingpage) {
6029 foreach ($node->settings as $setting) {
6030 $fullname = $setting->get_full_name();
6031 if (array_key_exists($fullname, $data)) {
6032 $return[$fullname] = $setting;
6038 return $return;
6042 * Internal function - prints the search results
6044 * @param string $query String to search for
6045 * @return string empty or XHTML
6047 function admin_search_settings_html($query) {
6048 global $CFG, $OUTPUT;
6050 $textlib = textlib_get_instance();
6051 if ($textlib->strlen($query) < 2) {
6052 return '';
6054 $query = $textlib->strtolower($query);
6056 $adminroot = admin_get_root();
6057 $findings = $adminroot->search($query);
6058 $return = '';
6059 $savebutton = false;
6061 foreach ($findings as $found) {
6062 $page = $found->page;
6063 $settings = $found->settings;
6064 if ($page->is_hidden()) {
6065 // hidden pages are not displayed in search results
6066 continue;
6068 if ($page instanceof admin_externalpage) {
6069 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6070 } else if ($page instanceof admin_settingpage) {
6071 $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');
6072 } else {
6073 continue;
6075 if (!empty($settings)) {
6076 $return .= '<fieldset class="adminsettings">'."\n";
6077 foreach ($settings as $setting) {
6078 if (empty($setting->nosave)) {
6079 $savebutton = true;
6081 $return .= '<div class="clearer"><!-- --></div>'."\n";
6082 $fullname = $setting->get_full_name();
6083 if (array_key_exists($fullname, $adminroot->errors)) {
6084 $data = $adminroot->errors[$fullname]->data;
6085 } else {
6086 $data = $setting->get_setting();
6087 // do not use defaults if settings not available - upgradesettings handles the defaults!
6089 $return .= $setting->output_html($data, $query);
6091 $return .= '</fieldset>';
6095 if ($savebutton) {
6096 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6099 return $return;
6103 * Internal function - returns arrays of html pages with uninitialised settings
6105 * @param object $node Instance of admin_category or admin_settingpage
6106 * @return array
6108 function admin_output_new_settings_by_page($node) {
6109 global $OUTPUT;
6110 $return = array();
6112 if ($node instanceof admin_category) {
6113 $entries = array_keys($node->children);
6114 foreach ($entries as $entry) {
6115 $return += admin_output_new_settings_by_page($node->children[$entry]);
6118 } else if ($node instanceof admin_settingpage) {
6119 $newsettings = array();
6120 foreach ($node->settings as $setting) {
6121 if (is_null($setting->get_setting())) {
6122 $newsettings[] = $setting;
6125 if (count($newsettings) > 0) {
6126 $adminroot = admin_get_root();
6127 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6128 $page .= '<fieldset class="adminsettings">'."\n";
6129 foreach ($newsettings as $setting) {
6130 $fullname = $setting->get_full_name();
6131 if (array_key_exists($fullname, $adminroot->errors)) {
6132 $data = $adminroot->errors[$fullname]->data;
6133 } else {
6134 $data = $setting->get_setting();
6135 if (is_null($data)) {
6136 $data = $setting->get_defaultsetting();
6139 $page .= '<div class="clearer"><!-- --></div>'."\n";
6140 $page .= $setting->output_html($data);
6142 $page .= '</fieldset>';
6143 $return[$node->name] = $page;
6147 return $return;
6151 * Format admin settings
6153 * @param object $setting
6154 * @param string $title label element
6155 * @param string $form form fragment, html code - not highlighted automatically
6156 * @param string $description
6157 * @param bool $label link label to id, true by default
6158 * @param string $warning warning text
6159 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6160 * @param string $query search query to be highlighted
6161 * @return string XHTML
6163 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6164 global $CFG;
6166 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6167 $fullname = $setting->get_full_name();
6169 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6170 if ($label) {
6171 $labelfor = 'for = "'.$setting->get_id().'"';
6172 } else {
6173 $labelfor = '';
6176 $override = '';
6177 if (empty($setting->plugin)) {
6178 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6179 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6181 } else {
6182 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6183 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6187 if ($warning !== '') {
6188 $warning = '<div class="form-warning">'.$warning.'</div>';
6191 if (is_null($defaultinfo)) {
6192 $defaultinfo = '';
6193 } else {
6194 if ($defaultinfo === '') {
6195 $defaultinfo = get_string('emptysettingvalue', 'admin');
6197 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6198 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6202 $str = '
6203 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6204 <div class="form-label">
6205 <label '.$labelfor.'>'.highlightfast($query, $title).'<span class="form-shortname">'.highlightfast($query, $name).'</span>
6206 '.$override.$warning.'
6207 </label>
6208 </div>
6209 <div class="form-setting">'.$form.$defaultinfo.'</div>
6210 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6211 </div>';
6213 $adminroot = admin_get_root();
6214 if (array_key_exists($fullname, $adminroot->errors)) {
6215 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6218 return $str;
6222 * Based on find_new_settings{@link ()} in upgradesettings.php
6223 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6225 * @param object $node Instance of admin_category, or admin_settingpage
6226 * @return boolean true if any settings haven't been initialised, false if they all have
6228 function any_new_admin_settings($node) {
6230 if ($node instanceof admin_category) {
6231 $entries = array_keys($node->children);
6232 foreach ($entries as $entry) {
6233 if (any_new_admin_settings($node->children[$entry])) {
6234 return true;
6238 } else if ($node instanceof admin_settingpage) {
6239 foreach ($node->settings as $setting) {
6240 if ($setting->get_setting() === NULL) {
6241 return true;
6246 return false;
6250 * Moved from admin/replace.php so that we can use this in cron
6252 * @param string $search string to look for
6253 * @param string $replace string to replace
6254 * @return bool success or fail
6256 function db_replace($search, $replace) {
6257 global $DB, $CFG, $OUTPUT;
6259 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6260 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6261 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6262 'block_instances', '');
6264 // Turn off time limits, sometimes upgrades can be slow.
6265 @set_time_limit(0);
6267 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6268 return false;
6270 foreach ($tables as $table) {
6272 if (in_array($table, $skiptables)) { // Don't process these
6273 continue;
6276 if ($columns = $DB->get_columns($table)) {
6277 $DB->set_debug(true);
6278 foreach ($columns as $column => $data) {
6279 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6280 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6281 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6284 $DB->set_debug(false);
6288 // delete modinfo caches
6289 rebuild_course_cache(0, true);
6291 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6292 $blocks = get_plugin_list('block');
6293 foreach ($blocks as $blockname=>$fullblock) {
6294 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6295 continue;
6298 if (!is_readable($fullblock.'/lib.php')) {
6299 continue;
6302 $function = 'block_'.$blockname.'_global_db_replace';
6303 include_once($fullblock.'/lib.php');
6304 if (!function_exists($function)) {
6305 continue;
6308 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6309 $function($search, $replace);
6310 echo $OUTPUT->notification("...finished", 'notifysuccess');
6313 return true;
6317 * Manage repository settings
6319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6321 class admin_setting_managerepository extends admin_setting {
6322 /** @var string */
6323 private $baseurl;
6326 * calls parent::__construct with specific arguments
6328 public function __construct() {
6329 global $CFG;
6330 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6331 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6335 * Always returns true, does nothing
6337 * @return true
6339 public function get_setting() {
6340 return true;
6344 * Always returns true does nothing
6346 * @return true
6348 public function get_defaultsetting() {
6349 return true;
6353 * Always returns s_managerepository
6355 * @return string Always return 's_managerepository'
6357 public function get_full_name() {
6358 return 's_managerepository';
6362 * Always returns '' doesn't do anything
6364 public function write_setting($data) {
6365 $url = $this->baseurl . '&amp;new=' . $data;
6366 return '';
6367 // TODO
6368 // Should not use redirect and exit here
6369 // Find a better way to do this.
6370 // redirect($url);
6371 // exit;
6375 * Searches repository plugins for one that matches $query
6377 * @param string $query The string to search for
6378 * @return bool true if found, false if not
6380 public function is_related($query) {
6381 if (parent::is_related($query)) {
6382 return true;
6385 $textlib = textlib_get_instance();
6386 $repositories= get_plugin_list('repository');
6387 foreach ($repositories as $p => $dir) {
6388 if (strpos($p, $query) !== false) {
6389 return true;
6392 foreach (repository::get_types() as $instance) {
6393 $title = $instance->get_typename();
6394 if (strpos($textlib->strtolower($title), $query) !== false) {
6395 return true;
6398 return false;
6402 * Helper function that generates a moodle_url object
6403 * relevant to the repository
6406 function repository_action_url($repository) {
6407 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6411 * Builds XHTML to display the control
6413 * @param string $data Unused
6414 * @param string $query
6415 * @return string XHTML
6417 public function output_html($data, $query='') {
6418 global $CFG, $USER, $OUTPUT;
6420 // Get strings that are used
6421 $strshow = get_string('on', 'repository');
6422 $strhide = get_string('off', 'repository');
6423 $strdelete = get_string('disabled', 'repository');
6425 $actionchoicesforexisting = array(
6426 'show' => $strshow,
6427 'hide' => $strhide,
6428 'delete' => $strdelete
6431 $actionchoicesfornew = array(
6432 'newon' => $strshow,
6433 'newoff' => $strhide,
6434 'delete' => $strdelete
6437 $return = '';
6438 $return .= $OUTPUT->box_start('generalbox');
6440 // Set strings that are used multiple times
6441 $settingsstr = get_string('settings');
6442 $disablestr = get_string('disable');
6444 // Table to list plug-ins
6445 $table = new html_table();
6446 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6447 $table->align = array('left', 'center', 'center', 'center', 'center');
6448 $table->data = array();
6450 // Get list of used plug-ins
6451 $instances = repository::get_types();
6452 if (!empty($instances)) {
6453 // Array to store plugins being used
6454 $alreadyplugins = array();
6455 $totalinstances = count($instances);
6456 $updowncount = 1;
6457 foreach ($instances as $i) {
6458 $settings = '';
6459 $typename = $i->get_typename();
6460 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6461 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6462 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6464 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6465 // Calculate number of instances in order to display them for the Moodle administrator
6466 if (!empty($instanceoptionnames)) {
6467 $params = array();
6468 $params['context'] = array(get_system_context());
6469 $params['onlyvisible'] = false;
6470 $params['type'] = $typename;
6471 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6472 // site instances
6473 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6474 $params['context'] = array();
6475 $instances = repository::static_function($typename, 'get_instances', $params);
6476 $courseinstances = array();
6477 $userinstances = array();
6479 foreach ($instances as $instance) {
6480 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6481 $courseinstances[] = $instance;
6482 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6483 $userinstances[] = $instance;
6486 // course instances
6487 $instancenumber = count($courseinstances);
6488 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6490 // user private instances
6491 $instancenumber = count($userinstances);
6492 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6493 } else {
6494 $admininstancenumbertext = "";
6495 $courseinstancenumbertext = "";
6496 $userinstancenumbertext = "";
6499 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6501 $settings .= $OUTPUT->container_start('mdl-left');
6502 $settings .= '<br/>';
6503 $settings .= $admininstancenumbertext;
6504 $settings .= '<br/>';
6505 $settings .= $courseinstancenumbertext;
6506 $settings .= '<br/>';
6507 $settings .= $userinstancenumbertext;
6508 $settings .= $OUTPUT->container_end();
6510 // Get the current visibility
6511 if ($i->get_visible()) {
6512 $currentaction = 'show';
6513 } else {
6514 $currentaction = 'hide';
6517 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6519 // Display up/down link
6520 $updown = '';
6521 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6523 if ($updowncount > 1) {
6524 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6525 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6527 else {
6528 $updown .= $spacer;
6530 if ($updowncount < $totalinstances) {
6531 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6532 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6534 else {
6535 $updown .= $spacer;
6538 $updowncount++;
6540 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6542 if (!in_array($typename, $alreadyplugins)) {
6543 $alreadyplugins[] = $typename;
6548 // Get all the plugins that exist on disk
6549 $plugins = get_plugin_list('repository');
6550 if (!empty($plugins)) {
6551 foreach ($plugins as $plugin => $dir) {
6552 // Check that it has not already been listed
6553 if (!in_array($plugin, $alreadyplugins)) {
6554 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6555 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6560 $return .= html_writer::table($table);
6561 $return .= $OUTPUT->box_end();
6562 return highlight($query, $return);
6567 * Special checkbox for enable mobile web service
6568 * If enable then we store the service id of the mobile service into config table
6569 * If disable then we unstore the service id from the config table
6571 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6573 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6576 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6577 * @return boolean
6579 private function is_xmlrpc_cap_allowed() {
6580 global $DB, $CFG;
6582 //if the $this->xmlrpcuse variable is not set, it needs to be set
6583 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6584 $params = array();
6585 $params['permission'] = CAP_ALLOW;
6586 $params['roleid'] = $CFG->defaultuserroleid;
6587 $params['capability'] = 'webservice/xmlrpc:use';
6588 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6591 return $this->xmlrpcuse;
6595 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6596 * @param type $status true to allow, false to not set
6598 private function set_xmlrpc_cap($status) {
6599 global $CFG;
6600 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6601 //need to allow the cap
6602 $permission = CAP_ALLOW;
6603 $assign = true;
6604 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6605 //need to disallow the cap
6606 $permission = CAP_INHERIT;
6607 $assign = true;
6609 if (!empty($assign)) {
6610 $systemcontext = get_system_context();
6611 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6616 * Builds XHTML to display the control.
6617 * The main purpose of this overloading is to display a warning when https
6618 * is not supported by the server
6619 * @param string $data Unused
6620 * @param string $query
6621 * @return string XHTML
6623 public function output_html($data, $query='') {
6624 global $CFG, $OUTPUT;
6625 $html = parent::output_html($data, $query);
6627 if ((string)$data === $this->yes) {
6628 require_once($CFG->dirroot . "/lib/filelib.php");
6629 $curl = new curl();
6630 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6631 $curl->head($httpswwwroot . "/login/index.php");
6632 $info = $curl->get_info();
6633 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6634 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6638 return $html;
6642 * Retrieves the current setting using the objects name
6644 * @return string
6646 public function get_setting() {
6647 global $CFG;
6649 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6650 // Or if web services aren't enabled this can't be,
6651 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6652 return 0;
6655 require_once($CFG->dirroot . '/webservice/lib.php');
6656 $webservicemanager = new webservice();
6657 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6658 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6659 return $this->config_read($this->name); //same as returning 1
6660 } else {
6661 return 0;
6666 * Save the selected setting
6668 * @param string $data The selected site
6669 * @return string empty string or error message
6671 public function write_setting($data) {
6672 global $DB, $CFG;
6674 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6675 if (empty($CFG->defaultuserroleid)) {
6676 return '';
6679 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6681 require_once($CFG->dirroot . '/webservice/lib.php');
6682 $webservicemanager = new webservice();
6684 if ((string)$data === $this->yes) {
6685 //code run when enable mobile web service
6686 //enable web service systeme if necessary
6687 set_config('enablewebservices', true);
6689 //enable mobile service
6690 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6691 $mobileservice->enabled = 1;
6692 $webservicemanager->update_external_service($mobileservice);
6694 //enable xml-rpc server
6695 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6697 if (!in_array('xmlrpc', $activeprotocols)) {
6698 $activeprotocols[] = 'xmlrpc';
6699 set_config('webserviceprotocols', implode(',', $activeprotocols));
6702 //allow xml-rpc:use capability for authenticated user
6703 $this->set_xmlrpc_cap(true);
6705 } else {
6706 //disable web service system if no other services are enabled
6707 $otherenabledservices = $DB->get_records_select('external_services',
6708 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6709 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6710 if (empty($otherenabledservices)) {
6711 set_config('enablewebservices', false);
6713 //also disable xml-rpc server
6714 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6715 $protocolkey = array_search('xmlrpc', $activeprotocols);
6716 if ($protocolkey !== false) {
6717 unset($activeprotocols[$protocolkey]);
6718 set_config('webserviceprotocols', implode(',', $activeprotocols));
6721 //disallow xml-rpc:use capability for authenticated user
6722 $this->set_xmlrpc_cap(false);
6725 //disable the mobile service
6726 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6727 $mobileservice->enabled = 0;
6728 $webservicemanager->update_external_service($mobileservice);
6731 return (parent::write_setting($data));
6736 * Special class for management of external services
6738 * @author Petr Skoda (skodak)
6740 class admin_setting_manageexternalservices extends admin_setting {
6742 * Calls parent::__construct with specific arguments
6744 public function __construct() {
6745 $this->nosave = true;
6746 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6750 * Always returns true, does nothing
6752 * @return true
6754 public function get_setting() {
6755 return true;
6759 * Always returns true, does nothing
6761 * @return true
6763 public function get_defaultsetting() {
6764 return true;
6768 * Always returns '', does not write anything
6770 * @return string Always returns ''
6772 public function write_setting($data) {
6773 // do not write any setting
6774 return '';
6778 * Checks if $query is one of the available external services
6780 * @param string $query The string to search for
6781 * @return bool Returns true if found, false if not
6783 public function is_related($query) {
6784 global $DB;
6786 if (parent::is_related($query)) {
6787 return true;
6790 $textlib = textlib_get_instance();
6791 $services = $DB->get_records('external_services', array(), 'id, name');
6792 foreach ($services as $service) {
6793 if (strpos($textlib->strtolower($service->name), $query) !== false) {
6794 return true;
6797 return false;
6801 * Builds the XHTML to display the control
6803 * @param string $data Unused
6804 * @param string $query
6805 * @return string
6807 public function output_html($data, $query='') {
6808 global $CFG, $OUTPUT, $DB;
6810 // display strings
6811 $stradministration = get_string('administration');
6812 $stredit = get_string('edit');
6813 $strservice = get_string('externalservice', 'webservice');
6814 $strdelete = get_string('delete');
6815 $strplugin = get_string('plugin', 'admin');
6816 $stradd = get_string('add');
6817 $strfunctions = get_string('functions', 'webservice');
6818 $strusers = get_string('users');
6819 $strserviceusers = get_string('serviceusers', 'webservice');
6821 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6822 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6823 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6825 // built in services
6826 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6827 $return = "";
6828 if (!empty($services)) {
6829 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
6833 $table = new html_table();
6834 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
6835 $table->align = array('left', 'left', 'center', 'center', 'center');
6836 $table->size = array('30%', '20%', '20%', '20%', '10%');
6837 $table->width = '100%';
6838 $table->data = array();
6840 // iterate through auth plugins and add to the display table
6841 foreach ($services as $service) {
6842 $name = $service->name;
6844 // hide/show link
6845 if ($service->enabled) {
6846 $displayname = "<span>$name</span>";
6847 } else {
6848 $displayname = "<span class=\"dimmed_text\">$name</span>";
6851 $plugin = $service->component;
6853 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6855 if ($service->restrictedusers) {
6856 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6857 } else {
6858 $users = get_string('allusers', 'webservice');
6861 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6863 // add a row to the table
6864 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
6866 $return .= html_writer::table($table);
6869 // Custom services
6870 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
6871 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
6873 $table = new html_table();
6874 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
6875 $table->align = array('left', 'center', 'center', 'center', 'center');
6876 $table->size = array('30%', '20%', '20%', '20%', '10%');
6877 $table->width = '100%';
6878 $table->data = array();
6880 // iterate through auth plugins and add to the display table
6881 foreach ($services as $service) {
6882 $name = $service->name;
6884 // hide/show link
6885 if ($service->enabled) {
6886 $displayname = "<span>$name</span>";
6887 } else {
6888 $displayname = "<span class=\"dimmed_text\">$name</span>";
6891 // delete link
6892 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
6894 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6896 if ($service->restrictedusers) {
6897 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6898 } else {
6899 $users = get_string('allusers', 'webservice');
6902 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6904 // add a row to the table
6905 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
6907 // add new custom service option
6908 $return .= html_writer::table($table);
6910 $return .= '<br />';
6911 // add a token to the table
6912 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
6914 return highlight($query, $return);
6920 * Special class for plagiarism administration.
6922 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6924 class admin_setting_manageplagiarism extends admin_setting {
6926 * Calls parent::__construct with specific arguments
6928 public function __construct() {
6929 $this->nosave = true;
6930 parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
6934 * Always returns true
6936 * @return true
6938 public function get_setting() {
6939 return true;
6943 * Always returns true
6945 * @return true
6947 public function get_defaultsetting() {
6948 return true;
6952 * Always returns '' and doesn't write anything
6954 * @return string Always returns ''
6956 public function write_setting($data) {
6957 // do not write any setting
6958 return '';
6962 * Return XHTML to display control
6964 * @param mixed $data Unused
6965 * @param string $query
6966 * @return string highlight
6968 public function output_html($data, $query='') {
6969 global $CFG, $OUTPUT;
6971 // display strings
6972 $txt = get_strings(array('settings', 'name'));
6974 $plagiarismplugins = get_plugin_list('plagiarism');
6975 if (empty($plagiarismplugins)) {
6976 return get_string('nopluginsinstalled', 'plagiarism');
6979 $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
6980 $return .= $OUTPUT->box_start('generalbox authsui');
6982 $table = new html_table();
6983 $table->head = array($txt->name, $txt->settings);
6984 $table->align = array('left', 'center');
6985 $table->data = array();
6986 $table->attributes['class'] = 'manageplagiarismtable generaltable';
6988 // iterate through auth plugins and add to the display table
6989 $authcount = count($plagiarismplugins);
6990 foreach ($plagiarismplugins as $plugin => $dir) {
6991 if (file_exists($dir.'/settings.php')) {
6992 $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
6993 // settings link
6994 $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
6995 // add a row to the table
6996 $table->data[] =array($displayname, $settings);
6999 $return .= html_writer::table($table);
7000 $return .= get_string('configplagiarismplugins', 'plagiarism');
7001 $return .= $OUTPUT->box_end();
7002 return highlight($query, $return);
7008 * Special class for overview of external services
7010 * @author Jerome Mouneyrac
7012 class admin_setting_webservicesoverview extends admin_setting {
7015 * Calls parent::__construct with specific arguments
7017 public function __construct() {
7018 $this->nosave = true;
7019 parent::__construct('webservicesoverviewui',
7020 get_string('webservicesoverview', 'webservice'), '', '');
7024 * Always returns true, does nothing
7026 * @return true
7028 public function get_setting() {
7029 return true;
7033 * Always returns true, does nothing
7035 * @return true
7037 public function get_defaultsetting() {
7038 return true;
7042 * Always returns '', does not write anything
7044 * @return string Always returns ''
7046 public function write_setting($data) {
7047 // do not write any setting
7048 return '';
7052 * Builds the XHTML to display the control
7054 * @param string $data Unused
7055 * @param string $query
7056 * @return string
7058 public function output_html($data, $query='') {
7059 global $CFG, $OUTPUT;
7061 $return = "";
7062 $brtag = html_writer::empty_tag('br');
7064 // Enable mobile web service
7065 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7066 get_string('enablemobilewebservice', 'admin'),
7067 get_string('configenablemobilewebservice',
7068 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7069 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7070 $wsmobileparam = new stdClass();
7071 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7072 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7073 get_string('externalservices', 'webservice'));
7074 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7075 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7076 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7077 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7078 . $brtag . $brtag;
7080 /// One system controlling Moodle with Token
7081 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7082 $table = new html_table();
7083 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7084 get_string('description'));
7085 $table->size = array('30%', '10%', '60%');
7086 $table->align = array('left', 'left', 'left');
7087 $table->width = '90%';
7088 $table->data = array();
7090 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7091 . $brtag . $brtag;
7093 /// 1. Enable Web Services
7094 $row = array();
7095 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7096 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7097 array('href' => $url));
7098 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7099 if ($CFG->enablewebservices) {
7100 $status = get_string('yes');
7102 $row[1] = $status;
7103 $row[2] = get_string('enablewsdescription', 'webservice');
7104 $table->data[] = $row;
7106 /// 2. Enable protocols
7107 $row = array();
7108 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7109 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7110 array('href' => $url));
7111 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7112 //retrieve activated protocol
7113 $active_protocols = empty($CFG->webserviceprotocols) ?
7114 array() : explode(',', $CFG->webserviceprotocols);
7115 if (!empty($active_protocols)) {
7116 $status = "";
7117 foreach ($active_protocols as $protocol) {
7118 $status .= $protocol . $brtag;
7121 $row[1] = $status;
7122 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7123 $table->data[] = $row;
7125 /// 3. Create user account
7126 $row = array();
7127 $url = new moodle_url("/user/editadvanced.php?id=-1");
7128 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7129 array('href' => $url));
7130 $row[1] = "";
7131 $row[2] = get_string('createuserdescription', 'webservice');
7132 $table->data[] = $row;
7134 /// 4. Add capability to users
7135 $row = array();
7136 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7137 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7138 array('href' => $url));
7139 $row[1] = "";
7140 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7141 $table->data[] = $row;
7143 /// 5. Select a web service
7144 $row = array();
7145 $url = new moodle_url("/admin/settings.php?section=externalservices");
7146 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7147 array('href' => $url));
7148 $row[1] = "";
7149 $row[2] = get_string('createservicedescription', 'webservice');
7150 $table->data[] = $row;
7152 /// 6. Add functions
7153 $row = array();
7154 $url = new moodle_url("/admin/settings.php?section=externalservices");
7155 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7156 array('href' => $url));
7157 $row[1] = "";
7158 $row[2] = get_string('addfunctionsdescription', 'webservice');
7159 $table->data[] = $row;
7161 /// 7. Add the specific user
7162 $row = array();
7163 $url = new moodle_url("/admin/settings.php?section=externalservices");
7164 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7165 array('href' => $url));
7166 $row[1] = "";
7167 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7168 $table->data[] = $row;
7170 /// 8. Create token for the specific user
7171 $row = array();
7172 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7173 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7174 array('href' => $url));
7175 $row[1] = "";
7176 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7177 $table->data[] = $row;
7179 /// 9. Enable the documentation
7180 $row = array();
7181 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7182 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7183 array('href' => $url));
7184 $status = '<span class="warning">' . get_string('no') . '</span>';
7185 if ($CFG->enablewsdocumentation) {
7186 $status = get_string('yes');
7188 $row[1] = $status;
7189 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7190 $table->data[] = $row;
7192 /// 10. Test the service
7193 $row = array();
7194 $url = new moodle_url("/admin/webservice/testclient.php");
7195 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7196 array('href' => $url));
7197 $row[1] = "";
7198 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7199 $table->data[] = $row;
7201 $return .= html_writer::table($table);
7203 /// Users as clients with token
7204 $return .= $brtag . $brtag . $brtag;
7205 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7206 $table = new html_table();
7207 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7208 get_string('description'));
7209 $table->size = array('30%', '10%', '60%');
7210 $table->align = array('left', 'left', 'left');
7211 $table->width = '90%';
7212 $table->data = array();
7214 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7215 $brtag . $brtag;
7217 /// 1. Enable Web Services
7218 $row = array();
7219 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7220 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7221 array('href' => $url));
7222 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7223 if ($CFG->enablewebservices) {
7224 $status = get_string('yes');
7226 $row[1] = $status;
7227 $row[2] = get_string('enablewsdescription', 'webservice');
7228 $table->data[] = $row;
7230 /// 2. Enable protocols
7231 $row = array();
7232 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7233 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7234 array('href' => $url));
7235 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7236 //retrieve activated protocol
7237 $active_protocols = empty($CFG->webserviceprotocols) ?
7238 array() : explode(',', $CFG->webserviceprotocols);
7239 if (!empty($active_protocols)) {
7240 $status = "";
7241 foreach ($active_protocols as $protocol) {
7242 $status .= $protocol . $brtag;
7245 $row[1] = $status;
7246 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7247 $table->data[] = $row;
7250 /// 3. Select a web service
7251 $row = array();
7252 $url = new moodle_url("/admin/settings.php?section=externalservices");
7253 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7254 array('href' => $url));
7255 $row[1] = "";
7256 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7257 $table->data[] = $row;
7259 /// 4. Add functions
7260 $row = array();
7261 $url = new moodle_url("/admin/settings.php?section=externalservices");
7262 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7263 array('href' => $url));
7264 $row[1] = "";
7265 $row[2] = get_string('addfunctionsdescription', 'webservice');
7266 $table->data[] = $row;
7268 /// 5. Add capability to users
7269 $row = array();
7270 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7271 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7272 array('href' => $url));
7273 $row[1] = "";
7274 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7275 $table->data[] = $row;
7277 /// 6. Test the service
7278 $row = array();
7279 $url = new moodle_url("/admin/webservice/testclient.php");
7280 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7281 array('href' => $url));
7282 $row[1] = "";
7283 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7284 $table->data[] = $row;
7286 $return .= html_writer::table($table);
7288 return highlight($query, $return);
7295 * Special class for web service protocol administration.
7297 * @author Petr Skoda (skodak)
7299 class admin_setting_managewebserviceprotocols extends admin_setting {
7302 * Calls parent::__construct with specific arguments
7304 public function __construct() {
7305 $this->nosave = true;
7306 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7310 * Always returns true, does nothing
7312 * @return true
7314 public function get_setting() {
7315 return true;
7319 * Always returns true, does nothing
7321 * @return true
7323 public function get_defaultsetting() {
7324 return true;
7328 * Always returns '', does not write anything
7330 * @return string Always returns ''
7332 public function write_setting($data) {
7333 // do not write any setting
7334 return '';
7338 * Checks if $query is one of the available webservices
7340 * @param string $query The string to search for
7341 * @return bool Returns true if found, false if not
7343 public function is_related($query) {
7344 if (parent::is_related($query)) {
7345 return true;
7348 $textlib = textlib_get_instance();
7349 $protocols = get_plugin_list('webservice');
7350 foreach ($protocols as $protocol=>$location) {
7351 if (strpos($protocol, $query) !== false) {
7352 return true;
7354 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7355 if (strpos($textlib->strtolower($protocolstr), $query) !== false) {
7356 return true;
7359 return false;
7363 * Builds the XHTML to display the control
7365 * @param string $data Unused
7366 * @param string $query
7367 * @return string
7369 public function output_html($data, $query='') {
7370 global $CFG, $OUTPUT;
7372 // display strings
7373 $stradministration = get_string('administration');
7374 $strsettings = get_string('settings');
7375 $stredit = get_string('edit');
7376 $strprotocol = get_string('protocol', 'webservice');
7377 $strenable = get_string('enable');
7378 $strdisable = get_string('disable');
7379 $strversion = get_string('version');
7380 $struninstall = get_string('uninstallplugin', 'admin');
7382 $protocols_available = get_plugin_list('webservice');
7383 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7384 ksort($protocols_available);
7386 foreach ($active_protocols as $key=>$protocol) {
7387 if (empty($protocols_available[$protocol])) {
7388 unset($active_protocols[$key]);
7392 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7393 $return .= $OUTPUT->box_start('generalbox webservicesui');
7395 $table = new html_table();
7396 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7397 $table->align = array('left', 'center', 'center', 'center', 'center');
7398 $table->width = '100%';
7399 $table->data = array();
7401 // iterate through auth plugins and add to the display table
7402 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7403 foreach ($protocols_available as $protocol => $location) {
7404 $name = get_string('pluginname', 'webservice_'.$protocol);
7406 $plugin = new stdClass();
7407 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7408 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7410 $version = isset($plugin->version) ? $plugin->version : '';
7412 // hide/show link
7413 if (in_array($protocol, $active_protocols)) {
7414 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7415 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
7416 $displayname = "<span>$name</span>";
7417 } else {
7418 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7419 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
7420 $displayname = "<span class=\"dimmed_text\">$name</span>";
7423 // delete link
7424 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7426 // settings link
7427 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7428 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7429 } else {
7430 $settings = '';
7433 // add a row to the table
7434 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7436 $return .= html_writer::table($table);
7437 $return .= get_string('configwebserviceplugins', 'webservice');
7438 $return .= $OUTPUT->box_end();
7440 return highlight($query, $return);
7446 * Special class for web service token administration.
7448 * @author Jerome Mouneyrac
7450 class admin_setting_managewebservicetokens extends admin_setting {
7453 * Calls parent::__construct with specific arguments
7455 public function __construct() {
7456 $this->nosave = true;
7457 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7461 * Always returns true, does nothing
7463 * @return true
7465 public function get_setting() {
7466 return true;
7470 * Always returns true, does nothing
7472 * @return true
7474 public function get_defaultsetting() {
7475 return true;
7479 * Always returns '', does not write anything
7481 * @return string Always returns ''
7483 public function write_setting($data) {
7484 // do not write any setting
7485 return '';
7489 * Builds the XHTML to display the control
7491 * @param string $data Unused
7492 * @param string $query
7493 * @return string
7495 public function output_html($data, $query='') {
7496 global $CFG, $OUTPUT, $DB, $USER;
7498 // display strings
7499 $stroperation = get_string('operation', 'webservice');
7500 $strtoken = get_string('token', 'webservice');
7501 $strservice = get_string('service', 'webservice');
7502 $struser = get_string('user');
7503 $strcontext = get_string('context', 'webservice');
7504 $strvaliduntil = get_string('validuntil', 'webservice');
7505 $striprestriction = get_string('iprestriction', 'webservice');
7507 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7509 $table = new html_table();
7510 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7511 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7512 $table->width = '100%';
7513 $table->data = array();
7515 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7517 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7519 //here retrieve token list (including linked users firstname/lastname and linked services name)
7520 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.validuntil, s.id AS serviceid
7521 FROM {external_tokens} t, {user} u, {external_services} s
7522 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7523 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7524 if (!empty($tokens)) {
7525 foreach ($tokens as $token) {
7526 //TODO: retrieve context
7528 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7529 $delete .= get_string('delete')."</a>";
7531 $validuntil = '';
7532 if (!empty($token->validuntil)) {
7533 $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
7536 $iprestriction = '';
7537 if (!empty($token->iprestriction)) {
7538 $iprestriction = $token->iprestriction;
7541 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7542 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7543 $useratag .= $token->firstname." ".$token->lastname;
7544 $useratag .= html_writer::end_tag('a');
7546 //check user missing capabilities
7547 require_once($CFG->dirroot . '/webservice/lib.php');
7548 $webservicemanager = new webservice();
7549 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7550 array(array('id' => $token->userid)), $token->serviceid);
7552 if (!is_siteadmin($token->userid) and
7553 key_exists($token->userid, $usermissingcaps)) {
7554 $missingcapabilities = implode(',',
7555 $usermissingcaps[$token->userid]);
7556 if (!empty($missingcapabilities)) {
7557 $useratag .= html_writer::tag('div',
7558 get_string('usermissingcaps', 'webservice',
7559 $missingcapabilities)
7560 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7561 array('class' => 'missingcaps'));
7565 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7568 $return .= html_writer::table($table);
7569 } else {
7570 $return .= get_string('notoken', 'webservice');
7573 $return .= $OUTPUT->box_end();
7574 // add a token to the table
7575 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7576 $return .= get_string('add')."</a>";
7578 return highlight($query, $return);
7584 * Colour picker
7586 * @copyright 2010 Sam Hemelryk
7587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7589 class admin_setting_configcolourpicker extends admin_setting {
7592 * Information for previewing the colour
7594 * @var array|null
7596 protected $previewconfig = null;
7600 * @param string $name
7601 * @param string $visiblename
7602 * @param string $description
7603 * @param string $defaultsetting
7604 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7606 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7607 $this->previewconfig = $previewconfig;
7608 parent::__construct($name, $visiblename, $description, $defaultsetting);
7612 * Return the setting
7614 * @return mixed returns config if successful else null
7616 public function get_setting() {
7617 return $this->config_read($this->name);
7621 * Saves the setting
7623 * @param string $data
7624 * @return bool
7626 public function write_setting($data) {
7627 $data = $this->validate($data);
7628 if ($data === false) {
7629 return get_string('validateerror', 'admin');
7631 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7635 * Validates the colour that was entered by the user
7637 * @param string $data
7638 * @return string|false
7640 protected function validate($data) {
7641 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7642 if (strpos($data, '#')!==0) {
7643 $data = '#'.$data;
7645 return $data;
7646 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7647 return $data;
7648 } else if (empty($data)) {
7649 return $this->defaultsetting;
7650 } else {
7651 return false;
7656 * Generates the HTML for the setting
7658 * @global moodle_page $PAGE
7659 * @global core_renderer $OUTPUT
7660 * @param string $data
7661 * @param string $query
7663 public function output_html($data, $query = '') {
7664 global $PAGE, $OUTPUT;
7665 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7666 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7667 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7668 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
7669 if (!empty($this->previewconfig)) {
7670 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7672 $content .= html_writer::end_tag('div');
7673 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7678 * Administration interface for user specified regular expressions for device detection.
7680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7682 class admin_setting_devicedetectregex extends admin_setting {
7685 * Calls parent::__construct with specific args
7687 * @param string $name
7688 * @param string $visiblename
7689 * @param string $description
7690 * @param mixed $defaultsetting
7692 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7693 global $CFG;
7694 parent::__construct($name, $visiblename, $description, $defaultsetting);
7698 * Return the current setting(s)
7700 * @return array Current settings array
7702 public function get_setting() {
7703 global $CFG;
7705 $config = $this->config_read($this->name);
7706 if (is_null($config)) {
7707 return null;
7710 return $this->prepare_form_data($config);
7714 * Save selected settings
7716 * @param array $data Array of settings to save
7717 * @return bool
7719 public function write_setting($data) {
7720 if (empty($data)) {
7721 $data = array();
7724 if ($this->config_write($this->name, $this->process_form_data($data))) {
7725 return ''; // success
7726 } else {
7727 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
7732 * Return XHTML field(s) for regexes
7734 * @param array $data Array of options to set in HTML
7735 * @return string XHTML string for the fields and wrapping div(s)
7737 public function output_html($data, $query='') {
7738 global $OUTPUT;
7740 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
7741 $out .= html_writer::start_tag('thead');
7742 $out .= html_writer::start_tag('tr');
7743 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
7744 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
7745 $out .= html_writer::end_tag('tr');
7746 $out .= html_writer::end_tag('thead');
7747 $out .= html_writer::start_tag('tbody');
7749 if (empty($data)) {
7750 $looplimit = 1;
7751 } else {
7752 $looplimit = (count($data)/2)+1;
7755 for ($i=0; $i<$looplimit; $i++) {
7756 $out .= html_writer::start_tag('tr');
7758 $expressionname = 'expression'.$i;
7760 if (!empty($data[$expressionname])){
7761 $expression = $data[$expressionname];
7762 } else {
7763 $expression = '';
7766 $out .= html_writer::tag('td',
7767 html_writer::empty_tag('input',
7768 array(
7769 'type' => 'text',
7770 'class' => 'form-text',
7771 'name' => $this->get_full_name().'[expression'.$i.']',
7772 'value' => $expression,
7774 ), array('class' => 'c'.$i)
7777 $valuename = 'value'.$i;
7779 if (!empty($data[$valuename])){
7780 $value = $data[$valuename];
7781 } else {
7782 $value= '';
7785 $out .= html_writer::tag('td',
7786 html_writer::empty_tag('input',
7787 array(
7788 'type' => 'text',
7789 'class' => 'form-text',
7790 'name' => $this->get_full_name().'[value'.$i.']',
7791 'value' => $value,
7793 ), array('class' => 'c'.$i)
7796 $out .= html_writer::end_tag('tr');
7799 $out .= html_writer::end_tag('tbody');
7800 $out .= html_writer::end_tag('table');
7802 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
7806 * Converts the string of regexes
7808 * @see self::process_form_data()
7809 * @param $regexes string of regexes
7810 * @return array of form fields and their values
7812 protected function prepare_form_data($regexes) {
7814 $regexes = json_decode($regexes);
7816 $form = array();
7818 $i = 0;
7820 foreach ($regexes as $value => $regex) {
7821 $expressionname = 'expression'.$i;
7822 $valuename = 'value'.$i;
7824 $form[$expressionname] = $regex;
7825 $form[$valuename] = $value;
7826 $i++;
7829 return $form;
7833 * Converts the data from admin settings form into a string of regexes
7835 * @see self::prepare_form_data()
7836 * @param array $data array of admin form fields and values
7837 * @return false|string of regexes
7839 protected function process_form_data(array $form) {
7841 $count = count($form); // number of form field values
7843 if ($count % 2) {
7844 // we must get five fields per expression
7845 return false;
7848 $regexes = array();
7849 for ($i = 0; $i < $count / 2; $i++) {
7850 $expressionname = "expression".$i;
7851 $valuename = "value".$i;
7853 $expression = trim($form['expression'.$i]);
7854 $value = trim($form['value'.$i]);
7856 if (empty($expression)){
7857 continue;
7860 $regexes[$value] = $expression;
7863 $regexes = json_encode($regexes);
7865 return $regexes;
7870 * Multiselect for current modules
7872 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7874 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
7876 * Calls parent::__construct - note array $choices is not required
7878 * @param string $name setting name
7879 * @param string $visiblename localised setting name
7880 * @param string $description setting description
7881 * @param array $defaultsetting a plain array of default module ids
7883 public function __construct($name, $visiblename, $description, $defaultsetting = array()) {
7884 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
7888 * Loads an array of current module choices
7890 * @return bool always return true
7892 public function load_choices() {
7893 if (is_array($this->choices)) {
7894 return true;
7896 $this->choices = array();
7898 global $CFG, $DB;
7899 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7900 foreach ($records as $record) {
7901 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7902 $this->choices[$record->id] = $record->name;
7905 return true;