MDL-46649 gradereport_history: Add apis to get users and user count, also refactor...
[moodle.git] / lib / adminlib.php
blobeabb1a105eb6582951a866ecbfb6e91daa9aabfd
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 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // delete all the logs
206 $DB->delete_records('log', array('module' => $pluginname));
208 // delete log_display information
209 $DB->delete_records('log_display', array('component' => $component));
211 // delete the module configuration records
212 unset_all_config_for_plugin($component);
213 if ($type === 'mod') {
214 unset_all_config_for_plugin($pluginname);
217 // delete message provider
218 message_provider_uninstall($component);
220 // delete the plugin tables
221 $xmldbfilepath = $plugindirectory . '/db/install.xml';
222 drop_plugin_tables($component, $xmldbfilepath, false);
223 if ($type === 'mod' or $type === 'block') {
224 // non-frankenstyle table prefixes
225 drop_plugin_tables($name, $xmldbfilepath, false);
228 // delete the capabilities that were defined by this module
229 capabilities_cleanup($component);
231 // remove event handlers and dequeue pending events
232 events_uninstall($component);
234 // Delete all remaining files in the filepool owned by the component.
235 $fs = get_file_storage();
236 $fs->delete_component_files($component);
238 // Finally purge all caches.
239 purge_all_caches();
241 // Invalidate the hash used for upgrade detections.
242 set_config('allversionshash', '');
244 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
248 * Returns the version of installed component
250 * @param string $component component name
251 * @param string $source either 'disk' or 'installed' - where to get the version information from
252 * @return string|bool version number or false if the component is not found
254 function get_component_version($component, $source='installed') {
255 global $CFG, $DB;
257 list($type, $name) = core_component::normalize_component($component);
259 // moodle core or a core subsystem
260 if ($type === 'core') {
261 if ($source === 'installed') {
262 if (empty($CFG->version)) {
263 return false;
264 } else {
265 return $CFG->version;
267 } else {
268 if (!is_readable($CFG->dirroot.'/version.php')) {
269 return false;
270 } else {
271 $version = null; //initialize variable for IDEs
272 include($CFG->dirroot.'/version.php');
273 return $version;
278 // activity module
279 if ($type === 'mod') {
280 if ($source === 'installed') {
281 if ($CFG->version < 2013092001.02) {
282 return $DB->get_field('modules', 'version', array('name'=>$name));
283 } else {
284 return get_config('mod_'.$name, 'version');
287 } else {
288 $mods = core_component::get_plugin_list('mod');
289 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
290 return false;
291 } else {
292 $plugin = new stdClass();
293 $plugin->version = null;
294 $module = $plugin;
295 include($mods[$name].'/version.php');
296 return $plugin->version;
301 // block
302 if ($type === 'block') {
303 if ($source === 'installed') {
304 if ($CFG->version < 2013092001.02) {
305 return $DB->get_field('block', 'version', array('name'=>$name));
306 } else {
307 return get_config('block_'.$name, 'version');
309 } else {
310 $blocks = core_component::get_plugin_list('block');
311 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
312 return false;
313 } else {
314 $plugin = new stdclass();
315 include($blocks[$name].'/version.php');
316 return $plugin->version;
321 // all other plugin types
322 if ($source === 'installed') {
323 return get_config($type.'_'.$name, 'version');
324 } else {
325 $plugins = core_component::get_plugin_list($type);
326 if (empty($plugins[$name])) {
327 return false;
328 } else {
329 $plugin = new stdclass();
330 include($plugins[$name].'/version.php');
331 return $plugin->version;
337 * Delete all plugin tables
339 * @param string $name Name of plugin, used as table prefix
340 * @param string $file Path to install.xml file
341 * @param bool $feedback defaults to true
342 * @return bool Always returns true
344 function drop_plugin_tables($name, $file, $feedback=true) {
345 global $CFG, $DB;
347 // first try normal delete
348 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
349 return true;
352 // then try to find all tables that start with name and are not in any xml file
353 $used_tables = get_used_table_names();
355 $tables = $DB->get_tables();
357 /// Iterate over, fixing id fields as necessary
358 foreach ($tables as $table) {
359 if (in_array($table, $used_tables)) {
360 continue;
363 if (strpos($table, $name) !== 0) {
364 continue;
367 // found orphan table --> delete it
368 if ($DB->get_manager()->table_exists($table)) {
369 $xmldb_table = new xmldb_table($table);
370 $DB->get_manager()->drop_table($xmldb_table);
374 return true;
378 * Returns names of all known tables == tables that moodle knows about.
380 * @return array Array of lowercase table names
382 function get_used_table_names() {
383 $table_names = array();
384 $dbdirs = get_db_directories();
386 foreach ($dbdirs as $dbdir) {
387 $file = $dbdir.'/install.xml';
389 $xmldb_file = new xmldb_file($file);
391 if (!$xmldb_file->fileExists()) {
392 continue;
395 $loaded = $xmldb_file->loadXMLStructure();
396 $structure = $xmldb_file->getStructure();
398 if ($loaded and $tables = $structure->getTables()) {
399 foreach($tables as $table) {
400 $table_names[] = strtolower($table->getName());
405 return $table_names;
409 * Returns list of all directories where we expect install.xml files
410 * @return array Array of paths
412 function get_db_directories() {
413 global $CFG;
415 $dbdirs = array();
417 /// First, the main one (lib/db)
418 $dbdirs[] = $CFG->libdir.'/db';
420 /// Then, all the ones defined by core_component::get_plugin_types()
421 $plugintypes = core_component::get_plugin_types();
422 foreach ($plugintypes as $plugintype => $pluginbasedir) {
423 if ($plugins = core_component::get_plugin_list($plugintype)) {
424 foreach ($plugins as $plugin => $plugindir) {
425 $dbdirs[] = $plugindir.'/db';
430 return $dbdirs;
434 * Try to obtain or release the cron lock.
435 * @param string $name name of lock
436 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
437 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
438 * @return bool true if lock obtained
440 function set_cron_lock($name, $until, $ignorecurrent=false) {
441 global $DB;
442 if (empty($name)) {
443 debugging("Tried to get a cron lock for a null fieldname");
444 return false;
447 // remove lock by force == remove from config table
448 if (is_null($until)) {
449 set_config($name, null);
450 return true;
453 if (!$ignorecurrent) {
454 // read value from db - other processes might have changed it
455 $value = $DB->get_field('config', 'value', array('name'=>$name));
457 if ($value and $value > time()) {
458 //lock active
459 return false;
463 set_config($name, $until);
464 return true;
468 * Test if and critical warnings are present
469 * @return bool
471 function admin_critical_warnings_present() {
472 global $SESSION;
474 if (!has_capability('moodle/site:config', context_system::instance())) {
475 return 0;
478 if (!isset($SESSION->admin_critical_warning)) {
479 $SESSION->admin_critical_warning = 0;
480 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
481 $SESSION->admin_critical_warning = 1;
485 return $SESSION->admin_critical_warning;
489 * Detects if float supports at least 10 decimal digits
491 * Detects if float supports at least 10 decimal digits
492 * and also if float-->string conversion works as expected.
494 * @return bool true if problem found
496 function is_float_problem() {
497 $num1 = 2009010200.01;
498 $num2 = 2009010200.02;
500 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
504 * Try to verify that dataroot is not accessible from web.
506 * Try to verify that dataroot is not accessible from web.
507 * It is not 100% correct but might help to reduce number of vulnerable sites.
508 * Protection from httpd.conf and .htaccess is not detected properly.
510 * @uses INSECURE_DATAROOT_WARNING
511 * @uses INSECURE_DATAROOT_ERROR
512 * @param bool $fetchtest try to test public access by fetching file, default false
513 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
515 function is_dataroot_insecure($fetchtest=false) {
516 global $CFG;
518 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
520 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
521 $rp = strrev(trim($rp, '/'));
522 $rp = explode('/', $rp);
523 foreach($rp as $r) {
524 if (strpos($siteroot, '/'.$r.'/') === 0) {
525 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
526 } else {
527 break; // probably alias root
531 $siteroot = strrev($siteroot);
532 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
534 if (strpos($dataroot, $siteroot) !== 0) {
535 return false;
538 if (!$fetchtest) {
539 return INSECURE_DATAROOT_WARNING;
542 // now try all methods to fetch a test file using http protocol
544 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
545 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
546 $httpdocroot = $matches[1];
547 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
548 make_upload_directory('diag');
549 $testfile = $CFG->dataroot.'/diag/public.txt';
550 if (!file_exists($testfile)) {
551 file_put_contents($testfile, 'test file, do not delete');
552 @chmod($testfile, $CFG->filepermissions);
554 $teststr = trim(file_get_contents($testfile));
555 if (empty($teststr)) {
556 // hmm, strange
557 return INSECURE_DATAROOT_WARNING;
560 $testurl = $datarooturl.'/diag/public.txt';
561 if (extension_loaded('curl') and
562 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
563 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
564 ($ch = @curl_init($testurl)) !== false) {
565 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
566 curl_setopt($ch, CURLOPT_HEADER, false);
567 $data = curl_exec($ch);
568 if (!curl_errno($ch)) {
569 $data = trim($data);
570 if ($data === $teststr) {
571 curl_close($ch);
572 return INSECURE_DATAROOT_ERROR;
575 curl_close($ch);
578 if ($data = @file_get_contents($testurl)) {
579 $data = trim($data);
580 if ($data === $teststr) {
581 return INSECURE_DATAROOT_ERROR;
585 preg_match('|https?://([^/]+)|i', $testurl, $matches);
586 $sitename = $matches[1];
587 $error = 0;
588 if ($fp = @fsockopen($sitename, 80, $error)) {
589 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
590 $localurl = $matches[1];
591 $out = "GET $localurl HTTP/1.1\r\n";
592 $out .= "Host: $sitename\r\n";
593 $out .= "Connection: Close\r\n\r\n";
594 fwrite($fp, $out);
595 $data = '';
596 $incoming = false;
597 while (!feof($fp)) {
598 if ($incoming) {
599 $data .= fgets($fp, 1024);
600 } else if (@fgets($fp, 1024) === "\r\n") {
601 $incoming = true;
604 fclose($fp);
605 $data = trim($data);
606 if ($data === $teststr) {
607 return INSECURE_DATAROOT_ERROR;
611 return INSECURE_DATAROOT_WARNING;
615 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
617 function enable_cli_maintenance_mode() {
618 global $CFG;
620 if (file_exists("$CFG->dataroot/climaintenance.html")) {
621 unlink("$CFG->dataroot/climaintenance.html");
624 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
625 $data = $CFG->maintenance_message;
626 $data = bootstrap_renderer::early_error_content($data, null, null, null);
627 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
629 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
630 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
632 } else {
633 $data = get_string('sitemaintenance', 'admin');
634 $data = bootstrap_renderer::early_error_content($data, null, null, null);
635 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
638 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
639 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
642 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
646 * Interface for anything appearing in the admin tree
648 * The interface that is implemented by anything that appears in the admin tree
649 * block. It forces inheriting classes to define a method for checking user permissions
650 * and methods for finding something in the admin tree.
652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
654 interface part_of_admin_tree {
657 * Finds a named part_of_admin_tree.
659 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
660 * and not parentable_part_of_admin_tree, then this function should only check if
661 * $this->name matches $name. If it does, it should return a reference to $this,
662 * otherwise, it should return a reference to NULL.
664 * If a class inherits parentable_part_of_admin_tree, this method should be called
665 * recursively on all child objects (assuming, of course, the parent object's name
666 * doesn't match the search criterion).
668 * @param string $name The internal name of the part_of_admin_tree we're searching for.
669 * @return mixed An object reference or a NULL reference.
671 public function locate($name);
674 * Removes named part_of_admin_tree.
676 * @param string $name The internal name of the part_of_admin_tree we want to remove.
677 * @return bool success.
679 public function prune($name);
682 * Search using query
683 * @param string $query
684 * @return mixed array-object structure of found settings and pages
686 public function search($query);
689 * Verifies current user's access to this part_of_admin_tree.
691 * Used to check if the current user has access to this part of the admin tree or
692 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
693 * then this method is usually just a call to has_capability() in the site context.
695 * If a class inherits parentable_part_of_admin_tree, this method should return the
696 * logical OR of the return of check_access() on all child objects.
698 * @return bool True if the user has access, false if she doesn't.
700 public function check_access();
703 * Mostly useful for removing of some parts of the tree in admin tree block.
705 * @return True is hidden from normal list view
707 public function is_hidden();
710 * Show we display Save button at the page bottom?
711 * @return bool
713 public function show_save();
718 * Interface implemented by any part_of_admin_tree that has children.
720 * The interface implemented by any part_of_admin_tree that can be a parent
721 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
722 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
723 * include an add method for adding other part_of_admin_tree objects as children.
725 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
727 interface parentable_part_of_admin_tree extends part_of_admin_tree {
730 * Adds a part_of_admin_tree object to the admin tree.
732 * Used to add a part_of_admin_tree object to this object or a child of this
733 * object. $something should only be added if $destinationname matches
734 * $this->name. If it doesn't, add should be called on child objects that are
735 * also parentable_part_of_admin_tree's.
737 * $something should be appended as the last child in the $destinationname. If the
738 * $beforesibling is specified, $something should be prepended to it. If the given
739 * sibling is not found, $something should be appended to the end of $destinationname
740 * and a developer debugging message should be displayed.
742 * @param string $destinationname The internal name of the new parent for $something.
743 * @param part_of_admin_tree $something The object to be added.
744 * @return bool True on success, false on failure.
746 public function add($destinationname, $something, $beforesibling = null);
752 * The object used to represent folders (a.k.a. categories) in the admin tree block.
754 * Each admin_category object contains a number of part_of_admin_tree objects.
756 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
758 class admin_category implements parentable_part_of_admin_tree {
760 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
761 protected $children;
762 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
763 public $name;
764 /** @var string The displayed name for this category. Usually obtained through get_string() */
765 public $visiblename;
766 /** @var bool Should this category be hidden in admin tree block? */
767 public $hidden;
768 /** @var mixed Either a string or an array or strings */
769 public $path;
770 /** @var mixed Either a string or an array or strings */
771 public $visiblepath;
773 /** @var array fast lookup category cache, all categories of one tree point to one cache */
774 protected $category_cache;
776 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
777 protected $sort = false;
778 /** @var bool If set to true children will be sorted in ascending order. */
779 protected $sortasc = true;
780 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
781 protected $sortsplit = true;
782 /** @var bool $sorted True if the children have been sorted and don't need resorting */
783 protected $sorted = false;
786 * Constructor for an empty admin category
788 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
789 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
790 * @param bool $hidden hide category in admin tree block, defaults to false
792 public function __construct($name, $visiblename, $hidden=false) {
793 $this->children = array();
794 $this->name = $name;
795 $this->visiblename = $visiblename;
796 $this->hidden = $hidden;
800 * Returns a reference to the part_of_admin_tree object with internal name $name.
802 * @param string $name The internal name of the object we want.
803 * @param bool $findpath initialize path and visiblepath arrays
804 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
805 * defaults to false
807 public function locate($name, $findpath=false) {
808 if (!isset($this->category_cache[$this->name])) {
809 // somebody much have purged the cache
810 $this->category_cache[$this->name] = $this;
813 if ($this->name == $name) {
814 if ($findpath) {
815 $this->visiblepath[] = $this->visiblename;
816 $this->path[] = $this->name;
818 return $this;
821 // quick category lookup
822 if (!$findpath and isset($this->category_cache[$name])) {
823 return $this->category_cache[$name];
826 $return = NULL;
827 foreach($this->children as $childid=>$unused) {
828 if ($return = $this->children[$childid]->locate($name, $findpath)) {
829 break;
833 if (!is_null($return) and $findpath) {
834 $return->visiblepath[] = $this->visiblename;
835 $return->path[] = $this->name;
838 return $return;
842 * Search using query
844 * @param string query
845 * @return mixed array-object structure of found settings and pages
847 public function search($query) {
848 $result = array();
849 foreach ($this->get_children() as $child) {
850 $subsearch = $child->search($query);
851 if (!is_array($subsearch)) {
852 debugging('Incorrect search result from '.$child->name);
853 continue;
855 $result = array_merge($result, $subsearch);
857 return $result;
861 * Removes part_of_admin_tree object with internal name $name.
863 * @param string $name The internal name of the object we want to remove.
864 * @return bool success
866 public function prune($name) {
868 if ($this->name == $name) {
869 return false; //can not remove itself
872 foreach($this->children as $precedence => $child) {
873 if ($child->name == $name) {
874 // clear cache and delete self
875 while($this->category_cache) {
876 // delete the cache, but keep the original array address
877 array_pop($this->category_cache);
879 unset($this->children[$precedence]);
880 return true;
881 } else if ($this->children[$precedence]->prune($name)) {
882 return true;
885 return false;
889 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
891 * By default the new part of the tree is appended as the last child of the parent. You
892 * can specify a sibling node that the new part should be prepended to. If the given
893 * sibling is not found, the part is appended to the end (as it would be by default) and
894 * a developer debugging message is displayed.
896 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
897 * @param string $destinationame The internal name of the immediate parent that we want for $something.
898 * @param mixed $something A part_of_admin_tree or setting instance to be added.
899 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
900 * @return bool True if successfully added, false if $something can not be added.
902 public function add($parentname, $something, $beforesibling = null) {
903 global $CFG;
905 $parent = $this->locate($parentname);
906 if (is_null($parent)) {
907 debugging('parent does not exist!');
908 return false;
911 if ($something instanceof part_of_admin_tree) {
912 if (!($parent instanceof parentable_part_of_admin_tree)) {
913 debugging('error - parts of tree can be inserted only into parentable parts');
914 return false;
916 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
917 // The name of the node is already used, simply warn the developer that this should not happen.
918 // It is intentional to check for the debug level before performing the check.
919 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
921 if (is_null($beforesibling)) {
922 // Append $something as the parent's last child.
923 $parent->children[] = $something;
924 } else {
925 if (!is_string($beforesibling) or trim($beforesibling) === '') {
926 throw new coding_exception('Unexpected value of the beforesibling parameter');
928 // Try to find the position of the sibling.
929 $siblingposition = null;
930 foreach ($parent->children as $childposition => $child) {
931 if ($child->name === $beforesibling) {
932 $siblingposition = $childposition;
933 break;
936 if (is_null($siblingposition)) {
937 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
938 $parent->children[] = $something;
939 } else {
940 $parent->children = array_merge(
941 array_slice($parent->children, 0, $siblingposition),
942 array($something),
943 array_slice($parent->children, $siblingposition)
947 if ($something instanceof admin_category) {
948 if (isset($this->category_cache[$something->name])) {
949 debugging('Duplicate admin category name: '.$something->name);
950 } else {
951 $this->category_cache[$something->name] = $something;
952 $something->category_cache =& $this->category_cache;
953 foreach ($something->children as $child) {
954 // just in case somebody already added subcategories
955 if ($child instanceof admin_category) {
956 if (isset($this->category_cache[$child->name])) {
957 debugging('Duplicate admin category name: '.$child->name);
958 } else {
959 $this->category_cache[$child->name] = $child;
960 $child->category_cache =& $this->category_cache;
966 return true;
968 } else {
969 debugging('error - can not add this element');
970 return false;
976 * Checks if the user has access to anything in this category.
978 * @return bool True if the user has access to at least one child in this category, false otherwise.
980 public function check_access() {
981 foreach ($this->children as $child) {
982 if ($child->check_access()) {
983 return true;
986 return false;
990 * Is this category hidden in admin tree block?
992 * @return bool True if hidden
994 public function is_hidden() {
995 return $this->hidden;
999 * Show we display Save button at the page bottom?
1000 * @return bool
1002 public function show_save() {
1003 foreach ($this->children as $child) {
1004 if ($child->show_save()) {
1005 return true;
1008 return false;
1012 * Sets sorting on this category.
1014 * Please note this function doesn't actually do the sorting.
1015 * It can be called anytime.
1016 * Sorting occurs when the user calls get_children.
1017 * Code using the children array directly won't see the sorted results.
1019 * @param bool $sort If set to true children will be sorted, if false they won't be.
1020 * @param bool $asc If true sorting will be ascending, otherwise descending.
1021 * @param bool $split If true we sort pages and sub categories separately.
1023 public function set_sorting($sort, $asc = true, $split = true) {
1024 $this->sort = (bool)$sort;
1025 $this->sortasc = (bool)$asc;
1026 $this->sortsplit = (bool)$split;
1030 * Returns the children associated with this category.
1032 * @return part_of_admin_tree[]
1034 public function get_children() {
1035 // If we should sort and it hasn't already been sorted.
1036 if ($this->sort && !$this->sorted) {
1037 if ($this->sortsplit) {
1038 $categories = array();
1039 $pages = array();
1040 foreach ($this->children as $child) {
1041 if ($child instanceof admin_category) {
1042 $categories[] = $child;
1043 } else {
1044 $pages[] = $child;
1047 core_collator::asort_objects_by_property($categories, 'visiblename');
1048 core_collator::asort_objects_by_property($pages, 'visiblename');
1049 if (!$this->sortasc) {
1050 $categories = array_reverse($categories);
1051 $pages = array_reverse($pages);
1053 $this->children = array_merge($pages, $categories);
1054 } else {
1055 core_collator::asort_objects_by_property($this->children, 'visiblename');
1056 if (!$this->sortasc) {
1057 $this->children = array_reverse($this->children);
1060 $this->sorted = true;
1062 return $this->children;
1066 * Magically gets a property from this object.
1068 * @param $property
1069 * @return part_of_admin_tree[]
1070 * @throws coding_exception
1072 public function __get($property) {
1073 if ($property === 'children') {
1074 return $this->get_children();
1076 throw new coding_exception('Invalid property requested.');
1080 * Magically sets a property against this object.
1082 * @param string $property
1083 * @param mixed $value
1084 * @throws coding_exception
1086 public function __set($property, $value) {
1087 if ($property === 'children') {
1088 $this->sorted = false;
1089 $this->children = $value;
1090 } else {
1091 throw new coding_exception('Invalid property requested.');
1096 * Checks if an inaccessible property is set.
1098 * @param string $property
1099 * @return bool
1100 * @throws coding_exception
1102 public function __isset($property) {
1103 if ($property === 'children') {
1104 return isset($this->children);
1106 throw new coding_exception('Invalid property requested.');
1112 * Root of admin settings tree, does not have any parent.
1114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1116 class admin_root extends admin_category {
1117 /** @var array List of errors */
1118 public $errors;
1119 /** @var string search query */
1120 public $search;
1121 /** @var bool full tree flag - true means all settings required, false only pages required */
1122 public $fulltree;
1123 /** @var bool flag indicating loaded tree */
1124 public $loaded;
1125 /** @var mixed site custom defaults overriding defaults in settings files*/
1126 public $custom_defaults;
1129 * @param bool $fulltree true means all settings required,
1130 * false only pages required
1132 public function __construct($fulltree) {
1133 global $CFG;
1135 parent::__construct('root', get_string('administration'), false);
1136 $this->errors = array();
1137 $this->search = '';
1138 $this->fulltree = $fulltree;
1139 $this->loaded = false;
1141 $this->category_cache = array();
1143 // load custom defaults if found
1144 $this->custom_defaults = null;
1145 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1146 if (is_readable($defaultsfile)) {
1147 $defaults = array();
1148 include($defaultsfile);
1149 if (is_array($defaults) and count($defaults)) {
1150 $this->custom_defaults = $defaults;
1156 * Empties children array, and sets loaded to false
1158 * @param bool $requirefulltree
1160 public function purge_children($requirefulltree) {
1161 $this->children = array();
1162 $this->fulltree = ($requirefulltree || $this->fulltree);
1163 $this->loaded = false;
1164 //break circular dependencies - this helps PHP 5.2
1165 while($this->category_cache) {
1166 array_pop($this->category_cache);
1168 $this->category_cache = array();
1174 * Links external PHP pages into the admin tree.
1176 * See detailed usage example at the top of this document (adminlib.php)
1178 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1180 class admin_externalpage implements part_of_admin_tree {
1182 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1183 public $name;
1185 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1186 public $visiblename;
1188 /** @var string The external URL that we should link to when someone requests this external page. */
1189 public $url;
1191 /** @var string The role capability/permission a user must have to access this external page. */
1192 public $req_capability;
1194 /** @var object The context in which capability/permission should be checked, default is site context. */
1195 public $context;
1197 /** @var bool hidden in admin tree block. */
1198 public $hidden;
1200 /** @var mixed either string or array of string */
1201 public $path;
1203 /** @var array list of visible names of page parents */
1204 public $visiblepath;
1207 * Constructor for adding an external page into the admin tree.
1209 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1210 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1211 * @param string $url The external URL that we should link to when someone requests this external page.
1212 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1213 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1214 * @param stdClass $context The context the page relates to. Not sure what happens
1215 * if you specify something other than system or front page. Defaults to system.
1217 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1218 $this->name = $name;
1219 $this->visiblename = $visiblename;
1220 $this->url = $url;
1221 if (is_array($req_capability)) {
1222 $this->req_capability = $req_capability;
1223 } else {
1224 $this->req_capability = array($req_capability);
1226 $this->hidden = $hidden;
1227 $this->context = $context;
1231 * Returns a reference to the part_of_admin_tree object with internal name $name.
1233 * @param string $name The internal name of the object we want.
1234 * @param bool $findpath defaults to false
1235 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1237 public function locate($name, $findpath=false) {
1238 if ($this->name == $name) {
1239 if ($findpath) {
1240 $this->visiblepath = array($this->visiblename);
1241 $this->path = array($this->name);
1243 return $this;
1244 } else {
1245 $return = NULL;
1246 return $return;
1251 * This function always returns false, required function by interface
1253 * @param string $name
1254 * @return false
1256 public function prune($name) {
1257 return false;
1261 * Search using query
1263 * @param string $query
1264 * @return mixed array-object structure of found settings and pages
1266 public function search($query) {
1267 $found = false;
1268 if (strpos(strtolower($this->name), $query) !== false) {
1269 $found = true;
1270 } else if (strpos(core_text::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 * Determines if the current user has access to this external page based on $this->req_capability.
1286 * @return bool True if user has access, false otherwise.
1288 public function check_access() {
1289 global $CFG;
1290 $context = empty($this->context) ? context_system::instance() : $this->context;
1291 foreach($this->req_capability as $cap) {
1292 if (has_capability($cap, $context)) {
1293 return true;
1296 return false;
1300 * Is this external page hidden in admin tree block?
1302 * @return bool True if hidden
1304 public function is_hidden() {
1305 return $this->hidden;
1309 * Show we display Save button at the page bottom?
1310 * @return bool
1312 public function show_save() {
1313 return false;
1319 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1323 class admin_settingpage implements part_of_admin_tree {
1325 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1326 public $name;
1328 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1329 public $visiblename;
1331 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1332 public $settings;
1334 /** @var string The role capability/permission a user must have to access this external page. */
1335 public $req_capability;
1337 /** @var object The context in which capability/permission should be checked, default is site context. */
1338 public $context;
1340 /** @var bool hidden in admin tree block. */
1341 public $hidden;
1343 /** @var mixed string of paths or array of strings of paths */
1344 public $path;
1346 /** @var array list of visible names of page parents */
1347 public $visiblepath;
1350 * see admin_settingpage for details of this function
1352 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1353 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1354 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1355 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1356 * @param stdClass $context The context the page relates to. Not sure what happens
1357 * if you specify something other than system or front page. Defaults to system.
1359 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1360 $this->settings = new stdClass();
1361 $this->name = $name;
1362 $this->visiblename = $visiblename;
1363 if (is_array($req_capability)) {
1364 $this->req_capability = $req_capability;
1365 } else {
1366 $this->req_capability = array($req_capability);
1368 $this->hidden = $hidden;
1369 $this->context = $context;
1373 * see admin_category
1375 * @param string $name
1376 * @param bool $findpath
1377 * @return mixed Object (this) if name == this->name, else returns null
1379 public function locate($name, $findpath=false) {
1380 if ($this->name == $name) {
1381 if ($findpath) {
1382 $this->visiblepath = array($this->visiblename);
1383 $this->path = array($this->name);
1385 return $this;
1386 } else {
1387 $return = NULL;
1388 return $return;
1393 * Search string in settings page.
1395 * @param string $query
1396 * @return array
1398 public function search($query) {
1399 $found = array();
1401 foreach ($this->settings as $setting) {
1402 if ($setting->is_related($query)) {
1403 $found[] = $setting;
1407 if ($found) {
1408 $result = new stdClass();
1409 $result->page = $this;
1410 $result->settings = $found;
1411 return array($this->name => $result);
1414 $found = false;
1415 if (strpos(strtolower($this->name), $query) !== false) {
1416 $found = true;
1417 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1418 $found = true;
1420 if ($found) {
1421 $result = new stdClass();
1422 $result->page = $this;
1423 $result->settings = array();
1424 return array($this->name => $result);
1425 } else {
1426 return array();
1431 * This function always returns false, required by interface
1433 * @param string $name
1434 * @return bool Always false
1436 public function prune($name) {
1437 return false;
1441 * adds an admin_setting to this admin_settingpage
1443 * 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
1444 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1446 * @param object $setting is the admin_setting object you want to add
1447 * @return bool true if successful, false if not
1449 public function add($setting) {
1450 if (!($setting instanceof admin_setting)) {
1451 debugging('error - not a setting instance');
1452 return false;
1455 $this->settings->{$setting->name} = $setting;
1456 return true;
1460 * see admin_externalpage
1462 * @return bool Returns true for yes false for no
1464 public function check_access() {
1465 global $CFG;
1466 $context = empty($this->context) ? context_system::instance() : $this->context;
1467 foreach($this->req_capability as $cap) {
1468 if (has_capability($cap, $context)) {
1469 return true;
1472 return false;
1476 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1477 * @return string Returns an XHTML string
1479 public function output_html() {
1480 $adminroot = admin_get_root();
1481 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1482 foreach($this->settings as $setting) {
1483 $fullname = $setting->get_full_name();
1484 if (array_key_exists($fullname, $adminroot->errors)) {
1485 $data = $adminroot->errors[$fullname]->data;
1486 } else {
1487 $data = $setting->get_setting();
1488 // do not use defaults if settings not available - upgrade settings handles the defaults!
1490 $return .= $setting->output_html($data);
1492 $return .= '</fieldset>';
1493 return $return;
1497 * Is this settings page hidden in admin tree block?
1499 * @return bool True if hidden
1501 public function is_hidden() {
1502 return $this->hidden;
1506 * Show we display Save button at the page bottom?
1507 * @return bool
1509 public function show_save() {
1510 foreach($this->settings as $setting) {
1511 if (empty($setting->nosave)) {
1512 return true;
1515 return false;
1521 * Admin settings class. Only exists on setting pages.
1522 * Read & write happens at this level; no authentication.
1524 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1526 abstract class admin_setting {
1527 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1528 public $name;
1529 /** @var string localised name */
1530 public $visiblename;
1531 /** @var string localised long description in Markdown format */
1532 public $description;
1533 /** @var mixed Can be string or array of string */
1534 public $defaultsetting;
1535 /** @var string */
1536 public $updatedcallback;
1537 /** @var mixed can be String or Null. Null means main config table */
1538 public $plugin; // null means main config table
1539 /** @var bool true indicates this setting does not actually save anything, just information */
1540 public $nosave = false;
1541 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1542 public $affectsmodinfo = false;
1543 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1544 private $flags = array();
1547 * Constructor
1548 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1549 * or 'myplugin/mysetting' for ones in config_plugins.
1550 * @param string $visiblename localised name
1551 * @param string $description localised long description
1552 * @param mixed $defaultsetting string or array depending on implementation
1554 public function __construct($name, $visiblename, $description, $defaultsetting) {
1555 $this->parse_setting_name($name);
1556 $this->visiblename = $visiblename;
1557 $this->description = $description;
1558 $this->defaultsetting = $defaultsetting;
1562 * Generic function to add a flag to this admin setting.
1564 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1565 * @param bool $default - The default for the flag
1566 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1567 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1569 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1570 if (empty($this->flags[$shortname])) {
1571 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1572 } else {
1573 $this->flags[$shortname]->set_options($enabled, $default);
1578 * Set the enabled options flag on this admin setting.
1580 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1581 * @param bool $default - The default for the flag
1583 public function set_enabled_flag_options($enabled, $default) {
1584 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1588 * Set the advanced options flag on this admin setting.
1590 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1591 * @param bool $default - The default for the flag
1593 public function set_advanced_flag_options($enabled, $default) {
1594 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1599 * Set the locked options flag on this admin setting.
1601 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1602 * @param bool $default - The default for the flag
1604 public function set_locked_flag_options($enabled, $default) {
1605 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1609 * Get the currently saved value for a setting flag
1611 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1612 * @return bool
1614 public function get_setting_flag_value(admin_setting_flag $flag) {
1615 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1616 if (!isset($value)) {
1617 $value = $flag->get_default();
1620 return !empty($value);
1624 * Get the list of defaults for the flags on this setting.
1626 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1628 public function get_setting_flag_defaults(& $defaults) {
1629 foreach ($this->flags as $flag) {
1630 if ($flag->is_enabled() && $flag->get_default()) {
1631 $defaults[] = $flag->get_displayname();
1637 * Output the input fields for the advanced and locked flags on this setting.
1639 * @param bool $adv - The current value of the advanced flag.
1640 * @param bool $locked - The current value of the locked flag.
1641 * @return string $output - The html for the flags.
1643 public function output_setting_flags() {
1644 $output = '';
1646 foreach ($this->flags as $flag) {
1647 if ($flag->is_enabled()) {
1648 $output .= $flag->output_setting_flag($this);
1652 if (!empty($output)) {
1653 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1655 return $output;
1659 * Write the values of the flags for this admin setting.
1661 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1662 * @return bool - true if successful.
1664 public function write_setting_flags($data) {
1665 $result = true;
1666 foreach ($this->flags as $flag) {
1667 $result = $result && $flag->write_setting_flag($this, $data);
1669 return $result;
1673 * Set up $this->name and potentially $this->plugin
1675 * Set up $this->name and possibly $this->plugin based on whether $name looks
1676 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1677 * on the names, that is, output a developer debug warning if the name
1678 * contains anything other than [a-zA-Z0-9_]+.
1680 * @param string $name the setting name passed in to the constructor.
1682 private function parse_setting_name($name) {
1683 $bits = explode('/', $name);
1684 if (count($bits) > 2) {
1685 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1687 $this->name = array_pop($bits);
1688 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1689 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1691 if (!empty($bits)) {
1692 $this->plugin = array_pop($bits);
1693 if ($this->plugin === 'moodle') {
1694 $this->plugin = null;
1695 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1702 * Returns the fullname prefixed by the plugin
1703 * @return string
1705 public function get_full_name() {
1706 return 's_'.$this->plugin.'_'.$this->name;
1710 * Returns the ID string based on plugin and name
1711 * @return string
1713 public function get_id() {
1714 return 'id_s_'.$this->plugin.'_'.$this->name;
1718 * @param bool $affectsmodinfo If true, changes to this setting will
1719 * cause the course cache to be rebuilt
1721 public function set_affects_modinfo($affectsmodinfo) {
1722 $this->affectsmodinfo = $affectsmodinfo;
1726 * Returns the config if possible
1728 * @return mixed returns config if successful else null
1730 public function config_read($name) {
1731 global $CFG;
1732 if (!empty($this->plugin)) {
1733 $value = get_config($this->plugin, $name);
1734 return $value === false ? NULL : $value;
1736 } else {
1737 if (isset($CFG->$name)) {
1738 return $CFG->$name;
1739 } else {
1740 return NULL;
1746 * Used to set a config pair and log change
1748 * @param string $name
1749 * @param mixed $value Gets converted to string if not null
1750 * @return bool Write setting to config table
1752 public function config_write($name, $value) {
1753 global $DB, $USER, $CFG;
1755 if ($this->nosave) {
1756 return true;
1759 // make sure it is a real change
1760 $oldvalue = get_config($this->plugin, $name);
1761 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1762 $value = is_null($value) ? null : (string)$value;
1764 if ($oldvalue === $value) {
1765 return true;
1768 // store change
1769 set_config($name, $value, $this->plugin);
1771 // Some admin settings affect course modinfo
1772 if ($this->affectsmodinfo) {
1773 // Clear course cache for all courses
1774 rebuild_course_cache(0, true);
1777 $this->add_to_config_log($name, $oldvalue, $value);
1779 return true; // BC only
1783 * Log config changes if necessary.
1784 * @param string $name
1785 * @param string $oldvalue
1786 * @param string $value
1788 protected function add_to_config_log($name, $oldvalue, $value) {
1789 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1793 * Returns current value of this setting
1794 * @return mixed array or string depending on instance, NULL means not set yet
1796 public abstract function get_setting();
1799 * Returns default setting if exists
1800 * @return mixed array or string depending on instance; NULL means no default, user must supply
1802 public function get_defaultsetting() {
1803 $adminroot = admin_get_root(false, false);
1804 if (!empty($adminroot->custom_defaults)) {
1805 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1806 if (isset($adminroot->custom_defaults[$plugin])) {
1807 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1808 return $adminroot->custom_defaults[$plugin][$this->name];
1812 return $this->defaultsetting;
1816 * Store new setting
1818 * @param mixed $data string or array, must not be NULL
1819 * @return string empty string if ok, string error message otherwise
1821 public abstract function write_setting($data);
1824 * Return part of form with setting
1825 * This function should always be overwritten
1827 * @param mixed $data array or string depending on setting
1828 * @param string $query
1829 * @return string
1831 public function output_html($data, $query='') {
1832 // should be overridden
1833 return;
1837 * Function called if setting updated - cleanup, cache reset, etc.
1838 * @param string $functionname Sets the function name
1839 * @return void
1841 public function set_updatedcallback($functionname) {
1842 $this->updatedcallback = $functionname;
1846 * Execute postupdatecallback if necessary.
1847 * @param mixed $original original value before write_setting()
1848 * @return bool true if changed, false if not.
1850 public function post_write_settings($original) {
1851 // Comparison must work for arrays too.
1852 if (serialize($original) === serialize($this->get_setting())) {
1853 return false;
1856 $callbackfunction = $this->updatedcallback;
1857 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1858 $callbackfunction($this->get_full_name());
1860 return true;
1864 * Is setting related to query text - used when searching
1865 * @param string $query
1866 * @return bool
1868 public function is_related($query) {
1869 if (strpos(strtolower($this->name), $query) !== false) {
1870 return true;
1872 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1873 return true;
1875 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1876 return true;
1878 $current = $this->get_setting();
1879 if (!is_null($current)) {
1880 if (is_string($current)) {
1881 if (strpos(core_text::strtolower($current), $query) !== false) {
1882 return true;
1886 $default = $this->get_defaultsetting();
1887 if (!is_null($default)) {
1888 if (is_string($default)) {
1889 if (strpos(core_text::strtolower($default), $query) !== false) {
1890 return true;
1894 return false;
1899 * An additional option that can be applied to an admin setting.
1900 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1904 class admin_setting_flag {
1905 /** @var bool Flag to indicate if this option can be toggled for this setting */
1906 private $enabled = false;
1907 /** @var bool Flag to indicate if this option defaults to true or false */
1908 private $default = false;
1909 /** @var string Short string used to create setting name - e.g. 'adv' */
1910 private $shortname = '';
1911 /** @var string String used as the label for this flag */
1912 private $displayname = '';
1913 /** @const Checkbox for this flag is displayed in admin page */
1914 const ENABLED = true;
1915 /** @const Checkbox for this flag is not displayed in admin page */
1916 const DISABLED = false;
1919 * Constructor
1921 * @param bool $enabled Can this option can be toggled.
1922 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1923 * @param bool $default The default checked state for this setting option.
1924 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1925 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1927 public function __construct($enabled, $default, $shortname, $displayname) {
1928 $this->shortname = $shortname;
1929 $this->displayname = $displayname;
1930 $this->set_options($enabled, $default);
1934 * Update the values of this setting options class
1936 * @param bool $enabled Can this option can be toggled.
1937 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1938 * @param bool $default The default checked state for this setting option.
1940 public function set_options($enabled, $default) {
1941 $this->enabled = $enabled;
1942 $this->default = $default;
1946 * Should this option appear in the interface and be toggleable?
1948 * @return bool Is it enabled?
1950 public function is_enabled() {
1951 return $this->enabled;
1955 * Should this option be checked by default?
1957 * @return bool Is it on by default?
1959 public function get_default() {
1960 return $this->default;
1964 * Return the short name for this flag. e.g. 'adv' or 'locked'
1966 * @return string
1968 public function get_shortname() {
1969 return $this->shortname;
1973 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1975 * @return string
1977 public function get_displayname() {
1978 return $this->displayname;
1982 * Save the submitted data for this flag - or set it to the default if $data is null.
1984 * @param admin_setting $setting - The admin setting for this flag
1985 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1986 * @return bool
1988 public function write_setting_flag(admin_setting $setting, $data) {
1989 $result = true;
1990 if ($this->is_enabled()) {
1991 if (!isset($data)) {
1992 $value = $this->get_default();
1993 } else {
1994 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
1996 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
1999 return $result;
2004 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2006 * @param admin_setting $setting - The admin setting for this flag
2007 * @return string - The html for the checkbox.
2009 public function output_setting_flag(admin_setting $setting) {
2010 $value = $setting->get_setting_flag_value($this);
2011 $output = ' <input type="checkbox" class="form-checkbox" ' .
2012 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2013 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2014 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2015 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2016 $this->get_displayname() .
2017 ' </label> ';
2018 return $output;
2024 * No setting - just heading and text.
2026 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2028 class admin_setting_heading extends admin_setting {
2031 * not a setting, just text
2032 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2033 * @param string $heading heading
2034 * @param string $information text in box
2036 public function __construct($name, $heading, $information) {
2037 $this->nosave = true;
2038 parent::__construct($name, $heading, $information, '');
2042 * Always returns true
2043 * @return bool Always returns true
2045 public function get_setting() {
2046 return true;
2050 * Always returns true
2051 * @return bool Always returns true
2053 public function get_defaultsetting() {
2054 return true;
2058 * Never write settings
2059 * @return string Always returns an empty string
2061 public function write_setting($data) {
2062 // do not write any setting
2063 return '';
2067 * Returns an HTML string
2068 * @return string Returns an HTML string
2070 public function output_html($data, $query='') {
2071 global $OUTPUT;
2072 $return = '';
2073 if ($this->visiblename != '') {
2074 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2076 if ($this->description != '') {
2077 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2079 return $return;
2085 * The most flexibly setting, user is typing text
2087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2089 class admin_setting_configtext extends admin_setting {
2091 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2092 public $paramtype;
2093 /** @var int default field size */
2094 public $size;
2097 * Config text constructor
2099 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2100 * @param string $visiblename localised
2101 * @param string $description long localised info
2102 * @param string $defaultsetting
2103 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2104 * @param int $size default field size
2106 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2107 $this->paramtype = $paramtype;
2108 if (!is_null($size)) {
2109 $this->size = $size;
2110 } else {
2111 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2113 parent::__construct($name, $visiblename, $description, $defaultsetting);
2117 * Return the setting
2119 * @return mixed returns config if successful else null
2121 public function get_setting() {
2122 return $this->config_read($this->name);
2125 public function write_setting($data) {
2126 if ($this->paramtype === PARAM_INT and $data === '') {
2127 // do not complain if '' used instead of 0
2128 $data = 0;
2130 // $data is a string
2131 $validated = $this->validate($data);
2132 if ($validated !== true) {
2133 return $validated;
2135 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2139 * Validate data before storage
2140 * @param string data
2141 * @return mixed true if ok string if error found
2143 public function validate($data) {
2144 // allow paramtype to be a custom regex if it is the form of /pattern/
2145 if (preg_match('#^/.*/$#', $this->paramtype)) {
2146 if (preg_match($this->paramtype, $data)) {
2147 return true;
2148 } else {
2149 return get_string('validateerror', 'admin');
2152 } else if ($this->paramtype === PARAM_RAW) {
2153 return true;
2155 } else {
2156 $cleaned = clean_param($data, $this->paramtype);
2157 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2158 return true;
2159 } else {
2160 return get_string('validateerror', 'admin');
2166 * Return an XHTML string for the setting
2167 * @return string Returns an XHTML string
2169 public function output_html($data, $query='') {
2170 $default = $this->get_defaultsetting();
2172 return format_admin_setting($this, $this->visiblename,
2173 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2174 $this->description, true, '', $default, $query);
2180 * General text area without html editor.
2182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2184 class admin_setting_configtextarea extends admin_setting_configtext {
2185 private $rows;
2186 private $cols;
2189 * @param string $name
2190 * @param string $visiblename
2191 * @param string $description
2192 * @param mixed $defaultsetting string or array
2193 * @param mixed $paramtype
2194 * @param string $cols The number of columns to make the editor
2195 * @param string $rows The number of rows to make the editor
2197 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2198 $this->rows = $rows;
2199 $this->cols = $cols;
2200 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2204 * Returns an XHTML string for the editor
2206 * @param string $data
2207 * @param string $query
2208 * @return string XHTML string for the editor
2210 public function output_html($data, $query='') {
2211 $default = $this->get_defaultsetting();
2213 $defaultinfo = $default;
2214 if (!is_null($default) and $default !== '') {
2215 $defaultinfo = "\n".$default;
2218 return format_admin_setting($this, $this->visiblename,
2219 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2220 $this->description, true, '', $defaultinfo, $query);
2226 * General text area with html editor.
2228 class admin_setting_confightmleditor extends admin_setting_configtext {
2229 private $rows;
2230 private $cols;
2233 * @param string $name
2234 * @param string $visiblename
2235 * @param string $description
2236 * @param mixed $defaultsetting string or array
2237 * @param mixed $paramtype
2239 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2240 $this->rows = $rows;
2241 $this->cols = $cols;
2242 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2243 editors_head_setup();
2247 * Returns an XHTML string for the editor
2249 * @param string $data
2250 * @param string $query
2251 * @return string XHTML string for the editor
2253 public function output_html($data, $query='') {
2254 $default = $this->get_defaultsetting();
2256 $defaultinfo = $default;
2257 if (!is_null($default) and $default !== '') {
2258 $defaultinfo = "\n".$default;
2261 $editor = editors_get_preferred_editor(FORMAT_HTML);
2262 $editor->use_editor($this->get_id(), array('noclean'=>true));
2264 return format_admin_setting($this, $this->visiblename,
2265 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2266 $this->description, true, '', $defaultinfo, $query);
2272 * Password field, allows unmasking of password
2274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2276 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2278 * Constructor
2279 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2280 * @param string $visiblename localised
2281 * @param string $description long localised info
2282 * @param string $defaultsetting default password
2284 public function __construct($name, $visiblename, $description, $defaultsetting) {
2285 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2289 * Log config changes if necessary.
2290 * @param string $name
2291 * @param string $oldvalue
2292 * @param string $value
2294 protected function add_to_config_log($name, $oldvalue, $value) {
2295 if ($value !== '') {
2296 $value = '********';
2298 if ($oldvalue !== '' and $oldvalue !== null) {
2299 $oldvalue = '********';
2301 parent::add_to_config_log($name, $oldvalue, $value);
2305 * Returns XHTML for the field
2306 * Writes Javascript into the HTML below right before the last div
2308 * @todo Make javascript available through newer methods if possible
2309 * @param string $data Value for the field
2310 * @param string $query Passed as final argument for format_admin_setting
2311 * @return string XHTML field
2313 public function output_html($data, $query='') {
2314 $id = $this->get_id();
2315 $unmask = get_string('unmaskpassword', 'form');
2316 $unmaskjs = '<script type="text/javascript">
2317 //<![CDATA[
2318 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2320 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2322 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2324 var unmaskchb = document.createElement("input");
2325 unmaskchb.setAttribute("type", "checkbox");
2326 unmaskchb.setAttribute("id", "'.$id.'unmask");
2327 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2328 unmaskdiv.appendChild(unmaskchb);
2330 var unmasklbl = document.createElement("label");
2331 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2332 if (is_ie) {
2333 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2334 } else {
2335 unmasklbl.setAttribute("for", "'.$id.'unmask");
2337 unmaskdiv.appendChild(unmasklbl);
2339 if (is_ie) {
2340 // ugly hack to work around the famous onchange IE bug
2341 unmaskchb.onclick = function() {this.blur();};
2342 unmaskdiv.onclick = function() {this.blur();};
2344 //]]>
2345 </script>';
2346 return format_admin_setting($this, $this->visiblename,
2347 '<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>',
2348 $this->description, true, '', NULL, $query);
2353 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2354 * Note: Only advanced makes sense right now - locked does not.
2356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2358 class admin_setting_configempty extends admin_setting_configtext {
2361 * @param string $name
2362 * @param string $visiblename
2363 * @param string $description
2365 public function __construct($name, $visiblename, $description) {
2366 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2370 * Returns an XHTML string for the hidden field
2372 * @param string $data
2373 * @param string $query
2374 * @return string XHTML string for the editor
2376 public function output_html($data, $query='') {
2377 return format_admin_setting($this,
2378 $this->visiblename,
2379 '<div class="form-empty" >' .
2380 '<input type="hidden"' .
2381 ' id="'. $this->get_id() .'"' .
2382 ' name="'. $this->get_full_name() .'"' .
2383 ' value=""/></div>',
2384 $this->description,
2385 true,
2387 get_string('none'),
2388 $query);
2394 * Path to directory
2396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2398 class admin_setting_configfile extends admin_setting_configtext {
2400 * Constructor
2401 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2402 * @param string $visiblename localised
2403 * @param string $description long localised info
2404 * @param string $defaultdirectory default directory location
2406 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2407 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2411 * Returns XHTML for the field
2413 * Returns XHTML for the field and also checks whether the file
2414 * specified in $data exists using file_exists()
2416 * @param string $data File name and path to use in value attr
2417 * @param string $query
2418 * @return string XHTML field
2420 public function output_html($data, $query='') {
2421 $default = $this->get_defaultsetting();
2423 if ($data) {
2424 if (file_exists($data)) {
2425 $executable = '<span class="pathok">&#x2714;</span>';
2426 } else {
2427 $executable = '<span class="patherror">&#x2718;</span>';
2429 } else {
2430 $executable = '';
2433 return format_admin_setting($this, $this->visiblename,
2434 '<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>',
2435 $this->description, true, '', $default, $query);
2438 * checks if execpatch has been disabled in config.php
2440 public function write_setting($data) {
2441 global $CFG;
2442 if (!empty($CFG->preventexecpath)) {
2443 return '';
2445 return parent::write_setting($data);
2451 * Path to executable file
2453 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2455 class admin_setting_configexecutable extends admin_setting_configfile {
2458 * Returns an XHTML field
2460 * @param string $data This is the value for the field
2461 * @param string $query
2462 * @return string XHTML field
2464 public function output_html($data, $query='') {
2465 global $CFG;
2466 $default = $this->get_defaultsetting();
2468 if ($data) {
2469 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2470 $executable = '<span class="pathok">&#x2714;</span>';
2471 } else {
2472 $executable = '<span class="patherror">&#x2718;</span>';
2474 } else {
2475 $executable = '';
2477 if (!empty($CFG->preventexecpath)) {
2478 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2481 return format_admin_setting($this, $this->visiblename,
2482 '<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>',
2483 $this->description, true, '', $default, $query);
2489 * Path to directory
2491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2493 class admin_setting_configdirectory extends admin_setting_configfile {
2496 * Returns an XHTML field
2498 * @param string $data This is the value for the field
2499 * @param string $query
2500 * @return string XHTML
2502 public function output_html($data, $query='') {
2503 $default = $this->get_defaultsetting();
2505 if ($data) {
2506 if (file_exists($data) and is_dir($data)) {
2507 $executable = '<span class="pathok">&#x2714;</span>';
2508 } else {
2509 $executable = '<span class="patherror">&#x2718;</span>';
2511 } else {
2512 $executable = '';
2515 return format_admin_setting($this, $this->visiblename,
2516 '<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>',
2517 $this->description, true, '', $default, $query);
2523 * Checkbox
2525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2527 class admin_setting_configcheckbox extends admin_setting {
2528 /** @var string Value used when checked */
2529 public $yes;
2530 /** @var string Value used when not checked */
2531 public $no;
2534 * Constructor
2535 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2536 * @param string $visiblename localised
2537 * @param string $description long localised info
2538 * @param string $defaultsetting
2539 * @param string $yes value used when checked
2540 * @param string $no value used when not checked
2542 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2543 parent::__construct($name, $visiblename, $description, $defaultsetting);
2544 $this->yes = (string)$yes;
2545 $this->no = (string)$no;
2549 * Retrieves the current setting using the objects name
2551 * @return string
2553 public function get_setting() {
2554 return $this->config_read($this->name);
2558 * Sets the value for the setting
2560 * Sets the value for the setting to either the yes or no values
2561 * of the object by comparing $data to yes
2563 * @param mixed $data Gets converted to str for comparison against yes value
2564 * @return string empty string or error
2566 public function write_setting($data) {
2567 if ((string)$data === $this->yes) { // convert to strings before comparison
2568 $data = $this->yes;
2569 } else {
2570 $data = $this->no;
2572 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2576 * Returns an XHTML checkbox field
2578 * @param string $data If $data matches yes then checkbox is checked
2579 * @param string $query
2580 * @return string XHTML field
2582 public function output_html($data, $query='') {
2583 $default = $this->get_defaultsetting();
2585 if (!is_null($default)) {
2586 if ((string)$default === $this->yes) {
2587 $defaultinfo = get_string('checkboxyes', 'admin');
2588 } else {
2589 $defaultinfo = get_string('checkboxno', 'admin');
2591 } else {
2592 $defaultinfo = NULL;
2595 if ((string)$data === $this->yes) { // convert to strings before comparison
2596 $checked = 'checked="checked"';
2597 } else {
2598 $checked = '';
2601 return format_admin_setting($this, $this->visiblename,
2602 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2603 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2604 $this->description, true, '', $defaultinfo, $query);
2610 * Multiple checkboxes, each represents different value, stored in csv format
2612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2614 class admin_setting_configmulticheckbox extends admin_setting {
2615 /** @var array Array of choices value=>label */
2616 public $choices;
2619 * Constructor: uses parent::__construct
2621 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2622 * @param string $visiblename localised
2623 * @param string $description long localised info
2624 * @param array $defaultsetting array of selected
2625 * @param array $choices array of $value=>$label for each checkbox
2627 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2628 $this->choices = $choices;
2629 parent::__construct($name, $visiblename, $description, $defaultsetting);
2633 * This public function may be used in ancestors for lazy loading of choices
2635 * @todo Check if this function is still required content commented out only returns true
2636 * @return bool true if loaded, false if error
2638 public function load_choices() {
2640 if (is_array($this->choices)) {
2641 return true;
2643 .... load choices here
2645 return true;
2649 * Is setting related to query text - used when searching
2651 * @param string $query
2652 * @return bool true on related, false on not or failure
2654 public function is_related($query) {
2655 if (!$this->load_choices() or empty($this->choices)) {
2656 return false;
2658 if (parent::is_related($query)) {
2659 return true;
2662 foreach ($this->choices as $desc) {
2663 if (strpos(core_text::strtolower($desc), $query) !== false) {
2664 return true;
2667 return false;
2671 * Returns the current setting if it is set
2673 * @return mixed null if null, else an array
2675 public function get_setting() {
2676 $result = $this->config_read($this->name);
2678 if (is_null($result)) {
2679 return NULL;
2681 if ($result === '') {
2682 return array();
2684 $enabled = explode(',', $result);
2685 $setting = array();
2686 foreach ($enabled as $option) {
2687 $setting[$option] = 1;
2689 return $setting;
2693 * Saves the setting(s) provided in $data
2695 * @param array $data An array of data, if not array returns empty str
2696 * @return mixed empty string on useless data or bool true=success, false=failed
2698 public function write_setting($data) {
2699 if (!is_array($data)) {
2700 return ''; // ignore it
2702 if (!$this->load_choices() or empty($this->choices)) {
2703 return '';
2705 unset($data['xxxxx']);
2706 $result = array();
2707 foreach ($data as $key => $value) {
2708 if ($value and array_key_exists($key, $this->choices)) {
2709 $result[] = $key;
2712 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2716 * Returns XHTML field(s) as required by choices
2718 * Relies on data being an array should data ever be another valid vartype with
2719 * acceptable value this may cause a warning/error
2720 * if (!is_array($data)) would fix the problem
2722 * @todo Add vartype handling to ensure $data is an array
2724 * @param array $data An array of checked values
2725 * @param string $query
2726 * @return string XHTML field
2728 public function output_html($data, $query='') {
2729 if (!$this->load_choices() or empty($this->choices)) {
2730 return '';
2732 $default = $this->get_defaultsetting();
2733 if (is_null($default)) {
2734 $default = array();
2736 if (is_null($data)) {
2737 $data = array();
2739 $options = array();
2740 $defaults = array();
2741 foreach ($this->choices as $key=>$description) {
2742 if (!empty($data[$key])) {
2743 $checked = 'checked="checked"';
2744 } else {
2745 $checked = '';
2747 if (!empty($default[$key])) {
2748 $defaults[] = $description;
2751 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2752 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2755 if (is_null($default)) {
2756 $defaultinfo = NULL;
2757 } else if (!empty($defaults)) {
2758 $defaultinfo = implode(', ', $defaults);
2759 } else {
2760 $defaultinfo = get_string('none');
2763 $return = '<div class="form-multicheckbox">';
2764 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2765 if ($options) {
2766 $return .= '<ul>';
2767 foreach ($options as $option) {
2768 $return .= '<li>'.$option.'</li>';
2770 $return .= '</ul>';
2772 $return .= '</div>';
2774 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2781 * Multiple checkboxes 2, value stored as string 00101011
2783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2785 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2788 * Returns the setting if set
2790 * @return mixed null if not set, else an array of set settings
2792 public function get_setting() {
2793 $result = $this->config_read($this->name);
2794 if (is_null($result)) {
2795 return NULL;
2797 if (!$this->load_choices()) {
2798 return NULL;
2800 $result = str_pad($result, count($this->choices), '0');
2801 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2802 $setting = array();
2803 foreach ($this->choices as $key=>$unused) {
2804 $value = array_shift($result);
2805 if ($value) {
2806 $setting[$key] = 1;
2809 return $setting;
2813 * Save setting(s) provided in $data param
2815 * @param array $data An array of settings to save
2816 * @return mixed empty string for bad data or bool true=>success, false=>error
2818 public function write_setting($data) {
2819 if (!is_array($data)) {
2820 return ''; // ignore it
2822 if (!$this->load_choices() or empty($this->choices)) {
2823 return '';
2825 $result = '';
2826 foreach ($this->choices as $key=>$unused) {
2827 if (!empty($data[$key])) {
2828 $result .= '1';
2829 } else {
2830 $result .= '0';
2833 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2839 * Select one value from list
2841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2843 class admin_setting_configselect extends admin_setting {
2844 /** @var array Array of choices value=>label */
2845 public $choices;
2848 * Constructor
2849 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2850 * @param string $visiblename localised
2851 * @param string $description long localised info
2852 * @param string|int $defaultsetting
2853 * @param array $choices array of $value=>$label for each selection
2855 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2856 $this->choices = $choices;
2857 parent::__construct($name, $visiblename, $description, $defaultsetting);
2861 * This function may be used in ancestors for lazy loading of choices
2863 * Override this method if loading of choices is expensive, such
2864 * as when it requires multiple db requests.
2866 * @return bool true if loaded, false if error
2868 public function load_choices() {
2870 if (is_array($this->choices)) {
2871 return true;
2873 .... load choices here
2875 return true;
2879 * Check if this is $query is related to a choice
2881 * @param string $query
2882 * @return bool true if related, false if not
2884 public function is_related($query) {
2885 if (parent::is_related($query)) {
2886 return true;
2888 if (!$this->load_choices()) {
2889 return false;
2891 foreach ($this->choices as $key=>$value) {
2892 if (strpos(core_text::strtolower($key), $query) !== false) {
2893 return true;
2895 if (strpos(core_text::strtolower($value), $query) !== false) {
2896 return true;
2899 return false;
2903 * Return the setting
2905 * @return mixed returns config if successful else null
2907 public function get_setting() {
2908 return $this->config_read($this->name);
2912 * Save a setting
2914 * @param string $data
2915 * @return string empty of error string
2917 public function write_setting($data) {
2918 if (!$this->load_choices() or empty($this->choices)) {
2919 return '';
2921 if (!array_key_exists($data, $this->choices)) {
2922 return ''; // ignore it
2925 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2929 * Returns XHTML select field
2931 * Ensure the options are loaded, and generate the XHTML for the select
2932 * element and any warning message. Separating this out from output_html
2933 * makes it easier to subclass this class.
2935 * @param string $data the option to show as selected.
2936 * @param string $current the currently selected option in the database, null if none.
2937 * @param string $default the default selected option.
2938 * @return array the HTML for the select element, and a warning message.
2940 public function output_select_html($data, $current, $default, $extraname = '') {
2941 if (!$this->load_choices() or empty($this->choices)) {
2942 return array('', '');
2945 $warning = '';
2946 if (is_null($current)) {
2947 // first run
2948 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2949 // no warning
2950 } else if (!array_key_exists($current, $this->choices)) {
2951 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2952 if (!is_null($default) and $data == $current) {
2953 $data = $default; // use default instead of first value when showing the form
2957 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2958 foreach ($this->choices as $key => $value) {
2959 // the string cast is needed because key may be integer - 0 is equal to most strings!
2960 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2962 $selecthtml .= '</select>';
2963 return array($selecthtml, $warning);
2967 * Returns XHTML select field and wrapping div(s)
2969 * @see output_select_html()
2971 * @param string $data the option to show as selected
2972 * @param string $query
2973 * @return string XHTML field and wrapping div
2975 public function output_html($data, $query='') {
2976 $default = $this->get_defaultsetting();
2977 $current = $this->get_setting();
2979 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2980 if (!$selecthtml) {
2981 return '';
2984 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2985 $defaultinfo = $this->choices[$default];
2986 } else {
2987 $defaultinfo = NULL;
2990 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2992 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2998 * Select multiple items from list
3000 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3002 class admin_setting_configmultiselect extends admin_setting_configselect {
3004 * Constructor
3005 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3006 * @param string $visiblename localised
3007 * @param string $description long localised info
3008 * @param array $defaultsetting array of selected items
3009 * @param array $choices array of $value=>$label for each list item
3011 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3012 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3016 * Returns the select setting(s)
3018 * @return mixed null or array. Null if no settings else array of setting(s)
3020 public function get_setting() {
3021 $result = $this->config_read($this->name);
3022 if (is_null($result)) {
3023 return NULL;
3025 if ($result === '') {
3026 return array();
3028 return explode(',', $result);
3032 * Saves setting(s) provided through $data
3034 * Potential bug in the works should anyone call with this function
3035 * using a vartype that is not an array
3037 * @param array $data
3039 public function write_setting($data) {
3040 if (!is_array($data)) {
3041 return ''; //ignore it
3043 if (!$this->load_choices() or empty($this->choices)) {
3044 return '';
3047 unset($data['xxxxx']);
3049 $save = array();
3050 foreach ($data as $value) {
3051 if (!array_key_exists($value, $this->choices)) {
3052 continue; // ignore it
3054 $save[] = $value;
3057 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3061 * Is setting related to query text - used when searching
3063 * @param string $query
3064 * @return bool true if related, false if not
3066 public function is_related($query) {
3067 if (!$this->load_choices() or empty($this->choices)) {
3068 return false;
3070 if (parent::is_related($query)) {
3071 return true;
3074 foreach ($this->choices as $desc) {
3075 if (strpos(core_text::strtolower($desc), $query) !== false) {
3076 return true;
3079 return false;
3083 * Returns XHTML multi-select field
3085 * @todo Add vartype handling to ensure $data is an array
3086 * @param array $data Array of values to select by default
3087 * @param string $query
3088 * @return string XHTML multi-select field
3090 public function output_html($data, $query='') {
3091 if (!$this->load_choices() or empty($this->choices)) {
3092 return '';
3094 $choices = $this->choices;
3095 $default = $this->get_defaultsetting();
3096 if (is_null($default)) {
3097 $default = array();
3099 if (is_null($data)) {
3100 $data = array();
3103 $defaults = array();
3104 $size = min(10, count($this->choices));
3105 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3106 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3107 foreach ($this->choices as $key => $description) {
3108 if (in_array($key, $data)) {
3109 $selected = 'selected="selected"';
3110 } else {
3111 $selected = '';
3113 if (in_array($key, $default)) {
3114 $defaults[] = $description;
3117 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3120 if (is_null($default)) {
3121 $defaultinfo = NULL;
3122 } if (!empty($defaults)) {
3123 $defaultinfo = implode(', ', $defaults);
3124 } else {
3125 $defaultinfo = get_string('none');
3128 $return .= '</select></div>';
3129 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3134 * Time selector
3136 * This is a liiitle bit messy. we're using two selects, but we're returning
3137 * them as an array named after $name (so we only use $name2 internally for the setting)
3139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3141 class admin_setting_configtime extends admin_setting {
3142 /** @var string Used for setting second select (minutes) */
3143 public $name2;
3146 * Constructor
3147 * @param string $hoursname setting for hours
3148 * @param string $minutesname setting for hours
3149 * @param string $visiblename localised
3150 * @param string $description long localised info
3151 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3153 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3154 $this->name2 = $minutesname;
3155 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3159 * Get the selected time
3161 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3163 public function get_setting() {
3164 $result1 = $this->config_read($this->name);
3165 $result2 = $this->config_read($this->name2);
3166 if (is_null($result1) or is_null($result2)) {
3167 return NULL;
3170 return array('h' => $result1, 'm' => $result2);
3174 * Store the time (hours and minutes)
3176 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3177 * @return bool true if success, false if not
3179 public function write_setting($data) {
3180 if (!is_array($data)) {
3181 return '';
3184 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3185 return ($result ? '' : get_string('errorsetting', 'admin'));
3189 * Returns XHTML time select fields
3191 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3192 * @param string $query
3193 * @return string XHTML time select fields and wrapping div(s)
3195 public function output_html($data, $query='') {
3196 $default = $this->get_defaultsetting();
3198 if (is_array($default)) {
3199 $defaultinfo = $default['h'].':'.$default['m'];
3200 } else {
3201 $defaultinfo = NULL;
3204 $return = '<div class="form-time defaultsnext">'.
3205 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
3206 for ($i = 0; $i < 24; $i++) {
3207 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3209 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
3210 for ($i = 0; $i < 60; $i += 5) {
3211 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3213 $return .= '</select></div>';
3214 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3221 * Seconds duration setting.
3223 * @copyright 2012 Petr Skoda (http://skodak.org)
3224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3226 class admin_setting_configduration extends admin_setting {
3228 /** @var int default duration unit */
3229 protected $defaultunit;
3232 * Constructor
3233 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3234 * or 'myplugin/mysetting' for ones in config_plugins.
3235 * @param string $visiblename localised name
3236 * @param string $description localised long description
3237 * @param mixed $defaultsetting string or array depending on implementation
3238 * @param int $defaultunit - day, week, etc. (in seconds)
3240 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3241 if (is_number($defaultsetting)) {
3242 $defaultsetting = self::parse_seconds($defaultsetting);
3244 $units = self::get_units();
3245 if (isset($units[$defaultunit])) {
3246 $this->defaultunit = $defaultunit;
3247 } else {
3248 $this->defaultunit = 86400;
3250 parent::__construct($name, $visiblename, $description, $defaultsetting);
3254 * Returns selectable units.
3255 * @static
3256 * @return array
3258 protected static function get_units() {
3259 return array(
3260 604800 => get_string('weeks'),
3261 86400 => get_string('days'),
3262 3600 => get_string('hours'),
3263 60 => get_string('minutes'),
3264 1 => get_string('seconds'),
3269 * Converts seconds to some more user friendly string.
3270 * @static
3271 * @param int $seconds
3272 * @return string
3274 protected static function get_duration_text($seconds) {
3275 if (empty($seconds)) {
3276 return get_string('none');
3278 $data = self::parse_seconds($seconds);
3279 switch ($data['u']) {
3280 case (60*60*24*7):
3281 return get_string('numweeks', '', $data['v']);
3282 case (60*60*24):
3283 return get_string('numdays', '', $data['v']);
3284 case (60*60):
3285 return get_string('numhours', '', $data['v']);
3286 case (60):
3287 return get_string('numminutes', '', $data['v']);
3288 default:
3289 return get_string('numseconds', '', $data['v']*$data['u']);
3294 * Finds suitable units for given duration.
3295 * @static
3296 * @param int $seconds
3297 * @return array
3299 protected static function parse_seconds($seconds) {
3300 foreach (self::get_units() as $unit => $unused) {
3301 if ($seconds % $unit === 0) {
3302 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3305 return array('v'=>(int)$seconds, 'u'=>1);
3309 * Get the selected duration as array.
3311 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3313 public function get_setting() {
3314 $seconds = $this->config_read($this->name);
3315 if (is_null($seconds)) {
3316 return null;
3319 return self::parse_seconds($seconds);
3323 * Store the duration as seconds.
3325 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3326 * @return bool true if success, false if not
3328 public function write_setting($data) {
3329 if (!is_array($data)) {
3330 return '';
3333 $seconds = (int)($data['v']*$data['u']);
3334 if ($seconds < 0) {
3335 return get_string('errorsetting', 'admin');
3338 $result = $this->config_write($this->name, $seconds);
3339 return ($result ? '' : get_string('errorsetting', 'admin'));
3343 * Returns duration text+select fields.
3345 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3346 * @param string $query
3347 * @return string duration text+select fields and wrapping div(s)
3349 public function output_html($data, $query='') {
3350 $default = $this->get_defaultsetting();
3352 if (is_number($default)) {
3353 $defaultinfo = self::get_duration_text($default);
3354 } else if (is_array($default)) {
3355 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3356 } else {
3357 $defaultinfo = null;
3360 $units = self::get_units();
3362 $return = '<div class="form-duration defaultsnext">';
3363 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3364 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3365 foreach ($units as $val => $text) {
3366 $selected = '';
3367 if ($data['v'] == 0) {
3368 if ($val == $this->defaultunit) {
3369 $selected = ' selected="selected"';
3371 } else if ($val == $data['u']) {
3372 $selected = ' selected="selected"';
3374 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3376 $return .= '</select></div>';
3377 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3383 * Used to validate a textarea used for ip addresses
3385 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3387 class admin_setting_configiplist extends admin_setting_configtextarea {
3390 * Validate the contents of the textarea as IP addresses
3392 * Used to validate a new line separated list of IP addresses collected from
3393 * a textarea control
3395 * @param string $data A list of IP Addresses separated by new lines
3396 * @return mixed bool true for success or string:error on failure
3398 public function validate($data) {
3399 if(!empty($data)) {
3400 $ips = explode("\n", $data);
3401 } else {
3402 return true;
3404 $result = true;
3405 foreach($ips as $ip) {
3406 $ip = trim($ip);
3407 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3408 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3409 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3410 $result = true;
3411 } else {
3412 $result = false;
3413 break;
3416 if($result) {
3417 return true;
3418 } else {
3419 return get_string('validateerror', 'admin');
3426 * An admin setting for selecting one or more users who have a capability
3427 * in the system context
3429 * An admin setting for selecting one or more users, who have a particular capability
3430 * in the system context. Warning, make sure the list will never be too long. There is
3431 * no paging or searching of this list.
3433 * To correctly get a list of users from this config setting, you need to call the
3434 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3438 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3439 /** @var string The capabilities name */
3440 protected $capability;
3441 /** @var int include admin users too */
3442 protected $includeadmins;
3445 * Constructor.
3447 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3448 * @param string $visiblename localised name
3449 * @param string $description localised long description
3450 * @param array $defaultsetting array of usernames
3451 * @param string $capability string capability name.
3452 * @param bool $includeadmins include administrators
3454 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3455 $this->capability = $capability;
3456 $this->includeadmins = $includeadmins;
3457 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3461 * Load all of the uses who have the capability into choice array
3463 * @return bool Always returns true
3465 function load_choices() {
3466 if (is_array($this->choices)) {
3467 return true;
3469 list($sort, $sortparams) = users_order_by_sql('u');
3470 if (!empty($sortparams)) {
3471 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3472 'This is unexpected, and a problem because there is no way to pass these ' .
3473 'parameters to get_users_by_capability. See MDL-34657.');
3475 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3476 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3477 $this->choices = array(
3478 '$@NONE@$' => get_string('nobody'),
3479 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3481 if ($this->includeadmins) {
3482 $admins = get_admins();
3483 foreach ($admins as $user) {
3484 $this->choices[$user->id] = fullname($user);
3487 if (is_array($users)) {
3488 foreach ($users as $user) {
3489 $this->choices[$user->id] = fullname($user);
3492 return true;
3496 * Returns the default setting for class
3498 * @return mixed Array, or string. Empty string if no default
3500 public function get_defaultsetting() {
3501 $this->load_choices();
3502 $defaultsetting = parent::get_defaultsetting();
3503 if (empty($defaultsetting)) {
3504 return array('$@NONE@$');
3505 } else if (array_key_exists($defaultsetting, $this->choices)) {
3506 return $defaultsetting;
3507 } else {
3508 return '';
3513 * Returns the current setting
3515 * @return mixed array or string
3517 public function get_setting() {
3518 $result = parent::get_setting();
3519 if ($result === null) {
3520 // this is necessary for settings upgrade
3521 return null;
3523 if (empty($result)) {
3524 $result = array('$@NONE@$');
3526 return $result;
3530 * Save the chosen setting provided as $data
3532 * @param array $data
3533 * @return mixed string or array
3535 public function write_setting($data) {
3536 // If all is selected, remove any explicit options.
3537 if (in_array('$@ALL@$', $data)) {
3538 $data = array('$@ALL@$');
3540 // None never needs to be written to the DB.
3541 if (in_array('$@NONE@$', $data)) {
3542 unset($data[array_search('$@NONE@$', $data)]);
3544 return parent::write_setting($data);
3550 * Special checkbox for calendar - resets SESSION vars.
3552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3554 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3556 * Calls the parent::__construct with default values
3558 * name => calendar_adminseesall
3559 * visiblename => get_string('adminseesall', 'admin')
3560 * description => get_string('helpadminseesall', 'admin')
3561 * defaultsetting => 0
3563 public function __construct() {
3564 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3565 get_string('helpadminseesall', 'admin'), '0');
3569 * Stores the setting passed in $data
3571 * @param mixed gets converted to string for comparison
3572 * @return string empty string or error message
3574 public function write_setting($data) {
3575 global $SESSION;
3576 return parent::write_setting($data);
3581 * Special select for settings that are altered in setup.php and can not be altered on the fly
3583 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3585 class admin_setting_special_selectsetup extends admin_setting_configselect {
3587 * Reads the setting directly from the database
3589 * @return mixed
3591 public function get_setting() {
3592 // read directly from db!
3593 return get_config(NULL, $this->name);
3597 * Save the setting passed in $data
3599 * @param string $data The setting to save
3600 * @return string empty or error message
3602 public function write_setting($data) {
3603 global $CFG;
3604 // do not change active CFG setting!
3605 $current = $CFG->{$this->name};
3606 $result = parent::write_setting($data);
3607 $CFG->{$this->name} = $current;
3608 return $result;
3614 * Special select for frontpage - stores data in course table
3616 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3618 class admin_setting_sitesetselect extends admin_setting_configselect {
3620 * Returns the site name for the selected site
3622 * @see get_site()
3623 * @return string The site name of the selected site
3625 public function get_setting() {
3626 $site = course_get_format(get_site())->get_course();
3627 return $site->{$this->name};
3631 * Updates the database and save the setting
3633 * @param string data
3634 * @return string empty or error message
3636 public function write_setting($data) {
3637 global $DB, $SITE, $COURSE;
3638 if (!in_array($data, array_keys($this->choices))) {
3639 return get_string('errorsetting', 'admin');
3641 $record = new stdClass();
3642 $record->id = SITEID;
3643 $temp = $this->name;
3644 $record->$temp = $data;
3645 $record->timemodified = time();
3647 course_get_format($SITE)->update_course_format_options($record);
3648 $DB->update_record('course', $record);
3650 // Reset caches.
3651 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3652 if ($SITE->id == $COURSE->id) {
3653 $COURSE = $SITE;
3655 format_base::reset_course_cache($SITE->id);
3657 return '';
3664 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3665 * block to hidden.
3667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3669 class admin_setting_bloglevel extends admin_setting_configselect {
3671 * Updates the database and save the setting
3673 * @param string data
3674 * @return string empty or error message
3676 public function write_setting($data) {
3677 global $DB, $CFG;
3678 if ($data == 0) {
3679 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3680 foreach ($blogblocks as $block) {
3681 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3683 } else {
3684 // reenable all blocks only when switching from disabled blogs
3685 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3686 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3687 foreach ($blogblocks as $block) {
3688 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3692 return parent::write_setting($data);
3698 * Special select - lists on the frontpage - hacky
3700 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3702 class admin_setting_courselist_frontpage extends admin_setting {
3703 /** @var array Array of choices value=>label */
3704 public $choices;
3707 * Construct override, requires one param
3709 * @param bool $loggedin Is the user logged in
3711 public function __construct($loggedin) {
3712 global $CFG;
3713 require_once($CFG->dirroot.'/course/lib.php');
3714 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3715 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3716 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3717 $defaults = array(FRONTPAGEALLCOURSELIST);
3718 parent::__construct($name, $visiblename, $description, $defaults);
3722 * Loads the choices available
3724 * @return bool always returns true
3726 public function load_choices() {
3727 if (is_array($this->choices)) {
3728 return true;
3730 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3731 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3732 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3733 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3734 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3735 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3736 'none' => get_string('none'));
3737 if ($this->name === 'frontpage') {
3738 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3740 return true;
3744 * Returns the selected settings
3746 * @param mixed array or setting or null
3748 public function get_setting() {
3749 $result = $this->config_read($this->name);
3750 if (is_null($result)) {
3751 return NULL;
3753 if ($result === '') {
3754 return array();
3756 return explode(',', $result);
3760 * Save the selected options
3762 * @param array $data
3763 * @return mixed empty string (data is not an array) or bool true=success false=failure
3765 public function write_setting($data) {
3766 if (!is_array($data)) {
3767 return '';
3769 $this->load_choices();
3770 $save = array();
3771 foreach($data as $datum) {
3772 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3773 continue;
3775 $save[$datum] = $datum; // no duplicates
3777 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3781 * Return XHTML select field and wrapping div
3783 * @todo Add vartype handling to make sure $data is an array
3784 * @param array $data Array of elements to select by default
3785 * @return string XHTML select field and wrapping div
3787 public function output_html($data, $query='') {
3788 $this->load_choices();
3789 $currentsetting = array();
3790 foreach ($data as $key) {
3791 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3792 $currentsetting[] = $key; // already selected first
3796 $return = '<div class="form-group">';
3797 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3798 if (!array_key_exists($i, $currentsetting)) {
3799 $currentsetting[$i] = 'none'; //none
3801 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3802 foreach ($this->choices as $key => $value) {
3803 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3805 $return .= '</select>';
3806 if ($i !== count($this->choices) - 2) {
3807 $return .= '<br />';
3810 $return .= '</div>';
3812 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3818 * Special checkbox for frontpage - stores data in course table
3820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3822 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3824 * Returns the current sites name
3826 * @return string
3828 public function get_setting() {
3829 $site = course_get_format(get_site())->get_course();
3830 return $site->{$this->name};
3834 * Save the selected setting
3836 * @param string $data The selected site
3837 * @return string empty string or error message
3839 public function write_setting($data) {
3840 global $DB, $SITE, $COURSE;
3841 $record = new stdClass();
3842 $record->id = $SITE->id;
3843 $record->{$this->name} = ($data == '1' ? 1 : 0);
3844 $record->timemodified = time();
3846 course_get_format($SITE)->update_course_format_options($record);
3847 $DB->update_record('course', $record);
3849 // Reset caches.
3850 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3851 if ($SITE->id == $COURSE->id) {
3852 $COURSE = $SITE;
3854 format_base::reset_course_cache($SITE->id);
3856 return '';
3861 * Special text for frontpage - stores data in course table.
3862 * Empty string means not set here. Manual setting is required.
3864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3866 class admin_setting_sitesettext extends admin_setting_configtext {
3868 * Return the current setting
3870 * @return mixed string or null
3872 public function get_setting() {
3873 $site = course_get_format(get_site())->get_course();
3874 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3878 * Validate the selected data
3880 * @param string $data The selected value to validate
3881 * @return mixed true or message string
3883 public function validate($data) {
3884 $cleaned = clean_param($data, PARAM_TEXT);
3885 if ($cleaned === '') {
3886 return get_string('required');
3888 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3889 return true;
3890 } else {
3891 return get_string('validateerror', 'admin');
3896 * Save the selected setting
3898 * @param string $data The selected value
3899 * @return string empty or error message
3901 public function write_setting($data) {
3902 global $DB, $SITE, $COURSE;
3903 $data = trim($data);
3904 $validated = $this->validate($data);
3905 if ($validated !== true) {
3906 return $validated;
3909 $record = new stdClass();
3910 $record->id = $SITE->id;
3911 $record->{$this->name} = $data;
3912 $record->timemodified = time();
3914 course_get_format($SITE)->update_course_format_options($record);
3915 $DB->update_record('course', $record);
3917 // Reset caches.
3918 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3919 if ($SITE->id == $COURSE->id) {
3920 $COURSE = $SITE;
3922 format_base::reset_course_cache($SITE->id);
3924 return '';
3930 * Special text editor for site description.
3932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3934 class admin_setting_special_frontpagedesc extends admin_setting {
3936 * Calls parent::__construct with specific arguments
3938 public function __construct() {
3939 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3940 editors_head_setup();
3944 * Return the current setting
3945 * @return string The current setting
3947 public function get_setting() {
3948 $site = course_get_format(get_site())->get_course();
3949 return $site->{$this->name};
3953 * Save the new setting
3955 * @param string $data The new value to save
3956 * @return string empty or error message
3958 public function write_setting($data) {
3959 global $DB, $SITE, $COURSE;
3960 $record = new stdClass();
3961 $record->id = $SITE->id;
3962 $record->{$this->name} = $data;
3963 $record->timemodified = time();
3965 course_get_format($SITE)->update_course_format_options($record);
3966 $DB->update_record('course', $record);
3968 // Reset caches.
3969 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3970 if ($SITE->id == $COURSE->id) {
3971 $COURSE = $SITE;
3973 format_base::reset_course_cache($SITE->id);
3975 return '';
3979 * Returns XHTML for the field plus wrapping div
3981 * @param string $data The current value
3982 * @param string $query
3983 * @return string The XHTML output
3985 public function output_html($data, $query='') {
3986 global $CFG;
3988 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3990 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3996 * Administration interface for emoticon_manager settings.
3998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4000 class admin_setting_emoticons extends admin_setting {
4003 * Calls parent::__construct with specific args
4005 public function __construct() {
4006 global $CFG;
4008 $manager = get_emoticon_manager();
4009 $defaults = $this->prepare_form_data($manager->default_emoticons());
4010 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4014 * Return the current setting(s)
4016 * @return array Current settings array
4018 public function get_setting() {
4019 global $CFG;
4021 $manager = get_emoticon_manager();
4023 $config = $this->config_read($this->name);
4024 if (is_null($config)) {
4025 return null;
4028 $config = $manager->decode_stored_config($config);
4029 if (is_null($config)) {
4030 return null;
4033 return $this->prepare_form_data($config);
4037 * Save selected settings
4039 * @param array $data Array of settings to save
4040 * @return bool
4042 public function write_setting($data) {
4044 $manager = get_emoticon_manager();
4045 $emoticons = $this->process_form_data($data);
4047 if ($emoticons === false) {
4048 return false;
4051 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4052 return ''; // success
4053 } else {
4054 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4059 * Return XHTML field(s) for options
4061 * @param array $data Array of options to set in HTML
4062 * @return string XHTML string for the fields and wrapping div(s)
4064 public function output_html($data, $query='') {
4065 global $OUTPUT;
4067 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4068 $out .= html_writer::start_tag('thead');
4069 $out .= html_writer::start_tag('tr');
4070 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4071 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4072 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4073 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4074 $out .= html_writer::tag('th', '');
4075 $out .= html_writer::end_tag('tr');
4076 $out .= html_writer::end_tag('thead');
4077 $out .= html_writer::start_tag('tbody');
4078 $i = 0;
4079 foreach($data as $field => $value) {
4080 switch ($i) {
4081 case 0:
4082 $out .= html_writer::start_tag('tr');
4083 $current_text = $value;
4084 $current_filename = '';
4085 $current_imagecomponent = '';
4086 $current_altidentifier = '';
4087 $current_altcomponent = '';
4088 case 1:
4089 $current_filename = $value;
4090 case 2:
4091 $current_imagecomponent = $value;
4092 case 3:
4093 $current_altidentifier = $value;
4094 case 4:
4095 $current_altcomponent = $value;
4098 $out .= html_writer::tag('td',
4099 html_writer::empty_tag('input',
4100 array(
4101 'type' => 'text',
4102 'class' => 'form-text',
4103 'name' => $this->get_full_name().'['.$field.']',
4104 'value' => $value,
4106 ), array('class' => 'c'.$i)
4109 if ($i == 4) {
4110 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4111 $alt = get_string($current_altidentifier, $current_altcomponent);
4112 } else {
4113 $alt = $current_text;
4115 if ($current_filename) {
4116 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4117 } else {
4118 $out .= html_writer::tag('td', '');
4120 $out .= html_writer::end_tag('tr');
4121 $i = 0;
4122 } else {
4123 $i++;
4127 $out .= html_writer::end_tag('tbody');
4128 $out .= html_writer::end_tag('table');
4129 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4130 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4132 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4136 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4138 * @see self::process_form_data()
4139 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4140 * @return array of form fields and their values
4142 protected function prepare_form_data(array $emoticons) {
4144 $form = array();
4145 $i = 0;
4146 foreach ($emoticons as $emoticon) {
4147 $form['text'.$i] = $emoticon->text;
4148 $form['imagename'.$i] = $emoticon->imagename;
4149 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4150 $form['altidentifier'.$i] = $emoticon->altidentifier;
4151 $form['altcomponent'.$i] = $emoticon->altcomponent;
4152 $i++;
4154 // add one more blank field set for new object
4155 $form['text'.$i] = '';
4156 $form['imagename'.$i] = '';
4157 $form['imagecomponent'.$i] = '';
4158 $form['altidentifier'.$i] = '';
4159 $form['altcomponent'.$i] = '';
4161 return $form;
4165 * Converts the data from admin settings form into an array of emoticon objects
4167 * @see self::prepare_form_data()
4168 * @param array $data array of admin form fields and values
4169 * @return false|array of emoticon objects
4171 protected function process_form_data(array $form) {
4173 $count = count($form); // number of form field values
4175 if ($count % 5) {
4176 // we must get five fields per emoticon object
4177 return false;
4180 $emoticons = array();
4181 for ($i = 0; $i < $count / 5; $i++) {
4182 $emoticon = new stdClass();
4183 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4184 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4185 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4186 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4187 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4189 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4190 // prevent from breaking http://url.addresses by accident
4191 $emoticon->text = '';
4194 if (strlen($emoticon->text) < 2) {
4195 // do not allow single character emoticons
4196 $emoticon->text = '';
4199 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4200 // emoticon text must contain some non-alphanumeric character to prevent
4201 // breaking HTML tags
4202 $emoticon->text = '';
4205 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4206 $emoticons[] = $emoticon;
4209 return $emoticons;
4215 * Special setting for limiting of the list of available languages.
4217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4219 class admin_setting_langlist extends admin_setting_configtext {
4221 * Calls parent::__construct with specific arguments
4223 public function __construct() {
4224 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4228 * Save the new setting
4230 * @param string $data The new setting
4231 * @return bool
4233 public function write_setting($data) {
4234 $return = parent::write_setting($data);
4235 get_string_manager()->reset_caches();
4236 return $return;
4242 * Selection of one of the recognised countries using the list
4243 * returned by {@link get_list_of_countries()}.
4245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4247 class admin_settings_country_select extends admin_setting_configselect {
4248 protected $includeall;
4249 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4250 $this->includeall = $includeall;
4251 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4255 * Lazy-load the available choices for the select box
4257 public function load_choices() {
4258 global $CFG;
4259 if (is_array($this->choices)) {
4260 return true;
4262 $this->choices = array_merge(
4263 array('0' => get_string('choosedots')),
4264 get_string_manager()->get_list_of_countries($this->includeall));
4265 return true;
4271 * admin_setting_configselect for the default number of sections in a course,
4272 * simply so we can lazy-load the choices.
4274 * @copyright 2011 The Open University
4275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4277 class admin_settings_num_course_sections extends admin_setting_configselect {
4278 public function __construct($name, $visiblename, $description, $defaultsetting) {
4279 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4282 /** Lazy-load the available choices for the select box */
4283 public function load_choices() {
4284 $max = get_config('moodlecourse', 'maxsections');
4285 if (!isset($max) || !is_numeric($max)) {
4286 $max = 52;
4288 for ($i = 0; $i <= $max; $i++) {
4289 $this->choices[$i] = "$i";
4291 return true;
4297 * Course category selection
4299 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4301 class admin_settings_coursecat_select extends admin_setting_configselect {
4303 * Calls parent::__construct with specific arguments
4305 public function __construct($name, $visiblename, $description, $defaultsetting) {
4306 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4310 * Load the available choices for the select box
4312 * @return bool
4314 public function load_choices() {
4315 global $CFG;
4316 require_once($CFG->dirroot.'/course/lib.php');
4317 if (is_array($this->choices)) {
4318 return true;
4320 $this->choices = make_categories_options();
4321 return true;
4327 * Special control for selecting days to backup
4329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4331 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4333 * Calls parent::__construct with specific arguments
4335 public function __construct() {
4336 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4337 $this->plugin = 'backup';
4341 * Load the available choices for the select box
4343 * @return bool Always returns true
4345 public function load_choices() {
4346 if (is_array($this->choices)) {
4347 return true;
4349 $this->choices = array();
4350 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4351 foreach ($days as $day) {
4352 $this->choices[$day] = get_string($day, 'calendar');
4354 return true;
4360 * Special debug setting
4362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4364 class admin_setting_special_debug extends admin_setting_configselect {
4366 * Calls parent::__construct with specific arguments
4368 public function __construct() {
4369 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4373 * Load the available choices for the select box
4375 * @return bool
4377 public function load_choices() {
4378 if (is_array($this->choices)) {
4379 return true;
4381 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4382 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4383 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4384 DEBUG_ALL => get_string('debugall', 'admin'),
4385 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4386 return true;
4392 * Special admin control
4394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4396 class admin_setting_special_calendar_weekend extends admin_setting {
4398 * Calls parent::__construct with specific arguments
4400 public function __construct() {
4401 $name = 'calendar_weekend';
4402 $visiblename = get_string('calendar_weekend', 'admin');
4403 $description = get_string('helpweekenddays', 'admin');
4404 $default = array ('0', '6'); // Saturdays and Sundays
4405 parent::__construct($name, $visiblename, $description, $default);
4409 * Gets the current settings as an array
4411 * @return mixed Null if none, else array of settings
4413 public function get_setting() {
4414 $result = $this->config_read($this->name);
4415 if (is_null($result)) {
4416 return NULL;
4418 if ($result === '') {
4419 return array();
4421 $settings = array();
4422 for ($i=0; $i<7; $i++) {
4423 if ($result & (1 << $i)) {
4424 $settings[] = $i;
4427 return $settings;
4431 * Save the new settings
4433 * @param array $data Array of new settings
4434 * @return bool
4436 public function write_setting($data) {
4437 if (!is_array($data)) {
4438 return '';
4440 unset($data['xxxxx']);
4441 $result = 0;
4442 foreach($data as $index) {
4443 $result |= 1 << $index;
4445 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4449 * Return XHTML to display the control
4451 * @param array $data array of selected days
4452 * @param string $query
4453 * @return string XHTML for display (field + wrapping div(s)
4455 public function output_html($data, $query='') {
4456 // The order matters very much because of the implied numeric keys
4457 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4458 $return = '<table><thead><tr>';
4459 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4460 foreach($days as $index => $day) {
4461 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4463 $return .= '</tr></thead><tbody><tr>';
4464 foreach($days as $index => $day) {
4465 $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>';
4467 $return .= '</tr></tbody></table>';
4469 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4476 * Admin setting that allows a user to pick a behaviour.
4478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4480 class admin_setting_question_behaviour extends admin_setting_configselect {
4482 * @param string $name name of config variable
4483 * @param string $visiblename display name
4484 * @param string $description description
4485 * @param string $default default.
4487 public function __construct($name, $visiblename, $description, $default) {
4488 parent::__construct($name, $visiblename, $description, $default, NULL);
4492 * Load list of behaviours as choices
4493 * @return bool true => success, false => error.
4495 public function load_choices() {
4496 global $CFG;
4497 require_once($CFG->dirroot . '/question/engine/lib.php');
4498 $this->choices = question_engine::get_behaviour_options('');
4499 return true;
4505 * Admin setting that allows a user to pick appropriate roles for something.
4507 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4509 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4510 /** @var array Array of capabilities which identify roles */
4511 private $types;
4514 * @param string $name Name of config variable
4515 * @param string $visiblename Display name
4516 * @param string $description Description
4517 * @param array $types Array of archetypes which identify
4518 * roles that will be enabled by default.
4520 public function __construct($name, $visiblename, $description, $types) {
4521 parent::__construct($name, $visiblename, $description, NULL, NULL);
4522 $this->types = $types;
4526 * Load roles as choices
4528 * @return bool true=>success, false=>error
4530 public function load_choices() {
4531 global $CFG, $DB;
4532 if (during_initial_install()) {
4533 return false;
4535 if (is_array($this->choices)) {
4536 return true;
4538 if ($roles = get_all_roles()) {
4539 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4540 return true;
4541 } else {
4542 return false;
4547 * Return the default setting for this control
4549 * @return array Array of default settings
4551 public function get_defaultsetting() {
4552 global $CFG;
4554 if (during_initial_install()) {
4555 return null;
4557 $result = array();
4558 foreach($this->types as $archetype) {
4559 if ($caproles = get_archetype_roles($archetype)) {
4560 foreach ($caproles as $caprole) {
4561 $result[$caprole->id] = 1;
4565 return $result;
4571 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4575 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4577 * Constructor
4578 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4579 * @param string $visiblename localised
4580 * @param string $description long localised info
4581 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4582 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4583 * @param int $size default field size
4585 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4586 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4587 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4593 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4595 * @copyright 2009 Petr Skoda (http://skodak.org)
4596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4598 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4601 * Constructor
4602 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4603 * @param string $visiblename localised
4604 * @param string $description long localised info
4605 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4606 * @param string $yes value used when checked
4607 * @param string $no value used when not checked
4609 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4610 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4611 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4618 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4620 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4622 * @copyright 2010 Sam Hemelryk
4623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4625 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4627 * Constructor
4628 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4629 * @param string $visiblename localised
4630 * @param string $description long localised info
4631 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4632 * @param string $yes value used when checked
4633 * @param string $no value used when not checked
4635 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4636 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4637 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4644 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4648 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4650 * Calls parent::__construct with specific arguments
4652 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4653 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4654 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4661 * Graded roles in gradebook
4663 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4665 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4667 * Calls parent::__construct with specific arguments
4669 public function __construct() {
4670 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4671 get_string('configgradebookroles', 'admin'),
4672 array('student'));
4679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4681 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4683 * Saves the new settings passed in $data
4685 * @param string $data
4686 * @return mixed string or Array
4688 public function write_setting($data) {
4689 global $CFG, $DB;
4691 $oldvalue = $this->config_read($this->name);
4692 $return = parent::write_setting($data);
4693 $newvalue = $this->config_read($this->name);
4695 if ($oldvalue !== $newvalue) {
4696 // force full regrading
4697 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4700 return $return;
4706 * Which roles to show on course description page
4708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4710 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4712 * Calls parent::__construct with specific arguments
4714 public function __construct() {
4715 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4716 get_string('coursecontact_desc', 'admin'),
4717 array('editingteacher'));
4724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4726 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4728 * Calls parent::__construct with specific arguments
4730 function admin_setting_special_gradelimiting() {
4731 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4732 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4736 * Force site regrading
4738 function regrade_all() {
4739 global $CFG;
4740 require_once("$CFG->libdir/gradelib.php");
4741 grade_force_site_regrading();
4745 * Saves the new settings
4747 * @param mixed $data
4748 * @return string empty string or error message
4750 function write_setting($data) {
4751 $previous = $this->get_setting();
4753 if ($previous === null) {
4754 if ($data) {
4755 $this->regrade_all();
4757 } else {
4758 if ($data != $previous) {
4759 $this->regrade_all();
4762 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4769 * Primary grade export plugin - has state tracking.
4771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4773 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4775 * Calls parent::__construct with specific arguments
4777 public function __construct() {
4778 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4779 get_string('configgradeexport', 'admin'), array(), NULL);
4783 * Load the available choices for the multicheckbox
4785 * @return bool always returns true
4787 public function load_choices() {
4788 if (is_array($this->choices)) {
4789 return true;
4791 $this->choices = array();
4793 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4794 foreach($plugins as $plugin => $unused) {
4795 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4798 return true;
4804 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4808 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4810 * Config gradepointmax constructor
4812 * @param string $name Overidden by "gradepointmax"
4813 * @param string $visiblename Overridden by "gradepointmax" language string.
4814 * @param string $description Overridden by "gradepointmax_help" language string.
4815 * @param string $defaultsetting Not used, overridden by 100.
4816 * @param mixed $paramtype Overridden by PARAM_INT.
4817 * @param int $size Overridden by 5.
4819 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4820 $name = 'gradepointdefault';
4821 $visiblename = get_string('gradepointdefault', 'grades');
4822 $description = get_string('gradepointdefault_help', 'grades');
4823 $defaultsetting = 100;
4824 $paramtype = PARAM_INT;
4825 $size = 5;
4826 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4830 * Validate data before storage
4831 * @param string $data The submitted data
4832 * @return bool|string true if ok, string if error found
4834 public function validate($data) {
4835 global $CFG;
4836 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4837 return true;
4838 } else {
4839 return get_string('gradepointdefault_validateerror', 'grades');
4846 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4850 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4853 * Config gradepointmax constructor
4855 * @param string $name Overidden by "gradepointmax"
4856 * @param string $visiblename Overridden by "gradepointmax" language string.
4857 * @param string $description Overridden by "gradepointmax_help" language string.
4858 * @param string $defaultsetting Not used, overridden by 100.
4859 * @param mixed $paramtype Overridden by PARAM_INT.
4860 * @param int $size Overridden by 5.
4862 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4863 $name = 'gradepointmax';
4864 $visiblename = get_string('gradepointmax', 'grades');
4865 $description = get_string('gradepointmax_help', 'grades');
4866 $defaultsetting = 100;
4867 $paramtype = PARAM_INT;
4868 $size = 5;
4869 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4873 * Save the selected setting
4875 * @param string $data The selected site
4876 * @return string empty string or error message
4878 public function write_setting($data) {
4879 if ($data === '') {
4880 $data = (int)$this->defaultsetting;
4881 } else {
4882 $data = $data;
4884 return parent::write_setting($data);
4888 * Validate data before storage
4889 * @param string $data The submitted data
4890 * @return bool|string true if ok, string if error found
4892 public function validate($data) {
4893 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4894 return true;
4895 } else {
4896 return get_string('gradepointmax_validateerror', 'grades');
4901 * Return an XHTML string for the setting
4902 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4903 * @param string $query search query to be highlighted
4904 * @return string XHTML to display control
4906 public function output_html($data, $query = '') {
4907 $default = $this->get_defaultsetting();
4909 $attr = array(
4910 'type' => 'text',
4911 'size' => $this->size,
4912 'id' => $this->get_id(),
4913 'name' => $this->get_full_name(),
4914 'value' => s($data),
4915 'maxlength' => '5'
4917 $input = html_writer::empty_tag('input', $attr);
4919 $attr = array('class' => 'form-text defaultsnext');
4920 $div = html_writer::tag('div', $input, $attr);
4921 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
4927 * Grade category settings
4929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4931 class admin_setting_gradecat_combo extends admin_setting {
4932 /** @var array Array of choices */
4933 public $choices;
4936 * Sets choices and calls parent::__construct with passed arguments
4937 * @param string $name
4938 * @param string $visiblename
4939 * @param string $description
4940 * @param mixed $defaultsetting string or array depending on implementation
4941 * @param array $choices An array of choices for the control
4943 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4944 $this->choices = $choices;
4945 parent::__construct($name, $visiblename, $description, $defaultsetting);
4949 * Return the current setting(s) array
4951 * @return array Array of value=>xx, forced=>xx, adv=>xx
4953 public function get_setting() {
4954 global $CFG;
4956 $value = $this->config_read($this->name);
4957 $flag = $this->config_read($this->name.'_flag');
4959 if (is_null($value) or is_null($flag)) {
4960 return NULL;
4963 $flag = (int)$flag;
4964 $forced = (boolean)(1 & $flag); // first bit
4965 $adv = (boolean)(2 & $flag); // second bit
4967 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4971 * Save the new settings passed in $data
4973 * @todo Add vartype handling to ensure $data is array
4974 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4975 * @return string empty or error message
4977 public function write_setting($data) {
4978 global $CFG;
4980 $value = $data['value'];
4981 $forced = empty($data['forced']) ? 0 : 1;
4982 $adv = empty($data['adv']) ? 0 : 2;
4983 $flag = ($forced | $adv); //bitwise or
4985 if (!in_array($value, array_keys($this->choices))) {
4986 return 'Error setting ';
4989 $oldvalue = $this->config_read($this->name);
4990 $oldflag = (int)$this->config_read($this->name.'_flag');
4991 $oldforced = (1 & $oldflag); // first bit
4993 $result1 = $this->config_write($this->name, $value);
4994 $result2 = $this->config_write($this->name.'_flag', $flag);
4996 // force regrade if needed
4997 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4998 require_once($CFG->libdir.'/gradelib.php');
4999 grade_category::updated_forced_settings();
5002 if ($result1 and $result2) {
5003 return '';
5004 } else {
5005 return get_string('errorsetting', 'admin');
5010 * Return XHTML to display the field and wrapping div
5012 * @todo Add vartype handling to ensure $data is array
5013 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5014 * @param string $query
5015 * @return string XHTML to display control
5017 public function output_html($data, $query='') {
5018 $value = $data['value'];
5019 $forced = !empty($data['forced']);
5020 $adv = !empty($data['adv']);
5022 $default = $this->get_defaultsetting();
5023 if (!is_null($default)) {
5024 $defaultinfo = array();
5025 if (isset($this->choices[$default['value']])) {
5026 $defaultinfo[] = $this->choices[$default['value']];
5028 if (!empty($default['forced'])) {
5029 $defaultinfo[] = get_string('force');
5031 if (!empty($default['adv'])) {
5032 $defaultinfo[] = get_string('advanced');
5034 $defaultinfo = implode(', ', $defaultinfo);
5036 } else {
5037 $defaultinfo = NULL;
5041 $return = '<div class="form-group">';
5042 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5043 foreach ($this->choices as $key => $val) {
5044 // the string cast is needed because key may be integer - 0 is equal to most strings!
5045 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5047 $return .= '</select>';
5048 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5049 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5050 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5051 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5052 $return .= '</div>';
5054 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5060 * Selection of grade report in user profiles
5062 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5064 class admin_setting_grade_profilereport extends admin_setting_configselect {
5066 * Calls parent::__construct with specific arguments
5068 public function __construct() {
5069 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5073 * Loads an array of choices for the configselect control
5075 * @return bool always return true
5077 public function load_choices() {
5078 if (is_array($this->choices)) {
5079 return true;
5081 $this->choices = array();
5083 global $CFG;
5084 require_once($CFG->libdir.'/gradelib.php');
5086 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5087 if (file_exists($plugindir.'/lib.php')) {
5088 require_once($plugindir.'/lib.php');
5089 $functionname = 'grade_report_'.$plugin.'_profilereport';
5090 if (function_exists($functionname)) {
5091 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5095 return true;
5101 * Special class for register auth selection
5103 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5105 class admin_setting_special_registerauth extends admin_setting_configselect {
5107 * Calls parent::__construct with specific arguments
5109 public function __construct() {
5110 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5114 * Returns the default option
5116 * @return string empty or default option
5118 public function get_defaultsetting() {
5119 $this->load_choices();
5120 $defaultsetting = parent::get_defaultsetting();
5121 if (array_key_exists($defaultsetting, $this->choices)) {
5122 return $defaultsetting;
5123 } else {
5124 return '';
5129 * Loads the possible choices for the array
5131 * @return bool always returns true
5133 public function load_choices() {
5134 global $CFG;
5136 if (is_array($this->choices)) {
5137 return true;
5139 $this->choices = array();
5140 $this->choices[''] = get_string('disable');
5142 $authsenabled = get_enabled_auth_plugins(true);
5144 foreach ($authsenabled as $auth) {
5145 $authplugin = get_auth_plugin($auth);
5146 if (!$authplugin->can_signup()) {
5147 continue;
5149 // Get the auth title (from core or own auth lang files)
5150 $authtitle = $authplugin->get_title();
5151 $this->choices[$auth] = $authtitle;
5153 return true;
5159 * General plugins manager
5161 class admin_page_pluginsoverview extends admin_externalpage {
5164 * Sets basic information about the external page
5166 public function __construct() {
5167 global $CFG;
5168 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5169 "$CFG->wwwroot/$CFG->admin/plugins.php");
5174 * Module manage page
5176 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5178 class admin_page_managemods extends admin_externalpage {
5180 * Calls parent::__construct with specific arguments
5182 public function __construct() {
5183 global $CFG;
5184 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5188 * Try to find the specified module
5190 * @param string $query The module to search for
5191 * @return array
5193 public function search($query) {
5194 global $CFG, $DB;
5195 if ($result = parent::search($query)) {
5196 return $result;
5199 $found = false;
5200 if ($modules = $DB->get_records('modules')) {
5201 foreach ($modules as $module) {
5202 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5203 continue;
5205 if (strpos($module->name, $query) !== false) {
5206 $found = true;
5207 break;
5209 $strmodulename = get_string('modulename', $module->name);
5210 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5211 $found = true;
5212 break;
5216 if ($found) {
5217 $result = new stdClass();
5218 $result->page = $this;
5219 $result->settings = array();
5220 return array($this->name => $result);
5221 } else {
5222 return array();
5229 * Special class for enrol plugins management.
5231 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5232 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5234 class admin_setting_manageenrols extends admin_setting {
5236 * Calls parent::__construct with specific arguments
5238 public function __construct() {
5239 $this->nosave = true;
5240 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5244 * Always returns true, does nothing
5246 * @return true
5248 public function get_setting() {
5249 return true;
5253 * Always returns true, does nothing
5255 * @return true
5257 public function get_defaultsetting() {
5258 return true;
5262 * Always returns '', does not write anything
5264 * @return string Always returns ''
5266 public function write_setting($data) {
5267 // do not write any setting
5268 return '';
5272 * Checks if $query is one of the available enrol plugins
5274 * @param string $query The string to search for
5275 * @return bool Returns true if found, false if not
5277 public function is_related($query) {
5278 if (parent::is_related($query)) {
5279 return true;
5282 $query = core_text::strtolower($query);
5283 $enrols = enrol_get_plugins(false);
5284 foreach ($enrols as $name=>$enrol) {
5285 $localised = get_string('pluginname', 'enrol_'.$name);
5286 if (strpos(core_text::strtolower($name), $query) !== false) {
5287 return true;
5289 if (strpos(core_text::strtolower($localised), $query) !== false) {
5290 return true;
5293 return false;
5297 * Builds the XHTML to display the control
5299 * @param string $data Unused
5300 * @param string $query
5301 * @return string
5303 public function output_html($data, $query='') {
5304 global $CFG, $OUTPUT, $DB, $PAGE;
5306 // Display strings.
5307 $strup = get_string('up');
5308 $strdown = get_string('down');
5309 $strsettings = get_string('settings');
5310 $strenable = get_string('enable');
5311 $strdisable = get_string('disable');
5312 $struninstall = get_string('uninstallplugin', 'core_admin');
5313 $strusage = get_string('enrolusage', 'enrol');
5314 $strversion = get_string('version');
5315 $strtest = get_string('testsettings', 'core_enrol');
5317 $pluginmanager = core_plugin_manager::instance();
5319 $enrols_available = enrol_get_plugins(false);
5320 $active_enrols = enrol_get_plugins(true);
5322 $allenrols = array();
5323 foreach ($active_enrols as $key=>$enrol) {
5324 $allenrols[$key] = true;
5326 foreach ($enrols_available as $key=>$enrol) {
5327 $allenrols[$key] = true;
5329 // Now find all borked plugins and at least allow then to uninstall.
5330 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5331 foreach ($condidates as $candidate) {
5332 if (empty($allenrols[$candidate])) {
5333 $allenrols[$candidate] = true;
5337 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5338 $return .= $OUTPUT->box_start('generalbox enrolsui');
5340 $table = new html_table();
5341 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5342 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5343 $table->id = 'courseenrolmentplugins';
5344 $table->attributes['class'] = 'admintable generaltable';
5345 $table->data = array();
5347 // Iterate through enrol plugins and add to the display table.
5348 $updowncount = 1;
5349 $enrolcount = count($active_enrols);
5350 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5351 $printed = array();
5352 foreach($allenrols as $enrol => $unused) {
5353 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5354 $version = get_config('enrol_'.$enrol, 'version');
5355 if ($version === false) {
5356 $version = '';
5359 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5360 $name = get_string('pluginname', 'enrol_'.$enrol);
5361 } else {
5362 $name = $enrol;
5364 // Usage.
5365 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5366 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5367 $usage = "$ci / $cp";
5369 // Hide/show links.
5370 $class = '';
5371 if (isset($active_enrols[$enrol])) {
5372 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5373 $hideshow = "<a href=\"$aurl\">";
5374 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5375 $enabled = true;
5376 $displayname = $name;
5377 } else if (isset($enrols_available[$enrol])) {
5378 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5379 $hideshow = "<a href=\"$aurl\">";
5380 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5381 $enabled = false;
5382 $displayname = $name;
5383 $class = 'dimmed_text';
5384 } else {
5385 $hideshow = '';
5386 $enabled = false;
5387 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5389 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5390 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5391 } else {
5392 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5395 // Up/down link (only if enrol is enabled).
5396 $updown = '';
5397 if ($enabled) {
5398 if ($updowncount > 1) {
5399 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5400 $updown .= "<a href=\"$aurl\">";
5401 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5402 } else {
5403 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5405 if ($updowncount < $enrolcount) {
5406 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5407 $updown .= "<a href=\"$aurl\">";
5408 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5409 } else {
5410 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5412 ++$updowncount;
5415 // Add settings link.
5416 if (!$version) {
5417 $settings = '';
5418 } else if ($surl = $plugininfo->get_settings_url()) {
5419 $settings = html_writer::link($surl, $strsettings);
5420 } else {
5421 $settings = '';
5424 // Add uninstall info.
5425 $uninstall = '';
5426 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5427 $uninstall = html_writer::link($uninstallurl, $struninstall);
5430 $test = '';
5431 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5432 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5433 $test = html_writer::link($testsettingsurl, $strtest);
5436 // Add a row to the table.
5437 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5438 if ($class) {
5439 $row->attributes['class'] = $class;
5441 $table->data[] = $row;
5443 $printed[$enrol] = true;
5446 $return .= html_writer::table($table);
5447 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5448 $return .= $OUTPUT->box_end();
5449 return highlight($query, $return);
5455 * Blocks manage page
5457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5459 class admin_page_manageblocks extends admin_externalpage {
5461 * Calls parent::__construct with specific arguments
5463 public function __construct() {
5464 global $CFG;
5465 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5469 * Search for a specific block
5471 * @param string $query The string to search for
5472 * @return array
5474 public function search($query) {
5475 global $CFG, $DB;
5476 if ($result = parent::search($query)) {
5477 return $result;
5480 $found = false;
5481 if ($blocks = $DB->get_records('block')) {
5482 foreach ($blocks as $block) {
5483 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5484 continue;
5486 if (strpos($block->name, $query) !== false) {
5487 $found = true;
5488 break;
5490 $strblockname = get_string('pluginname', 'block_'.$block->name);
5491 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5492 $found = true;
5493 break;
5497 if ($found) {
5498 $result = new stdClass();
5499 $result->page = $this;
5500 $result->settings = array();
5501 return array($this->name => $result);
5502 } else {
5503 return array();
5509 * Message outputs configuration
5511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5513 class admin_page_managemessageoutputs extends admin_externalpage {
5515 * Calls parent::__construct with specific arguments
5517 public function __construct() {
5518 global $CFG;
5519 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5523 * Search for a specific message processor
5525 * @param string $query The string to search for
5526 * @return array
5528 public function search($query) {
5529 global $CFG, $DB;
5530 if ($result = parent::search($query)) {
5531 return $result;
5534 $found = false;
5535 if ($processors = get_message_processors()) {
5536 foreach ($processors as $processor) {
5537 if (!$processor->available) {
5538 continue;
5540 if (strpos($processor->name, $query) !== false) {
5541 $found = true;
5542 break;
5544 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5545 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5546 $found = true;
5547 break;
5551 if ($found) {
5552 $result = new stdClass();
5553 $result->page = $this;
5554 $result->settings = array();
5555 return array($this->name => $result);
5556 } else {
5557 return array();
5563 * Default message outputs configuration
5565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5567 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5569 * Calls parent::__construct with specific arguments
5571 public function __construct() {
5572 global $CFG;
5573 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5579 * Manage question behaviours page
5581 * @copyright 2011 The Open University
5582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5584 class admin_page_manageqbehaviours extends admin_externalpage {
5586 * Constructor
5588 public function __construct() {
5589 global $CFG;
5590 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5591 new moodle_url('/admin/qbehaviours.php'));
5595 * Search question behaviours for the specified string
5597 * @param string $query The string to search for in question behaviours
5598 * @return array
5600 public function search($query) {
5601 global $CFG;
5602 if ($result = parent::search($query)) {
5603 return $result;
5606 $found = false;
5607 require_once($CFG->dirroot . '/question/engine/lib.php');
5608 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5609 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5610 $query) !== false) {
5611 $found = true;
5612 break;
5615 if ($found) {
5616 $result = new stdClass();
5617 $result->page = $this;
5618 $result->settings = array();
5619 return array($this->name => $result);
5620 } else {
5621 return array();
5628 * Question type manage page
5630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5632 class admin_page_manageqtypes extends admin_externalpage {
5634 * Calls parent::__construct with specific arguments
5636 public function __construct() {
5637 global $CFG;
5638 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5639 new moodle_url('/admin/qtypes.php'));
5643 * Search question types for the specified string
5645 * @param string $query The string to search for in question types
5646 * @return array
5648 public function search($query) {
5649 global $CFG;
5650 if ($result = parent::search($query)) {
5651 return $result;
5654 $found = false;
5655 require_once($CFG->dirroot . '/question/engine/bank.php');
5656 foreach (question_bank::get_all_qtypes() as $qtype) {
5657 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5658 $found = true;
5659 break;
5662 if ($found) {
5663 $result = new stdClass();
5664 $result->page = $this;
5665 $result->settings = array();
5666 return array($this->name => $result);
5667 } else {
5668 return array();
5674 class admin_page_manageportfolios extends admin_externalpage {
5676 * Calls parent::__construct with specific arguments
5678 public function __construct() {
5679 global $CFG;
5680 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5681 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5685 * Searches page for the specified string.
5686 * @param string $query The string to search for
5687 * @return bool True if it is found on this page
5689 public function search($query) {
5690 global $CFG;
5691 if ($result = parent::search($query)) {
5692 return $result;
5695 $found = false;
5696 $portfolios = core_component::get_plugin_list('portfolio');
5697 foreach ($portfolios as $p => $dir) {
5698 if (strpos($p, $query) !== false) {
5699 $found = true;
5700 break;
5703 if (!$found) {
5704 foreach (portfolio_instances(false, false) as $instance) {
5705 $title = $instance->get('name');
5706 if (strpos(core_text::strtolower($title), $query) !== false) {
5707 $found = true;
5708 break;
5713 if ($found) {
5714 $result = new stdClass();
5715 $result->page = $this;
5716 $result->settings = array();
5717 return array($this->name => $result);
5718 } else {
5719 return array();
5725 class admin_page_managerepositories extends admin_externalpage {
5727 * Calls parent::__construct with specific arguments
5729 public function __construct() {
5730 global $CFG;
5731 parent::__construct('managerepositories', get_string('manage',
5732 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5736 * Searches page for the specified string.
5737 * @param string $query The string to search for
5738 * @return bool True if it is found on this page
5740 public function search($query) {
5741 global $CFG;
5742 if ($result = parent::search($query)) {
5743 return $result;
5746 $found = false;
5747 $repositories= core_component::get_plugin_list('repository');
5748 foreach ($repositories as $p => $dir) {
5749 if (strpos($p, $query) !== false) {
5750 $found = true;
5751 break;
5754 if (!$found) {
5755 foreach (repository::get_types() as $instance) {
5756 $title = $instance->get_typename();
5757 if (strpos(core_text::strtolower($title), $query) !== false) {
5758 $found = true;
5759 break;
5764 if ($found) {
5765 $result = new stdClass();
5766 $result->page = $this;
5767 $result->settings = array();
5768 return array($this->name => $result);
5769 } else {
5770 return array();
5777 * Special class for authentication administration.
5779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5781 class admin_setting_manageauths extends admin_setting {
5783 * Calls parent::__construct with specific arguments
5785 public function __construct() {
5786 $this->nosave = true;
5787 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5791 * Always returns true
5793 * @return true
5795 public function get_setting() {
5796 return true;
5800 * Always returns true
5802 * @return true
5804 public function get_defaultsetting() {
5805 return true;
5809 * Always returns '' and doesn't write anything
5811 * @return string Always returns ''
5813 public function write_setting($data) {
5814 // do not write any setting
5815 return '';
5819 * Search to find if Query is related to auth plugin
5821 * @param string $query The string to search for
5822 * @return bool true for related false for not
5824 public function is_related($query) {
5825 if (parent::is_related($query)) {
5826 return true;
5829 $authsavailable = core_component::get_plugin_list('auth');
5830 foreach ($authsavailable as $auth => $dir) {
5831 if (strpos($auth, $query) !== false) {
5832 return true;
5834 $authplugin = get_auth_plugin($auth);
5835 $authtitle = $authplugin->get_title();
5836 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5837 return true;
5840 return false;
5844 * Return XHTML to display control
5846 * @param mixed $data Unused
5847 * @param string $query
5848 * @return string highlight
5850 public function output_html($data, $query='') {
5851 global $CFG, $OUTPUT, $DB;
5853 // display strings
5854 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5855 'settings', 'edit', 'name', 'enable', 'disable',
5856 'up', 'down', 'none', 'users'));
5857 $txt->updown = "$txt->up/$txt->down";
5858 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5859 $txt->testsettings = get_string('testsettings', 'core_auth');
5861 $authsavailable = core_component::get_plugin_list('auth');
5862 get_enabled_auth_plugins(true); // fix the list of enabled auths
5863 if (empty($CFG->auth)) {
5864 $authsenabled = array();
5865 } else {
5866 $authsenabled = explode(',', $CFG->auth);
5869 // construct the display array, with enabled auth plugins at the top, in order
5870 $displayauths = array();
5871 $registrationauths = array();
5872 $registrationauths[''] = $txt->disable;
5873 $authplugins = array();
5874 foreach ($authsenabled as $auth) {
5875 $authplugin = get_auth_plugin($auth);
5876 $authplugins[$auth] = $authplugin;
5877 /// Get the auth title (from core or own auth lang files)
5878 $authtitle = $authplugin->get_title();
5879 /// Apply titles
5880 $displayauths[$auth] = $authtitle;
5881 if ($authplugin->can_signup()) {
5882 $registrationauths[$auth] = $authtitle;
5886 foreach ($authsavailable as $auth => $dir) {
5887 if (array_key_exists($auth, $displayauths)) {
5888 continue; //already in the list
5890 $authplugin = get_auth_plugin($auth);
5891 $authplugins[$auth] = $authplugin;
5892 /// Get the auth title (from core or own auth lang files)
5893 $authtitle = $authplugin->get_title();
5894 /// Apply titles
5895 $displayauths[$auth] = $authtitle;
5896 if ($authplugin->can_signup()) {
5897 $registrationauths[$auth] = $authtitle;
5901 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5902 $return .= $OUTPUT->box_start('generalbox authsui');
5904 $table = new html_table();
5905 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5906 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5907 $table->data = array();
5908 $table->attributes['class'] = 'admintable generaltable';
5909 $table->id = 'manageauthtable';
5911 //add always enabled plugins first
5912 $displayname = $displayauths['manual'];
5913 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5914 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5915 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
5916 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5917 $displayname = $displayauths['nologin'];
5918 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5919 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
5920 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5923 // iterate through auth plugins and add to the display table
5924 $updowncount = 1;
5925 $authcount = count($authsenabled);
5926 $url = "auth.php?sesskey=" . sesskey();
5927 foreach ($displayauths as $auth => $name) {
5928 if ($auth == 'manual' or $auth == 'nologin') {
5929 continue;
5931 $class = '';
5932 // hide/show link
5933 if (in_array($auth, $authsenabled)) {
5934 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5935 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5936 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5937 $enabled = true;
5938 $displayname = $name;
5940 else {
5941 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5942 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5943 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5944 $enabled = false;
5945 $displayname = $name;
5946 $class = 'dimmed_text';
5949 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
5951 // up/down link (only if auth is enabled)
5952 $updown = '';
5953 if ($enabled) {
5954 if ($updowncount > 1) {
5955 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5956 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5958 else {
5959 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5961 if ($updowncount < $authcount) {
5962 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5963 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5965 else {
5966 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5968 ++ $updowncount;
5971 // settings link
5972 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5973 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5974 } else {
5975 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5978 // Uninstall link.
5979 $uninstall = '';
5980 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
5981 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
5984 $test = '';
5985 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
5986 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
5987 $test = html_writer::link($testurl, $txt->testsettings);
5990 // Add a row to the table.
5991 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
5992 if ($class) {
5993 $row->attributes['class'] = $class;
5995 $table->data[] = $row;
5997 $return .= html_writer::table($table);
5998 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5999 $return .= $OUTPUT->box_end();
6000 return highlight($query, $return);
6006 * Special class for authentication administration.
6008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6010 class admin_setting_manageeditors extends admin_setting {
6012 * Calls parent::__construct with specific arguments
6014 public function __construct() {
6015 $this->nosave = true;
6016 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6020 * Always returns true, does nothing
6022 * @return true
6024 public function get_setting() {
6025 return true;
6029 * Always returns true, does nothing
6031 * @return true
6033 public function get_defaultsetting() {
6034 return true;
6038 * Always returns '', does not write anything
6040 * @return string Always returns ''
6042 public function write_setting($data) {
6043 // do not write any setting
6044 return '';
6048 * Checks if $query is one of the available editors
6050 * @param string $query The string to search for
6051 * @return bool Returns true if found, false if not
6053 public function is_related($query) {
6054 if (parent::is_related($query)) {
6055 return true;
6058 $editors_available = editors_get_available();
6059 foreach ($editors_available as $editor=>$editorstr) {
6060 if (strpos($editor, $query) !== false) {
6061 return true;
6063 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6064 return true;
6067 return false;
6071 * Builds the XHTML to display the control
6073 * @param string $data Unused
6074 * @param string $query
6075 * @return string
6077 public function output_html($data, $query='') {
6078 global $CFG, $OUTPUT;
6080 // display strings
6081 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6082 'up', 'down', 'none'));
6083 $struninstall = get_string('uninstallplugin', 'core_admin');
6085 $txt->updown = "$txt->up/$txt->down";
6087 $editors_available = editors_get_available();
6088 $active_editors = explode(',', $CFG->texteditors);
6090 $active_editors = array_reverse($active_editors);
6091 foreach ($active_editors as $key=>$editor) {
6092 if (empty($editors_available[$editor])) {
6093 unset($active_editors[$key]);
6094 } else {
6095 $name = $editors_available[$editor];
6096 unset($editors_available[$editor]);
6097 $editors_available[$editor] = $name;
6100 if (empty($active_editors)) {
6101 //$active_editors = array('textarea');
6103 $editors_available = array_reverse($editors_available, true);
6104 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6105 $return .= $OUTPUT->box_start('generalbox editorsui');
6107 $table = new html_table();
6108 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6109 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6110 $table->id = 'editormanagement';
6111 $table->attributes['class'] = 'admintable generaltable';
6112 $table->data = array();
6114 // iterate through auth plugins and add to the display table
6115 $updowncount = 1;
6116 $editorcount = count($active_editors);
6117 $url = "editors.php?sesskey=" . sesskey();
6118 foreach ($editors_available as $editor => $name) {
6119 // hide/show link
6120 $class = '';
6121 if (in_array($editor, $active_editors)) {
6122 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6123 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6124 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6125 $enabled = true;
6126 $displayname = $name;
6128 else {
6129 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6130 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6131 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6132 $enabled = false;
6133 $displayname = $name;
6134 $class = 'dimmed_text';
6137 // up/down link (only if auth is enabled)
6138 $updown = '';
6139 if ($enabled) {
6140 if ($updowncount > 1) {
6141 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6142 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6144 else {
6145 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6147 if ($updowncount < $editorcount) {
6148 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6149 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6151 else {
6152 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6154 ++ $updowncount;
6157 // settings link
6158 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6159 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6160 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6161 } else {
6162 $settings = '';
6165 $uninstall = '';
6166 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6167 $uninstall = html_writer::link($uninstallurl, $struninstall);
6170 // Add a row to the table.
6171 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6172 if ($class) {
6173 $row->attributes['class'] = $class;
6175 $table->data[] = $row;
6177 $return .= html_writer::table($table);
6178 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6179 $return .= $OUTPUT->box_end();
6180 return highlight($query, $return);
6186 * Special class for license administration.
6188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6190 class admin_setting_managelicenses extends admin_setting {
6192 * Calls parent::__construct with specific arguments
6194 public function __construct() {
6195 $this->nosave = true;
6196 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6200 * Always returns true, does nothing
6202 * @return true
6204 public function get_setting() {
6205 return true;
6209 * Always returns true, does nothing
6211 * @return true
6213 public function get_defaultsetting() {
6214 return true;
6218 * Always returns '', does not write anything
6220 * @return string Always returns ''
6222 public function write_setting($data) {
6223 // do not write any setting
6224 return '';
6228 * Builds the XHTML to display the control
6230 * @param string $data Unused
6231 * @param string $query
6232 * @return string
6234 public function output_html($data, $query='') {
6235 global $CFG, $OUTPUT;
6236 require_once($CFG->libdir . '/licenselib.php');
6237 $url = "licenses.php?sesskey=" . sesskey();
6239 // display strings
6240 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6241 $licenses = license_manager::get_licenses();
6243 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6245 $return .= $OUTPUT->box_start('generalbox editorsui');
6247 $table = new html_table();
6248 $table->head = array($txt->name, $txt->enable);
6249 $table->colclasses = array('leftalign', 'centeralign');
6250 $table->id = 'availablelicenses';
6251 $table->attributes['class'] = 'admintable generaltable';
6252 $table->data = array();
6254 foreach ($licenses as $value) {
6255 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6257 if ($value->enabled == 1) {
6258 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6259 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6260 } else {
6261 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6262 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6265 if ($value->shortname == $CFG->sitedefaultlicense) {
6266 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6267 $hideshow = '';
6270 $enabled = true;
6272 $table->data[] =array($displayname, $hideshow);
6274 $return .= html_writer::table($table);
6275 $return .= $OUTPUT->box_end();
6276 return highlight($query, $return);
6281 * Course formats manager. Allows to enable/disable formats and jump to settings
6283 class admin_setting_manageformats extends admin_setting {
6286 * Calls parent::__construct with specific arguments
6288 public function __construct() {
6289 $this->nosave = true;
6290 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6294 * Always returns true
6296 * @return true
6298 public function get_setting() {
6299 return true;
6303 * Always returns true
6305 * @return true
6307 public function get_defaultsetting() {
6308 return true;
6312 * Always returns '' and doesn't write anything
6314 * @param mixed $data string or array, must not be NULL
6315 * @return string Always returns ''
6317 public function write_setting($data) {
6318 // do not write any setting
6319 return '';
6323 * Search to find if Query is related to format plugin
6325 * @param string $query The string to search for
6326 * @return bool true for related false for not
6328 public function is_related($query) {
6329 if (parent::is_related($query)) {
6330 return true;
6332 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6333 foreach ($formats as $format) {
6334 if (strpos($format->component, $query) !== false ||
6335 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6336 return true;
6339 return false;
6343 * Return XHTML to display control
6345 * @param mixed $data Unused
6346 * @param string $query
6347 * @return string highlight
6349 public function output_html($data, $query='') {
6350 global $CFG, $OUTPUT;
6351 $return = '';
6352 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6353 $return .= $OUTPUT->box_start('generalbox formatsui');
6355 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6357 // display strings
6358 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6359 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6360 $txt->updown = "$txt->up/$txt->down";
6362 $table = new html_table();
6363 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6364 $table->align = array('left', 'center', 'center', 'center', 'center');
6365 $table->attributes['class'] = 'manageformattable generaltable admintable';
6366 $table->data = array();
6368 $cnt = 0;
6369 $defaultformat = get_config('moodlecourse', 'format');
6370 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6371 foreach ($formats as $format) {
6372 $url = new moodle_url('/admin/courseformats.php',
6373 array('sesskey' => sesskey(), 'format' => $format->name));
6374 $isdefault = '';
6375 $class = '';
6376 if ($format->is_enabled()) {
6377 $strformatname = $format->displayname;
6378 if ($defaultformat === $format->name) {
6379 $hideshow = $txt->default;
6380 } else {
6381 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6382 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6384 } else {
6385 $strformatname = $format->displayname;
6386 $class = 'dimmed_text';
6387 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6388 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6390 $updown = '';
6391 if ($cnt) {
6392 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6393 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6394 } else {
6395 $updown .= $spacer;
6397 if ($cnt < count($formats) - 1) {
6398 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6399 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6400 } else {
6401 $updown .= $spacer;
6403 $cnt++;
6404 $settings = '';
6405 if ($format->get_settings_url()) {
6406 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6408 $uninstall = '';
6409 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6410 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6412 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6413 if ($class) {
6414 $row->attributes['class'] = $class;
6416 $table->data[] = $row;
6418 $return .= html_writer::table($table);
6419 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6420 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6421 $return .= $OUTPUT->box_end();
6422 return highlight($query, $return);
6427 * Special class for filter administration.
6429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6431 class admin_page_managefilters extends admin_externalpage {
6433 * Calls parent::__construct with specific arguments
6435 public function __construct() {
6436 global $CFG;
6437 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6441 * Searches all installed filters for specified filter
6443 * @param string $query The filter(string) to search for
6444 * @param string $query
6446 public function search($query) {
6447 global $CFG;
6448 if ($result = parent::search($query)) {
6449 return $result;
6452 $found = false;
6453 $filternames = filter_get_all_installed();
6454 foreach ($filternames as $path => $strfiltername) {
6455 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6456 $found = true;
6457 break;
6459 if (strpos($path, $query) !== false) {
6460 $found = true;
6461 break;
6465 if ($found) {
6466 $result = new stdClass;
6467 $result->page = $this;
6468 $result->settings = array();
6469 return array($this->name => $result);
6470 } else {
6471 return array();
6478 * Initialise admin page - this function does require login and permission
6479 * checks specified in page definition.
6481 * This function must be called on each admin page before other code.
6483 * @global moodle_page $PAGE
6485 * @param string $section name of page
6486 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6487 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6488 * added to the turn blocks editing on/off form, so this page reloads correctly.
6489 * @param string $actualurl if the actual page being viewed is not the normal one for this
6490 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6491 * @param array $options Additional options that can be specified for page setup.
6492 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6494 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6495 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6497 $PAGE->set_context(null); // hack - set context to something, by default to system context
6499 $site = get_site();
6500 require_login();
6502 if (!empty($options['pagelayout'])) {
6503 // A specific page layout has been requested.
6504 $PAGE->set_pagelayout($options['pagelayout']);
6505 } else if ($section === 'upgradesettings') {
6506 $PAGE->set_pagelayout('maintenance');
6507 } else {
6508 $PAGE->set_pagelayout('admin');
6511 $adminroot = admin_get_root(false, false); // settings not required for external pages
6512 $extpage = $adminroot->locate($section, true);
6514 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6515 // The requested section isn't in the admin tree
6516 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6517 if (!has_capability('moodle/site:config', context_system::instance())) {
6518 // The requested section could depend on a different capability
6519 // but most likely the user has inadequate capabilities
6520 print_error('accessdenied', 'admin');
6521 } else {
6522 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6526 // this eliminates our need to authenticate on the actual pages
6527 if (!$extpage->check_access()) {
6528 print_error('accessdenied', 'admin');
6529 die;
6532 navigation_node::require_admin_tree();
6534 // $PAGE->set_extra_button($extrabutton); TODO
6536 if (!$actualurl) {
6537 $actualurl = $extpage->url;
6540 $PAGE->set_url($actualurl, $extraurlparams);
6541 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6542 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6545 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6546 // During initial install.
6547 $strinstallation = get_string('installation', 'install');
6548 $strsettings = get_string('settings');
6549 $PAGE->navbar->add($strsettings);
6550 $PAGE->set_title($strinstallation);
6551 $PAGE->set_heading($strinstallation);
6552 $PAGE->set_cacheable(false);
6553 return;
6556 // Locate the current item on the navigation and make it active when found.
6557 $path = $extpage->path;
6558 $node = $PAGE->settingsnav;
6559 while ($node && count($path) > 0) {
6560 $node = $node->get(array_pop($path));
6562 if ($node) {
6563 $node->make_active();
6566 // Normal case.
6567 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6568 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6569 $USER->editing = $adminediting;
6572 $visiblepathtosection = array_reverse($extpage->visiblepath);
6574 if ($PAGE->user_allowed_editing()) {
6575 if ($PAGE->user_is_editing()) {
6576 $caption = get_string('blockseditoff');
6577 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6578 } else {
6579 $caption = get_string('blocksediton');
6580 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6582 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6585 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6586 $PAGE->set_heading($SITE->fullname);
6588 // prevent caching in nav block
6589 $PAGE->navigation->clear_cache();
6593 * Returns the reference to admin tree root
6595 * @return object admin_root object
6597 function admin_get_root($reload=false, $requirefulltree=true) {
6598 global $CFG, $DB, $OUTPUT;
6600 static $ADMIN = NULL;
6602 if (is_null($ADMIN)) {
6603 // create the admin tree!
6604 $ADMIN = new admin_root($requirefulltree);
6607 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6608 $ADMIN->purge_children($requirefulltree);
6611 if (!$ADMIN->loaded) {
6612 // we process this file first to create categories first and in correct order
6613 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6615 // now we process all other files in admin/settings to build the admin tree
6616 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6617 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6618 continue;
6620 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6621 // plugins are loaded last - they may insert pages anywhere
6622 continue;
6624 require($file);
6626 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6628 $ADMIN->loaded = true;
6631 return $ADMIN;
6634 /// settings utility functions
6637 * This function applies default settings.
6639 * @param object $node, NULL means complete tree, null by default
6640 * @param bool $unconditional if true overrides all values with defaults, null buy default
6642 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6643 global $CFG;
6645 if (is_null($node)) {
6646 core_plugin_manager::reset_caches();
6647 $node = admin_get_root(true, true);
6650 if ($node instanceof admin_category) {
6651 $entries = array_keys($node->children);
6652 foreach ($entries as $entry) {
6653 admin_apply_default_settings($node->children[$entry], $unconditional);
6656 } else if ($node instanceof admin_settingpage) {
6657 foreach ($node->settings as $setting) {
6658 if (!$unconditional and !is_null($setting->get_setting())) {
6659 //do not override existing defaults
6660 continue;
6662 $defaultsetting = $setting->get_defaultsetting();
6663 if (is_null($defaultsetting)) {
6664 // no value yet - default maybe applied after admin user creation or in upgradesettings
6665 continue;
6667 $setting->write_setting($defaultsetting);
6668 $setting->write_setting_flags(null);
6671 // Just in case somebody modifies the list of active plugins directly.
6672 core_plugin_manager::reset_caches();
6676 * Store changed settings, this function updates the errors variable in $ADMIN
6678 * @param object $formdata from form
6679 * @return int number of changed settings
6681 function admin_write_settings($formdata) {
6682 global $CFG, $SITE, $DB;
6684 $olddbsessions = !empty($CFG->dbsessions);
6685 $formdata = (array)$formdata;
6687 $data = array();
6688 foreach ($formdata as $fullname=>$value) {
6689 if (strpos($fullname, 's_') !== 0) {
6690 continue; // not a config value
6692 $data[$fullname] = $value;
6695 $adminroot = admin_get_root();
6696 $settings = admin_find_write_settings($adminroot, $data);
6698 $count = 0;
6699 foreach ($settings as $fullname=>$setting) {
6700 /** @var $setting admin_setting */
6701 $original = $setting->get_setting();
6702 $error = $setting->write_setting($data[$fullname]);
6703 if ($error !== '') {
6704 $adminroot->errors[$fullname] = new stdClass();
6705 $adminroot->errors[$fullname]->data = $data[$fullname];
6706 $adminroot->errors[$fullname]->id = $setting->get_id();
6707 $adminroot->errors[$fullname]->error = $error;
6708 } else {
6709 $setting->write_setting_flags($data);
6711 if ($setting->post_write_settings($original)) {
6712 $count++;
6716 if ($olddbsessions != !empty($CFG->dbsessions)) {
6717 require_logout();
6720 // Now update $SITE - just update the fields, in case other people have a
6721 // a reference to it (e.g. $PAGE, $COURSE).
6722 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6723 foreach (get_object_vars($newsite) as $field => $value) {
6724 $SITE->$field = $value;
6727 // now reload all settings - some of them might depend on the changed
6728 admin_get_root(true);
6729 return $count;
6733 * Internal recursive function - finds all settings from submitted form
6735 * @param object $node Instance of admin_category, or admin_settingpage
6736 * @param array $data
6737 * @return array
6739 function admin_find_write_settings($node, $data) {
6740 $return = array();
6742 if (empty($data)) {
6743 return $return;
6746 if ($node instanceof admin_category) {
6747 $entries = array_keys($node->children);
6748 foreach ($entries as $entry) {
6749 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6752 } else if ($node instanceof admin_settingpage) {
6753 foreach ($node->settings as $setting) {
6754 $fullname = $setting->get_full_name();
6755 if (array_key_exists($fullname, $data)) {
6756 $return[$fullname] = $setting;
6762 return $return;
6766 * Internal function - prints the search results
6768 * @param string $query String to search for
6769 * @return string empty or XHTML
6771 function admin_search_settings_html($query) {
6772 global $CFG, $OUTPUT;
6774 if (core_text::strlen($query) < 2) {
6775 return '';
6777 $query = core_text::strtolower($query);
6779 $adminroot = admin_get_root();
6780 $findings = $adminroot->search($query);
6781 $return = '';
6782 $savebutton = false;
6784 foreach ($findings as $found) {
6785 $page = $found->page;
6786 $settings = $found->settings;
6787 if ($page->is_hidden()) {
6788 // hidden pages are not displayed in search results
6789 continue;
6791 if ($page instanceof admin_externalpage) {
6792 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6793 } else if ($page instanceof admin_settingpage) {
6794 $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');
6795 } else {
6796 continue;
6798 if (!empty($settings)) {
6799 $return .= '<fieldset class="adminsettings">'."\n";
6800 foreach ($settings as $setting) {
6801 if (empty($setting->nosave)) {
6802 $savebutton = true;
6804 $return .= '<div class="clearer"><!-- --></div>'."\n";
6805 $fullname = $setting->get_full_name();
6806 if (array_key_exists($fullname, $adminroot->errors)) {
6807 $data = $adminroot->errors[$fullname]->data;
6808 } else {
6809 $data = $setting->get_setting();
6810 // do not use defaults if settings not available - upgradesettings handles the defaults!
6812 $return .= $setting->output_html($data, $query);
6814 $return .= '</fieldset>';
6818 if ($savebutton) {
6819 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6822 return $return;
6826 * Internal function - returns arrays of html pages with uninitialised settings
6828 * @param object $node Instance of admin_category or admin_settingpage
6829 * @return array
6831 function admin_output_new_settings_by_page($node) {
6832 global $OUTPUT;
6833 $return = array();
6835 if ($node instanceof admin_category) {
6836 $entries = array_keys($node->children);
6837 foreach ($entries as $entry) {
6838 $return += admin_output_new_settings_by_page($node->children[$entry]);
6841 } else if ($node instanceof admin_settingpage) {
6842 $newsettings = array();
6843 foreach ($node->settings as $setting) {
6844 if (is_null($setting->get_setting())) {
6845 $newsettings[] = $setting;
6848 if (count($newsettings) > 0) {
6849 $adminroot = admin_get_root();
6850 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6851 $page .= '<fieldset class="adminsettings">'."\n";
6852 foreach ($newsettings as $setting) {
6853 $fullname = $setting->get_full_name();
6854 if (array_key_exists($fullname, $adminroot->errors)) {
6855 $data = $adminroot->errors[$fullname]->data;
6856 } else {
6857 $data = $setting->get_setting();
6858 if (is_null($data)) {
6859 $data = $setting->get_defaultsetting();
6862 $page .= '<div class="clearer"><!-- --></div>'."\n";
6863 $page .= $setting->output_html($data);
6865 $page .= '</fieldset>';
6866 $return[$node->name] = $page;
6870 return $return;
6874 * Format admin settings
6876 * @param object $setting
6877 * @param string $title label element
6878 * @param string $form form fragment, html code - not highlighted automatically
6879 * @param string $description
6880 * @param bool $label link label to id, true by default
6881 * @param string $warning warning text
6882 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6883 * @param string $query search query to be highlighted
6884 * @return string XHTML
6886 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6887 global $CFG;
6889 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6890 $fullname = $setting->get_full_name();
6892 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6893 if ($label) {
6894 $labelfor = 'for = "'.$setting->get_id().'"';
6895 } else {
6896 $labelfor = '';
6898 $form .= $setting->output_setting_flags();
6900 $override = '';
6901 if (empty($setting->plugin)) {
6902 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6903 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6905 } else {
6906 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6907 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6911 if ($warning !== '') {
6912 $warning = '<div class="form-warning">'.$warning.'</div>';
6915 $defaults = array();
6916 if (!is_null($defaultinfo)) {
6917 if ($defaultinfo === '') {
6918 $defaultinfo = get_string('emptysettingvalue', 'admin');
6920 $defaults[] = $defaultinfo;
6923 $setting->get_setting_flag_defaults($defaults);
6925 if (!empty($defaults)) {
6926 $defaultinfo = implode(', ', $defaults);
6927 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6928 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6932 $str = '
6933 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6934 <div class="form-label">
6935 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6936 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6937 </div>
6938 <div class="form-setting">'.$form.$defaultinfo.'</div>
6939 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6940 </div>';
6942 $adminroot = admin_get_root();
6943 if (array_key_exists($fullname, $adminroot->errors)) {
6944 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6947 return $str;
6951 * Based on find_new_settings{@link ()} in upgradesettings.php
6952 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6954 * @param object $node Instance of admin_category, or admin_settingpage
6955 * @return boolean true if any settings haven't been initialised, false if they all have
6957 function any_new_admin_settings($node) {
6959 if ($node instanceof admin_category) {
6960 $entries = array_keys($node->children);
6961 foreach ($entries as $entry) {
6962 if (any_new_admin_settings($node->children[$entry])) {
6963 return true;
6967 } else if ($node instanceof admin_settingpage) {
6968 foreach ($node->settings as $setting) {
6969 if ($setting->get_setting() === NULL) {
6970 return true;
6975 return false;
6979 * Moved from admin/replace.php so that we can use this in cron
6981 * @param string $search string to look for
6982 * @param string $replace string to replace
6983 * @return bool success or fail
6985 function db_replace($search, $replace) {
6986 global $DB, $CFG, $OUTPUT;
6988 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6989 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
6990 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6991 'block_instances', '');
6993 // Turn off time limits, sometimes upgrades can be slow.
6994 core_php_time_limit::raise();
6996 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6997 return false;
6999 foreach ($tables as $table) {
7001 if (in_array($table, $skiptables)) { // Don't process these
7002 continue;
7005 if ($columns = $DB->get_columns($table)) {
7006 $DB->set_debug(true);
7007 foreach ($columns as $column) {
7008 $DB->replace_all_text($table, $column, $search, $replace);
7010 $DB->set_debug(false);
7014 // delete modinfo caches
7015 rebuild_course_cache(0, true);
7017 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7018 $blocks = core_component::get_plugin_list('block');
7019 foreach ($blocks as $blockname=>$fullblock) {
7020 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7021 continue;
7024 if (!is_readable($fullblock.'/lib.php')) {
7025 continue;
7028 $function = 'block_'.$blockname.'_global_db_replace';
7029 include_once($fullblock.'/lib.php');
7030 if (!function_exists($function)) {
7031 continue;
7034 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7035 $function($search, $replace);
7036 echo $OUTPUT->notification("...finished", 'notifysuccess');
7039 purge_all_caches();
7041 return true;
7045 * Manage repository settings
7047 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7049 class admin_setting_managerepository extends admin_setting {
7050 /** @var string */
7051 private $baseurl;
7054 * calls parent::__construct with specific arguments
7056 public function __construct() {
7057 global $CFG;
7058 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7059 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7063 * Always returns true, does nothing
7065 * @return true
7067 public function get_setting() {
7068 return true;
7072 * Always returns true does nothing
7074 * @return true
7076 public function get_defaultsetting() {
7077 return true;
7081 * Always returns s_managerepository
7083 * @return string Always return 's_managerepository'
7085 public function get_full_name() {
7086 return 's_managerepository';
7090 * Always returns '' doesn't do anything
7092 public function write_setting($data) {
7093 $url = $this->baseurl . '&amp;new=' . $data;
7094 return '';
7095 // TODO
7096 // Should not use redirect and exit here
7097 // Find a better way to do this.
7098 // redirect($url);
7099 // exit;
7103 * Searches repository plugins for one that matches $query
7105 * @param string $query The string to search for
7106 * @return bool true if found, false if not
7108 public function is_related($query) {
7109 if (parent::is_related($query)) {
7110 return true;
7113 $repositories= core_component::get_plugin_list('repository');
7114 foreach ($repositories as $p => $dir) {
7115 if (strpos($p, $query) !== false) {
7116 return true;
7119 foreach (repository::get_types() as $instance) {
7120 $title = $instance->get_typename();
7121 if (strpos(core_text::strtolower($title), $query) !== false) {
7122 return true;
7125 return false;
7129 * Helper function that generates a moodle_url object
7130 * relevant to the repository
7133 function repository_action_url($repository) {
7134 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7138 * Builds XHTML to display the control
7140 * @param string $data Unused
7141 * @param string $query
7142 * @return string XHTML
7144 public function output_html($data, $query='') {
7145 global $CFG, $USER, $OUTPUT;
7147 // Get strings that are used
7148 $strshow = get_string('on', 'repository');
7149 $strhide = get_string('off', 'repository');
7150 $strdelete = get_string('disabled', 'repository');
7152 $actionchoicesforexisting = array(
7153 'show' => $strshow,
7154 'hide' => $strhide,
7155 'delete' => $strdelete
7158 $actionchoicesfornew = array(
7159 'newon' => $strshow,
7160 'newoff' => $strhide,
7161 'delete' => $strdelete
7164 $return = '';
7165 $return .= $OUTPUT->box_start('generalbox');
7167 // Set strings that are used multiple times
7168 $settingsstr = get_string('settings');
7169 $disablestr = get_string('disable');
7171 // Table to list plug-ins
7172 $table = new html_table();
7173 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7174 $table->align = array('left', 'center', 'center', 'center', 'center');
7175 $table->data = array();
7177 // Get list of used plug-ins
7178 $repositorytypes = repository::get_types();
7179 if (!empty($repositorytypes)) {
7180 // Array to store plugins being used
7181 $alreadyplugins = array();
7182 $totalrepositorytypes = count($repositorytypes);
7183 $updowncount = 1;
7184 foreach ($repositorytypes as $i) {
7185 $settings = '';
7186 $typename = $i->get_typename();
7187 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7188 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7189 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7191 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7192 // Calculate number of instances in order to display them for the Moodle administrator
7193 if (!empty($instanceoptionnames)) {
7194 $params = array();
7195 $params['context'] = array(context_system::instance());
7196 $params['onlyvisible'] = false;
7197 $params['type'] = $typename;
7198 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7199 // site instances
7200 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7201 $params['context'] = array();
7202 $instances = repository::static_function($typename, 'get_instances', $params);
7203 $courseinstances = array();
7204 $userinstances = array();
7206 foreach ($instances as $instance) {
7207 $repocontext = context::instance_by_id($instance->instance->contextid);
7208 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7209 $courseinstances[] = $instance;
7210 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7211 $userinstances[] = $instance;
7214 // course instances
7215 $instancenumber = count($courseinstances);
7216 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7218 // user private instances
7219 $instancenumber = count($userinstances);
7220 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7221 } else {
7222 $admininstancenumbertext = "";
7223 $courseinstancenumbertext = "";
7224 $userinstancenumbertext = "";
7227 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7229 $settings .= $OUTPUT->container_start('mdl-left');
7230 $settings .= '<br/>';
7231 $settings .= $admininstancenumbertext;
7232 $settings .= '<br/>';
7233 $settings .= $courseinstancenumbertext;
7234 $settings .= '<br/>';
7235 $settings .= $userinstancenumbertext;
7236 $settings .= $OUTPUT->container_end();
7238 // Get the current visibility
7239 if ($i->get_visible()) {
7240 $currentaction = 'show';
7241 } else {
7242 $currentaction = 'hide';
7245 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7247 // Display up/down link
7248 $updown = '';
7249 // Should be done with CSS instead.
7250 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7252 if ($updowncount > 1) {
7253 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7254 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7256 else {
7257 $updown .= $spacer;
7259 if ($updowncount < $totalrepositorytypes) {
7260 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7261 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7263 else {
7264 $updown .= $spacer;
7267 $updowncount++;
7269 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7271 if (!in_array($typename, $alreadyplugins)) {
7272 $alreadyplugins[] = $typename;
7277 // Get all the plugins that exist on disk
7278 $plugins = core_component::get_plugin_list('repository');
7279 if (!empty($plugins)) {
7280 foreach ($plugins as $plugin => $dir) {
7281 // Check that it has not already been listed
7282 if (!in_array($plugin, $alreadyplugins)) {
7283 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7284 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7289 $return .= html_writer::table($table);
7290 $return .= $OUTPUT->box_end();
7291 return highlight($query, $return);
7296 * Special checkbox for enable mobile web service
7297 * If enable then we store the service id of the mobile service into config table
7298 * If disable then we unstore the service id from the config table
7300 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7302 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7303 private $xmlrpcuse;
7304 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7305 private $restuse;
7308 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7310 * @return boolean
7312 private function is_protocol_cap_allowed() {
7313 global $DB, $CFG;
7315 // We keep xmlrpc enabled for backward compatibility.
7316 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7317 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7318 $params = array();
7319 $params['permission'] = CAP_ALLOW;
7320 $params['roleid'] = $CFG->defaultuserroleid;
7321 $params['capability'] = 'webservice/xmlrpc:use';
7322 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7325 // If the $this->restuse variable is not set, it needs to be set.
7326 if (empty($this->restuse) and $this->restuse!==false) {
7327 $params = array();
7328 $params['permission'] = CAP_ALLOW;
7329 $params['roleid'] = $CFG->defaultuserroleid;
7330 $params['capability'] = 'webservice/rest:use';
7331 $this->restuse = $DB->record_exists('role_capabilities', $params);
7334 return ($this->xmlrpcuse && $this->restuse);
7338 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7339 * @param type $status true to allow, false to not set
7341 private function set_protocol_cap($status) {
7342 global $CFG;
7343 if ($status and !$this->is_protocol_cap_allowed()) {
7344 //need to allow the cap
7345 $permission = CAP_ALLOW;
7346 $assign = true;
7347 } else if (!$status and $this->is_protocol_cap_allowed()){
7348 //need to disallow the cap
7349 $permission = CAP_INHERIT;
7350 $assign = true;
7352 if (!empty($assign)) {
7353 $systemcontext = context_system::instance();
7354 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7355 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7360 * Builds XHTML to display the control.
7361 * The main purpose of this overloading is to display a warning when https
7362 * is not supported by the server
7363 * @param string $data Unused
7364 * @param string $query
7365 * @return string XHTML
7367 public function output_html($data, $query='') {
7368 global $CFG, $OUTPUT;
7369 $html = parent::output_html($data, $query);
7371 if ((string)$data === $this->yes) {
7372 require_once($CFG->dirroot . "/lib/filelib.php");
7373 $curl = new curl();
7374 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7375 $curl->head($httpswwwroot . "/login/index.php");
7376 $info = $curl->get_info();
7377 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7378 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7382 return $html;
7386 * Retrieves the current setting using the objects name
7388 * @return string
7390 public function get_setting() {
7391 global $CFG;
7393 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7394 // Or if web services aren't enabled this can't be,
7395 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7396 return 0;
7399 require_once($CFG->dirroot . '/webservice/lib.php');
7400 $webservicemanager = new webservice();
7401 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7402 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7403 return $this->config_read($this->name); //same as returning 1
7404 } else {
7405 return 0;
7410 * Save the selected setting
7412 * @param string $data The selected site
7413 * @return string empty string or error message
7415 public function write_setting($data) {
7416 global $DB, $CFG;
7418 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7419 if (empty($CFG->defaultuserroleid)) {
7420 return '';
7423 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7425 require_once($CFG->dirroot . '/webservice/lib.php');
7426 $webservicemanager = new webservice();
7428 $updateprotocol = false;
7429 if ((string)$data === $this->yes) {
7430 //code run when enable mobile web service
7431 //enable web service systeme if necessary
7432 set_config('enablewebservices', true);
7434 //enable mobile service
7435 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7436 $mobileservice->enabled = 1;
7437 $webservicemanager->update_external_service($mobileservice);
7439 //enable xml-rpc server
7440 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7442 if (!in_array('xmlrpc', $activeprotocols)) {
7443 $activeprotocols[] = 'xmlrpc';
7444 $updateprotocol = true;
7447 if (!in_array('rest', $activeprotocols)) {
7448 $activeprotocols[] = 'rest';
7449 $updateprotocol = true;
7452 if ($updateprotocol) {
7453 set_config('webserviceprotocols', implode(',', $activeprotocols));
7456 //allow xml-rpc:use capability for authenticated user
7457 $this->set_protocol_cap(true);
7459 } else {
7460 //disable web service system if no other services are enabled
7461 $otherenabledservices = $DB->get_records_select('external_services',
7462 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7463 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7464 if (empty($otherenabledservices)) {
7465 set_config('enablewebservices', false);
7467 //also disable xml-rpc server
7468 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7469 $protocolkey = array_search('xmlrpc', $activeprotocols);
7470 if ($protocolkey !== false) {
7471 unset($activeprotocols[$protocolkey]);
7472 $updateprotocol = true;
7475 $protocolkey = array_search('rest', $activeprotocols);
7476 if ($protocolkey !== false) {
7477 unset($activeprotocols[$protocolkey]);
7478 $updateprotocol = true;
7481 if ($updateprotocol) {
7482 set_config('webserviceprotocols', implode(',', $activeprotocols));
7485 //disallow xml-rpc:use capability for authenticated user
7486 $this->set_protocol_cap(false);
7489 //disable the mobile service
7490 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7491 $mobileservice->enabled = 0;
7492 $webservicemanager->update_external_service($mobileservice);
7495 return (parent::write_setting($data));
7500 * Special class for management of external services
7502 * @author Petr Skoda (skodak)
7504 class admin_setting_manageexternalservices extends admin_setting {
7506 * Calls parent::__construct with specific arguments
7508 public function __construct() {
7509 $this->nosave = true;
7510 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7514 * Always returns true, does nothing
7516 * @return true
7518 public function get_setting() {
7519 return true;
7523 * Always returns true, does nothing
7525 * @return true
7527 public function get_defaultsetting() {
7528 return true;
7532 * Always returns '', does not write anything
7534 * @return string Always returns ''
7536 public function write_setting($data) {
7537 // do not write any setting
7538 return '';
7542 * Checks if $query is one of the available external services
7544 * @param string $query The string to search for
7545 * @return bool Returns true if found, false if not
7547 public function is_related($query) {
7548 global $DB;
7550 if (parent::is_related($query)) {
7551 return true;
7554 $services = $DB->get_records('external_services', array(), 'id, name');
7555 foreach ($services as $service) {
7556 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7557 return true;
7560 return false;
7564 * Builds the XHTML to display the control
7566 * @param string $data Unused
7567 * @param string $query
7568 * @return string
7570 public function output_html($data, $query='') {
7571 global $CFG, $OUTPUT, $DB;
7573 // display strings
7574 $stradministration = get_string('administration');
7575 $stredit = get_string('edit');
7576 $strservice = get_string('externalservice', 'webservice');
7577 $strdelete = get_string('delete');
7578 $strplugin = get_string('plugin', 'admin');
7579 $stradd = get_string('add');
7580 $strfunctions = get_string('functions', 'webservice');
7581 $strusers = get_string('users');
7582 $strserviceusers = get_string('serviceusers', 'webservice');
7584 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7585 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7586 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7588 // built in services
7589 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7590 $return = "";
7591 if (!empty($services)) {
7592 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7596 $table = new html_table();
7597 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7598 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7599 $table->id = 'builtinservices';
7600 $table->attributes['class'] = 'admintable externalservices generaltable';
7601 $table->data = array();
7603 // iterate through auth plugins and add to the display table
7604 foreach ($services as $service) {
7605 $name = $service->name;
7607 // hide/show link
7608 if ($service->enabled) {
7609 $displayname = "<span>$name</span>";
7610 } else {
7611 $displayname = "<span class=\"dimmed_text\">$name</span>";
7614 $plugin = $service->component;
7616 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7618 if ($service->restrictedusers) {
7619 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7620 } else {
7621 $users = get_string('allusers', 'webservice');
7624 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7626 // add a row to the table
7627 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7629 $return .= html_writer::table($table);
7632 // Custom services
7633 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7634 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7636 $table = new html_table();
7637 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7638 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7639 $table->id = 'customservices';
7640 $table->attributes['class'] = 'admintable externalservices generaltable';
7641 $table->data = array();
7643 // iterate through auth plugins and add to the display table
7644 foreach ($services as $service) {
7645 $name = $service->name;
7647 // hide/show link
7648 if ($service->enabled) {
7649 $displayname = "<span>$name</span>";
7650 } else {
7651 $displayname = "<span class=\"dimmed_text\">$name</span>";
7654 // delete link
7655 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7657 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7659 if ($service->restrictedusers) {
7660 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7661 } else {
7662 $users = get_string('allusers', 'webservice');
7665 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7667 // add a row to the table
7668 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7670 // add new custom service option
7671 $return .= html_writer::table($table);
7673 $return .= '<br />';
7674 // add a token to the table
7675 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7677 return highlight($query, $return);
7682 * Special class for overview of external services
7684 * @author Jerome Mouneyrac
7686 class admin_setting_webservicesoverview extends admin_setting {
7689 * Calls parent::__construct with specific arguments
7691 public function __construct() {
7692 $this->nosave = true;
7693 parent::__construct('webservicesoverviewui',
7694 get_string('webservicesoverview', 'webservice'), '', '');
7698 * Always returns true, does nothing
7700 * @return true
7702 public function get_setting() {
7703 return true;
7707 * Always returns true, does nothing
7709 * @return true
7711 public function get_defaultsetting() {
7712 return true;
7716 * Always returns '', does not write anything
7718 * @return string Always returns ''
7720 public function write_setting($data) {
7721 // do not write any setting
7722 return '';
7726 * Builds the XHTML to display the control
7728 * @param string $data Unused
7729 * @param string $query
7730 * @return string
7732 public function output_html($data, $query='') {
7733 global $CFG, $OUTPUT;
7735 $return = "";
7736 $brtag = html_writer::empty_tag('br');
7738 // Enable mobile web service
7739 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7740 get_string('enablemobilewebservice', 'admin'),
7741 get_string('configenablemobilewebservice',
7742 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7743 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7744 $wsmobileparam = new stdClass();
7745 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7746 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7747 get_string('externalservices', 'webservice'));
7748 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7749 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7750 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7751 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7752 . $brtag . $brtag;
7754 /// One system controlling Moodle with Token
7755 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7756 $table = new html_table();
7757 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7758 get_string('description'));
7759 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7760 $table->id = 'onesystemcontrol';
7761 $table->attributes['class'] = 'admintable wsoverview generaltable';
7762 $table->data = array();
7764 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7765 . $brtag . $brtag;
7767 /// 1. Enable Web Services
7768 $row = array();
7769 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7770 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7771 array('href' => $url));
7772 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7773 if ($CFG->enablewebservices) {
7774 $status = get_string('yes');
7776 $row[1] = $status;
7777 $row[2] = get_string('enablewsdescription', 'webservice');
7778 $table->data[] = $row;
7780 /// 2. Enable protocols
7781 $row = array();
7782 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7783 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7784 array('href' => $url));
7785 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7786 //retrieve activated protocol
7787 $active_protocols = empty($CFG->webserviceprotocols) ?
7788 array() : explode(',', $CFG->webserviceprotocols);
7789 if (!empty($active_protocols)) {
7790 $status = "";
7791 foreach ($active_protocols as $protocol) {
7792 $status .= $protocol . $brtag;
7795 $row[1] = $status;
7796 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7797 $table->data[] = $row;
7799 /// 3. Create user account
7800 $row = array();
7801 $url = new moodle_url("/user/editadvanced.php?id=-1");
7802 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7803 array('href' => $url));
7804 $row[1] = "";
7805 $row[2] = get_string('createuserdescription', 'webservice');
7806 $table->data[] = $row;
7808 /// 4. Add capability to users
7809 $row = array();
7810 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7811 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7812 array('href' => $url));
7813 $row[1] = "";
7814 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7815 $table->data[] = $row;
7817 /// 5. Select a web service
7818 $row = array();
7819 $url = new moodle_url("/admin/settings.php?section=externalservices");
7820 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7821 array('href' => $url));
7822 $row[1] = "";
7823 $row[2] = get_string('createservicedescription', 'webservice');
7824 $table->data[] = $row;
7826 /// 6. Add functions
7827 $row = array();
7828 $url = new moodle_url("/admin/settings.php?section=externalservices");
7829 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7830 array('href' => $url));
7831 $row[1] = "";
7832 $row[2] = get_string('addfunctionsdescription', 'webservice');
7833 $table->data[] = $row;
7835 /// 7. Add the specific user
7836 $row = array();
7837 $url = new moodle_url("/admin/settings.php?section=externalservices");
7838 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7839 array('href' => $url));
7840 $row[1] = "";
7841 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7842 $table->data[] = $row;
7844 /// 8. Create token for the specific user
7845 $row = array();
7846 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7847 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7848 array('href' => $url));
7849 $row[1] = "";
7850 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7851 $table->data[] = $row;
7853 /// 9. Enable the documentation
7854 $row = array();
7855 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7856 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7857 array('href' => $url));
7858 $status = '<span class="warning">' . get_string('no') . '</span>';
7859 if ($CFG->enablewsdocumentation) {
7860 $status = get_string('yes');
7862 $row[1] = $status;
7863 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7864 $table->data[] = $row;
7866 /// 10. Test the service
7867 $row = array();
7868 $url = new moodle_url("/admin/webservice/testclient.php");
7869 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7870 array('href' => $url));
7871 $row[1] = "";
7872 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7873 $table->data[] = $row;
7875 $return .= html_writer::table($table);
7877 /// Users as clients with token
7878 $return .= $brtag . $brtag . $brtag;
7879 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7880 $table = new html_table();
7881 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7882 get_string('description'));
7883 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7884 $table->id = 'userasclients';
7885 $table->attributes['class'] = 'admintable wsoverview generaltable';
7886 $table->data = array();
7888 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7889 $brtag . $brtag;
7891 /// 1. Enable Web Services
7892 $row = array();
7893 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7894 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7895 array('href' => $url));
7896 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7897 if ($CFG->enablewebservices) {
7898 $status = get_string('yes');
7900 $row[1] = $status;
7901 $row[2] = get_string('enablewsdescription', 'webservice');
7902 $table->data[] = $row;
7904 /// 2. Enable protocols
7905 $row = array();
7906 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7907 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7908 array('href' => $url));
7909 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7910 //retrieve activated protocol
7911 $active_protocols = empty($CFG->webserviceprotocols) ?
7912 array() : explode(',', $CFG->webserviceprotocols);
7913 if (!empty($active_protocols)) {
7914 $status = "";
7915 foreach ($active_protocols as $protocol) {
7916 $status .= $protocol . $brtag;
7919 $row[1] = $status;
7920 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7921 $table->data[] = $row;
7924 /// 3. Select a web service
7925 $row = array();
7926 $url = new moodle_url("/admin/settings.php?section=externalservices");
7927 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7928 array('href' => $url));
7929 $row[1] = "";
7930 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7931 $table->data[] = $row;
7933 /// 4. Add functions
7934 $row = array();
7935 $url = new moodle_url("/admin/settings.php?section=externalservices");
7936 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7937 array('href' => $url));
7938 $row[1] = "";
7939 $row[2] = get_string('addfunctionsdescription', 'webservice');
7940 $table->data[] = $row;
7942 /// 5. Add capability to users
7943 $row = array();
7944 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7945 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7946 array('href' => $url));
7947 $row[1] = "";
7948 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7949 $table->data[] = $row;
7951 /// 6. Test the service
7952 $row = array();
7953 $url = new moodle_url("/admin/webservice/testclient.php");
7954 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7955 array('href' => $url));
7956 $row[1] = "";
7957 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7958 $table->data[] = $row;
7960 $return .= html_writer::table($table);
7962 return highlight($query, $return);
7969 * Special class for web service protocol administration.
7971 * @author Petr Skoda (skodak)
7973 class admin_setting_managewebserviceprotocols extends admin_setting {
7976 * Calls parent::__construct with specific arguments
7978 public function __construct() {
7979 $this->nosave = true;
7980 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7984 * Always returns true, does nothing
7986 * @return true
7988 public function get_setting() {
7989 return true;
7993 * Always returns true, does nothing
7995 * @return true
7997 public function get_defaultsetting() {
7998 return true;
8002 * Always returns '', does not write anything
8004 * @return string Always returns ''
8006 public function write_setting($data) {
8007 // do not write any setting
8008 return '';
8012 * Checks if $query is one of the available webservices
8014 * @param string $query The string to search for
8015 * @return bool Returns true if found, false if not
8017 public function is_related($query) {
8018 if (parent::is_related($query)) {
8019 return true;
8022 $protocols = core_component::get_plugin_list('webservice');
8023 foreach ($protocols as $protocol=>$location) {
8024 if (strpos($protocol, $query) !== false) {
8025 return true;
8027 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8028 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8029 return true;
8032 return false;
8036 * Builds the XHTML to display the control
8038 * @param string $data Unused
8039 * @param string $query
8040 * @return string
8042 public function output_html($data, $query='') {
8043 global $CFG, $OUTPUT;
8045 // display strings
8046 $stradministration = get_string('administration');
8047 $strsettings = get_string('settings');
8048 $stredit = get_string('edit');
8049 $strprotocol = get_string('protocol', 'webservice');
8050 $strenable = get_string('enable');
8051 $strdisable = get_string('disable');
8052 $strversion = get_string('version');
8054 $protocols_available = core_component::get_plugin_list('webservice');
8055 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8056 ksort($protocols_available);
8058 foreach ($active_protocols as $key=>$protocol) {
8059 if (empty($protocols_available[$protocol])) {
8060 unset($active_protocols[$key]);
8064 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8065 $return .= $OUTPUT->box_start('generalbox webservicesui');
8067 $table = new html_table();
8068 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8069 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8070 $table->id = 'webserviceprotocols';
8071 $table->attributes['class'] = 'admintable generaltable';
8072 $table->data = array();
8074 // iterate through auth plugins and add to the display table
8075 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8076 foreach ($protocols_available as $protocol => $location) {
8077 $name = get_string('pluginname', 'webservice_'.$protocol);
8079 $plugin = new stdClass();
8080 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8081 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8083 $version = isset($plugin->version) ? $plugin->version : '';
8085 // hide/show link
8086 if (in_array($protocol, $active_protocols)) {
8087 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8088 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8089 $displayname = "<span>$name</span>";
8090 } else {
8091 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8092 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8093 $displayname = "<span class=\"dimmed_text\">$name</span>";
8096 // settings link
8097 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8098 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8099 } else {
8100 $settings = '';
8103 // add a row to the table
8104 $table->data[] = array($displayname, $version, $hideshow, $settings);
8106 $return .= html_writer::table($table);
8107 $return .= get_string('configwebserviceplugins', 'webservice');
8108 $return .= $OUTPUT->box_end();
8110 return highlight($query, $return);
8116 * Special class for web service token administration.
8118 * @author Jerome Mouneyrac
8120 class admin_setting_managewebservicetokens extends admin_setting {
8123 * Calls parent::__construct with specific arguments
8125 public function __construct() {
8126 $this->nosave = true;
8127 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8131 * Always returns true, does nothing
8133 * @return true
8135 public function get_setting() {
8136 return true;
8140 * Always returns true, does nothing
8142 * @return true
8144 public function get_defaultsetting() {
8145 return true;
8149 * Always returns '', does not write anything
8151 * @return string Always returns ''
8153 public function write_setting($data) {
8154 // do not write any setting
8155 return '';
8159 * Builds the XHTML to display the control
8161 * @param string $data Unused
8162 * @param string $query
8163 * @return string
8165 public function output_html($data, $query='') {
8166 global $CFG, $OUTPUT, $DB, $USER;
8168 // display strings
8169 $stroperation = get_string('operation', 'webservice');
8170 $strtoken = get_string('token', 'webservice');
8171 $strservice = get_string('service', 'webservice');
8172 $struser = get_string('user');
8173 $strcontext = get_string('context', 'webservice');
8174 $strvaliduntil = get_string('validuntil', 'webservice');
8175 $striprestriction = get_string('iprestriction', 'webservice');
8177 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8179 $table = new html_table();
8180 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8181 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8182 $table->id = 'webservicetokens';
8183 $table->attributes['class'] = 'admintable generaltable';
8184 $table->data = array();
8186 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8188 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8190 //here retrieve token list (including linked users firstname/lastname and linked services name)
8191 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8192 FROM {external_tokens} t, {user} u, {external_services} s
8193 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8194 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8195 if (!empty($tokens)) {
8196 foreach ($tokens as $token) {
8197 //TODO: retrieve context
8199 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8200 $delete .= get_string('delete')."</a>";
8202 $validuntil = '';
8203 if (!empty($token->validuntil)) {
8204 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8207 $iprestriction = '';
8208 if (!empty($token->iprestriction)) {
8209 $iprestriction = $token->iprestriction;
8212 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8213 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8214 $useratag .= $token->firstname." ".$token->lastname;
8215 $useratag .= html_writer::end_tag('a');
8217 //check user missing capabilities
8218 require_once($CFG->dirroot . '/webservice/lib.php');
8219 $webservicemanager = new webservice();
8220 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8221 array(array('id' => $token->userid)), $token->serviceid);
8223 if (!is_siteadmin($token->userid) and
8224 array_key_exists($token->userid, $usermissingcaps)) {
8225 $missingcapabilities = implode(', ',
8226 $usermissingcaps[$token->userid]);
8227 if (!empty($missingcapabilities)) {
8228 $useratag .= html_writer::tag('div',
8229 get_string('usermissingcaps', 'webservice',
8230 $missingcapabilities)
8231 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8232 array('class' => 'missingcaps'));
8236 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8239 $return .= html_writer::table($table);
8240 } else {
8241 $return .= get_string('notoken', 'webservice');
8244 $return .= $OUTPUT->box_end();
8245 // add a token to the table
8246 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8247 $return .= get_string('add')."</a>";
8249 return highlight($query, $return);
8255 * Colour picker
8257 * @copyright 2010 Sam Hemelryk
8258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8260 class admin_setting_configcolourpicker extends admin_setting {
8263 * Information for previewing the colour
8265 * @var array|null
8267 protected $previewconfig = null;
8270 * Use default when empty.
8272 protected $usedefaultwhenempty = true;
8276 * @param string $name
8277 * @param string $visiblename
8278 * @param string $description
8279 * @param string $defaultsetting
8280 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8282 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8283 $usedefaultwhenempty = true) {
8284 $this->previewconfig = $previewconfig;
8285 $this->usedefaultwhenempty = $usedefaultwhenempty;
8286 parent::__construct($name, $visiblename, $description, $defaultsetting);
8290 * Return the setting
8292 * @return mixed returns config if successful else null
8294 public function get_setting() {
8295 return $this->config_read($this->name);
8299 * Saves the setting
8301 * @param string $data
8302 * @return bool
8304 public function write_setting($data) {
8305 $data = $this->validate($data);
8306 if ($data === false) {
8307 return get_string('validateerror', 'admin');
8309 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8313 * Validates the colour that was entered by the user
8315 * @param string $data
8316 * @return string|false
8318 protected function validate($data) {
8320 * List of valid HTML colour names
8322 * @var array
8324 $colornames = array(
8325 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8326 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8327 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8328 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8329 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8330 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8331 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8332 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8333 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8334 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8335 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8336 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8337 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8338 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8339 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8340 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8341 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8342 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8343 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8344 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8345 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8346 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8347 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8348 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8349 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8350 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8351 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8352 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8353 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8354 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8355 'whitesmoke', 'yellow', 'yellowgreen'
8358 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8359 if (strpos($data, '#')!==0) {
8360 $data = '#'.$data;
8362 return $data;
8363 } else if (in_array(strtolower($data), $colornames)) {
8364 return $data;
8365 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8366 return $data;
8367 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8368 return $data;
8369 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8370 return $data;
8371 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8372 return $data;
8373 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8374 return $data;
8375 } else if (empty($data)) {
8376 if ($this->usedefaultwhenempty){
8377 return $this->defaultsetting;
8378 } else {
8379 return '';
8381 } else {
8382 return false;
8387 * Generates the HTML for the setting
8389 * @global moodle_page $PAGE
8390 * @global core_renderer $OUTPUT
8391 * @param string $data
8392 * @param string $query
8394 public function output_html($data, $query = '') {
8395 global $PAGE, $OUTPUT;
8396 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8397 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8398 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8399 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8400 if (!empty($this->previewconfig)) {
8401 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8403 $content .= html_writer::end_tag('div');
8404 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
8410 * Class used for uploading of one file into file storage,
8411 * the file name is stored in config table.
8413 * Please note you need to implement your own '_pluginfile' callback function,
8414 * this setting only stores the file, it does not deal with file serving.
8416 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8419 class admin_setting_configstoredfile extends admin_setting {
8420 /** @var array file area options - should be one file only */
8421 protected $options;
8422 /** @var string name of the file area */
8423 protected $filearea;
8424 /** @var int intemid */
8425 protected $itemid;
8426 /** @var string used for detection of changes */
8427 protected $oldhashes;
8430 * Create new stored file setting.
8432 * @param string $name low level setting name
8433 * @param string $visiblename human readable setting name
8434 * @param string $description description of setting
8435 * @param mixed $filearea file area for file storage
8436 * @param int $itemid itemid for file storage
8437 * @param array $options file area options
8439 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8440 parent::__construct($name, $visiblename, $description, '');
8441 $this->filearea = $filearea;
8442 $this->itemid = $itemid;
8443 $this->options = (array)$options;
8447 * Applies defaults and returns all options.
8448 * @return array
8450 protected function get_options() {
8451 global $CFG;
8453 require_once("$CFG->libdir/filelib.php");
8454 require_once("$CFG->dirroot/repository/lib.php");
8455 $defaults = array(
8456 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8457 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8458 'context' => context_system::instance());
8459 foreach($this->options as $k => $v) {
8460 $defaults[$k] = $v;
8463 return $defaults;
8466 public function get_setting() {
8467 return $this->config_read($this->name);
8470 public function write_setting($data) {
8471 global $USER;
8473 // Let's not deal with validation here, this is for admins only.
8474 $current = $this->get_setting();
8475 if (empty($data) && $current === null) {
8476 // This will be the case when applying default settings (installation).
8477 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8478 } else if (!is_number($data)) {
8479 // Draft item id is expected here!
8480 return get_string('errorsetting', 'admin');
8483 $options = $this->get_options();
8484 $fs = get_file_storage();
8485 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8487 $this->oldhashes = null;
8488 if ($current) {
8489 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8490 if ($file = $fs->get_file_by_hash($hash)) {
8491 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8493 unset($file);
8496 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8497 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8498 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8499 // with an error because the draft area does not exist, as he did not use it.
8500 $usercontext = context_user::instance($USER->id);
8501 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8502 return get_string('errorsetting', 'admin');
8506 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8507 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8509 $filepath = '';
8510 if ($files) {
8511 /** @var stored_file $file */
8512 $file = reset($files);
8513 $filepath = $file->get_filepath().$file->get_filename();
8516 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8519 public function post_write_settings($original) {
8520 $options = $this->get_options();
8521 $fs = get_file_storage();
8522 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8524 $current = $this->get_setting();
8525 $newhashes = null;
8526 if ($current) {
8527 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8528 if ($file = $fs->get_file_by_hash($hash)) {
8529 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8531 unset($file);
8534 if ($this->oldhashes === $newhashes) {
8535 $this->oldhashes = null;
8536 return false;
8538 $this->oldhashes = null;
8540 $callbackfunction = $this->updatedcallback;
8541 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8542 $callbackfunction($this->get_full_name());
8544 return true;
8547 public function output_html($data, $query = '') {
8548 global $PAGE, $CFG;
8550 $options = $this->get_options();
8551 $id = $this->get_id();
8552 $elname = $this->get_full_name();
8553 $draftitemid = file_get_submitted_draft_itemid($elname);
8554 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8555 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8557 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8558 require_once("$CFG->dirroot/lib/form/filemanager.php");
8560 $fmoptions = new stdClass();
8561 $fmoptions->mainfile = $options['mainfile'];
8562 $fmoptions->maxbytes = $options['maxbytes'];
8563 $fmoptions->maxfiles = $options['maxfiles'];
8564 $fmoptions->client_id = uniqid();
8565 $fmoptions->itemid = $draftitemid;
8566 $fmoptions->subdirs = $options['subdirs'];
8567 $fmoptions->target = $id;
8568 $fmoptions->accepted_types = $options['accepted_types'];
8569 $fmoptions->return_types = $options['return_types'];
8570 $fmoptions->context = $options['context'];
8571 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8573 $fm = new form_filemanager($fmoptions);
8574 $output = $PAGE->get_renderer('core', 'files');
8575 $html = $output->render($fm);
8577 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8578 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8580 return format_admin_setting($this, $this->visiblename,
8581 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8587 * Administration interface for user specified regular expressions for device detection.
8589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8591 class admin_setting_devicedetectregex extends admin_setting {
8594 * Calls parent::__construct with specific args
8596 * @param string $name
8597 * @param string $visiblename
8598 * @param string $description
8599 * @param mixed $defaultsetting
8601 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8602 global $CFG;
8603 parent::__construct($name, $visiblename, $description, $defaultsetting);
8607 * Return the current setting(s)
8609 * @return array Current settings array
8611 public function get_setting() {
8612 global $CFG;
8614 $config = $this->config_read($this->name);
8615 if (is_null($config)) {
8616 return null;
8619 return $this->prepare_form_data($config);
8623 * Save selected settings
8625 * @param array $data Array of settings to save
8626 * @return bool
8628 public function write_setting($data) {
8629 if (empty($data)) {
8630 $data = array();
8633 if ($this->config_write($this->name, $this->process_form_data($data))) {
8634 return ''; // success
8635 } else {
8636 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8641 * Return XHTML field(s) for regexes
8643 * @param array $data Array of options to set in HTML
8644 * @return string XHTML string for the fields and wrapping div(s)
8646 public function output_html($data, $query='') {
8647 global $OUTPUT;
8649 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8650 $out .= html_writer::start_tag('thead');
8651 $out .= html_writer::start_tag('tr');
8652 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8653 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8654 $out .= html_writer::end_tag('tr');
8655 $out .= html_writer::end_tag('thead');
8656 $out .= html_writer::start_tag('tbody');
8658 if (empty($data)) {
8659 $looplimit = 1;
8660 } else {
8661 $looplimit = (count($data)/2)+1;
8664 for ($i=0; $i<$looplimit; $i++) {
8665 $out .= html_writer::start_tag('tr');
8667 $expressionname = 'expression'.$i;
8669 if (!empty($data[$expressionname])){
8670 $expression = $data[$expressionname];
8671 } else {
8672 $expression = '';
8675 $out .= html_writer::tag('td',
8676 html_writer::empty_tag('input',
8677 array(
8678 'type' => 'text',
8679 'class' => 'form-text',
8680 'name' => $this->get_full_name().'[expression'.$i.']',
8681 'value' => $expression,
8683 ), array('class' => 'c'.$i)
8686 $valuename = 'value'.$i;
8688 if (!empty($data[$valuename])){
8689 $value = $data[$valuename];
8690 } else {
8691 $value= '';
8694 $out .= html_writer::tag('td',
8695 html_writer::empty_tag('input',
8696 array(
8697 'type' => 'text',
8698 'class' => 'form-text',
8699 'name' => $this->get_full_name().'[value'.$i.']',
8700 'value' => $value,
8702 ), array('class' => 'c'.$i)
8705 $out .= html_writer::end_tag('tr');
8708 $out .= html_writer::end_tag('tbody');
8709 $out .= html_writer::end_tag('table');
8711 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8715 * Converts the string of regexes
8717 * @see self::process_form_data()
8718 * @param $regexes string of regexes
8719 * @return array of form fields and their values
8721 protected function prepare_form_data($regexes) {
8723 $regexes = json_decode($regexes);
8725 $form = array();
8727 $i = 0;
8729 foreach ($regexes as $value => $regex) {
8730 $expressionname = 'expression'.$i;
8731 $valuename = 'value'.$i;
8733 $form[$expressionname] = $regex;
8734 $form[$valuename] = $value;
8735 $i++;
8738 return $form;
8742 * Converts the data from admin settings form into a string of regexes
8744 * @see self::prepare_form_data()
8745 * @param array $data array of admin form fields and values
8746 * @return false|string of regexes
8748 protected function process_form_data(array $form) {
8750 $count = count($form); // number of form field values
8752 if ($count % 2) {
8753 // we must get five fields per expression
8754 return false;
8757 $regexes = array();
8758 for ($i = 0; $i < $count / 2; $i++) {
8759 $expressionname = "expression".$i;
8760 $valuename = "value".$i;
8762 $expression = trim($form['expression'.$i]);
8763 $value = trim($form['value'.$i]);
8765 if (empty($expression)){
8766 continue;
8769 $regexes[$value] = $expression;
8772 $regexes = json_encode($regexes);
8774 return $regexes;
8779 * Multiselect for current modules
8781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8783 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8784 private $excludesystem;
8787 * Calls parent::__construct - note array $choices is not required
8789 * @param string $name setting name
8790 * @param string $visiblename localised setting name
8791 * @param string $description setting description
8792 * @param array $defaultsetting a plain array of default module ids
8793 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8795 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8796 $excludesystem = true) {
8797 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8798 $this->excludesystem = $excludesystem;
8802 * Loads an array of current module choices
8804 * @return bool always return true
8806 public function load_choices() {
8807 if (is_array($this->choices)) {
8808 return true;
8810 $this->choices = array();
8812 global $CFG, $DB;
8813 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8814 foreach ($records as $record) {
8815 // Exclude modules if the code doesn't exist
8816 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8817 // Also exclude system modules (if specified)
8818 if (!($this->excludesystem &&
8819 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8820 MOD_ARCHETYPE_SYSTEM)) {
8821 $this->choices[$record->id] = $record->name;
8825 return true;
8830 * Admin setting to show if a php extension is enabled or not.
8832 * @copyright 2013 Damyon Wiese
8833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8835 class admin_setting_php_extension_enabled extends admin_setting {
8837 /** @var string The name of the extension to check for */
8838 private $extension;
8841 * Calls parent::__construct with specific arguments
8843 public function __construct($name, $visiblename, $description, $extension) {
8844 $this->extension = $extension;
8845 $this->nosave = true;
8846 parent::__construct($name, $visiblename, $description, '');
8850 * Always returns true, does nothing
8852 * @return true
8854 public function get_setting() {
8855 return true;
8859 * Always returns true, does nothing
8861 * @return true
8863 public function get_defaultsetting() {
8864 return true;
8868 * Always returns '', does not write anything
8870 * @return string Always returns ''
8872 public function write_setting($data) {
8873 // Do not write any setting.
8874 return '';
8878 * Outputs the html for this setting.
8879 * @return string Returns an XHTML string
8881 public function output_html($data, $query='') {
8882 global $OUTPUT;
8884 $o = '';
8885 if (!extension_loaded($this->extension)) {
8886 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8888 $o .= format_admin_setting($this, $this->visiblename, $warning);
8890 return $o;