MDL-47153 tool_monitor: added rule_updated event
[moodle.git] / lib / adminlib.php
blob66ad92bbd313625e05eb142f8f60f0420c2cf2fe
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 Inbound Message datakeys.
206 $DB->delete_records_select('messageinbound_datakeys',
207 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($pluginname));
209 // Delete Inbound Message handlers.
210 $DB->delete_records('messageinbound_handlers', array('component' => $pluginname));
212 // delete all the logs
213 $DB->delete_records('log', array('module' => $pluginname));
215 // delete log_display information
216 $DB->delete_records('log_display', array('component' => $component));
218 // delete the module configuration records
219 unset_all_config_for_plugin($component);
220 if ($type === 'mod') {
221 unset_all_config_for_plugin($pluginname);
224 // delete message provider
225 message_provider_uninstall($component);
227 // delete the plugin tables
228 $xmldbfilepath = $plugindirectory . '/db/install.xml';
229 drop_plugin_tables($component, $xmldbfilepath, false);
230 if ($type === 'mod' or $type === 'block') {
231 // non-frankenstyle table prefixes
232 drop_plugin_tables($name, $xmldbfilepath, false);
235 // delete the capabilities that were defined by this module
236 capabilities_cleanup($component);
238 // remove event handlers and dequeue pending events
239 events_uninstall($component);
241 // Delete all remaining files in the filepool owned by the component.
242 $fs = get_file_storage();
243 $fs->delete_component_files($component);
245 // Finally purge all caches.
246 purge_all_caches();
248 // Invalidate the hash used for upgrade detections.
249 set_config('allversionshash', '');
251 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
255 * Returns the version of installed component
257 * @param string $component component name
258 * @param string $source either 'disk' or 'installed' - where to get the version information from
259 * @return string|bool version number or false if the component is not found
261 function get_component_version($component, $source='installed') {
262 global $CFG, $DB;
264 list($type, $name) = core_component::normalize_component($component);
266 // moodle core or a core subsystem
267 if ($type === 'core') {
268 if ($source === 'installed') {
269 if (empty($CFG->version)) {
270 return false;
271 } else {
272 return $CFG->version;
274 } else {
275 if (!is_readable($CFG->dirroot.'/version.php')) {
276 return false;
277 } else {
278 $version = null; //initialize variable for IDEs
279 include($CFG->dirroot.'/version.php');
280 return $version;
285 // activity module
286 if ($type === 'mod') {
287 if ($source === 'installed') {
288 if ($CFG->version < 2013092001.02) {
289 return $DB->get_field('modules', 'version', array('name'=>$name));
290 } else {
291 return get_config('mod_'.$name, 'version');
294 } else {
295 $mods = core_component::get_plugin_list('mod');
296 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
297 return false;
298 } else {
299 $plugin = new stdClass();
300 $plugin->version = null;
301 $module = $plugin;
302 include($mods[$name].'/version.php');
303 return $plugin->version;
308 // block
309 if ($type === 'block') {
310 if ($source === 'installed') {
311 if ($CFG->version < 2013092001.02) {
312 return $DB->get_field('block', 'version', array('name'=>$name));
313 } else {
314 return get_config('block_'.$name, 'version');
316 } else {
317 $blocks = core_component::get_plugin_list('block');
318 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
319 return false;
320 } else {
321 $plugin = new stdclass();
322 include($blocks[$name].'/version.php');
323 return $plugin->version;
328 // all other plugin types
329 if ($source === 'installed') {
330 return get_config($type.'_'.$name, 'version');
331 } else {
332 $plugins = core_component::get_plugin_list($type);
333 if (empty($plugins[$name])) {
334 return false;
335 } else {
336 $plugin = new stdclass();
337 include($plugins[$name].'/version.php');
338 return $plugin->version;
344 * Delete all plugin tables
346 * @param string $name Name of plugin, used as table prefix
347 * @param string $file Path to install.xml file
348 * @param bool $feedback defaults to true
349 * @return bool Always returns true
351 function drop_plugin_tables($name, $file, $feedback=true) {
352 global $CFG, $DB;
354 // first try normal delete
355 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
356 return true;
359 // then try to find all tables that start with name and are not in any xml file
360 $used_tables = get_used_table_names();
362 $tables = $DB->get_tables();
364 /// Iterate over, fixing id fields as necessary
365 foreach ($tables as $table) {
366 if (in_array($table, $used_tables)) {
367 continue;
370 if (strpos($table, $name) !== 0) {
371 continue;
374 // found orphan table --> delete it
375 if ($DB->get_manager()->table_exists($table)) {
376 $xmldb_table = new xmldb_table($table);
377 $DB->get_manager()->drop_table($xmldb_table);
381 return true;
385 * Returns names of all known tables == tables that moodle knows about.
387 * @return array Array of lowercase table names
389 function get_used_table_names() {
390 $table_names = array();
391 $dbdirs = get_db_directories();
393 foreach ($dbdirs as $dbdir) {
394 $file = $dbdir.'/install.xml';
396 $xmldb_file = new xmldb_file($file);
398 if (!$xmldb_file->fileExists()) {
399 continue;
402 $loaded = $xmldb_file->loadXMLStructure();
403 $structure = $xmldb_file->getStructure();
405 if ($loaded and $tables = $structure->getTables()) {
406 foreach($tables as $table) {
407 $table_names[] = strtolower($table->getName());
412 return $table_names;
416 * Returns list of all directories where we expect install.xml files
417 * @return array Array of paths
419 function get_db_directories() {
420 global $CFG;
422 $dbdirs = array();
424 /// First, the main one (lib/db)
425 $dbdirs[] = $CFG->libdir.'/db';
427 /// Then, all the ones defined by core_component::get_plugin_types()
428 $plugintypes = core_component::get_plugin_types();
429 foreach ($plugintypes as $plugintype => $pluginbasedir) {
430 if ($plugins = core_component::get_plugin_list($plugintype)) {
431 foreach ($plugins as $plugin => $plugindir) {
432 $dbdirs[] = $plugindir.'/db';
437 return $dbdirs;
441 * Try to obtain or release the cron lock.
442 * @param string $name name of lock
443 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
444 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
445 * @return bool true if lock obtained
447 function set_cron_lock($name, $until, $ignorecurrent=false) {
448 global $DB;
449 if (empty($name)) {
450 debugging("Tried to get a cron lock for a null fieldname");
451 return false;
454 // remove lock by force == remove from config table
455 if (is_null($until)) {
456 set_config($name, null);
457 return true;
460 if (!$ignorecurrent) {
461 // read value from db - other processes might have changed it
462 $value = $DB->get_field('config', 'value', array('name'=>$name));
464 if ($value and $value > time()) {
465 //lock active
466 return false;
470 set_config($name, $until);
471 return true;
475 * Test if and critical warnings are present
476 * @return bool
478 function admin_critical_warnings_present() {
479 global $SESSION;
481 if (!has_capability('moodle/site:config', context_system::instance())) {
482 return 0;
485 if (!isset($SESSION->admin_critical_warning)) {
486 $SESSION->admin_critical_warning = 0;
487 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
488 $SESSION->admin_critical_warning = 1;
492 return $SESSION->admin_critical_warning;
496 * Detects if float supports at least 10 decimal digits
498 * Detects if float supports at least 10 decimal digits
499 * and also if float-->string conversion works as expected.
501 * @return bool true if problem found
503 function is_float_problem() {
504 $num1 = 2009010200.01;
505 $num2 = 2009010200.02;
507 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
511 * Try to verify that dataroot is not accessible from web.
513 * Try to verify that dataroot is not accessible from web.
514 * It is not 100% correct but might help to reduce number of vulnerable sites.
515 * Protection from httpd.conf and .htaccess is not detected properly.
517 * @uses INSECURE_DATAROOT_WARNING
518 * @uses INSECURE_DATAROOT_ERROR
519 * @param bool $fetchtest try to test public access by fetching file, default false
520 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
522 function is_dataroot_insecure($fetchtest=false) {
523 global $CFG;
525 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
527 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
528 $rp = strrev(trim($rp, '/'));
529 $rp = explode('/', $rp);
530 foreach($rp as $r) {
531 if (strpos($siteroot, '/'.$r.'/') === 0) {
532 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
533 } else {
534 break; // probably alias root
538 $siteroot = strrev($siteroot);
539 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
541 if (strpos($dataroot, $siteroot) !== 0) {
542 return false;
545 if (!$fetchtest) {
546 return INSECURE_DATAROOT_WARNING;
549 // now try all methods to fetch a test file using http protocol
551 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
552 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
553 $httpdocroot = $matches[1];
554 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
555 make_upload_directory('diag');
556 $testfile = $CFG->dataroot.'/diag/public.txt';
557 if (!file_exists($testfile)) {
558 file_put_contents($testfile, 'test file, do not delete');
559 @chmod($testfile, $CFG->filepermissions);
561 $teststr = trim(file_get_contents($testfile));
562 if (empty($teststr)) {
563 // hmm, strange
564 return INSECURE_DATAROOT_WARNING;
567 $testurl = $datarooturl.'/diag/public.txt';
568 if (extension_loaded('curl') and
569 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
570 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
571 ($ch = @curl_init($testurl)) !== false) {
572 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
573 curl_setopt($ch, CURLOPT_HEADER, false);
574 $data = curl_exec($ch);
575 if (!curl_errno($ch)) {
576 $data = trim($data);
577 if ($data === $teststr) {
578 curl_close($ch);
579 return INSECURE_DATAROOT_ERROR;
582 curl_close($ch);
585 if ($data = @file_get_contents($testurl)) {
586 $data = trim($data);
587 if ($data === $teststr) {
588 return INSECURE_DATAROOT_ERROR;
592 preg_match('|https?://([^/]+)|i', $testurl, $matches);
593 $sitename = $matches[1];
594 $error = 0;
595 if ($fp = @fsockopen($sitename, 80, $error)) {
596 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
597 $localurl = $matches[1];
598 $out = "GET $localurl HTTP/1.1\r\n";
599 $out .= "Host: $sitename\r\n";
600 $out .= "Connection: Close\r\n\r\n";
601 fwrite($fp, $out);
602 $data = '';
603 $incoming = false;
604 while (!feof($fp)) {
605 if ($incoming) {
606 $data .= fgets($fp, 1024);
607 } else if (@fgets($fp, 1024) === "\r\n") {
608 $incoming = true;
611 fclose($fp);
612 $data = trim($data);
613 if ($data === $teststr) {
614 return INSECURE_DATAROOT_ERROR;
618 return INSECURE_DATAROOT_WARNING;
622 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
624 function enable_cli_maintenance_mode() {
625 global $CFG;
627 if (file_exists("$CFG->dataroot/climaintenance.html")) {
628 unlink("$CFG->dataroot/climaintenance.html");
631 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
632 $data = $CFG->maintenance_message;
633 $data = bootstrap_renderer::early_error_content($data, null, null, null);
634 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
636 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
637 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
639 } else {
640 $data = get_string('sitemaintenance', 'admin');
641 $data = bootstrap_renderer::early_error_content($data, null, null, null);
642 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
645 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
646 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
649 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
653 * Interface for anything appearing in the admin tree
655 * The interface that is implemented by anything that appears in the admin tree
656 * block. It forces inheriting classes to define a method for checking user permissions
657 * and methods for finding something in the admin tree.
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
661 interface part_of_admin_tree {
664 * Finds a named part_of_admin_tree.
666 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
667 * and not parentable_part_of_admin_tree, then this function should only check if
668 * $this->name matches $name. If it does, it should return a reference to $this,
669 * otherwise, it should return a reference to NULL.
671 * If a class inherits parentable_part_of_admin_tree, this method should be called
672 * recursively on all child objects (assuming, of course, the parent object's name
673 * doesn't match the search criterion).
675 * @param string $name The internal name of the part_of_admin_tree we're searching for.
676 * @return mixed An object reference or a NULL reference.
678 public function locate($name);
681 * Removes named part_of_admin_tree.
683 * @param string $name The internal name of the part_of_admin_tree we want to remove.
684 * @return bool success.
686 public function prune($name);
689 * Search using query
690 * @param string $query
691 * @return mixed array-object structure of found settings and pages
693 public function search($query);
696 * Verifies current user's access to this part_of_admin_tree.
698 * Used to check if the current user has access to this part of the admin tree or
699 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
700 * then this method is usually just a call to has_capability() in the site context.
702 * If a class inherits parentable_part_of_admin_tree, this method should return the
703 * logical OR of the return of check_access() on all child objects.
705 * @return bool True if the user has access, false if she doesn't.
707 public function check_access();
710 * Mostly useful for removing of some parts of the tree in admin tree block.
712 * @return True is hidden from normal list view
714 public function is_hidden();
717 * Show we display Save button at the page bottom?
718 * @return bool
720 public function show_save();
725 * Interface implemented by any part_of_admin_tree that has children.
727 * The interface implemented by any part_of_admin_tree that can be a parent
728 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
729 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
730 * include an add method for adding other part_of_admin_tree objects as children.
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 interface parentable_part_of_admin_tree extends part_of_admin_tree {
737 * Adds a part_of_admin_tree object to the admin tree.
739 * Used to add a part_of_admin_tree object to this object or a child of this
740 * object. $something should only be added if $destinationname matches
741 * $this->name. If it doesn't, add should be called on child objects that are
742 * also parentable_part_of_admin_tree's.
744 * $something should be appended as the last child in the $destinationname. If the
745 * $beforesibling is specified, $something should be prepended to it. If the given
746 * sibling is not found, $something should be appended to the end of $destinationname
747 * and a developer debugging message should be displayed.
749 * @param string $destinationname The internal name of the new parent for $something.
750 * @param part_of_admin_tree $something The object to be added.
751 * @return bool True on success, false on failure.
753 public function add($destinationname, $something, $beforesibling = null);
759 * The object used to represent folders (a.k.a. categories) in the admin tree block.
761 * Each admin_category object contains a number of part_of_admin_tree objects.
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class admin_category implements parentable_part_of_admin_tree {
767 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
768 protected $children;
769 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
770 public $name;
771 /** @var string The displayed name for this category. Usually obtained through get_string() */
772 public $visiblename;
773 /** @var bool Should this category be hidden in admin tree block? */
774 public $hidden;
775 /** @var mixed Either a string or an array or strings */
776 public $path;
777 /** @var mixed Either a string or an array or strings */
778 public $visiblepath;
780 /** @var array fast lookup category cache, all categories of one tree point to one cache */
781 protected $category_cache;
783 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
784 protected $sort = false;
785 /** @var bool If set to true children will be sorted in ascending order. */
786 protected $sortasc = true;
787 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
788 protected $sortsplit = true;
789 /** @var bool $sorted True if the children have been sorted and don't need resorting */
790 protected $sorted = false;
793 * Constructor for an empty admin category
795 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
796 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
797 * @param bool $hidden hide category in admin tree block, defaults to false
799 public function __construct($name, $visiblename, $hidden=false) {
800 $this->children = array();
801 $this->name = $name;
802 $this->visiblename = $visiblename;
803 $this->hidden = $hidden;
807 * Returns a reference to the part_of_admin_tree object with internal name $name.
809 * @param string $name The internal name of the object we want.
810 * @param bool $findpath initialize path and visiblepath arrays
811 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
812 * defaults to false
814 public function locate($name, $findpath=false) {
815 if (!isset($this->category_cache[$this->name])) {
816 // somebody much have purged the cache
817 $this->category_cache[$this->name] = $this;
820 if ($this->name == $name) {
821 if ($findpath) {
822 $this->visiblepath[] = $this->visiblename;
823 $this->path[] = $this->name;
825 return $this;
828 // quick category lookup
829 if (!$findpath and isset($this->category_cache[$name])) {
830 return $this->category_cache[$name];
833 $return = NULL;
834 foreach($this->children as $childid=>$unused) {
835 if ($return = $this->children[$childid]->locate($name, $findpath)) {
836 break;
840 if (!is_null($return) and $findpath) {
841 $return->visiblepath[] = $this->visiblename;
842 $return->path[] = $this->name;
845 return $return;
849 * Search using query
851 * @param string query
852 * @return mixed array-object structure of found settings and pages
854 public function search($query) {
855 $result = array();
856 foreach ($this->get_children() as $child) {
857 $subsearch = $child->search($query);
858 if (!is_array($subsearch)) {
859 debugging('Incorrect search result from '.$child->name);
860 continue;
862 $result = array_merge($result, $subsearch);
864 return $result;
868 * Removes part_of_admin_tree object with internal name $name.
870 * @param string $name The internal name of the object we want to remove.
871 * @return bool success
873 public function prune($name) {
875 if ($this->name == $name) {
876 return false; //can not remove itself
879 foreach($this->children as $precedence => $child) {
880 if ($child->name == $name) {
881 // clear cache and delete self
882 while($this->category_cache) {
883 // delete the cache, but keep the original array address
884 array_pop($this->category_cache);
886 unset($this->children[$precedence]);
887 return true;
888 } else if ($this->children[$precedence]->prune($name)) {
889 return true;
892 return false;
896 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
898 * By default the new part of the tree is appended as the last child of the parent. You
899 * can specify a sibling node that the new part should be prepended to. If the given
900 * sibling is not found, the part is appended to the end (as it would be by default) and
901 * a developer debugging message is displayed.
903 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
904 * @param string $destinationame The internal name of the immediate parent that we want for $something.
905 * @param mixed $something A part_of_admin_tree or setting instance to be added.
906 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something, $beforesibling = null) {
910 global $CFG;
912 $parent = $this->locate($parentname);
913 if (is_null($parent)) {
914 debugging('parent does not exist!');
915 return false;
918 if ($something instanceof part_of_admin_tree) {
919 if (!($parent instanceof parentable_part_of_admin_tree)) {
920 debugging('error - parts of tree can be inserted only into parentable parts');
921 return false;
923 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
924 // The name of the node is already used, simply warn the developer that this should not happen.
925 // It is intentional to check for the debug level before performing the check.
926 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
928 if (is_null($beforesibling)) {
929 // Append $something as the parent's last child.
930 $parent->children[] = $something;
931 } else {
932 if (!is_string($beforesibling) or trim($beforesibling) === '') {
933 throw new coding_exception('Unexpected value of the beforesibling parameter');
935 // Try to find the position of the sibling.
936 $siblingposition = null;
937 foreach ($parent->children as $childposition => $child) {
938 if ($child->name === $beforesibling) {
939 $siblingposition = $childposition;
940 break;
943 if (is_null($siblingposition)) {
944 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
945 $parent->children[] = $something;
946 } else {
947 $parent->children = array_merge(
948 array_slice($parent->children, 0, $siblingposition),
949 array($something),
950 array_slice($parent->children, $siblingposition)
954 if ($something instanceof admin_category) {
955 if (isset($this->category_cache[$something->name])) {
956 debugging('Duplicate admin category name: '.$something->name);
957 } else {
958 $this->category_cache[$something->name] = $something;
959 $something->category_cache =& $this->category_cache;
960 foreach ($something->children as $child) {
961 // just in case somebody already added subcategories
962 if ($child instanceof admin_category) {
963 if (isset($this->category_cache[$child->name])) {
964 debugging('Duplicate admin category name: '.$child->name);
965 } else {
966 $this->category_cache[$child->name] = $child;
967 $child->category_cache =& $this->category_cache;
973 return true;
975 } else {
976 debugging('error - can not add this element');
977 return false;
983 * Checks if the user has access to anything in this category.
985 * @return bool True if the user has access to at least one child in this category, false otherwise.
987 public function check_access() {
988 foreach ($this->children as $child) {
989 if ($child->check_access()) {
990 return true;
993 return false;
997 * Is this category hidden in admin tree block?
999 * @return bool True if hidden
1001 public function is_hidden() {
1002 return $this->hidden;
1006 * Show we display Save button at the page bottom?
1007 * @return bool
1009 public function show_save() {
1010 foreach ($this->children as $child) {
1011 if ($child->show_save()) {
1012 return true;
1015 return false;
1019 * Sets sorting on this category.
1021 * Please note this function doesn't actually do the sorting.
1022 * It can be called anytime.
1023 * Sorting occurs when the user calls get_children.
1024 * Code using the children array directly won't see the sorted results.
1026 * @param bool $sort If set to true children will be sorted, if false they won't be.
1027 * @param bool $asc If true sorting will be ascending, otherwise descending.
1028 * @param bool $split If true we sort pages and sub categories separately.
1030 public function set_sorting($sort, $asc = true, $split = true) {
1031 $this->sort = (bool)$sort;
1032 $this->sortasc = (bool)$asc;
1033 $this->sortsplit = (bool)$split;
1037 * Returns the children associated with this category.
1039 * @return part_of_admin_tree[]
1041 public function get_children() {
1042 // If we should sort and it hasn't already been sorted.
1043 if ($this->sort && !$this->sorted) {
1044 if ($this->sortsplit) {
1045 $categories = array();
1046 $pages = array();
1047 foreach ($this->children as $child) {
1048 if ($child instanceof admin_category) {
1049 $categories[] = $child;
1050 } else {
1051 $pages[] = $child;
1054 core_collator::asort_objects_by_property($categories, 'visiblename');
1055 core_collator::asort_objects_by_property($pages, 'visiblename');
1056 if (!$this->sortasc) {
1057 $categories = array_reverse($categories);
1058 $pages = array_reverse($pages);
1060 $this->children = array_merge($pages, $categories);
1061 } else {
1062 core_collator::asort_objects_by_property($this->children, 'visiblename');
1063 if (!$this->sortasc) {
1064 $this->children = array_reverse($this->children);
1067 $this->sorted = true;
1069 return $this->children;
1073 * Magically gets a property from this object.
1075 * @param $property
1076 * @return part_of_admin_tree[]
1077 * @throws coding_exception
1079 public function __get($property) {
1080 if ($property === 'children') {
1081 return $this->get_children();
1083 throw new coding_exception('Invalid property requested.');
1087 * Magically sets a property against this object.
1089 * @param string $property
1090 * @param mixed $value
1091 * @throws coding_exception
1093 public function __set($property, $value) {
1094 if ($property === 'children') {
1095 $this->sorted = false;
1096 $this->children = $value;
1097 } else {
1098 throw new coding_exception('Invalid property requested.');
1103 * Checks if an inaccessible property is set.
1105 * @param string $property
1106 * @return bool
1107 * @throws coding_exception
1109 public function __isset($property) {
1110 if ($property === 'children') {
1111 return isset($this->children);
1113 throw new coding_exception('Invalid property requested.');
1119 * Root of admin settings tree, does not have any parent.
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class admin_root extends admin_category {
1124 /** @var array List of errors */
1125 public $errors;
1126 /** @var string search query */
1127 public $search;
1128 /** @var bool full tree flag - true means all settings required, false only pages required */
1129 public $fulltree;
1130 /** @var bool flag indicating loaded tree */
1131 public $loaded;
1132 /** @var mixed site custom defaults overriding defaults in settings files*/
1133 public $custom_defaults;
1136 * @param bool $fulltree true means all settings required,
1137 * false only pages required
1139 public function __construct($fulltree) {
1140 global $CFG;
1142 parent::__construct('root', get_string('administration'), false);
1143 $this->errors = array();
1144 $this->search = '';
1145 $this->fulltree = $fulltree;
1146 $this->loaded = false;
1148 $this->category_cache = array();
1150 // load custom defaults if found
1151 $this->custom_defaults = null;
1152 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1153 if (is_readable($defaultsfile)) {
1154 $defaults = array();
1155 include($defaultsfile);
1156 if (is_array($defaults) and count($defaults)) {
1157 $this->custom_defaults = $defaults;
1163 * Empties children array, and sets loaded to false
1165 * @param bool $requirefulltree
1167 public function purge_children($requirefulltree) {
1168 $this->children = array();
1169 $this->fulltree = ($requirefulltree || $this->fulltree);
1170 $this->loaded = false;
1171 //break circular dependencies - this helps PHP 5.2
1172 while($this->category_cache) {
1173 array_pop($this->category_cache);
1175 $this->category_cache = array();
1181 * Links external PHP pages into the admin tree.
1183 * See detailed usage example at the top of this document (adminlib.php)
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1187 class admin_externalpage implements part_of_admin_tree {
1189 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1190 public $name;
1192 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1193 public $visiblename;
1195 /** @var string The external URL that we should link to when someone requests this external page. */
1196 public $url;
1198 /** @var string The role capability/permission a user must have to access this external page. */
1199 public $req_capability;
1201 /** @var object The context in which capability/permission should be checked, default is site context. */
1202 public $context;
1204 /** @var bool hidden in admin tree block. */
1205 public $hidden;
1207 /** @var mixed either string or array of string */
1208 public $path;
1210 /** @var array list of visible names of page parents */
1211 public $visiblepath;
1214 * Constructor for adding an external page into the admin tree.
1216 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1217 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1218 * @param string $url The external URL that we should link to when someone requests this external page.
1219 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1220 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1221 * @param stdClass $context The context the page relates to. Not sure what happens
1222 * if you specify something other than system or front page. Defaults to system.
1224 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1225 $this->name = $name;
1226 $this->visiblename = $visiblename;
1227 $this->url = $url;
1228 if (is_array($req_capability)) {
1229 $this->req_capability = $req_capability;
1230 } else {
1231 $this->req_capability = array($req_capability);
1233 $this->hidden = $hidden;
1234 $this->context = $context;
1238 * Returns a reference to the part_of_admin_tree object with internal name $name.
1240 * @param string $name The internal name of the object we want.
1241 * @param bool $findpath defaults to false
1242 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1244 public function locate($name, $findpath=false) {
1245 if ($this->name == $name) {
1246 if ($findpath) {
1247 $this->visiblepath = array($this->visiblename);
1248 $this->path = array($this->name);
1250 return $this;
1251 } else {
1252 $return = NULL;
1253 return $return;
1258 * This function always returns false, required function by interface
1260 * @param string $name
1261 * @return false
1263 public function prune($name) {
1264 return false;
1268 * Search using query
1270 * @param string $query
1271 * @return mixed array-object structure of found settings and pages
1273 public function search($query) {
1274 $found = false;
1275 if (strpos(strtolower($this->name), $query) !== false) {
1276 $found = true;
1277 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1278 $found = true;
1280 if ($found) {
1281 $result = new stdClass();
1282 $result->page = $this;
1283 $result->settings = array();
1284 return array($this->name => $result);
1285 } else {
1286 return array();
1291 * Determines if the current user has access to this external page based on $this->req_capability.
1293 * @return bool True if user has access, false otherwise.
1295 public function check_access() {
1296 global $CFG;
1297 $context = empty($this->context) ? context_system::instance() : $this->context;
1298 foreach($this->req_capability as $cap) {
1299 if (has_capability($cap, $context)) {
1300 return true;
1303 return false;
1307 * Is this external page hidden in admin tree block?
1309 * @return bool True if hidden
1311 public function is_hidden() {
1312 return $this->hidden;
1316 * Show we display Save button at the page bottom?
1317 * @return bool
1319 public function show_save() {
1320 return false;
1326 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 class admin_settingpage implements part_of_admin_tree {
1332 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1333 public $name;
1335 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1336 public $visiblename;
1338 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1339 public $settings;
1341 /** @var string The role capability/permission a user must have to access this external page. */
1342 public $req_capability;
1344 /** @var object The context in which capability/permission should be checked, default is site context. */
1345 public $context;
1347 /** @var bool hidden in admin tree block. */
1348 public $hidden;
1350 /** @var mixed string of paths or array of strings of paths */
1351 public $path;
1353 /** @var array list of visible names of page parents */
1354 public $visiblepath;
1357 * see admin_settingpage for details of this function
1359 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1360 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1361 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1362 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1363 * @param stdClass $context The context the page relates to. Not sure what happens
1364 * if you specify something other than system or front page. Defaults to system.
1366 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1367 $this->settings = new stdClass();
1368 $this->name = $name;
1369 $this->visiblename = $visiblename;
1370 if (is_array($req_capability)) {
1371 $this->req_capability = $req_capability;
1372 } else {
1373 $this->req_capability = array($req_capability);
1375 $this->hidden = $hidden;
1376 $this->context = $context;
1380 * see admin_category
1382 * @param string $name
1383 * @param bool $findpath
1384 * @return mixed Object (this) if name == this->name, else returns null
1386 public function locate($name, $findpath=false) {
1387 if ($this->name == $name) {
1388 if ($findpath) {
1389 $this->visiblepath = array($this->visiblename);
1390 $this->path = array($this->name);
1392 return $this;
1393 } else {
1394 $return = NULL;
1395 return $return;
1400 * Search string in settings page.
1402 * @param string $query
1403 * @return array
1405 public function search($query) {
1406 $found = array();
1408 foreach ($this->settings as $setting) {
1409 if ($setting->is_related($query)) {
1410 $found[] = $setting;
1414 if ($found) {
1415 $result = new stdClass();
1416 $result->page = $this;
1417 $result->settings = $found;
1418 return array($this->name => $result);
1421 $found = false;
1422 if (strpos(strtolower($this->name), $query) !== false) {
1423 $found = true;
1424 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1425 $found = true;
1427 if ($found) {
1428 $result = new stdClass();
1429 $result->page = $this;
1430 $result->settings = array();
1431 return array($this->name => $result);
1432 } else {
1433 return array();
1438 * This function always returns false, required by interface
1440 * @param string $name
1441 * @return bool Always false
1443 public function prune($name) {
1444 return false;
1448 * adds an admin_setting to this admin_settingpage
1450 * 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
1451 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1453 * @param object $setting is the admin_setting object you want to add
1454 * @return bool true if successful, false if not
1456 public function add($setting) {
1457 if (!($setting instanceof admin_setting)) {
1458 debugging('error - not a setting instance');
1459 return false;
1462 $this->settings->{$setting->name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1554 * Constructor
1555 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1556 * or 'myplugin/mysetting' for ones in config_plugins.
1557 * @param string $visiblename localised name
1558 * @param string $description localised long description
1559 * @param mixed $defaultsetting string or array depending on implementation
1561 public function __construct($name, $visiblename, $description, $defaultsetting) {
1562 $this->parse_setting_name($name);
1563 $this->visiblename = $visiblename;
1564 $this->description = $description;
1565 $this->defaultsetting = $defaultsetting;
1569 * Generic function to add a flag to this admin setting.
1571 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1572 * @param bool $default - The default for the flag
1573 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1574 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1576 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1577 if (empty($this->flags[$shortname])) {
1578 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1579 } else {
1580 $this->flags[$shortname]->set_options($enabled, $default);
1585 * Set the enabled options flag on this admin setting.
1587 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1588 * @param bool $default - The default for the flag
1590 public function set_enabled_flag_options($enabled, $default) {
1591 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1595 * Set the advanced options flag on this admin setting.
1597 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1598 * @param bool $default - The default for the flag
1600 public function set_advanced_flag_options($enabled, $default) {
1601 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1606 * Set the locked options flag on this admin setting.
1608 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1609 * @param bool $default - The default for the flag
1611 public function set_locked_flag_options($enabled, $default) {
1612 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1616 * Get the currently saved value for a setting flag
1618 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1619 * @return bool
1621 public function get_setting_flag_value(admin_setting_flag $flag) {
1622 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1623 if (!isset($value)) {
1624 $value = $flag->get_default();
1627 return !empty($value);
1631 * Get the list of defaults for the flags on this setting.
1633 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1635 public function get_setting_flag_defaults(& $defaults) {
1636 foreach ($this->flags as $flag) {
1637 if ($flag->is_enabled() && $flag->get_default()) {
1638 $defaults[] = $flag->get_displayname();
1644 * Output the input fields for the advanced and locked flags on this setting.
1646 * @param bool $adv - The current value of the advanced flag.
1647 * @param bool $locked - The current value of the locked flag.
1648 * @return string $output - The html for the flags.
1650 public function output_setting_flags() {
1651 $output = '';
1653 foreach ($this->flags as $flag) {
1654 if ($flag->is_enabled()) {
1655 $output .= $flag->output_setting_flag($this);
1659 if (!empty($output)) {
1660 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1662 return $output;
1666 * Write the values of the flags for this admin setting.
1668 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1669 * @return bool - true if successful.
1671 public function write_setting_flags($data) {
1672 $result = true;
1673 foreach ($this->flags as $flag) {
1674 $result = $result && $flag->write_setting_flag($this, $data);
1676 return $result;
1680 * Set up $this->name and potentially $this->plugin
1682 * Set up $this->name and possibly $this->plugin based on whether $name looks
1683 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1684 * on the names, that is, output a developer debug warning if the name
1685 * contains anything other than [a-zA-Z0-9_]+.
1687 * @param string $name the setting name passed in to the constructor.
1689 private function parse_setting_name($name) {
1690 $bits = explode('/', $name);
1691 if (count($bits) > 2) {
1692 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1694 $this->name = array_pop($bits);
1695 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1698 if (!empty($bits)) {
1699 $this->plugin = array_pop($bits);
1700 if ($this->plugin === 'moodle') {
1701 $this->plugin = null;
1702 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1703 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1709 * Returns the fullname prefixed by the plugin
1710 * @return string
1712 public function get_full_name() {
1713 return 's_'.$this->plugin.'_'.$this->name;
1717 * Returns the ID string based on plugin and name
1718 * @return string
1720 public function get_id() {
1721 return 'id_s_'.$this->plugin.'_'.$this->name;
1725 * @param bool $affectsmodinfo If true, changes to this setting will
1726 * cause the course cache to be rebuilt
1728 public function set_affects_modinfo($affectsmodinfo) {
1729 $this->affectsmodinfo = $affectsmodinfo;
1733 * Returns the config if possible
1735 * @return mixed returns config if successful else null
1737 public function config_read($name) {
1738 global $CFG;
1739 if (!empty($this->plugin)) {
1740 $value = get_config($this->plugin, $name);
1741 return $value === false ? NULL : $value;
1743 } else {
1744 if (isset($CFG->$name)) {
1745 return $CFG->$name;
1746 } else {
1747 return NULL;
1753 * Used to set a config pair and log change
1755 * @param string $name
1756 * @param mixed $value Gets converted to string if not null
1757 * @return bool Write setting to config table
1759 public function config_write($name, $value) {
1760 global $DB, $USER, $CFG;
1762 if ($this->nosave) {
1763 return true;
1766 // make sure it is a real change
1767 $oldvalue = get_config($this->plugin, $name);
1768 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1769 $value = is_null($value) ? null : (string)$value;
1771 if ($oldvalue === $value) {
1772 return true;
1775 // store change
1776 set_config($name, $value, $this->plugin);
1778 // Some admin settings affect course modinfo
1779 if ($this->affectsmodinfo) {
1780 // Clear course cache for all courses
1781 rebuild_course_cache(0, true);
1784 $this->add_to_config_log($name, $oldvalue, $value);
1786 return true; // BC only
1790 * Log config changes if necessary.
1791 * @param string $name
1792 * @param string $oldvalue
1793 * @param string $value
1795 protected function add_to_config_log($name, $oldvalue, $value) {
1796 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1800 * Returns current value of this setting
1801 * @return mixed array or string depending on instance, NULL means not set yet
1803 public abstract function get_setting();
1806 * Returns default setting if exists
1807 * @return mixed array or string depending on instance; NULL means no default, user must supply
1809 public function get_defaultsetting() {
1810 $adminroot = admin_get_root(false, false);
1811 if (!empty($adminroot->custom_defaults)) {
1812 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1813 if (isset($adminroot->custom_defaults[$plugin])) {
1814 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1815 return $adminroot->custom_defaults[$plugin][$this->name];
1819 return $this->defaultsetting;
1823 * Store new setting
1825 * @param mixed $data string or array, must not be NULL
1826 * @return string empty string if ok, string error message otherwise
1828 public abstract function write_setting($data);
1831 * Return part of form with setting
1832 * This function should always be overwritten
1834 * @param mixed $data array or string depending on setting
1835 * @param string $query
1836 * @return string
1838 public function output_html($data, $query='') {
1839 // should be overridden
1840 return;
1844 * Function called if setting updated - cleanup, cache reset, etc.
1845 * @param string $functionname Sets the function name
1846 * @return void
1848 public function set_updatedcallback($functionname) {
1849 $this->updatedcallback = $functionname;
1853 * Execute postupdatecallback if necessary.
1854 * @param mixed $original original value before write_setting()
1855 * @return bool true if changed, false if not.
1857 public function post_write_settings($original) {
1858 // Comparison must work for arrays too.
1859 if (serialize($original) === serialize($this->get_setting())) {
1860 return false;
1863 $callbackfunction = $this->updatedcallback;
1864 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1865 $callbackfunction($this->get_full_name());
1867 return true;
1871 * Is setting related to query text - used when searching
1872 * @param string $query
1873 * @return bool
1875 public function is_related($query) {
1876 if (strpos(strtolower($this->name), $query) !== false) {
1877 return true;
1879 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1883 return true;
1885 $current = $this->get_setting();
1886 if (!is_null($current)) {
1887 if (is_string($current)) {
1888 if (strpos(core_text::strtolower($current), $query) !== false) {
1889 return true;
1893 $default = $this->get_defaultsetting();
1894 if (!is_null($default)) {
1895 if (is_string($default)) {
1896 if (strpos(core_text::strtolower($default), $query) !== false) {
1897 return true;
1901 return false;
1906 * An additional option that can be applied to an admin setting.
1907 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class admin_setting_flag {
1912 /** @var bool Flag to indicate if this option can be toggled for this setting */
1913 private $enabled = false;
1914 /** @var bool Flag to indicate if this option defaults to true or false */
1915 private $default = false;
1916 /** @var string Short string used to create setting name - e.g. 'adv' */
1917 private $shortname = '';
1918 /** @var string String used as the label for this flag */
1919 private $displayname = '';
1920 /** @const Checkbox for this flag is displayed in admin page */
1921 const ENABLED = true;
1922 /** @const Checkbox for this flag is not displayed in admin page */
1923 const DISABLED = false;
1926 * Constructor
1928 * @param bool $enabled Can this option can be toggled.
1929 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1930 * @param bool $default The default checked state for this setting option.
1931 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1932 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1934 public function __construct($enabled, $default, $shortname, $displayname) {
1935 $this->shortname = $shortname;
1936 $this->displayname = $displayname;
1937 $this->set_options($enabled, $default);
1941 * Update the values of this setting options class
1943 * @param bool $enabled Can this option can be toggled.
1944 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1945 * @param bool $default The default checked state for this setting option.
1947 public function set_options($enabled, $default) {
1948 $this->enabled = $enabled;
1949 $this->default = $default;
1953 * Should this option appear in the interface and be toggleable?
1955 * @return bool Is it enabled?
1957 public function is_enabled() {
1958 return $this->enabled;
1962 * Should this option be checked by default?
1964 * @return bool Is it on by default?
1966 public function get_default() {
1967 return $this->default;
1971 * Return the short name for this flag. e.g. 'adv' or 'locked'
1973 * @return string
1975 public function get_shortname() {
1976 return $this->shortname;
1980 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1982 * @return string
1984 public function get_displayname() {
1985 return $this->displayname;
1989 * Save the submitted data for this flag - or set it to the default if $data is null.
1991 * @param admin_setting $setting - The admin setting for this flag
1992 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1993 * @return bool
1995 public function write_setting_flag(admin_setting $setting, $data) {
1996 $result = true;
1997 if ($this->is_enabled()) {
1998 if (!isset($data)) {
1999 $value = $this->get_default();
2000 } else {
2001 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2003 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2006 return $result;
2011 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2013 * @param admin_setting $setting - The admin setting for this flag
2014 * @return string - The html for the checkbox.
2016 public function output_setting_flag(admin_setting $setting) {
2017 $value = $setting->get_setting_flag_value($this);
2018 $output = ' <input type="checkbox" class="form-checkbox" ' .
2019 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2020 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2021 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2022 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2023 $this->get_displayname() .
2024 ' </label> ';
2025 return $output;
2031 * No setting - just heading and text.
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class admin_setting_heading extends admin_setting {
2038 * not a setting, just text
2039 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2040 * @param string $heading heading
2041 * @param string $information text in box
2043 public function __construct($name, $heading, $information) {
2044 $this->nosave = true;
2045 parent::__construct($name, $heading, $information, '');
2049 * Always returns true
2050 * @return bool Always returns true
2052 public function get_setting() {
2053 return true;
2057 * Always returns true
2058 * @return bool Always returns true
2060 public function get_defaultsetting() {
2061 return true;
2065 * Never write settings
2066 * @return string Always returns an empty string
2068 public function write_setting($data) {
2069 // do not write any setting
2070 return '';
2074 * Returns an HTML string
2075 * @return string Returns an HTML string
2077 public function output_html($data, $query='') {
2078 global $OUTPUT;
2079 $return = '';
2080 if ($this->visiblename != '') {
2081 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2083 if ($this->description != '') {
2084 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2086 return $return;
2092 * The most flexibly setting, user is typing text
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configtext extends admin_setting {
2098 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2099 public $paramtype;
2100 /** @var int default field size */
2101 public $size;
2104 * Config text constructor
2106 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2107 * @param string $visiblename localised
2108 * @param string $description long localised info
2109 * @param string $defaultsetting
2110 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2111 * @param int $size default field size
2113 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2114 $this->paramtype = $paramtype;
2115 if (!is_null($size)) {
2116 $this->size = $size;
2117 } else {
2118 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2120 parent::__construct($name, $visiblename, $description, $defaultsetting);
2124 * Return the setting
2126 * @return mixed returns config if successful else null
2128 public function get_setting() {
2129 return $this->config_read($this->name);
2132 public function write_setting($data) {
2133 if ($this->paramtype === PARAM_INT and $data === '') {
2134 // do not complain if '' used instead of 0
2135 $data = 0;
2137 // $data is a string
2138 $validated = $this->validate($data);
2139 if ($validated !== true) {
2140 return $validated;
2142 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2146 * Validate data before storage
2147 * @param string data
2148 * @return mixed true if ok string if error found
2150 public function validate($data) {
2151 // allow paramtype to be a custom regex if it is the form of /pattern/
2152 if (preg_match('#^/.*/$#', $this->paramtype)) {
2153 if (preg_match($this->paramtype, $data)) {
2154 return true;
2155 } else {
2156 return get_string('validateerror', 'admin');
2159 } else if ($this->paramtype === PARAM_RAW) {
2160 return true;
2162 } else {
2163 $cleaned = clean_param($data, $this->paramtype);
2164 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2165 return true;
2166 } else {
2167 return get_string('validateerror', 'admin');
2173 * Return an XHTML string for the setting
2174 * @return string Returns an XHTML string
2176 public function output_html($data, $query='') {
2177 $default = $this->get_defaultsetting();
2179 return format_admin_setting($this, $this->visiblename,
2180 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2181 $this->description, true, '', $default, $query);
2187 * General text area without html editor.
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtextarea extends admin_setting_configtext {
2192 private $rows;
2193 private $cols;
2196 * @param string $name
2197 * @param string $visiblename
2198 * @param string $description
2199 * @param mixed $defaultsetting string or array
2200 * @param mixed $paramtype
2201 * @param string $cols The number of columns to make the editor
2202 * @param string $rows The number of rows to make the editor
2204 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2205 $this->rows = $rows;
2206 $this->cols = $cols;
2207 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2211 * Returns an XHTML string for the editor
2213 * @param string $data
2214 * @param string $query
2215 * @return string XHTML string for the editor
2217 public function output_html($data, $query='') {
2218 $default = $this->get_defaultsetting();
2220 $defaultinfo = $default;
2221 if (!is_null($default) and $default !== '') {
2222 $defaultinfo = "\n".$default;
2225 return format_admin_setting($this, $this->visiblename,
2226 '<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>',
2227 $this->description, true, '', $defaultinfo, $query);
2233 * General text area with html editor.
2235 class admin_setting_confightmleditor extends admin_setting_configtext {
2236 private $rows;
2237 private $cols;
2240 * @param string $name
2241 * @param string $visiblename
2242 * @param string $description
2243 * @param mixed $defaultsetting string or array
2244 * @param mixed $paramtype
2246 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2247 $this->rows = $rows;
2248 $this->cols = $cols;
2249 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2250 editors_head_setup();
2254 * Returns an XHTML string for the editor
2256 * @param string $data
2257 * @param string $query
2258 * @return string XHTML string for the editor
2260 public function output_html($data, $query='') {
2261 $default = $this->get_defaultsetting();
2263 $defaultinfo = $default;
2264 if (!is_null($default) and $default !== '') {
2265 $defaultinfo = "\n".$default;
2268 $editor = editors_get_preferred_editor(FORMAT_HTML);
2269 $editor->use_editor($this->get_id(), array('noclean'=>true));
2271 return format_admin_setting($this, $this->visiblename,
2272 '<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>',
2273 $this->description, true, '', $defaultinfo, $query);
2279 * Password field, allows unmasking of password
2281 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2283 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2285 * Constructor
2286 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2287 * @param string $visiblename localised
2288 * @param string $description long localised info
2289 * @param string $defaultsetting default password
2291 public function __construct($name, $visiblename, $description, $defaultsetting) {
2292 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2296 * Log config changes if necessary.
2297 * @param string $name
2298 * @param string $oldvalue
2299 * @param string $value
2301 protected function add_to_config_log($name, $oldvalue, $value) {
2302 if ($value !== '') {
2303 $value = '********';
2305 if ($oldvalue !== '' and $oldvalue !== null) {
2306 $oldvalue = '********';
2308 parent::add_to_config_log($name, $oldvalue, $value);
2312 * Returns XHTML for the field
2313 * Writes Javascript into the HTML below right before the last div
2315 * @todo Make javascript available through newer methods if possible
2316 * @param string $data Value for the field
2317 * @param string $query Passed as final argument for format_admin_setting
2318 * @return string XHTML field
2320 public function output_html($data, $query='') {
2321 $id = $this->get_id();
2322 $unmask = get_string('unmaskpassword', 'form');
2323 $unmaskjs = '<script type="text/javascript">
2324 //<![CDATA[
2325 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2327 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2329 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2331 var unmaskchb = document.createElement("input");
2332 unmaskchb.setAttribute("type", "checkbox");
2333 unmaskchb.setAttribute("id", "'.$id.'unmask");
2334 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2335 unmaskdiv.appendChild(unmaskchb);
2337 var unmasklbl = document.createElement("label");
2338 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2339 if (is_ie) {
2340 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2341 } else {
2342 unmasklbl.setAttribute("for", "'.$id.'unmask");
2344 unmaskdiv.appendChild(unmasklbl);
2346 if (is_ie) {
2347 // ugly hack to work around the famous onchange IE bug
2348 unmaskchb.onclick = function() {this.blur();};
2349 unmaskdiv.onclick = function() {this.blur();};
2351 //]]>
2352 </script>';
2353 return format_admin_setting($this, $this->visiblename,
2354 '<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>',
2355 $this->description, true, '', NULL, $query);
2360 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2361 * Note: Only advanced makes sense right now - locked does not.
2363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2365 class admin_setting_configempty extends admin_setting_configtext {
2368 * @param string $name
2369 * @param string $visiblename
2370 * @param string $description
2372 public function __construct($name, $visiblename, $description) {
2373 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2377 * Returns an XHTML string for the hidden field
2379 * @param string $data
2380 * @param string $query
2381 * @return string XHTML string for the editor
2383 public function output_html($data, $query='') {
2384 return format_admin_setting($this,
2385 $this->visiblename,
2386 '<div class="form-empty" >' .
2387 '<input type="hidden"' .
2388 ' id="'. $this->get_id() .'"' .
2389 ' name="'. $this->get_full_name() .'"' .
2390 ' value=""/></div>',
2391 $this->description,
2392 true,
2394 get_string('none'),
2395 $query);
2401 * Path to directory
2403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2405 class admin_setting_configfile extends admin_setting_configtext {
2407 * Constructor
2408 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2409 * @param string $visiblename localised
2410 * @param string $description long localised info
2411 * @param string $defaultdirectory default directory location
2413 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2414 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2418 * Returns XHTML for the field
2420 * Returns XHTML for the field and also checks whether the file
2421 * specified in $data exists using file_exists()
2423 * @param string $data File name and path to use in value attr
2424 * @param string $query
2425 * @return string XHTML field
2427 public function output_html($data, $query='') {
2428 $default = $this->get_defaultsetting();
2430 if ($data) {
2431 if (file_exists($data)) {
2432 $executable = '<span class="pathok">&#x2714;</span>';
2433 } else {
2434 $executable = '<span class="patherror">&#x2718;</span>';
2436 } else {
2437 $executable = '';
2440 return format_admin_setting($this, $this->visiblename,
2441 '<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>',
2442 $this->description, true, '', $default, $query);
2445 * checks if execpatch has been disabled in config.php
2447 public function write_setting($data) {
2448 global $CFG;
2449 if (!empty($CFG->preventexecpath)) {
2450 return '';
2452 return parent::write_setting($data);
2458 * Path to executable file
2460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2462 class admin_setting_configexecutable extends admin_setting_configfile {
2465 * Returns an XHTML field
2467 * @param string $data This is the value for the field
2468 * @param string $query
2469 * @return string XHTML field
2471 public function output_html($data, $query='') {
2472 global $CFG;
2473 $default = $this->get_defaultsetting();
2475 if ($data) {
2476 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2477 $executable = '<span class="pathok">&#x2714;</span>';
2478 } else {
2479 $executable = '<span class="patherror">&#x2718;</span>';
2481 } else {
2482 $executable = '';
2484 if (!empty($CFG->preventexecpath)) {
2485 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2488 return format_admin_setting($this, $this->visiblename,
2489 '<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>',
2490 $this->description, true, '', $default, $query);
2496 * Path to directory
2498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2500 class admin_setting_configdirectory extends admin_setting_configfile {
2503 * Returns an XHTML field
2505 * @param string $data This is the value for the field
2506 * @param string $query
2507 * @return string XHTML
2509 public function output_html($data, $query='') {
2510 $default = $this->get_defaultsetting();
2512 if ($data) {
2513 if (file_exists($data) and is_dir($data)) {
2514 $executable = '<span class="pathok">&#x2714;</span>';
2515 } else {
2516 $executable = '<span class="patherror">&#x2718;</span>';
2518 } else {
2519 $executable = '';
2522 return format_admin_setting($this, $this->visiblename,
2523 '<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>',
2524 $this->description, true, '', $default, $query);
2530 * Checkbox
2532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2534 class admin_setting_configcheckbox extends admin_setting {
2535 /** @var string Value used when checked */
2536 public $yes;
2537 /** @var string Value used when not checked */
2538 public $no;
2541 * Constructor
2542 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2543 * @param string $visiblename localised
2544 * @param string $description long localised info
2545 * @param string $defaultsetting
2546 * @param string $yes value used when checked
2547 * @param string $no value used when not checked
2549 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2550 parent::__construct($name, $visiblename, $description, $defaultsetting);
2551 $this->yes = (string)$yes;
2552 $this->no = (string)$no;
2556 * Retrieves the current setting using the objects name
2558 * @return string
2560 public function get_setting() {
2561 return $this->config_read($this->name);
2565 * Sets the value for the setting
2567 * Sets the value for the setting to either the yes or no values
2568 * of the object by comparing $data to yes
2570 * @param mixed $data Gets converted to str for comparison against yes value
2571 * @return string empty string or error
2573 public function write_setting($data) {
2574 if ((string)$data === $this->yes) { // convert to strings before comparison
2575 $data = $this->yes;
2576 } else {
2577 $data = $this->no;
2579 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2583 * Returns an XHTML checkbox field
2585 * @param string $data If $data matches yes then checkbox is checked
2586 * @param string $query
2587 * @return string XHTML field
2589 public function output_html($data, $query='') {
2590 $default = $this->get_defaultsetting();
2592 if (!is_null($default)) {
2593 if ((string)$default === $this->yes) {
2594 $defaultinfo = get_string('checkboxyes', 'admin');
2595 } else {
2596 $defaultinfo = get_string('checkboxno', 'admin');
2598 } else {
2599 $defaultinfo = NULL;
2602 if ((string)$data === $this->yes) { // convert to strings before comparison
2603 $checked = 'checked="checked"';
2604 } else {
2605 $checked = '';
2608 return format_admin_setting($this, $this->visiblename,
2609 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2610 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2611 $this->description, true, '', $defaultinfo, $query);
2617 * Multiple checkboxes, each represents different value, stored in csv format
2619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2621 class admin_setting_configmulticheckbox extends admin_setting {
2622 /** @var array Array of choices value=>label */
2623 public $choices;
2626 * Constructor: uses parent::__construct
2628 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2629 * @param string $visiblename localised
2630 * @param string $description long localised info
2631 * @param array $defaultsetting array of selected
2632 * @param array $choices array of $value=>$label for each checkbox
2634 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2635 $this->choices = $choices;
2636 parent::__construct($name, $visiblename, $description, $defaultsetting);
2640 * This public function may be used in ancestors for lazy loading of choices
2642 * @todo Check if this function is still required content commented out only returns true
2643 * @return bool true if loaded, false if error
2645 public function load_choices() {
2647 if (is_array($this->choices)) {
2648 return true;
2650 .... load choices here
2652 return true;
2656 * Is setting related to query text - used when searching
2658 * @param string $query
2659 * @return bool true on related, false on not or failure
2661 public function is_related($query) {
2662 if (!$this->load_choices() or empty($this->choices)) {
2663 return false;
2665 if (parent::is_related($query)) {
2666 return true;
2669 foreach ($this->choices as $desc) {
2670 if (strpos(core_text::strtolower($desc), $query) !== false) {
2671 return true;
2674 return false;
2678 * Returns the current setting if it is set
2680 * @return mixed null if null, else an array
2682 public function get_setting() {
2683 $result = $this->config_read($this->name);
2685 if (is_null($result)) {
2686 return NULL;
2688 if ($result === '') {
2689 return array();
2691 $enabled = explode(',', $result);
2692 $setting = array();
2693 foreach ($enabled as $option) {
2694 $setting[$option] = 1;
2696 return $setting;
2700 * Saves the setting(s) provided in $data
2702 * @param array $data An array of data, if not array returns empty str
2703 * @return mixed empty string on useless data or bool true=success, false=failed
2705 public function write_setting($data) {
2706 if (!is_array($data)) {
2707 return ''; // ignore it
2709 if (!$this->load_choices() or empty($this->choices)) {
2710 return '';
2712 unset($data['xxxxx']);
2713 $result = array();
2714 foreach ($data as $key => $value) {
2715 if ($value and array_key_exists($key, $this->choices)) {
2716 $result[] = $key;
2719 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2723 * Returns XHTML field(s) as required by choices
2725 * Relies on data being an array should data ever be another valid vartype with
2726 * acceptable value this may cause a warning/error
2727 * if (!is_array($data)) would fix the problem
2729 * @todo Add vartype handling to ensure $data is an array
2731 * @param array $data An array of checked values
2732 * @param string $query
2733 * @return string XHTML field
2735 public function output_html($data, $query='') {
2736 if (!$this->load_choices() or empty($this->choices)) {
2737 return '';
2739 $default = $this->get_defaultsetting();
2740 if (is_null($default)) {
2741 $default = array();
2743 if (is_null($data)) {
2744 $data = array();
2746 $options = array();
2747 $defaults = array();
2748 foreach ($this->choices as $key=>$description) {
2749 if (!empty($data[$key])) {
2750 $checked = 'checked="checked"';
2751 } else {
2752 $checked = '';
2754 if (!empty($default[$key])) {
2755 $defaults[] = $description;
2758 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2759 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2762 if (is_null($default)) {
2763 $defaultinfo = NULL;
2764 } else if (!empty($defaults)) {
2765 $defaultinfo = implode(', ', $defaults);
2766 } else {
2767 $defaultinfo = get_string('none');
2770 $return = '<div class="form-multicheckbox">';
2771 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2772 if ($options) {
2773 $return .= '<ul>';
2774 foreach ($options as $option) {
2775 $return .= '<li>'.$option.'</li>';
2777 $return .= '</ul>';
2779 $return .= '</div>';
2781 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2788 * Multiple checkboxes 2, value stored as string 00101011
2790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2792 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2795 * Returns the setting if set
2797 * @return mixed null if not set, else an array of set settings
2799 public function get_setting() {
2800 $result = $this->config_read($this->name);
2801 if (is_null($result)) {
2802 return NULL;
2804 if (!$this->load_choices()) {
2805 return NULL;
2807 $result = str_pad($result, count($this->choices), '0');
2808 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2809 $setting = array();
2810 foreach ($this->choices as $key=>$unused) {
2811 $value = array_shift($result);
2812 if ($value) {
2813 $setting[$key] = 1;
2816 return $setting;
2820 * Save setting(s) provided in $data param
2822 * @param array $data An array of settings to save
2823 * @return mixed empty string for bad data or bool true=>success, false=>error
2825 public function write_setting($data) {
2826 if (!is_array($data)) {
2827 return ''; // ignore it
2829 if (!$this->load_choices() or empty($this->choices)) {
2830 return '';
2832 $result = '';
2833 foreach ($this->choices as $key=>$unused) {
2834 if (!empty($data[$key])) {
2835 $result .= '1';
2836 } else {
2837 $result .= '0';
2840 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2846 * Select one value from list
2848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2850 class admin_setting_configselect extends admin_setting {
2851 /** @var array Array of choices value=>label */
2852 public $choices;
2855 * Constructor
2856 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2857 * @param string $visiblename localised
2858 * @param string $description long localised info
2859 * @param string|int $defaultsetting
2860 * @param array $choices array of $value=>$label for each selection
2862 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2863 $this->choices = $choices;
2864 parent::__construct($name, $visiblename, $description, $defaultsetting);
2868 * This function may be used in ancestors for lazy loading of choices
2870 * Override this method if loading of choices is expensive, such
2871 * as when it requires multiple db requests.
2873 * @return bool true if loaded, false if error
2875 public function load_choices() {
2877 if (is_array($this->choices)) {
2878 return true;
2880 .... load choices here
2882 return true;
2886 * Check if this is $query is related to a choice
2888 * @param string $query
2889 * @return bool true if related, false if not
2891 public function is_related($query) {
2892 if (parent::is_related($query)) {
2893 return true;
2895 if (!$this->load_choices()) {
2896 return false;
2898 foreach ($this->choices as $key=>$value) {
2899 if (strpos(core_text::strtolower($key), $query) !== false) {
2900 return true;
2902 if (strpos(core_text::strtolower($value), $query) !== false) {
2903 return true;
2906 return false;
2910 * Return the setting
2912 * @return mixed returns config if successful else null
2914 public function get_setting() {
2915 return $this->config_read($this->name);
2919 * Save a setting
2921 * @param string $data
2922 * @return string empty of error string
2924 public function write_setting($data) {
2925 if (!$this->load_choices() or empty($this->choices)) {
2926 return '';
2928 if (!array_key_exists($data, $this->choices)) {
2929 return ''; // ignore it
2932 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2936 * Returns XHTML select field
2938 * Ensure the options are loaded, and generate the XHTML for the select
2939 * element and any warning message. Separating this out from output_html
2940 * makes it easier to subclass this class.
2942 * @param string $data the option to show as selected.
2943 * @param string $current the currently selected option in the database, null if none.
2944 * @param string $default the default selected option.
2945 * @return array the HTML for the select element, and a warning message.
2947 public function output_select_html($data, $current, $default, $extraname = '') {
2948 if (!$this->load_choices() or empty($this->choices)) {
2949 return array('', '');
2952 $warning = '';
2953 if (is_null($current)) {
2954 // first run
2955 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2956 // no warning
2957 } else if (!array_key_exists($current, $this->choices)) {
2958 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2959 if (!is_null($default) and $data == $current) {
2960 $data = $default; // use default instead of first value when showing the form
2964 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2965 foreach ($this->choices as $key => $value) {
2966 // the string cast is needed because key may be integer - 0 is equal to most strings!
2967 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2969 $selecthtml .= '</select>';
2970 return array($selecthtml, $warning);
2974 * Returns XHTML select field and wrapping div(s)
2976 * @see output_select_html()
2978 * @param string $data the option to show as selected
2979 * @param string $query
2980 * @return string XHTML field and wrapping div
2982 public function output_html($data, $query='') {
2983 $default = $this->get_defaultsetting();
2984 $current = $this->get_setting();
2986 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2987 if (!$selecthtml) {
2988 return '';
2991 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2992 $defaultinfo = $this->choices[$default];
2993 } else {
2994 $defaultinfo = NULL;
2997 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2999 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3005 * Select multiple items from list
3007 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3009 class admin_setting_configmultiselect extends admin_setting_configselect {
3011 * Constructor
3012 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3013 * @param string $visiblename localised
3014 * @param string $description long localised info
3015 * @param array $defaultsetting array of selected items
3016 * @param array $choices array of $value=>$label for each list item
3018 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3019 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3023 * Returns the select setting(s)
3025 * @return mixed null or array. Null if no settings else array of setting(s)
3027 public function get_setting() {
3028 $result = $this->config_read($this->name);
3029 if (is_null($result)) {
3030 return NULL;
3032 if ($result === '') {
3033 return array();
3035 return explode(',', $result);
3039 * Saves setting(s) provided through $data
3041 * Potential bug in the works should anyone call with this function
3042 * using a vartype that is not an array
3044 * @param array $data
3046 public function write_setting($data) {
3047 if (!is_array($data)) {
3048 return ''; //ignore it
3050 if (!$this->load_choices() or empty($this->choices)) {
3051 return '';
3054 unset($data['xxxxx']);
3056 $save = array();
3057 foreach ($data as $value) {
3058 if (!array_key_exists($value, $this->choices)) {
3059 continue; // ignore it
3061 $save[] = $value;
3064 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3068 * Is setting related to query text - used when searching
3070 * @param string $query
3071 * @return bool true if related, false if not
3073 public function is_related($query) {
3074 if (!$this->load_choices() or empty($this->choices)) {
3075 return false;
3077 if (parent::is_related($query)) {
3078 return true;
3081 foreach ($this->choices as $desc) {
3082 if (strpos(core_text::strtolower($desc), $query) !== false) {
3083 return true;
3086 return false;
3090 * Returns XHTML multi-select field
3092 * @todo Add vartype handling to ensure $data is an array
3093 * @param array $data Array of values to select by default
3094 * @param string $query
3095 * @return string XHTML multi-select field
3097 public function output_html($data, $query='') {
3098 if (!$this->load_choices() or empty($this->choices)) {
3099 return '';
3101 $choices = $this->choices;
3102 $default = $this->get_defaultsetting();
3103 if (is_null($default)) {
3104 $default = array();
3106 if (is_null($data)) {
3107 $data = array();
3110 $defaults = array();
3111 $size = min(10, count($this->choices));
3112 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3113 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3114 foreach ($this->choices as $key => $description) {
3115 if (in_array($key, $data)) {
3116 $selected = 'selected="selected"';
3117 } else {
3118 $selected = '';
3120 if (in_array($key, $default)) {
3121 $defaults[] = $description;
3124 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3127 if (is_null($default)) {
3128 $defaultinfo = NULL;
3129 } if (!empty($defaults)) {
3130 $defaultinfo = implode(', ', $defaults);
3131 } else {
3132 $defaultinfo = get_string('none');
3135 $return .= '</select></div>';
3136 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3141 * Time selector
3143 * This is a liiitle bit messy. we're using two selects, but we're returning
3144 * them as an array named after $name (so we only use $name2 internally for the setting)
3146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3148 class admin_setting_configtime extends admin_setting {
3149 /** @var string Used for setting second select (minutes) */
3150 public $name2;
3153 * Constructor
3154 * @param string $hoursname setting for hours
3155 * @param string $minutesname setting for hours
3156 * @param string $visiblename localised
3157 * @param string $description long localised info
3158 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3160 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3161 $this->name2 = $minutesname;
3162 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3166 * Get the selected time
3168 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3170 public function get_setting() {
3171 $result1 = $this->config_read($this->name);
3172 $result2 = $this->config_read($this->name2);
3173 if (is_null($result1) or is_null($result2)) {
3174 return NULL;
3177 return array('h' => $result1, 'm' => $result2);
3181 * Store the time (hours and minutes)
3183 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3184 * @return bool true if success, false if not
3186 public function write_setting($data) {
3187 if (!is_array($data)) {
3188 return '';
3191 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3192 return ($result ? '' : get_string('errorsetting', 'admin'));
3196 * Returns XHTML time select fields
3198 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3199 * @param string $query
3200 * @return string XHTML time select fields and wrapping div(s)
3202 public function output_html($data, $query='') {
3203 $default = $this->get_defaultsetting();
3205 if (is_array($default)) {
3206 $defaultinfo = $default['h'].':'.$default['m'];
3207 } else {
3208 $defaultinfo = NULL;
3211 $return = '<div class="form-time defaultsnext">'.
3212 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
3213 for ($i = 0; $i < 24; $i++) {
3214 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3216 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
3217 for ($i = 0; $i < 60; $i += 5) {
3218 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3220 $return .= '</select></div>';
3221 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3228 * Seconds duration setting.
3230 * @copyright 2012 Petr Skoda (http://skodak.org)
3231 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3233 class admin_setting_configduration extends admin_setting {
3235 /** @var int default duration unit */
3236 protected $defaultunit;
3239 * Constructor
3240 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3241 * or 'myplugin/mysetting' for ones in config_plugins.
3242 * @param string $visiblename localised name
3243 * @param string $description localised long description
3244 * @param mixed $defaultsetting string or array depending on implementation
3245 * @param int $defaultunit - day, week, etc. (in seconds)
3247 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3248 if (is_number($defaultsetting)) {
3249 $defaultsetting = self::parse_seconds($defaultsetting);
3251 $units = self::get_units();
3252 if (isset($units[$defaultunit])) {
3253 $this->defaultunit = $defaultunit;
3254 } else {
3255 $this->defaultunit = 86400;
3257 parent::__construct($name, $visiblename, $description, $defaultsetting);
3261 * Returns selectable units.
3262 * @static
3263 * @return array
3265 protected static function get_units() {
3266 return array(
3267 604800 => get_string('weeks'),
3268 86400 => get_string('days'),
3269 3600 => get_string('hours'),
3270 60 => get_string('minutes'),
3271 1 => get_string('seconds'),
3276 * Converts seconds to some more user friendly string.
3277 * @static
3278 * @param int $seconds
3279 * @return string
3281 protected static function get_duration_text($seconds) {
3282 if (empty($seconds)) {
3283 return get_string('none');
3285 $data = self::parse_seconds($seconds);
3286 switch ($data['u']) {
3287 case (60*60*24*7):
3288 return get_string('numweeks', '', $data['v']);
3289 case (60*60*24):
3290 return get_string('numdays', '', $data['v']);
3291 case (60*60):
3292 return get_string('numhours', '', $data['v']);
3293 case (60):
3294 return get_string('numminutes', '', $data['v']);
3295 default:
3296 return get_string('numseconds', '', $data['v']*$data['u']);
3301 * Finds suitable units for given duration.
3302 * @static
3303 * @param int $seconds
3304 * @return array
3306 protected static function parse_seconds($seconds) {
3307 foreach (self::get_units() as $unit => $unused) {
3308 if ($seconds % $unit === 0) {
3309 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3312 return array('v'=>(int)$seconds, 'u'=>1);
3316 * Get the selected duration as array.
3318 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3320 public function get_setting() {
3321 $seconds = $this->config_read($this->name);
3322 if (is_null($seconds)) {
3323 return null;
3326 return self::parse_seconds($seconds);
3330 * Store the duration as seconds.
3332 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3333 * @return bool true if success, false if not
3335 public function write_setting($data) {
3336 if (!is_array($data)) {
3337 return '';
3340 $seconds = (int)($data['v']*$data['u']);
3341 if ($seconds < 0) {
3342 return get_string('errorsetting', 'admin');
3345 $result = $this->config_write($this->name, $seconds);
3346 return ($result ? '' : get_string('errorsetting', 'admin'));
3350 * Returns duration text+select fields.
3352 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3353 * @param string $query
3354 * @return string duration text+select fields and wrapping div(s)
3356 public function output_html($data, $query='') {
3357 $default = $this->get_defaultsetting();
3359 if (is_number($default)) {
3360 $defaultinfo = self::get_duration_text($default);
3361 } else if (is_array($default)) {
3362 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3363 } else {
3364 $defaultinfo = null;
3367 $units = self::get_units();
3369 $return = '<div class="form-duration defaultsnext">';
3370 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3371 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3372 foreach ($units as $val => $text) {
3373 $selected = '';
3374 if ($data['v'] == 0) {
3375 if ($val == $this->defaultunit) {
3376 $selected = ' selected="selected"';
3378 } else if ($val == $data['u']) {
3379 $selected = ' selected="selected"';
3381 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3383 $return .= '</select></div>';
3384 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3390 * Used to validate a textarea used for ip addresses
3392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3394 class admin_setting_configiplist extends admin_setting_configtextarea {
3397 * Validate the contents of the textarea as IP addresses
3399 * Used to validate a new line separated list of IP addresses collected from
3400 * a textarea control
3402 * @param string $data A list of IP Addresses separated by new lines
3403 * @return mixed bool true for success or string:error on failure
3405 public function validate($data) {
3406 if(!empty($data)) {
3407 $ips = explode("\n", $data);
3408 } else {
3409 return true;
3411 $result = true;
3412 foreach($ips as $ip) {
3413 $ip = trim($ip);
3414 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3415 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3416 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3417 $result = true;
3418 } else {
3419 $result = false;
3420 break;
3423 if($result) {
3424 return true;
3425 } else {
3426 return get_string('validateerror', 'admin');
3433 * An admin setting for selecting one or more users who have a capability
3434 * in the system context
3436 * An admin setting for selecting one or more users, who have a particular capability
3437 * in the system context. Warning, make sure the list will never be too long. There is
3438 * no paging or searching of this list.
3440 * To correctly get a list of users from this config setting, you need to call the
3441 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3445 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3446 /** @var string The capabilities name */
3447 protected $capability;
3448 /** @var int include admin users too */
3449 protected $includeadmins;
3452 * Constructor.
3454 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3455 * @param string $visiblename localised name
3456 * @param string $description localised long description
3457 * @param array $defaultsetting array of usernames
3458 * @param string $capability string capability name.
3459 * @param bool $includeadmins include administrators
3461 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3462 $this->capability = $capability;
3463 $this->includeadmins = $includeadmins;
3464 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3468 * Load all of the uses who have the capability into choice array
3470 * @return bool Always returns true
3472 function load_choices() {
3473 if (is_array($this->choices)) {
3474 return true;
3476 list($sort, $sortparams) = users_order_by_sql('u');
3477 if (!empty($sortparams)) {
3478 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3479 'This is unexpected, and a problem because there is no way to pass these ' .
3480 'parameters to get_users_by_capability. See MDL-34657.');
3482 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3483 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3484 $this->choices = array(
3485 '$@NONE@$' => get_string('nobody'),
3486 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3488 if ($this->includeadmins) {
3489 $admins = get_admins();
3490 foreach ($admins as $user) {
3491 $this->choices[$user->id] = fullname($user);
3494 if (is_array($users)) {
3495 foreach ($users as $user) {
3496 $this->choices[$user->id] = fullname($user);
3499 return true;
3503 * Returns the default setting for class
3505 * @return mixed Array, or string. Empty string if no default
3507 public function get_defaultsetting() {
3508 $this->load_choices();
3509 $defaultsetting = parent::get_defaultsetting();
3510 if (empty($defaultsetting)) {
3511 return array('$@NONE@$');
3512 } else if (array_key_exists($defaultsetting, $this->choices)) {
3513 return $defaultsetting;
3514 } else {
3515 return '';
3520 * Returns the current setting
3522 * @return mixed array or string
3524 public function get_setting() {
3525 $result = parent::get_setting();
3526 if ($result === null) {
3527 // this is necessary for settings upgrade
3528 return null;
3530 if (empty($result)) {
3531 $result = array('$@NONE@$');
3533 return $result;
3537 * Save the chosen setting provided as $data
3539 * @param array $data
3540 * @return mixed string or array
3542 public function write_setting($data) {
3543 // If all is selected, remove any explicit options.
3544 if (in_array('$@ALL@$', $data)) {
3545 $data = array('$@ALL@$');
3547 // None never needs to be written to the DB.
3548 if (in_array('$@NONE@$', $data)) {
3549 unset($data[array_search('$@NONE@$', $data)]);
3551 return parent::write_setting($data);
3557 * Special checkbox for calendar - resets SESSION vars.
3559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3561 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3563 * Calls the parent::__construct with default values
3565 * name => calendar_adminseesall
3566 * visiblename => get_string('adminseesall', 'admin')
3567 * description => get_string('helpadminseesall', 'admin')
3568 * defaultsetting => 0
3570 public function __construct() {
3571 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3572 get_string('helpadminseesall', 'admin'), '0');
3576 * Stores the setting passed in $data
3578 * @param mixed gets converted to string for comparison
3579 * @return string empty string or error message
3581 public function write_setting($data) {
3582 global $SESSION;
3583 return parent::write_setting($data);
3588 * Special select for settings that are altered in setup.php and can not be altered on the fly
3590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3592 class admin_setting_special_selectsetup extends admin_setting_configselect {
3594 * Reads the setting directly from the database
3596 * @return mixed
3598 public function get_setting() {
3599 // read directly from db!
3600 return get_config(NULL, $this->name);
3604 * Save the setting passed in $data
3606 * @param string $data The setting to save
3607 * @return string empty or error message
3609 public function write_setting($data) {
3610 global $CFG;
3611 // do not change active CFG setting!
3612 $current = $CFG->{$this->name};
3613 $result = parent::write_setting($data);
3614 $CFG->{$this->name} = $current;
3615 return $result;
3621 * Special select for frontpage - stores data in course table
3623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3625 class admin_setting_sitesetselect extends admin_setting_configselect {
3627 * Returns the site name for the selected site
3629 * @see get_site()
3630 * @return string The site name of the selected site
3632 public function get_setting() {
3633 $site = course_get_format(get_site())->get_course();
3634 return $site->{$this->name};
3638 * Updates the database and save the setting
3640 * @param string data
3641 * @return string empty or error message
3643 public function write_setting($data) {
3644 global $DB, $SITE, $COURSE;
3645 if (!in_array($data, array_keys($this->choices))) {
3646 return get_string('errorsetting', 'admin');
3648 $record = new stdClass();
3649 $record->id = SITEID;
3650 $temp = $this->name;
3651 $record->$temp = $data;
3652 $record->timemodified = time();
3654 course_get_format($SITE)->update_course_format_options($record);
3655 $DB->update_record('course', $record);
3657 // Reset caches.
3658 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3659 if ($SITE->id == $COURSE->id) {
3660 $COURSE = $SITE;
3662 format_base::reset_course_cache($SITE->id);
3664 return '';
3671 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3672 * block to hidden.
3674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3676 class admin_setting_bloglevel extends admin_setting_configselect {
3678 * Updates the database and save the setting
3680 * @param string data
3681 * @return string empty or error message
3683 public function write_setting($data) {
3684 global $DB, $CFG;
3685 if ($data == 0) {
3686 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3687 foreach ($blogblocks as $block) {
3688 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3690 } else {
3691 // reenable all blocks only when switching from disabled blogs
3692 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3693 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3694 foreach ($blogblocks as $block) {
3695 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3699 return parent::write_setting($data);
3705 * Special select - lists on the frontpage - hacky
3707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3709 class admin_setting_courselist_frontpage extends admin_setting {
3710 /** @var array Array of choices value=>label */
3711 public $choices;
3714 * Construct override, requires one param
3716 * @param bool $loggedin Is the user logged in
3718 public function __construct($loggedin) {
3719 global $CFG;
3720 require_once($CFG->dirroot.'/course/lib.php');
3721 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3722 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3723 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3724 $defaults = array(FRONTPAGEALLCOURSELIST);
3725 parent::__construct($name, $visiblename, $description, $defaults);
3729 * Loads the choices available
3731 * @return bool always returns true
3733 public function load_choices() {
3734 if (is_array($this->choices)) {
3735 return true;
3737 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3738 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3739 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3740 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3741 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3742 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3743 'none' => get_string('none'));
3744 if ($this->name === 'frontpage') {
3745 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3747 return true;
3751 * Returns the selected settings
3753 * @param mixed array or setting or null
3755 public function get_setting() {
3756 $result = $this->config_read($this->name);
3757 if (is_null($result)) {
3758 return NULL;
3760 if ($result === '') {
3761 return array();
3763 return explode(',', $result);
3767 * Save the selected options
3769 * @param array $data
3770 * @return mixed empty string (data is not an array) or bool true=success false=failure
3772 public function write_setting($data) {
3773 if (!is_array($data)) {
3774 return '';
3776 $this->load_choices();
3777 $save = array();
3778 foreach($data as $datum) {
3779 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3780 continue;
3782 $save[$datum] = $datum; // no duplicates
3784 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3788 * Return XHTML select field and wrapping div
3790 * @todo Add vartype handling to make sure $data is an array
3791 * @param array $data Array of elements to select by default
3792 * @return string XHTML select field and wrapping div
3794 public function output_html($data, $query='') {
3795 $this->load_choices();
3796 $currentsetting = array();
3797 foreach ($data as $key) {
3798 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3799 $currentsetting[] = $key; // already selected first
3803 $return = '<div class="form-group">';
3804 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3805 if (!array_key_exists($i, $currentsetting)) {
3806 $currentsetting[$i] = 'none'; //none
3808 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3809 foreach ($this->choices as $key => $value) {
3810 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3812 $return .= '</select>';
3813 if ($i !== count($this->choices) - 2) {
3814 $return .= '<br />';
3817 $return .= '</div>';
3819 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3825 * Special checkbox for frontpage - stores data in course table
3827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3829 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3831 * Returns the current sites name
3833 * @return string
3835 public function get_setting() {
3836 $site = course_get_format(get_site())->get_course();
3837 return $site->{$this->name};
3841 * Save the selected setting
3843 * @param string $data The selected site
3844 * @return string empty string or error message
3846 public function write_setting($data) {
3847 global $DB, $SITE, $COURSE;
3848 $record = new stdClass();
3849 $record->id = $SITE->id;
3850 $record->{$this->name} = ($data == '1' ? 1 : 0);
3851 $record->timemodified = time();
3853 course_get_format($SITE)->update_course_format_options($record);
3854 $DB->update_record('course', $record);
3856 // Reset caches.
3857 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3858 if ($SITE->id == $COURSE->id) {
3859 $COURSE = $SITE;
3861 format_base::reset_course_cache($SITE->id);
3863 return '';
3868 * Special text for frontpage - stores data in course table.
3869 * Empty string means not set here. Manual setting is required.
3871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3873 class admin_setting_sitesettext extends admin_setting_configtext {
3875 * Return the current setting
3877 * @return mixed string or null
3879 public function get_setting() {
3880 $site = course_get_format(get_site())->get_course();
3881 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3885 * Validate the selected data
3887 * @param string $data The selected value to validate
3888 * @return mixed true or message string
3890 public function validate($data) {
3891 $cleaned = clean_param($data, PARAM_TEXT);
3892 if ($cleaned === '') {
3893 return get_string('required');
3895 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3896 return true;
3897 } else {
3898 return get_string('validateerror', 'admin');
3903 * Save the selected setting
3905 * @param string $data The selected value
3906 * @return string empty or error message
3908 public function write_setting($data) {
3909 global $DB, $SITE, $COURSE;
3910 $data = trim($data);
3911 $validated = $this->validate($data);
3912 if ($validated !== true) {
3913 return $validated;
3916 $record = new stdClass();
3917 $record->id = $SITE->id;
3918 $record->{$this->name} = $data;
3919 $record->timemodified = time();
3921 course_get_format($SITE)->update_course_format_options($record);
3922 $DB->update_record('course', $record);
3924 // Reset caches.
3925 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3926 if ($SITE->id == $COURSE->id) {
3927 $COURSE = $SITE;
3929 format_base::reset_course_cache($SITE->id);
3931 return '';
3937 * Special text editor for site description.
3939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3941 class admin_setting_special_frontpagedesc extends admin_setting {
3943 * Calls parent::__construct with specific arguments
3945 public function __construct() {
3946 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3947 editors_head_setup();
3951 * Return the current setting
3952 * @return string The current setting
3954 public function get_setting() {
3955 $site = course_get_format(get_site())->get_course();
3956 return $site->{$this->name};
3960 * Save the new setting
3962 * @param string $data The new value to save
3963 * @return string empty or error message
3965 public function write_setting($data) {
3966 global $DB, $SITE, $COURSE;
3967 $record = new stdClass();
3968 $record->id = $SITE->id;
3969 $record->{$this->name} = $data;
3970 $record->timemodified = time();
3972 course_get_format($SITE)->update_course_format_options($record);
3973 $DB->update_record('course', $record);
3975 // Reset caches.
3976 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3977 if ($SITE->id == $COURSE->id) {
3978 $COURSE = $SITE;
3980 format_base::reset_course_cache($SITE->id);
3982 return '';
3986 * Returns XHTML for the field plus wrapping div
3988 * @param string $data The current value
3989 * @param string $query
3990 * @return string The XHTML output
3992 public function output_html($data, $query='') {
3993 global $CFG;
3995 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3997 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4003 * Administration interface for emoticon_manager settings.
4005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4007 class admin_setting_emoticons extends admin_setting {
4010 * Calls parent::__construct with specific args
4012 public function __construct() {
4013 global $CFG;
4015 $manager = get_emoticon_manager();
4016 $defaults = $this->prepare_form_data($manager->default_emoticons());
4017 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4021 * Return the current setting(s)
4023 * @return array Current settings array
4025 public function get_setting() {
4026 global $CFG;
4028 $manager = get_emoticon_manager();
4030 $config = $this->config_read($this->name);
4031 if (is_null($config)) {
4032 return null;
4035 $config = $manager->decode_stored_config($config);
4036 if (is_null($config)) {
4037 return null;
4040 return $this->prepare_form_data($config);
4044 * Save selected settings
4046 * @param array $data Array of settings to save
4047 * @return bool
4049 public function write_setting($data) {
4051 $manager = get_emoticon_manager();
4052 $emoticons = $this->process_form_data($data);
4054 if ($emoticons === false) {
4055 return false;
4058 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4059 return ''; // success
4060 } else {
4061 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4066 * Return XHTML field(s) for options
4068 * @param array $data Array of options to set in HTML
4069 * @return string XHTML string for the fields and wrapping div(s)
4071 public function output_html($data, $query='') {
4072 global $OUTPUT;
4074 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4075 $out .= html_writer::start_tag('thead');
4076 $out .= html_writer::start_tag('tr');
4077 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4078 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4079 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4080 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4081 $out .= html_writer::tag('th', '');
4082 $out .= html_writer::end_tag('tr');
4083 $out .= html_writer::end_tag('thead');
4084 $out .= html_writer::start_tag('tbody');
4085 $i = 0;
4086 foreach($data as $field => $value) {
4087 switch ($i) {
4088 case 0:
4089 $out .= html_writer::start_tag('tr');
4090 $current_text = $value;
4091 $current_filename = '';
4092 $current_imagecomponent = '';
4093 $current_altidentifier = '';
4094 $current_altcomponent = '';
4095 case 1:
4096 $current_filename = $value;
4097 case 2:
4098 $current_imagecomponent = $value;
4099 case 3:
4100 $current_altidentifier = $value;
4101 case 4:
4102 $current_altcomponent = $value;
4105 $out .= html_writer::tag('td',
4106 html_writer::empty_tag('input',
4107 array(
4108 'type' => 'text',
4109 'class' => 'form-text',
4110 'name' => $this->get_full_name().'['.$field.']',
4111 'value' => $value,
4113 ), array('class' => 'c'.$i)
4116 if ($i == 4) {
4117 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4118 $alt = get_string($current_altidentifier, $current_altcomponent);
4119 } else {
4120 $alt = $current_text;
4122 if ($current_filename) {
4123 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4124 } else {
4125 $out .= html_writer::tag('td', '');
4127 $out .= html_writer::end_tag('tr');
4128 $i = 0;
4129 } else {
4130 $i++;
4134 $out .= html_writer::end_tag('tbody');
4135 $out .= html_writer::end_tag('table');
4136 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4137 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4139 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4143 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4145 * @see self::process_form_data()
4146 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4147 * @return array of form fields and their values
4149 protected function prepare_form_data(array $emoticons) {
4151 $form = array();
4152 $i = 0;
4153 foreach ($emoticons as $emoticon) {
4154 $form['text'.$i] = $emoticon->text;
4155 $form['imagename'.$i] = $emoticon->imagename;
4156 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4157 $form['altidentifier'.$i] = $emoticon->altidentifier;
4158 $form['altcomponent'.$i] = $emoticon->altcomponent;
4159 $i++;
4161 // add one more blank field set for new object
4162 $form['text'.$i] = '';
4163 $form['imagename'.$i] = '';
4164 $form['imagecomponent'.$i] = '';
4165 $form['altidentifier'.$i] = '';
4166 $form['altcomponent'.$i] = '';
4168 return $form;
4172 * Converts the data from admin settings form into an array of emoticon objects
4174 * @see self::prepare_form_data()
4175 * @param array $data array of admin form fields and values
4176 * @return false|array of emoticon objects
4178 protected function process_form_data(array $form) {
4180 $count = count($form); // number of form field values
4182 if ($count % 5) {
4183 // we must get five fields per emoticon object
4184 return false;
4187 $emoticons = array();
4188 for ($i = 0; $i < $count / 5; $i++) {
4189 $emoticon = new stdClass();
4190 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4191 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4192 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4193 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4194 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4196 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4197 // prevent from breaking http://url.addresses by accident
4198 $emoticon->text = '';
4201 if (strlen($emoticon->text) < 2) {
4202 // do not allow single character emoticons
4203 $emoticon->text = '';
4206 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4207 // emoticon text must contain some non-alphanumeric character to prevent
4208 // breaking HTML tags
4209 $emoticon->text = '';
4212 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4213 $emoticons[] = $emoticon;
4216 return $emoticons;
4222 * Special setting for limiting of the list of available languages.
4224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4226 class admin_setting_langlist extends admin_setting_configtext {
4228 * Calls parent::__construct with specific arguments
4230 public function __construct() {
4231 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4235 * Save the new setting
4237 * @param string $data The new setting
4238 * @return bool
4240 public function write_setting($data) {
4241 $return = parent::write_setting($data);
4242 get_string_manager()->reset_caches();
4243 return $return;
4249 * Selection of one of the recognised countries using the list
4250 * returned by {@link get_list_of_countries()}.
4252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4254 class admin_settings_country_select extends admin_setting_configselect {
4255 protected $includeall;
4256 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4257 $this->includeall = $includeall;
4258 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4262 * Lazy-load the available choices for the select box
4264 public function load_choices() {
4265 global $CFG;
4266 if (is_array($this->choices)) {
4267 return true;
4269 $this->choices = array_merge(
4270 array('0' => get_string('choosedots')),
4271 get_string_manager()->get_list_of_countries($this->includeall));
4272 return true;
4278 * admin_setting_configselect for the default number of sections in a course,
4279 * simply so we can lazy-load the choices.
4281 * @copyright 2011 The Open University
4282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4284 class admin_settings_num_course_sections extends admin_setting_configselect {
4285 public function __construct($name, $visiblename, $description, $defaultsetting) {
4286 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4289 /** Lazy-load the available choices for the select box */
4290 public function load_choices() {
4291 $max = get_config('moodlecourse', 'maxsections');
4292 if (!isset($max) || !is_numeric($max)) {
4293 $max = 52;
4295 for ($i = 0; $i <= $max; $i++) {
4296 $this->choices[$i] = "$i";
4298 return true;
4304 * Course category selection
4306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4308 class admin_settings_coursecat_select extends admin_setting_configselect {
4310 * Calls parent::__construct with specific arguments
4312 public function __construct($name, $visiblename, $description, $defaultsetting) {
4313 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4317 * Load the available choices for the select box
4319 * @return bool
4321 public function load_choices() {
4322 global $CFG;
4323 require_once($CFG->dirroot.'/course/lib.php');
4324 if (is_array($this->choices)) {
4325 return true;
4327 $this->choices = make_categories_options();
4328 return true;
4334 * Special control for selecting days to backup
4336 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4338 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4340 * Calls parent::__construct with specific arguments
4342 public function __construct() {
4343 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4344 $this->plugin = 'backup';
4348 * Load the available choices for the select box
4350 * @return bool Always returns true
4352 public function load_choices() {
4353 if (is_array($this->choices)) {
4354 return true;
4356 $this->choices = array();
4357 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4358 foreach ($days as $day) {
4359 $this->choices[$day] = get_string($day, 'calendar');
4361 return true;
4367 * Special debug setting
4369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4371 class admin_setting_special_debug extends admin_setting_configselect {
4373 * Calls parent::__construct with specific arguments
4375 public function __construct() {
4376 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4380 * Load the available choices for the select box
4382 * @return bool
4384 public function load_choices() {
4385 if (is_array($this->choices)) {
4386 return true;
4388 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4389 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4390 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4391 DEBUG_ALL => get_string('debugall', 'admin'),
4392 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4393 return true;
4399 * Special admin control
4401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4403 class admin_setting_special_calendar_weekend extends admin_setting {
4405 * Calls parent::__construct with specific arguments
4407 public function __construct() {
4408 $name = 'calendar_weekend';
4409 $visiblename = get_string('calendar_weekend', 'admin');
4410 $description = get_string('helpweekenddays', 'admin');
4411 $default = array ('0', '6'); // Saturdays and Sundays
4412 parent::__construct($name, $visiblename, $description, $default);
4416 * Gets the current settings as an array
4418 * @return mixed Null if none, else array of settings
4420 public function get_setting() {
4421 $result = $this->config_read($this->name);
4422 if (is_null($result)) {
4423 return NULL;
4425 if ($result === '') {
4426 return array();
4428 $settings = array();
4429 for ($i=0; $i<7; $i++) {
4430 if ($result & (1 << $i)) {
4431 $settings[] = $i;
4434 return $settings;
4438 * Save the new settings
4440 * @param array $data Array of new settings
4441 * @return bool
4443 public function write_setting($data) {
4444 if (!is_array($data)) {
4445 return '';
4447 unset($data['xxxxx']);
4448 $result = 0;
4449 foreach($data as $index) {
4450 $result |= 1 << $index;
4452 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4456 * Return XHTML to display the control
4458 * @param array $data array of selected days
4459 * @param string $query
4460 * @return string XHTML for display (field + wrapping div(s)
4462 public function output_html($data, $query='') {
4463 // The order matters very much because of the implied numeric keys
4464 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4465 $return = '<table><thead><tr>';
4466 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4467 foreach($days as $index => $day) {
4468 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4470 $return .= '</tr></thead><tbody><tr>';
4471 foreach($days as $index => $day) {
4472 $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>';
4474 $return .= '</tr></tbody></table>';
4476 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4483 * Admin setting that allows a user to pick a behaviour.
4485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4487 class admin_setting_question_behaviour extends admin_setting_configselect {
4489 * @param string $name name of config variable
4490 * @param string $visiblename display name
4491 * @param string $description description
4492 * @param string $default default.
4494 public function __construct($name, $visiblename, $description, $default) {
4495 parent::__construct($name, $visiblename, $description, $default, NULL);
4499 * Load list of behaviours as choices
4500 * @return bool true => success, false => error.
4502 public function load_choices() {
4503 global $CFG;
4504 require_once($CFG->dirroot . '/question/engine/lib.php');
4505 $this->choices = question_engine::get_behaviour_options('');
4506 return true;
4512 * Admin setting that allows a user to pick appropriate roles for something.
4514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4516 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4517 /** @var array Array of capabilities which identify roles */
4518 private $types;
4521 * @param string $name Name of config variable
4522 * @param string $visiblename Display name
4523 * @param string $description Description
4524 * @param array $types Array of archetypes which identify
4525 * roles that will be enabled by default.
4527 public function __construct($name, $visiblename, $description, $types) {
4528 parent::__construct($name, $visiblename, $description, NULL, NULL);
4529 $this->types = $types;
4533 * Load roles as choices
4535 * @return bool true=>success, false=>error
4537 public function load_choices() {
4538 global $CFG, $DB;
4539 if (during_initial_install()) {
4540 return false;
4542 if (is_array($this->choices)) {
4543 return true;
4545 if ($roles = get_all_roles()) {
4546 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4547 return true;
4548 } else {
4549 return false;
4554 * Return the default setting for this control
4556 * @return array Array of default settings
4558 public function get_defaultsetting() {
4559 global $CFG;
4561 if (during_initial_install()) {
4562 return null;
4564 $result = array();
4565 foreach($this->types as $archetype) {
4566 if ($caproles = get_archetype_roles($archetype)) {
4567 foreach ($caproles as $caprole) {
4568 $result[$caprole->id] = 1;
4572 return $result;
4578 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4582 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4584 * Constructor
4585 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4586 * @param string $visiblename localised
4587 * @param string $description long localised info
4588 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4589 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4590 * @param int $size default field size
4592 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4593 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4594 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4600 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4602 * @copyright 2009 Petr Skoda (http://skodak.org)
4603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4605 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4608 * Constructor
4609 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4610 * @param string $visiblename localised
4611 * @param string $description long localised info
4612 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4613 * @param string $yes value used when checked
4614 * @param string $no value used when not checked
4616 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4617 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4618 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4625 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4627 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4629 * @copyright 2010 Sam Hemelryk
4630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4632 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4634 * Constructor
4635 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4636 * @param string $visiblename localised
4637 * @param string $description long localised info
4638 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4639 * @param string $yes value used when checked
4640 * @param string $no value used when not checked
4642 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4643 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4644 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4651 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4655 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4657 * Calls parent::__construct with specific arguments
4659 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4660 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4661 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4668 * Graded roles in gradebook
4670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4672 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4674 * Calls parent::__construct with specific arguments
4676 public function __construct() {
4677 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4678 get_string('configgradebookroles', 'admin'),
4679 array('student'));
4686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4688 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4690 * Saves the new settings passed in $data
4692 * @param string $data
4693 * @return mixed string or Array
4695 public function write_setting($data) {
4696 global $CFG, $DB;
4698 $oldvalue = $this->config_read($this->name);
4699 $return = parent::write_setting($data);
4700 $newvalue = $this->config_read($this->name);
4702 if ($oldvalue !== $newvalue) {
4703 // force full regrading
4704 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4707 return $return;
4713 * Which roles to show on course description page
4715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4717 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4719 * Calls parent::__construct with specific arguments
4721 public function __construct() {
4722 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4723 get_string('coursecontact_desc', 'admin'),
4724 array('editingteacher'));
4731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4733 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4735 * Calls parent::__construct with specific arguments
4737 function admin_setting_special_gradelimiting() {
4738 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4739 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4743 * Force site regrading
4745 function regrade_all() {
4746 global $CFG;
4747 require_once("$CFG->libdir/gradelib.php");
4748 grade_force_site_regrading();
4752 * Saves the new settings
4754 * @param mixed $data
4755 * @return string empty string or error message
4757 function write_setting($data) {
4758 $previous = $this->get_setting();
4760 if ($previous === null) {
4761 if ($data) {
4762 $this->regrade_all();
4764 } else {
4765 if ($data != $previous) {
4766 $this->regrade_all();
4769 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4776 * Primary grade export plugin - has state tracking.
4778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4780 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4782 * Calls parent::__construct with specific arguments
4784 public function __construct() {
4785 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4786 get_string('configgradeexport', 'admin'), array(), NULL);
4790 * Load the available choices for the multicheckbox
4792 * @return bool always returns true
4794 public function load_choices() {
4795 if (is_array($this->choices)) {
4796 return true;
4798 $this->choices = array();
4800 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4801 foreach($plugins as $plugin => $unused) {
4802 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4805 return true;
4811 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4813 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4815 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4817 * Config gradepointmax constructor
4819 * @param string $name Overidden by "gradepointmax"
4820 * @param string $visiblename Overridden by "gradepointmax" language string.
4821 * @param string $description Overridden by "gradepointmax_help" language string.
4822 * @param string $defaultsetting Not used, overridden by 100.
4823 * @param mixed $paramtype Overridden by PARAM_INT.
4824 * @param int $size Overridden by 5.
4826 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4827 $name = 'gradepointdefault';
4828 $visiblename = get_string('gradepointdefault', 'grades');
4829 $description = get_string('gradepointdefault_help', 'grades');
4830 $defaultsetting = 100;
4831 $paramtype = PARAM_INT;
4832 $size = 5;
4833 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4837 * Validate data before storage
4838 * @param string $data The submitted data
4839 * @return bool|string true if ok, string if error found
4841 public function validate($data) {
4842 global $CFG;
4843 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4844 return true;
4845 } else {
4846 return get_string('gradepointdefault_validateerror', 'grades');
4853 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4855 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4857 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4860 * Config gradepointmax constructor
4862 * @param string $name Overidden by "gradepointmax"
4863 * @param string $visiblename Overridden by "gradepointmax" language string.
4864 * @param string $description Overridden by "gradepointmax_help" language string.
4865 * @param string $defaultsetting Not used, overridden by 100.
4866 * @param mixed $paramtype Overridden by PARAM_INT.
4867 * @param int $size Overridden by 5.
4869 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4870 $name = 'gradepointmax';
4871 $visiblename = get_string('gradepointmax', 'grades');
4872 $description = get_string('gradepointmax_help', 'grades');
4873 $defaultsetting = 100;
4874 $paramtype = PARAM_INT;
4875 $size = 5;
4876 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4880 * Save the selected setting
4882 * @param string $data The selected site
4883 * @return string empty string or error message
4885 public function write_setting($data) {
4886 if ($data === '') {
4887 $data = (int)$this->defaultsetting;
4888 } else {
4889 $data = $data;
4891 return parent::write_setting($data);
4895 * Validate data before storage
4896 * @param string $data The submitted data
4897 * @return bool|string true if ok, string if error found
4899 public function validate($data) {
4900 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4901 return true;
4902 } else {
4903 return get_string('gradepointmax_validateerror', 'grades');
4908 * Return an XHTML string for the setting
4909 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4910 * @param string $query search query to be highlighted
4911 * @return string XHTML to display control
4913 public function output_html($data, $query = '') {
4914 $default = $this->get_defaultsetting();
4916 $attr = array(
4917 'type' => 'text',
4918 'size' => $this->size,
4919 'id' => $this->get_id(),
4920 'name' => $this->get_full_name(),
4921 'value' => s($data),
4922 'maxlength' => '5'
4924 $input = html_writer::empty_tag('input', $attr);
4926 $attr = array('class' => 'form-text defaultsnext');
4927 $div = html_writer::tag('div', $input, $attr);
4928 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
4934 * Grade category settings
4936 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4938 class admin_setting_gradecat_combo extends admin_setting {
4939 /** @var array Array of choices */
4940 public $choices;
4943 * Sets choices and calls parent::__construct with passed arguments
4944 * @param string $name
4945 * @param string $visiblename
4946 * @param string $description
4947 * @param mixed $defaultsetting string or array depending on implementation
4948 * @param array $choices An array of choices for the control
4950 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4951 $this->choices = $choices;
4952 parent::__construct($name, $visiblename, $description, $defaultsetting);
4956 * Return the current setting(s) array
4958 * @return array Array of value=>xx, forced=>xx, adv=>xx
4960 public function get_setting() {
4961 global $CFG;
4963 $value = $this->config_read($this->name);
4964 $flag = $this->config_read($this->name.'_flag');
4966 if (is_null($value) or is_null($flag)) {
4967 return NULL;
4970 $flag = (int)$flag;
4971 $forced = (boolean)(1 & $flag); // first bit
4972 $adv = (boolean)(2 & $flag); // second bit
4974 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4978 * Save the new settings passed in $data
4980 * @todo Add vartype handling to ensure $data is array
4981 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4982 * @return string empty or error message
4984 public function write_setting($data) {
4985 global $CFG;
4987 $value = $data['value'];
4988 $forced = empty($data['forced']) ? 0 : 1;
4989 $adv = empty($data['adv']) ? 0 : 2;
4990 $flag = ($forced | $adv); //bitwise or
4992 if (!in_array($value, array_keys($this->choices))) {
4993 return 'Error setting ';
4996 $oldvalue = $this->config_read($this->name);
4997 $oldflag = (int)$this->config_read($this->name.'_flag');
4998 $oldforced = (1 & $oldflag); // first bit
5000 $result1 = $this->config_write($this->name, $value);
5001 $result2 = $this->config_write($this->name.'_flag', $flag);
5003 // force regrade if needed
5004 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5005 require_once($CFG->libdir.'/gradelib.php');
5006 grade_category::updated_forced_settings();
5009 if ($result1 and $result2) {
5010 return '';
5011 } else {
5012 return get_string('errorsetting', 'admin');
5017 * Return XHTML to display the field and wrapping div
5019 * @todo Add vartype handling to ensure $data is array
5020 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5021 * @param string $query
5022 * @return string XHTML to display control
5024 public function output_html($data, $query='') {
5025 $value = $data['value'];
5026 $forced = !empty($data['forced']);
5027 $adv = !empty($data['adv']);
5029 $default = $this->get_defaultsetting();
5030 if (!is_null($default)) {
5031 $defaultinfo = array();
5032 if (isset($this->choices[$default['value']])) {
5033 $defaultinfo[] = $this->choices[$default['value']];
5035 if (!empty($default['forced'])) {
5036 $defaultinfo[] = get_string('force');
5038 if (!empty($default['adv'])) {
5039 $defaultinfo[] = get_string('advanced');
5041 $defaultinfo = implode(', ', $defaultinfo);
5043 } else {
5044 $defaultinfo = NULL;
5048 $return = '<div class="form-group">';
5049 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5050 foreach ($this->choices as $key => $val) {
5051 // the string cast is needed because key may be integer - 0 is equal to most strings!
5052 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5054 $return .= '</select>';
5055 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5056 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5057 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5058 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5059 $return .= '</div>';
5061 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5067 * Selection of grade report in user profiles
5069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5071 class admin_setting_grade_profilereport extends admin_setting_configselect {
5073 * Calls parent::__construct with specific arguments
5075 public function __construct() {
5076 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5080 * Loads an array of choices for the configselect control
5082 * @return bool always return true
5084 public function load_choices() {
5085 if (is_array($this->choices)) {
5086 return true;
5088 $this->choices = array();
5090 global $CFG;
5091 require_once($CFG->libdir.'/gradelib.php');
5093 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5094 if (file_exists($plugindir.'/lib.php')) {
5095 require_once($plugindir.'/lib.php');
5096 $functionname = 'grade_report_'.$plugin.'_profilereport';
5097 if (function_exists($functionname)) {
5098 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5102 return true;
5108 * Special class for register auth selection
5110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5112 class admin_setting_special_registerauth extends admin_setting_configselect {
5114 * Calls parent::__construct with specific arguments
5116 public function __construct() {
5117 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5121 * Returns the default option
5123 * @return string empty or default option
5125 public function get_defaultsetting() {
5126 $this->load_choices();
5127 $defaultsetting = parent::get_defaultsetting();
5128 if (array_key_exists($defaultsetting, $this->choices)) {
5129 return $defaultsetting;
5130 } else {
5131 return '';
5136 * Loads the possible choices for the array
5138 * @return bool always returns true
5140 public function load_choices() {
5141 global $CFG;
5143 if (is_array($this->choices)) {
5144 return true;
5146 $this->choices = array();
5147 $this->choices[''] = get_string('disable');
5149 $authsenabled = get_enabled_auth_plugins(true);
5151 foreach ($authsenabled as $auth) {
5152 $authplugin = get_auth_plugin($auth);
5153 if (!$authplugin->can_signup()) {
5154 continue;
5156 // Get the auth title (from core or own auth lang files)
5157 $authtitle = $authplugin->get_title();
5158 $this->choices[$auth] = $authtitle;
5160 return true;
5166 * General plugins manager
5168 class admin_page_pluginsoverview extends admin_externalpage {
5171 * Sets basic information about the external page
5173 public function __construct() {
5174 global $CFG;
5175 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5176 "$CFG->wwwroot/$CFG->admin/plugins.php");
5181 * Module manage page
5183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5185 class admin_page_managemods extends admin_externalpage {
5187 * Calls parent::__construct with specific arguments
5189 public function __construct() {
5190 global $CFG;
5191 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5195 * Try to find the specified module
5197 * @param string $query The module to search for
5198 * @return array
5200 public function search($query) {
5201 global $CFG, $DB;
5202 if ($result = parent::search($query)) {
5203 return $result;
5206 $found = false;
5207 if ($modules = $DB->get_records('modules')) {
5208 foreach ($modules as $module) {
5209 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5210 continue;
5212 if (strpos($module->name, $query) !== false) {
5213 $found = true;
5214 break;
5216 $strmodulename = get_string('modulename', $module->name);
5217 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5218 $found = true;
5219 break;
5223 if ($found) {
5224 $result = new stdClass();
5225 $result->page = $this;
5226 $result->settings = array();
5227 return array($this->name => $result);
5228 } else {
5229 return array();
5236 * Special class for enrol plugins management.
5238 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5241 class admin_setting_manageenrols extends admin_setting {
5243 * Calls parent::__construct with specific arguments
5245 public function __construct() {
5246 $this->nosave = true;
5247 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5251 * Always returns true, does nothing
5253 * @return true
5255 public function get_setting() {
5256 return true;
5260 * Always returns true, does nothing
5262 * @return true
5264 public function get_defaultsetting() {
5265 return true;
5269 * Always returns '', does not write anything
5271 * @return string Always returns ''
5273 public function write_setting($data) {
5274 // do not write any setting
5275 return '';
5279 * Checks if $query is one of the available enrol plugins
5281 * @param string $query The string to search for
5282 * @return bool Returns true if found, false if not
5284 public function is_related($query) {
5285 if (parent::is_related($query)) {
5286 return true;
5289 $query = core_text::strtolower($query);
5290 $enrols = enrol_get_plugins(false);
5291 foreach ($enrols as $name=>$enrol) {
5292 $localised = get_string('pluginname', 'enrol_'.$name);
5293 if (strpos(core_text::strtolower($name), $query) !== false) {
5294 return true;
5296 if (strpos(core_text::strtolower($localised), $query) !== false) {
5297 return true;
5300 return false;
5304 * Builds the XHTML to display the control
5306 * @param string $data Unused
5307 * @param string $query
5308 * @return string
5310 public function output_html($data, $query='') {
5311 global $CFG, $OUTPUT, $DB, $PAGE;
5313 // Display strings.
5314 $strup = get_string('up');
5315 $strdown = get_string('down');
5316 $strsettings = get_string('settings');
5317 $strenable = get_string('enable');
5318 $strdisable = get_string('disable');
5319 $struninstall = get_string('uninstallplugin', 'core_admin');
5320 $strusage = get_string('enrolusage', 'enrol');
5321 $strversion = get_string('version');
5322 $strtest = get_string('testsettings', 'core_enrol');
5324 $pluginmanager = core_plugin_manager::instance();
5326 $enrols_available = enrol_get_plugins(false);
5327 $active_enrols = enrol_get_plugins(true);
5329 $allenrols = array();
5330 foreach ($active_enrols as $key=>$enrol) {
5331 $allenrols[$key] = true;
5333 foreach ($enrols_available as $key=>$enrol) {
5334 $allenrols[$key] = true;
5336 // Now find all borked plugins and at least allow then to uninstall.
5337 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5338 foreach ($condidates as $candidate) {
5339 if (empty($allenrols[$candidate])) {
5340 $allenrols[$candidate] = true;
5344 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5345 $return .= $OUTPUT->box_start('generalbox enrolsui');
5347 $table = new html_table();
5348 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5349 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5350 $table->id = 'courseenrolmentplugins';
5351 $table->attributes['class'] = 'admintable generaltable';
5352 $table->data = array();
5354 // Iterate through enrol plugins and add to the display table.
5355 $updowncount = 1;
5356 $enrolcount = count($active_enrols);
5357 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5358 $printed = array();
5359 foreach($allenrols as $enrol => $unused) {
5360 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5361 $version = get_config('enrol_'.$enrol, 'version');
5362 if ($version === false) {
5363 $version = '';
5366 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5367 $name = get_string('pluginname', 'enrol_'.$enrol);
5368 } else {
5369 $name = $enrol;
5371 // Usage.
5372 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5373 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5374 $usage = "$ci / $cp";
5376 // Hide/show links.
5377 $class = '';
5378 if (isset($active_enrols[$enrol])) {
5379 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5380 $hideshow = "<a href=\"$aurl\">";
5381 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5382 $enabled = true;
5383 $displayname = $name;
5384 } else if (isset($enrols_available[$enrol])) {
5385 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5386 $hideshow = "<a href=\"$aurl\">";
5387 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5388 $enabled = false;
5389 $displayname = $name;
5390 $class = 'dimmed_text';
5391 } else {
5392 $hideshow = '';
5393 $enabled = false;
5394 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5396 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5397 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5398 } else {
5399 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5402 // Up/down link (only if enrol is enabled).
5403 $updown = '';
5404 if ($enabled) {
5405 if ($updowncount > 1) {
5406 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5407 $updown .= "<a href=\"$aurl\">";
5408 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5409 } else {
5410 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5412 if ($updowncount < $enrolcount) {
5413 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5414 $updown .= "<a href=\"$aurl\">";
5415 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5416 } else {
5417 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5419 ++$updowncount;
5422 // Add settings link.
5423 if (!$version) {
5424 $settings = '';
5425 } else if ($surl = $plugininfo->get_settings_url()) {
5426 $settings = html_writer::link($surl, $strsettings);
5427 } else {
5428 $settings = '';
5431 // Add uninstall info.
5432 $uninstall = '';
5433 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5434 $uninstall = html_writer::link($uninstallurl, $struninstall);
5437 $test = '';
5438 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5439 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5440 $test = html_writer::link($testsettingsurl, $strtest);
5443 // Add a row to the table.
5444 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5445 if ($class) {
5446 $row->attributes['class'] = $class;
5448 $table->data[] = $row;
5450 $printed[$enrol] = true;
5453 $return .= html_writer::table($table);
5454 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5455 $return .= $OUTPUT->box_end();
5456 return highlight($query, $return);
5462 * Blocks manage page
5464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5466 class admin_page_manageblocks extends admin_externalpage {
5468 * Calls parent::__construct with specific arguments
5470 public function __construct() {
5471 global $CFG;
5472 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5476 * Search for a specific block
5478 * @param string $query The string to search for
5479 * @return array
5481 public function search($query) {
5482 global $CFG, $DB;
5483 if ($result = parent::search($query)) {
5484 return $result;
5487 $found = false;
5488 if ($blocks = $DB->get_records('block')) {
5489 foreach ($blocks as $block) {
5490 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5491 continue;
5493 if (strpos($block->name, $query) !== false) {
5494 $found = true;
5495 break;
5497 $strblockname = get_string('pluginname', 'block_'.$block->name);
5498 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5499 $found = true;
5500 break;
5504 if ($found) {
5505 $result = new stdClass();
5506 $result->page = $this;
5507 $result->settings = array();
5508 return array($this->name => $result);
5509 } else {
5510 return array();
5516 * Message outputs configuration
5518 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5520 class admin_page_managemessageoutputs extends admin_externalpage {
5522 * Calls parent::__construct with specific arguments
5524 public function __construct() {
5525 global $CFG;
5526 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5530 * Search for a specific message processor
5532 * @param string $query The string to search for
5533 * @return array
5535 public function search($query) {
5536 global $CFG, $DB;
5537 if ($result = parent::search($query)) {
5538 return $result;
5541 $found = false;
5542 if ($processors = get_message_processors()) {
5543 foreach ($processors as $processor) {
5544 if (!$processor->available) {
5545 continue;
5547 if (strpos($processor->name, $query) !== false) {
5548 $found = true;
5549 break;
5551 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5552 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5553 $found = true;
5554 break;
5558 if ($found) {
5559 $result = new stdClass();
5560 $result->page = $this;
5561 $result->settings = array();
5562 return array($this->name => $result);
5563 } else {
5564 return array();
5570 * Default message outputs configuration
5572 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5574 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5576 * Calls parent::__construct with specific arguments
5578 public function __construct() {
5579 global $CFG;
5580 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5586 * Manage question behaviours page
5588 * @copyright 2011 The Open University
5589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5591 class admin_page_manageqbehaviours extends admin_externalpage {
5593 * Constructor
5595 public function __construct() {
5596 global $CFG;
5597 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5598 new moodle_url('/admin/qbehaviours.php'));
5602 * Search question behaviours for the specified string
5604 * @param string $query The string to search for in question behaviours
5605 * @return array
5607 public function search($query) {
5608 global $CFG;
5609 if ($result = parent::search($query)) {
5610 return $result;
5613 $found = false;
5614 require_once($CFG->dirroot . '/question/engine/lib.php');
5615 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5616 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5617 $query) !== false) {
5618 $found = true;
5619 break;
5622 if ($found) {
5623 $result = new stdClass();
5624 $result->page = $this;
5625 $result->settings = array();
5626 return array($this->name => $result);
5627 } else {
5628 return array();
5635 * Question type manage page
5637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5639 class admin_page_manageqtypes extends admin_externalpage {
5641 * Calls parent::__construct with specific arguments
5643 public function __construct() {
5644 global $CFG;
5645 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5646 new moodle_url('/admin/qtypes.php'));
5650 * Search question types for the specified string
5652 * @param string $query The string to search for in question types
5653 * @return array
5655 public function search($query) {
5656 global $CFG;
5657 if ($result = parent::search($query)) {
5658 return $result;
5661 $found = false;
5662 require_once($CFG->dirroot . '/question/engine/bank.php');
5663 foreach (question_bank::get_all_qtypes() as $qtype) {
5664 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5665 $found = true;
5666 break;
5669 if ($found) {
5670 $result = new stdClass();
5671 $result->page = $this;
5672 $result->settings = array();
5673 return array($this->name => $result);
5674 } else {
5675 return array();
5681 class admin_page_manageportfolios extends admin_externalpage {
5683 * Calls parent::__construct with specific arguments
5685 public function __construct() {
5686 global $CFG;
5687 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5688 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5692 * Searches page for the specified string.
5693 * @param string $query The string to search for
5694 * @return bool True if it is found on this page
5696 public function search($query) {
5697 global $CFG;
5698 if ($result = parent::search($query)) {
5699 return $result;
5702 $found = false;
5703 $portfolios = core_component::get_plugin_list('portfolio');
5704 foreach ($portfolios as $p => $dir) {
5705 if (strpos($p, $query) !== false) {
5706 $found = true;
5707 break;
5710 if (!$found) {
5711 foreach (portfolio_instances(false, false) as $instance) {
5712 $title = $instance->get('name');
5713 if (strpos(core_text::strtolower($title), $query) !== false) {
5714 $found = true;
5715 break;
5720 if ($found) {
5721 $result = new stdClass();
5722 $result->page = $this;
5723 $result->settings = array();
5724 return array($this->name => $result);
5725 } else {
5726 return array();
5732 class admin_page_managerepositories extends admin_externalpage {
5734 * Calls parent::__construct with specific arguments
5736 public function __construct() {
5737 global $CFG;
5738 parent::__construct('managerepositories', get_string('manage',
5739 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5743 * Searches page for the specified string.
5744 * @param string $query The string to search for
5745 * @return bool True if it is found on this page
5747 public function search($query) {
5748 global $CFG;
5749 if ($result = parent::search($query)) {
5750 return $result;
5753 $found = false;
5754 $repositories= core_component::get_plugin_list('repository');
5755 foreach ($repositories as $p => $dir) {
5756 if (strpos($p, $query) !== false) {
5757 $found = true;
5758 break;
5761 if (!$found) {
5762 foreach (repository::get_types() as $instance) {
5763 $title = $instance->get_typename();
5764 if (strpos(core_text::strtolower($title), $query) !== false) {
5765 $found = true;
5766 break;
5771 if ($found) {
5772 $result = new stdClass();
5773 $result->page = $this;
5774 $result->settings = array();
5775 return array($this->name => $result);
5776 } else {
5777 return array();
5784 * Special class for authentication administration.
5786 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5788 class admin_setting_manageauths extends admin_setting {
5790 * Calls parent::__construct with specific arguments
5792 public function __construct() {
5793 $this->nosave = true;
5794 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5798 * Always returns true
5800 * @return true
5802 public function get_setting() {
5803 return true;
5807 * Always returns true
5809 * @return true
5811 public function get_defaultsetting() {
5812 return true;
5816 * Always returns '' and doesn't write anything
5818 * @return string Always returns ''
5820 public function write_setting($data) {
5821 // do not write any setting
5822 return '';
5826 * Search to find if Query is related to auth plugin
5828 * @param string $query The string to search for
5829 * @return bool true for related false for not
5831 public function is_related($query) {
5832 if (parent::is_related($query)) {
5833 return true;
5836 $authsavailable = core_component::get_plugin_list('auth');
5837 foreach ($authsavailable as $auth => $dir) {
5838 if (strpos($auth, $query) !== false) {
5839 return true;
5841 $authplugin = get_auth_plugin($auth);
5842 $authtitle = $authplugin->get_title();
5843 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5844 return true;
5847 return false;
5851 * Return XHTML to display control
5853 * @param mixed $data Unused
5854 * @param string $query
5855 * @return string highlight
5857 public function output_html($data, $query='') {
5858 global $CFG, $OUTPUT, $DB;
5860 // display strings
5861 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5862 'settings', 'edit', 'name', 'enable', 'disable',
5863 'up', 'down', 'none', 'users'));
5864 $txt->updown = "$txt->up/$txt->down";
5865 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5866 $txt->testsettings = get_string('testsettings', 'core_auth');
5868 $authsavailable = core_component::get_plugin_list('auth');
5869 get_enabled_auth_plugins(true); // fix the list of enabled auths
5870 if (empty($CFG->auth)) {
5871 $authsenabled = array();
5872 } else {
5873 $authsenabled = explode(',', $CFG->auth);
5876 // construct the display array, with enabled auth plugins at the top, in order
5877 $displayauths = array();
5878 $registrationauths = array();
5879 $registrationauths[''] = $txt->disable;
5880 $authplugins = array();
5881 foreach ($authsenabled as $auth) {
5882 $authplugin = get_auth_plugin($auth);
5883 $authplugins[$auth] = $authplugin;
5884 /// Get the auth title (from core or own auth lang files)
5885 $authtitle = $authplugin->get_title();
5886 /// Apply titles
5887 $displayauths[$auth] = $authtitle;
5888 if ($authplugin->can_signup()) {
5889 $registrationauths[$auth] = $authtitle;
5893 foreach ($authsavailable as $auth => $dir) {
5894 if (array_key_exists($auth, $displayauths)) {
5895 continue; //already in the list
5897 $authplugin = get_auth_plugin($auth);
5898 $authplugins[$auth] = $authplugin;
5899 /// Get the auth title (from core or own auth lang files)
5900 $authtitle = $authplugin->get_title();
5901 /// Apply titles
5902 $displayauths[$auth] = $authtitle;
5903 if ($authplugin->can_signup()) {
5904 $registrationauths[$auth] = $authtitle;
5908 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5909 $return .= $OUTPUT->box_start('generalbox authsui');
5911 $table = new html_table();
5912 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5913 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5914 $table->data = array();
5915 $table->attributes['class'] = 'admintable generaltable';
5916 $table->id = 'manageauthtable';
5918 //add always enabled plugins first
5919 $displayname = $displayauths['manual'];
5920 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5921 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5922 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
5923 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5924 $displayname = $displayauths['nologin'];
5925 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5926 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
5927 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5930 // iterate through auth plugins and add to the display table
5931 $updowncount = 1;
5932 $authcount = count($authsenabled);
5933 $url = "auth.php?sesskey=" . sesskey();
5934 foreach ($displayauths as $auth => $name) {
5935 if ($auth == 'manual' or $auth == 'nologin') {
5936 continue;
5938 $class = '';
5939 // hide/show link
5940 if (in_array($auth, $authsenabled)) {
5941 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5942 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5943 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5944 $enabled = true;
5945 $displayname = $name;
5947 else {
5948 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5949 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5950 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5951 $enabled = false;
5952 $displayname = $name;
5953 $class = 'dimmed_text';
5956 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
5958 // up/down link (only if auth is enabled)
5959 $updown = '';
5960 if ($enabled) {
5961 if ($updowncount > 1) {
5962 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5963 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5965 else {
5966 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5968 if ($updowncount < $authcount) {
5969 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5970 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5972 else {
5973 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5975 ++ $updowncount;
5978 // settings link
5979 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5980 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5981 } else {
5982 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5985 // Uninstall link.
5986 $uninstall = '';
5987 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
5988 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
5991 $test = '';
5992 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
5993 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
5994 $test = html_writer::link($testurl, $txt->testsettings);
5997 // Add a row to the table.
5998 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
5999 if ($class) {
6000 $row->attributes['class'] = $class;
6002 $table->data[] = $row;
6004 $return .= html_writer::table($table);
6005 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6006 $return .= $OUTPUT->box_end();
6007 return highlight($query, $return);
6013 * Special class for authentication administration.
6015 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6017 class admin_setting_manageeditors extends admin_setting {
6019 * Calls parent::__construct with specific arguments
6021 public function __construct() {
6022 $this->nosave = true;
6023 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6027 * Always returns true, does nothing
6029 * @return true
6031 public function get_setting() {
6032 return true;
6036 * Always returns true, does nothing
6038 * @return true
6040 public function get_defaultsetting() {
6041 return true;
6045 * Always returns '', does not write anything
6047 * @return string Always returns ''
6049 public function write_setting($data) {
6050 // do not write any setting
6051 return '';
6055 * Checks if $query is one of the available editors
6057 * @param string $query The string to search for
6058 * @return bool Returns true if found, false if not
6060 public function is_related($query) {
6061 if (parent::is_related($query)) {
6062 return true;
6065 $editors_available = editors_get_available();
6066 foreach ($editors_available as $editor=>$editorstr) {
6067 if (strpos($editor, $query) !== false) {
6068 return true;
6070 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6071 return true;
6074 return false;
6078 * Builds the XHTML to display the control
6080 * @param string $data Unused
6081 * @param string $query
6082 * @return string
6084 public function output_html($data, $query='') {
6085 global $CFG, $OUTPUT;
6087 // display strings
6088 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6089 'up', 'down', 'none'));
6090 $struninstall = get_string('uninstallplugin', 'core_admin');
6092 $txt->updown = "$txt->up/$txt->down";
6094 $editors_available = editors_get_available();
6095 $active_editors = explode(',', $CFG->texteditors);
6097 $active_editors = array_reverse($active_editors);
6098 foreach ($active_editors as $key=>$editor) {
6099 if (empty($editors_available[$editor])) {
6100 unset($active_editors[$key]);
6101 } else {
6102 $name = $editors_available[$editor];
6103 unset($editors_available[$editor]);
6104 $editors_available[$editor] = $name;
6107 if (empty($active_editors)) {
6108 //$active_editors = array('textarea');
6110 $editors_available = array_reverse($editors_available, true);
6111 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6112 $return .= $OUTPUT->box_start('generalbox editorsui');
6114 $table = new html_table();
6115 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6116 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6117 $table->id = 'editormanagement';
6118 $table->attributes['class'] = 'admintable generaltable';
6119 $table->data = array();
6121 // iterate through auth plugins and add to the display table
6122 $updowncount = 1;
6123 $editorcount = count($active_editors);
6124 $url = "editors.php?sesskey=" . sesskey();
6125 foreach ($editors_available as $editor => $name) {
6126 // hide/show link
6127 $class = '';
6128 if (in_array($editor, $active_editors)) {
6129 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6130 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6131 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6132 $enabled = true;
6133 $displayname = $name;
6135 else {
6136 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6137 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6138 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6139 $enabled = false;
6140 $displayname = $name;
6141 $class = 'dimmed_text';
6144 // up/down link (only if auth is enabled)
6145 $updown = '';
6146 if ($enabled) {
6147 if ($updowncount > 1) {
6148 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6149 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6151 else {
6152 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6154 if ($updowncount < $editorcount) {
6155 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6156 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6158 else {
6159 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6161 ++ $updowncount;
6164 // settings link
6165 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6166 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6167 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6168 } else {
6169 $settings = '';
6172 $uninstall = '';
6173 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6174 $uninstall = html_writer::link($uninstallurl, $struninstall);
6177 // Add a row to the table.
6178 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6179 if ($class) {
6180 $row->attributes['class'] = $class;
6182 $table->data[] = $row;
6184 $return .= html_writer::table($table);
6185 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6186 $return .= $OUTPUT->box_end();
6187 return highlight($query, $return);
6193 * Special class for license administration.
6195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6197 class admin_setting_managelicenses extends admin_setting {
6199 * Calls parent::__construct with specific arguments
6201 public function __construct() {
6202 $this->nosave = true;
6203 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6207 * Always returns true, does nothing
6209 * @return true
6211 public function get_setting() {
6212 return true;
6216 * Always returns true, does nothing
6218 * @return true
6220 public function get_defaultsetting() {
6221 return true;
6225 * Always returns '', does not write anything
6227 * @return string Always returns ''
6229 public function write_setting($data) {
6230 // do not write any setting
6231 return '';
6235 * Builds the XHTML to display the control
6237 * @param string $data Unused
6238 * @param string $query
6239 * @return string
6241 public function output_html($data, $query='') {
6242 global $CFG, $OUTPUT;
6243 require_once($CFG->libdir . '/licenselib.php');
6244 $url = "licenses.php?sesskey=" . sesskey();
6246 // display strings
6247 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6248 $licenses = license_manager::get_licenses();
6250 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6252 $return .= $OUTPUT->box_start('generalbox editorsui');
6254 $table = new html_table();
6255 $table->head = array($txt->name, $txt->enable);
6256 $table->colclasses = array('leftalign', 'centeralign');
6257 $table->id = 'availablelicenses';
6258 $table->attributes['class'] = 'admintable generaltable';
6259 $table->data = array();
6261 foreach ($licenses as $value) {
6262 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6264 if ($value->enabled == 1) {
6265 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6266 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6267 } else {
6268 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6269 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6272 if ($value->shortname == $CFG->sitedefaultlicense) {
6273 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6274 $hideshow = '';
6277 $enabled = true;
6279 $table->data[] =array($displayname, $hideshow);
6281 $return .= html_writer::table($table);
6282 $return .= $OUTPUT->box_end();
6283 return highlight($query, $return);
6288 * Course formats manager. Allows to enable/disable formats and jump to settings
6290 class admin_setting_manageformats extends admin_setting {
6293 * Calls parent::__construct with specific arguments
6295 public function __construct() {
6296 $this->nosave = true;
6297 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6301 * Always returns true
6303 * @return true
6305 public function get_setting() {
6306 return true;
6310 * Always returns true
6312 * @return true
6314 public function get_defaultsetting() {
6315 return true;
6319 * Always returns '' and doesn't write anything
6321 * @param mixed $data string or array, must not be NULL
6322 * @return string Always returns ''
6324 public function write_setting($data) {
6325 // do not write any setting
6326 return '';
6330 * Search to find if Query is related to format plugin
6332 * @param string $query The string to search for
6333 * @return bool true for related false for not
6335 public function is_related($query) {
6336 if (parent::is_related($query)) {
6337 return true;
6339 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6340 foreach ($formats as $format) {
6341 if (strpos($format->component, $query) !== false ||
6342 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6343 return true;
6346 return false;
6350 * Return XHTML to display control
6352 * @param mixed $data Unused
6353 * @param string $query
6354 * @return string highlight
6356 public function output_html($data, $query='') {
6357 global $CFG, $OUTPUT;
6358 $return = '';
6359 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6360 $return .= $OUTPUT->box_start('generalbox formatsui');
6362 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6364 // display strings
6365 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6366 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6367 $txt->updown = "$txt->up/$txt->down";
6369 $table = new html_table();
6370 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6371 $table->align = array('left', 'center', 'center', 'center', 'center');
6372 $table->attributes['class'] = 'manageformattable generaltable admintable';
6373 $table->data = array();
6375 $cnt = 0;
6376 $defaultformat = get_config('moodlecourse', 'format');
6377 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6378 foreach ($formats as $format) {
6379 $url = new moodle_url('/admin/courseformats.php',
6380 array('sesskey' => sesskey(), 'format' => $format->name));
6381 $isdefault = '';
6382 $class = '';
6383 if ($format->is_enabled()) {
6384 $strformatname = $format->displayname;
6385 if ($defaultformat === $format->name) {
6386 $hideshow = $txt->default;
6387 } else {
6388 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6389 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6391 } else {
6392 $strformatname = $format->displayname;
6393 $class = 'dimmed_text';
6394 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6395 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6397 $updown = '';
6398 if ($cnt) {
6399 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6400 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6401 } else {
6402 $updown .= $spacer;
6404 if ($cnt < count($formats) - 1) {
6405 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6406 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6407 } else {
6408 $updown .= $spacer;
6410 $cnt++;
6411 $settings = '';
6412 if ($format->get_settings_url()) {
6413 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6415 $uninstall = '';
6416 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6417 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6419 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6420 if ($class) {
6421 $row->attributes['class'] = $class;
6423 $table->data[] = $row;
6425 $return .= html_writer::table($table);
6426 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6427 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6428 $return .= $OUTPUT->box_end();
6429 return highlight($query, $return);
6434 * Special class for filter administration.
6436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6438 class admin_page_managefilters extends admin_externalpage {
6440 * Calls parent::__construct with specific arguments
6442 public function __construct() {
6443 global $CFG;
6444 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6448 * Searches all installed filters for specified filter
6450 * @param string $query The filter(string) to search for
6451 * @param string $query
6453 public function search($query) {
6454 global $CFG;
6455 if ($result = parent::search($query)) {
6456 return $result;
6459 $found = false;
6460 $filternames = filter_get_all_installed();
6461 foreach ($filternames as $path => $strfiltername) {
6462 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6463 $found = true;
6464 break;
6466 if (strpos($path, $query) !== false) {
6467 $found = true;
6468 break;
6472 if ($found) {
6473 $result = new stdClass;
6474 $result->page = $this;
6475 $result->settings = array();
6476 return array($this->name => $result);
6477 } else {
6478 return array();
6485 * Initialise admin page - this function does require login and permission
6486 * checks specified in page definition.
6488 * This function must be called on each admin page before other code.
6490 * @global moodle_page $PAGE
6492 * @param string $section name of page
6493 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6494 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6495 * added to the turn blocks editing on/off form, so this page reloads correctly.
6496 * @param string $actualurl if the actual page being viewed is not the normal one for this
6497 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6498 * @param array $options Additional options that can be specified for page setup.
6499 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6501 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6502 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6504 $PAGE->set_context(null); // hack - set context to something, by default to system context
6506 $site = get_site();
6507 require_login();
6509 if (!empty($options['pagelayout'])) {
6510 // A specific page layout has been requested.
6511 $PAGE->set_pagelayout($options['pagelayout']);
6512 } else if ($section === 'upgradesettings') {
6513 $PAGE->set_pagelayout('maintenance');
6514 } else {
6515 $PAGE->set_pagelayout('admin');
6518 $adminroot = admin_get_root(false, false); // settings not required for external pages
6519 $extpage = $adminroot->locate($section, true);
6521 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6522 // The requested section isn't in the admin tree
6523 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6524 if (!has_capability('moodle/site:config', context_system::instance())) {
6525 // The requested section could depend on a different capability
6526 // but most likely the user has inadequate capabilities
6527 print_error('accessdenied', 'admin');
6528 } else {
6529 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6533 // this eliminates our need to authenticate on the actual pages
6534 if (!$extpage->check_access()) {
6535 print_error('accessdenied', 'admin');
6536 die;
6539 navigation_node::require_admin_tree();
6541 // $PAGE->set_extra_button($extrabutton); TODO
6543 if (!$actualurl) {
6544 $actualurl = $extpage->url;
6547 $PAGE->set_url($actualurl, $extraurlparams);
6548 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6549 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6552 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6553 // During initial install.
6554 $strinstallation = get_string('installation', 'install');
6555 $strsettings = get_string('settings');
6556 $PAGE->navbar->add($strsettings);
6557 $PAGE->set_title($strinstallation);
6558 $PAGE->set_heading($strinstallation);
6559 $PAGE->set_cacheable(false);
6560 return;
6563 // Locate the current item on the navigation and make it active when found.
6564 $path = $extpage->path;
6565 $node = $PAGE->settingsnav;
6566 while ($node && count($path) > 0) {
6567 $node = $node->get(array_pop($path));
6569 if ($node) {
6570 $node->make_active();
6573 // Normal case.
6574 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6575 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6576 $USER->editing = $adminediting;
6579 $visiblepathtosection = array_reverse($extpage->visiblepath);
6581 if ($PAGE->user_allowed_editing()) {
6582 if ($PAGE->user_is_editing()) {
6583 $caption = get_string('blockseditoff');
6584 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6585 } else {
6586 $caption = get_string('blocksediton');
6587 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6589 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6592 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6593 $PAGE->set_heading($SITE->fullname);
6595 // prevent caching in nav block
6596 $PAGE->navigation->clear_cache();
6600 * Returns the reference to admin tree root
6602 * @return object admin_root object
6604 function admin_get_root($reload=false, $requirefulltree=true) {
6605 global $CFG, $DB, $OUTPUT;
6607 static $ADMIN = NULL;
6609 if (is_null($ADMIN)) {
6610 // create the admin tree!
6611 $ADMIN = new admin_root($requirefulltree);
6614 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6615 $ADMIN->purge_children($requirefulltree);
6618 if (!$ADMIN->loaded) {
6619 // we process this file first to create categories first and in correct order
6620 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6622 // now we process all other files in admin/settings to build the admin tree
6623 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6624 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6625 continue;
6627 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6628 // plugins are loaded last - they may insert pages anywhere
6629 continue;
6631 require($file);
6633 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6635 $ADMIN->loaded = true;
6638 return $ADMIN;
6641 /// settings utility functions
6644 * This function applies default settings.
6646 * @param object $node, NULL means complete tree, null by default
6647 * @param bool $unconditional if true overrides all values with defaults, null buy default
6649 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6650 global $CFG;
6652 if (is_null($node)) {
6653 core_plugin_manager::reset_caches();
6654 $node = admin_get_root(true, true);
6657 if ($node instanceof admin_category) {
6658 $entries = array_keys($node->children);
6659 foreach ($entries as $entry) {
6660 admin_apply_default_settings($node->children[$entry], $unconditional);
6663 } else if ($node instanceof admin_settingpage) {
6664 foreach ($node->settings as $setting) {
6665 if (!$unconditional and !is_null($setting->get_setting())) {
6666 //do not override existing defaults
6667 continue;
6669 $defaultsetting = $setting->get_defaultsetting();
6670 if (is_null($defaultsetting)) {
6671 // no value yet - default maybe applied after admin user creation or in upgradesettings
6672 continue;
6674 $setting->write_setting($defaultsetting);
6675 $setting->write_setting_flags(null);
6678 // Just in case somebody modifies the list of active plugins directly.
6679 core_plugin_manager::reset_caches();
6683 * Store changed settings, this function updates the errors variable in $ADMIN
6685 * @param object $formdata from form
6686 * @return int number of changed settings
6688 function admin_write_settings($formdata) {
6689 global $CFG, $SITE, $DB;
6691 $olddbsessions = !empty($CFG->dbsessions);
6692 $formdata = (array)$formdata;
6694 $data = array();
6695 foreach ($formdata as $fullname=>$value) {
6696 if (strpos($fullname, 's_') !== 0) {
6697 continue; // not a config value
6699 $data[$fullname] = $value;
6702 $adminroot = admin_get_root();
6703 $settings = admin_find_write_settings($adminroot, $data);
6705 $count = 0;
6706 foreach ($settings as $fullname=>$setting) {
6707 /** @var $setting admin_setting */
6708 $original = $setting->get_setting();
6709 $error = $setting->write_setting($data[$fullname]);
6710 if ($error !== '') {
6711 $adminroot->errors[$fullname] = new stdClass();
6712 $adminroot->errors[$fullname]->data = $data[$fullname];
6713 $adminroot->errors[$fullname]->id = $setting->get_id();
6714 $adminroot->errors[$fullname]->error = $error;
6715 } else {
6716 $setting->write_setting_flags($data);
6718 if ($setting->post_write_settings($original)) {
6719 $count++;
6723 if ($olddbsessions != !empty($CFG->dbsessions)) {
6724 require_logout();
6727 // Now update $SITE - just update the fields, in case other people have a
6728 // a reference to it (e.g. $PAGE, $COURSE).
6729 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6730 foreach (get_object_vars($newsite) as $field => $value) {
6731 $SITE->$field = $value;
6734 // now reload all settings - some of them might depend on the changed
6735 admin_get_root(true);
6736 return $count;
6740 * Internal recursive function - finds all settings from submitted form
6742 * @param object $node Instance of admin_category, or admin_settingpage
6743 * @param array $data
6744 * @return array
6746 function admin_find_write_settings($node, $data) {
6747 $return = array();
6749 if (empty($data)) {
6750 return $return;
6753 if ($node instanceof admin_category) {
6754 $entries = array_keys($node->children);
6755 foreach ($entries as $entry) {
6756 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6759 } else if ($node instanceof admin_settingpage) {
6760 foreach ($node->settings as $setting) {
6761 $fullname = $setting->get_full_name();
6762 if (array_key_exists($fullname, $data)) {
6763 $return[$fullname] = $setting;
6769 return $return;
6773 * Internal function - prints the search results
6775 * @param string $query String to search for
6776 * @return string empty or XHTML
6778 function admin_search_settings_html($query) {
6779 global $CFG, $OUTPUT;
6781 if (core_text::strlen($query) < 2) {
6782 return '';
6784 $query = core_text::strtolower($query);
6786 $adminroot = admin_get_root();
6787 $findings = $adminroot->search($query);
6788 $return = '';
6789 $savebutton = false;
6791 foreach ($findings as $found) {
6792 $page = $found->page;
6793 $settings = $found->settings;
6794 if ($page->is_hidden()) {
6795 // hidden pages are not displayed in search results
6796 continue;
6798 if ($page instanceof admin_externalpage) {
6799 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6800 } else if ($page instanceof admin_settingpage) {
6801 $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');
6802 } else {
6803 continue;
6805 if (!empty($settings)) {
6806 $return .= '<fieldset class="adminsettings">'."\n";
6807 foreach ($settings as $setting) {
6808 if (empty($setting->nosave)) {
6809 $savebutton = true;
6811 $return .= '<div class="clearer"><!-- --></div>'."\n";
6812 $fullname = $setting->get_full_name();
6813 if (array_key_exists($fullname, $adminroot->errors)) {
6814 $data = $adminroot->errors[$fullname]->data;
6815 } else {
6816 $data = $setting->get_setting();
6817 // do not use defaults if settings not available - upgradesettings handles the defaults!
6819 $return .= $setting->output_html($data, $query);
6821 $return .= '</fieldset>';
6825 if ($savebutton) {
6826 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6829 return $return;
6833 * Internal function - returns arrays of html pages with uninitialised settings
6835 * @param object $node Instance of admin_category or admin_settingpage
6836 * @return array
6838 function admin_output_new_settings_by_page($node) {
6839 global $OUTPUT;
6840 $return = array();
6842 if ($node instanceof admin_category) {
6843 $entries = array_keys($node->children);
6844 foreach ($entries as $entry) {
6845 $return += admin_output_new_settings_by_page($node->children[$entry]);
6848 } else if ($node instanceof admin_settingpage) {
6849 $newsettings = array();
6850 foreach ($node->settings as $setting) {
6851 if (is_null($setting->get_setting())) {
6852 $newsettings[] = $setting;
6855 if (count($newsettings) > 0) {
6856 $adminroot = admin_get_root();
6857 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6858 $page .= '<fieldset class="adminsettings">'."\n";
6859 foreach ($newsettings as $setting) {
6860 $fullname = $setting->get_full_name();
6861 if (array_key_exists($fullname, $adminroot->errors)) {
6862 $data = $adminroot->errors[$fullname]->data;
6863 } else {
6864 $data = $setting->get_setting();
6865 if (is_null($data)) {
6866 $data = $setting->get_defaultsetting();
6869 $page .= '<div class="clearer"><!-- --></div>'."\n";
6870 $page .= $setting->output_html($data);
6872 $page .= '</fieldset>';
6873 $return[$node->name] = $page;
6877 return $return;
6881 * Format admin settings
6883 * @param object $setting
6884 * @param string $title label element
6885 * @param string $form form fragment, html code - not highlighted automatically
6886 * @param string $description
6887 * @param bool $label link label to id, true by default
6888 * @param string $warning warning text
6889 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6890 * @param string $query search query to be highlighted
6891 * @return string XHTML
6893 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6894 global $CFG;
6896 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6897 $fullname = $setting->get_full_name();
6899 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6900 if ($label) {
6901 $labelfor = 'for = "'.$setting->get_id().'"';
6902 } else {
6903 $labelfor = '';
6905 $form .= $setting->output_setting_flags();
6907 $override = '';
6908 if (empty($setting->plugin)) {
6909 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6910 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6912 } else {
6913 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6914 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6918 if ($warning !== '') {
6919 $warning = '<div class="form-warning">'.$warning.'</div>';
6922 $defaults = array();
6923 if (!is_null($defaultinfo)) {
6924 if ($defaultinfo === '') {
6925 $defaultinfo = get_string('emptysettingvalue', 'admin');
6927 $defaults[] = $defaultinfo;
6930 $setting->get_setting_flag_defaults($defaults);
6932 if (!empty($defaults)) {
6933 $defaultinfo = implode(', ', $defaults);
6934 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6935 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6939 $str = '
6940 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6941 <div class="form-label">
6942 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6943 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6944 </div>
6945 <div class="form-setting">'.$form.$defaultinfo.'</div>
6946 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6947 </div>';
6949 $adminroot = admin_get_root();
6950 if (array_key_exists($fullname, $adminroot->errors)) {
6951 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6954 return $str;
6958 * Based on find_new_settings{@link ()} in upgradesettings.php
6959 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6961 * @param object $node Instance of admin_category, or admin_settingpage
6962 * @return boolean true if any settings haven't been initialised, false if they all have
6964 function any_new_admin_settings($node) {
6966 if ($node instanceof admin_category) {
6967 $entries = array_keys($node->children);
6968 foreach ($entries as $entry) {
6969 if (any_new_admin_settings($node->children[$entry])) {
6970 return true;
6974 } else if ($node instanceof admin_settingpage) {
6975 foreach ($node->settings as $setting) {
6976 if ($setting->get_setting() === NULL) {
6977 return true;
6982 return false;
6986 * Moved from admin/replace.php so that we can use this in cron
6988 * @param string $search string to look for
6989 * @param string $replace string to replace
6990 * @return bool success or fail
6992 function db_replace($search, $replace) {
6993 global $DB, $CFG, $OUTPUT;
6995 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6996 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
6997 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6998 'block_instances', '');
7000 // Turn off time limits, sometimes upgrades can be slow.
7001 core_php_time_limit::raise();
7003 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7004 return false;
7006 foreach ($tables as $table) {
7008 if (in_array($table, $skiptables)) { // Don't process these
7009 continue;
7012 if ($columns = $DB->get_columns($table)) {
7013 $DB->set_debug(true);
7014 foreach ($columns as $column) {
7015 $DB->replace_all_text($table, $column, $search, $replace);
7017 $DB->set_debug(false);
7021 // delete modinfo caches
7022 rebuild_course_cache(0, true);
7024 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7025 $blocks = core_component::get_plugin_list('block');
7026 foreach ($blocks as $blockname=>$fullblock) {
7027 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7028 continue;
7031 if (!is_readable($fullblock.'/lib.php')) {
7032 continue;
7035 $function = 'block_'.$blockname.'_global_db_replace';
7036 include_once($fullblock.'/lib.php');
7037 if (!function_exists($function)) {
7038 continue;
7041 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7042 $function($search, $replace);
7043 echo $OUTPUT->notification("...finished", 'notifysuccess');
7046 purge_all_caches();
7048 return true;
7052 * Manage repository settings
7054 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7056 class admin_setting_managerepository extends admin_setting {
7057 /** @var string */
7058 private $baseurl;
7061 * calls parent::__construct with specific arguments
7063 public function __construct() {
7064 global $CFG;
7065 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7066 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7070 * Always returns true, does nothing
7072 * @return true
7074 public function get_setting() {
7075 return true;
7079 * Always returns true does nothing
7081 * @return true
7083 public function get_defaultsetting() {
7084 return true;
7088 * Always returns s_managerepository
7090 * @return string Always return 's_managerepository'
7092 public function get_full_name() {
7093 return 's_managerepository';
7097 * Always returns '' doesn't do anything
7099 public function write_setting($data) {
7100 $url = $this->baseurl . '&amp;new=' . $data;
7101 return '';
7102 // TODO
7103 // Should not use redirect and exit here
7104 // Find a better way to do this.
7105 // redirect($url);
7106 // exit;
7110 * Searches repository plugins for one that matches $query
7112 * @param string $query The string to search for
7113 * @return bool true if found, false if not
7115 public function is_related($query) {
7116 if (parent::is_related($query)) {
7117 return true;
7120 $repositories= core_component::get_plugin_list('repository');
7121 foreach ($repositories as $p => $dir) {
7122 if (strpos($p, $query) !== false) {
7123 return true;
7126 foreach (repository::get_types() as $instance) {
7127 $title = $instance->get_typename();
7128 if (strpos(core_text::strtolower($title), $query) !== false) {
7129 return true;
7132 return false;
7136 * Helper function that generates a moodle_url object
7137 * relevant to the repository
7140 function repository_action_url($repository) {
7141 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7145 * Builds XHTML to display the control
7147 * @param string $data Unused
7148 * @param string $query
7149 * @return string XHTML
7151 public function output_html($data, $query='') {
7152 global $CFG, $USER, $OUTPUT;
7154 // Get strings that are used
7155 $strshow = get_string('on', 'repository');
7156 $strhide = get_string('off', 'repository');
7157 $strdelete = get_string('disabled', 'repository');
7159 $actionchoicesforexisting = array(
7160 'show' => $strshow,
7161 'hide' => $strhide,
7162 'delete' => $strdelete
7165 $actionchoicesfornew = array(
7166 'newon' => $strshow,
7167 'newoff' => $strhide,
7168 'delete' => $strdelete
7171 $return = '';
7172 $return .= $OUTPUT->box_start('generalbox');
7174 // Set strings that are used multiple times
7175 $settingsstr = get_string('settings');
7176 $disablestr = get_string('disable');
7178 // Table to list plug-ins
7179 $table = new html_table();
7180 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7181 $table->align = array('left', 'center', 'center', 'center', 'center');
7182 $table->data = array();
7184 // Get list of used plug-ins
7185 $repositorytypes = repository::get_types();
7186 if (!empty($repositorytypes)) {
7187 // Array to store plugins being used
7188 $alreadyplugins = array();
7189 $totalrepositorytypes = count($repositorytypes);
7190 $updowncount = 1;
7191 foreach ($repositorytypes as $i) {
7192 $settings = '';
7193 $typename = $i->get_typename();
7194 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7195 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7196 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7198 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7199 // Calculate number of instances in order to display them for the Moodle administrator
7200 if (!empty($instanceoptionnames)) {
7201 $params = array();
7202 $params['context'] = array(context_system::instance());
7203 $params['onlyvisible'] = false;
7204 $params['type'] = $typename;
7205 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7206 // site instances
7207 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7208 $params['context'] = array();
7209 $instances = repository::static_function($typename, 'get_instances', $params);
7210 $courseinstances = array();
7211 $userinstances = array();
7213 foreach ($instances as $instance) {
7214 $repocontext = context::instance_by_id($instance->instance->contextid);
7215 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7216 $courseinstances[] = $instance;
7217 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7218 $userinstances[] = $instance;
7221 // course instances
7222 $instancenumber = count($courseinstances);
7223 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7225 // user private instances
7226 $instancenumber = count($userinstances);
7227 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7228 } else {
7229 $admininstancenumbertext = "";
7230 $courseinstancenumbertext = "";
7231 $userinstancenumbertext = "";
7234 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7236 $settings .= $OUTPUT->container_start('mdl-left');
7237 $settings .= '<br/>';
7238 $settings .= $admininstancenumbertext;
7239 $settings .= '<br/>';
7240 $settings .= $courseinstancenumbertext;
7241 $settings .= '<br/>';
7242 $settings .= $userinstancenumbertext;
7243 $settings .= $OUTPUT->container_end();
7245 // Get the current visibility
7246 if ($i->get_visible()) {
7247 $currentaction = 'show';
7248 } else {
7249 $currentaction = 'hide';
7252 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7254 // Display up/down link
7255 $updown = '';
7256 // Should be done with CSS instead.
7257 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7259 if ($updowncount > 1) {
7260 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7261 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7263 else {
7264 $updown .= $spacer;
7266 if ($updowncount < $totalrepositorytypes) {
7267 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7268 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7270 else {
7271 $updown .= $spacer;
7274 $updowncount++;
7276 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7278 if (!in_array($typename, $alreadyplugins)) {
7279 $alreadyplugins[] = $typename;
7284 // Get all the plugins that exist on disk
7285 $plugins = core_component::get_plugin_list('repository');
7286 if (!empty($plugins)) {
7287 foreach ($plugins as $plugin => $dir) {
7288 // Check that it has not already been listed
7289 if (!in_array($plugin, $alreadyplugins)) {
7290 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7291 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7296 $return .= html_writer::table($table);
7297 $return .= $OUTPUT->box_end();
7298 return highlight($query, $return);
7303 * Special checkbox for enable mobile web service
7304 * If enable then we store the service id of the mobile service into config table
7305 * If disable then we unstore the service id from the config table
7307 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7309 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7310 private $xmlrpcuse;
7311 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7312 private $restuse;
7315 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7317 * @return boolean
7319 private function is_protocol_cap_allowed() {
7320 global $DB, $CFG;
7322 // We keep xmlrpc enabled for backward compatibility.
7323 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7324 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7325 $params = array();
7326 $params['permission'] = CAP_ALLOW;
7327 $params['roleid'] = $CFG->defaultuserroleid;
7328 $params['capability'] = 'webservice/xmlrpc:use';
7329 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7332 // If the $this->restuse variable is not set, it needs to be set.
7333 if (empty($this->restuse) and $this->restuse!==false) {
7334 $params = array();
7335 $params['permission'] = CAP_ALLOW;
7336 $params['roleid'] = $CFG->defaultuserroleid;
7337 $params['capability'] = 'webservice/rest:use';
7338 $this->restuse = $DB->record_exists('role_capabilities', $params);
7341 return ($this->xmlrpcuse && $this->restuse);
7345 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7346 * @param type $status true to allow, false to not set
7348 private function set_protocol_cap($status) {
7349 global $CFG;
7350 if ($status and !$this->is_protocol_cap_allowed()) {
7351 //need to allow the cap
7352 $permission = CAP_ALLOW;
7353 $assign = true;
7354 } else if (!$status and $this->is_protocol_cap_allowed()){
7355 //need to disallow the cap
7356 $permission = CAP_INHERIT;
7357 $assign = true;
7359 if (!empty($assign)) {
7360 $systemcontext = context_system::instance();
7361 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7362 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7367 * Builds XHTML to display the control.
7368 * The main purpose of this overloading is to display a warning when https
7369 * is not supported by the server
7370 * @param string $data Unused
7371 * @param string $query
7372 * @return string XHTML
7374 public function output_html($data, $query='') {
7375 global $CFG, $OUTPUT;
7376 $html = parent::output_html($data, $query);
7378 if ((string)$data === $this->yes) {
7379 require_once($CFG->dirroot . "/lib/filelib.php");
7380 $curl = new curl();
7381 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7382 $curl->head($httpswwwroot . "/login/index.php");
7383 $info = $curl->get_info();
7384 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7385 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7389 return $html;
7393 * Retrieves the current setting using the objects name
7395 * @return string
7397 public function get_setting() {
7398 global $CFG;
7400 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7401 // Or if web services aren't enabled this can't be,
7402 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7403 return 0;
7406 require_once($CFG->dirroot . '/webservice/lib.php');
7407 $webservicemanager = new webservice();
7408 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7409 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7410 return $this->config_read($this->name); //same as returning 1
7411 } else {
7412 return 0;
7417 * Save the selected setting
7419 * @param string $data The selected site
7420 * @return string empty string or error message
7422 public function write_setting($data) {
7423 global $DB, $CFG;
7425 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7426 if (empty($CFG->defaultuserroleid)) {
7427 return '';
7430 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7432 require_once($CFG->dirroot . '/webservice/lib.php');
7433 $webservicemanager = new webservice();
7435 $updateprotocol = false;
7436 if ((string)$data === $this->yes) {
7437 //code run when enable mobile web service
7438 //enable web service systeme if necessary
7439 set_config('enablewebservices', true);
7441 //enable mobile service
7442 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7443 $mobileservice->enabled = 1;
7444 $webservicemanager->update_external_service($mobileservice);
7446 //enable xml-rpc server
7447 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7449 if (!in_array('xmlrpc', $activeprotocols)) {
7450 $activeprotocols[] = 'xmlrpc';
7451 $updateprotocol = true;
7454 if (!in_array('rest', $activeprotocols)) {
7455 $activeprotocols[] = 'rest';
7456 $updateprotocol = true;
7459 if ($updateprotocol) {
7460 set_config('webserviceprotocols', implode(',', $activeprotocols));
7463 //allow xml-rpc:use capability for authenticated user
7464 $this->set_protocol_cap(true);
7466 } else {
7467 //disable web service system if no other services are enabled
7468 $otherenabledservices = $DB->get_records_select('external_services',
7469 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7470 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7471 if (empty($otherenabledservices)) {
7472 set_config('enablewebservices', false);
7474 //also disable xml-rpc server
7475 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7476 $protocolkey = array_search('xmlrpc', $activeprotocols);
7477 if ($protocolkey !== false) {
7478 unset($activeprotocols[$protocolkey]);
7479 $updateprotocol = true;
7482 $protocolkey = array_search('rest', $activeprotocols);
7483 if ($protocolkey !== false) {
7484 unset($activeprotocols[$protocolkey]);
7485 $updateprotocol = true;
7488 if ($updateprotocol) {
7489 set_config('webserviceprotocols', implode(',', $activeprotocols));
7492 //disallow xml-rpc:use capability for authenticated user
7493 $this->set_protocol_cap(false);
7496 //disable the mobile service
7497 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7498 $mobileservice->enabled = 0;
7499 $webservicemanager->update_external_service($mobileservice);
7502 return (parent::write_setting($data));
7507 * Special class for management of external services
7509 * @author Petr Skoda (skodak)
7511 class admin_setting_manageexternalservices extends admin_setting {
7513 * Calls parent::__construct with specific arguments
7515 public function __construct() {
7516 $this->nosave = true;
7517 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7521 * Always returns true, does nothing
7523 * @return true
7525 public function get_setting() {
7526 return true;
7530 * Always returns true, does nothing
7532 * @return true
7534 public function get_defaultsetting() {
7535 return true;
7539 * Always returns '', does not write anything
7541 * @return string Always returns ''
7543 public function write_setting($data) {
7544 // do not write any setting
7545 return '';
7549 * Checks if $query is one of the available external services
7551 * @param string $query The string to search for
7552 * @return bool Returns true if found, false if not
7554 public function is_related($query) {
7555 global $DB;
7557 if (parent::is_related($query)) {
7558 return true;
7561 $services = $DB->get_records('external_services', array(), 'id, name');
7562 foreach ($services as $service) {
7563 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7564 return true;
7567 return false;
7571 * Builds the XHTML to display the control
7573 * @param string $data Unused
7574 * @param string $query
7575 * @return string
7577 public function output_html($data, $query='') {
7578 global $CFG, $OUTPUT, $DB;
7580 // display strings
7581 $stradministration = get_string('administration');
7582 $stredit = get_string('edit');
7583 $strservice = get_string('externalservice', 'webservice');
7584 $strdelete = get_string('delete');
7585 $strplugin = get_string('plugin', 'admin');
7586 $stradd = get_string('add');
7587 $strfunctions = get_string('functions', 'webservice');
7588 $strusers = get_string('users');
7589 $strserviceusers = get_string('serviceusers', 'webservice');
7591 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7592 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7593 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7595 // built in services
7596 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7597 $return = "";
7598 if (!empty($services)) {
7599 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7603 $table = new html_table();
7604 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7605 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7606 $table->id = 'builtinservices';
7607 $table->attributes['class'] = 'admintable externalservices generaltable';
7608 $table->data = array();
7610 // iterate through auth plugins and add to the display table
7611 foreach ($services as $service) {
7612 $name = $service->name;
7614 // hide/show link
7615 if ($service->enabled) {
7616 $displayname = "<span>$name</span>";
7617 } else {
7618 $displayname = "<span class=\"dimmed_text\">$name</span>";
7621 $plugin = $service->component;
7623 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7625 if ($service->restrictedusers) {
7626 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7627 } else {
7628 $users = get_string('allusers', 'webservice');
7631 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7633 // add a row to the table
7634 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7636 $return .= html_writer::table($table);
7639 // Custom services
7640 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7641 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7643 $table = new html_table();
7644 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7645 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7646 $table->id = 'customservices';
7647 $table->attributes['class'] = 'admintable externalservices generaltable';
7648 $table->data = array();
7650 // iterate through auth plugins and add to the display table
7651 foreach ($services as $service) {
7652 $name = $service->name;
7654 // hide/show link
7655 if ($service->enabled) {
7656 $displayname = "<span>$name</span>";
7657 } else {
7658 $displayname = "<span class=\"dimmed_text\">$name</span>";
7661 // delete link
7662 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7664 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7666 if ($service->restrictedusers) {
7667 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7668 } else {
7669 $users = get_string('allusers', 'webservice');
7672 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7674 // add a row to the table
7675 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7677 // add new custom service option
7678 $return .= html_writer::table($table);
7680 $return .= '<br />';
7681 // add a token to the table
7682 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7684 return highlight($query, $return);
7689 * Special class for overview of external services
7691 * @author Jerome Mouneyrac
7693 class admin_setting_webservicesoverview extends admin_setting {
7696 * Calls parent::__construct with specific arguments
7698 public function __construct() {
7699 $this->nosave = true;
7700 parent::__construct('webservicesoverviewui',
7701 get_string('webservicesoverview', 'webservice'), '', '');
7705 * Always returns true, does nothing
7707 * @return true
7709 public function get_setting() {
7710 return true;
7714 * Always returns true, does nothing
7716 * @return true
7718 public function get_defaultsetting() {
7719 return true;
7723 * Always returns '', does not write anything
7725 * @return string Always returns ''
7727 public function write_setting($data) {
7728 // do not write any setting
7729 return '';
7733 * Builds the XHTML to display the control
7735 * @param string $data Unused
7736 * @param string $query
7737 * @return string
7739 public function output_html($data, $query='') {
7740 global $CFG, $OUTPUT;
7742 $return = "";
7743 $brtag = html_writer::empty_tag('br');
7745 // Enable mobile web service
7746 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7747 get_string('enablemobilewebservice', 'admin'),
7748 get_string('configenablemobilewebservice',
7749 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7750 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7751 $wsmobileparam = new stdClass();
7752 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7753 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7754 get_string('externalservices', 'webservice'));
7755 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7756 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7757 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7758 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7759 . $brtag . $brtag;
7761 /// One system controlling Moodle with Token
7762 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7763 $table = new html_table();
7764 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7765 get_string('description'));
7766 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7767 $table->id = 'onesystemcontrol';
7768 $table->attributes['class'] = 'admintable wsoverview generaltable';
7769 $table->data = array();
7771 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7772 . $brtag . $brtag;
7774 /// 1. Enable Web Services
7775 $row = array();
7776 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7777 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7778 array('href' => $url));
7779 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7780 if ($CFG->enablewebservices) {
7781 $status = get_string('yes');
7783 $row[1] = $status;
7784 $row[2] = get_string('enablewsdescription', 'webservice');
7785 $table->data[] = $row;
7787 /// 2. Enable protocols
7788 $row = array();
7789 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7790 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7791 array('href' => $url));
7792 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7793 //retrieve activated protocol
7794 $active_protocols = empty($CFG->webserviceprotocols) ?
7795 array() : explode(',', $CFG->webserviceprotocols);
7796 if (!empty($active_protocols)) {
7797 $status = "";
7798 foreach ($active_protocols as $protocol) {
7799 $status .= $protocol . $brtag;
7802 $row[1] = $status;
7803 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7804 $table->data[] = $row;
7806 /// 3. Create user account
7807 $row = array();
7808 $url = new moodle_url("/user/editadvanced.php?id=-1");
7809 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7810 array('href' => $url));
7811 $row[1] = "";
7812 $row[2] = get_string('createuserdescription', 'webservice');
7813 $table->data[] = $row;
7815 /// 4. Add capability to users
7816 $row = array();
7817 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7818 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7819 array('href' => $url));
7820 $row[1] = "";
7821 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7822 $table->data[] = $row;
7824 /// 5. Select a web service
7825 $row = array();
7826 $url = new moodle_url("/admin/settings.php?section=externalservices");
7827 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7828 array('href' => $url));
7829 $row[1] = "";
7830 $row[2] = get_string('createservicedescription', 'webservice');
7831 $table->data[] = $row;
7833 /// 6. Add functions
7834 $row = array();
7835 $url = new moodle_url("/admin/settings.php?section=externalservices");
7836 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7837 array('href' => $url));
7838 $row[1] = "";
7839 $row[2] = get_string('addfunctionsdescription', 'webservice');
7840 $table->data[] = $row;
7842 /// 7. Add the specific user
7843 $row = array();
7844 $url = new moodle_url("/admin/settings.php?section=externalservices");
7845 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7846 array('href' => $url));
7847 $row[1] = "";
7848 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7849 $table->data[] = $row;
7851 /// 8. Create token for the specific user
7852 $row = array();
7853 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7854 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7855 array('href' => $url));
7856 $row[1] = "";
7857 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7858 $table->data[] = $row;
7860 /// 9. Enable the documentation
7861 $row = array();
7862 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7863 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7864 array('href' => $url));
7865 $status = '<span class="warning">' . get_string('no') . '</span>';
7866 if ($CFG->enablewsdocumentation) {
7867 $status = get_string('yes');
7869 $row[1] = $status;
7870 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7871 $table->data[] = $row;
7873 /// 10. Test the service
7874 $row = array();
7875 $url = new moodle_url("/admin/webservice/testclient.php");
7876 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7877 array('href' => $url));
7878 $row[1] = "";
7879 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7880 $table->data[] = $row;
7882 $return .= html_writer::table($table);
7884 /// Users as clients with token
7885 $return .= $brtag . $brtag . $brtag;
7886 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7887 $table = new html_table();
7888 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7889 get_string('description'));
7890 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7891 $table->id = 'userasclients';
7892 $table->attributes['class'] = 'admintable wsoverview generaltable';
7893 $table->data = array();
7895 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7896 $brtag . $brtag;
7898 /// 1. Enable Web Services
7899 $row = array();
7900 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7901 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7902 array('href' => $url));
7903 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7904 if ($CFG->enablewebservices) {
7905 $status = get_string('yes');
7907 $row[1] = $status;
7908 $row[2] = get_string('enablewsdescription', 'webservice');
7909 $table->data[] = $row;
7911 /// 2. Enable protocols
7912 $row = array();
7913 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7914 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7915 array('href' => $url));
7916 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7917 //retrieve activated protocol
7918 $active_protocols = empty($CFG->webserviceprotocols) ?
7919 array() : explode(',', $CFG->webserviceprotocols);
7920 if (!empty($active_protocols)) {
7921 $status = "";
7922 foreach ($active_protocols as $protocol) {
7923 $status .= $protocol . $brtag;
7926 $row[1] = $status;
7927 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7928 $table->data[] = $row;
7931 /// 3. Select a web service
7932 $row = array();
7933 $url = new moodle_url("/admin/settings.php?section=externalservices");
7934 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7935 array('href' => $url));
7936 $row[1] = "";
7937 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7938 $table->data[] = $row;
7940 /// 4. Add functions
7941 $row = array();
7942 $url = new moodle_url("/admin/settings.php?section=externalservices");
7943 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7944 array('href' => $url));
7945 $row[1] = "";
7946 $row[2] = get_string('addfunctionsdescription', 'webservice');
7947 $table->data[] = $row;
7949 /// 5. Add capability to users
7950 $row = array();
7951 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7952 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7953 array('href' => $url));
7954 $row[1] = "";
7955 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7956 $table->data[] = $row;
7958 /// 6. Test the service
7959 $row = array();
7960 $url = new moodle_url("/admin/webservice/testclient.php");
7961 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7962 array('href' => $url));
7963 $row[1] = "";
7964 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7965 $table->data[] = $row;
7967 $return .= html_writer::table($table);
7969 return highlight($query, $return);
7976 * Special class for web service protocol administration.
7978 * @author Petr Skoda (skodak)
7980 class admin_setting_managewebserviceprotocols extends admin_setting {
7983 * Calls parent::__construct with specific arguments
7985 public function __construct() {
7986 $this->nosave = true;
7987 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7991 * Always returns true, does nothing
7993 * @return true
7995 public function get_setting() {
7996 return true;
8000 * Always returns true, does nothing
8002 * @return true
8004 public function get_defaultsetting() {
8005 return true;
8009 * Always returns '', does not write anything
8011 * @return string Always returns ''
8013 public function write_setting($data) {
8014 // do not write any setting
8015 return '';
8019 * Checks if $query is one of the available webservices
8021 * @param string $query The string to search for
8022 * @return bool Returns true if found, false if not
8024 public function is_related($query) {
8025 if (parent::is_related($query)) {
8026 return true;
8029 $protocols = core_component::get_plugin_list('webservice');
8030 foreach ($protocols as $protocol=>$location) {
8031 if (strpos($protocol, $query) !== false) {
8032 return true;
8034 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8035 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8036 return true;
8039 return false;
8043 * Builds the XHTML to display the control
8045 * @param string $data Unused
8046 * @param string $query
8047 * @return string
8049 public function output_html($data, $query='') {
8050 global $CFG, $OUTPUT;
8052 // display strings
8053 $stradministration = get_string('administration');
8054 $strsettings = get_string('settings');
8055 $stredit = get_string('edit');
8056 $strprotocol = get_string('protocol', 'webservice');
8057 $strenable = get_string('enable');
8058 $strdisable = get_string('disable');
8059 $strversion = get_string('version');
8061 $protocols_available = core_component::get_plugin_list('webservice');
8062 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8063 ksort($protocols_available);
8065 foreach ($active_protocols as $key=>$protocol) {
8066 if (empty($protocols_available[$protocol])) {
8067 unset($active_protocols[$key]);
8071 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8072 $return .= $OUTPUT->box_start('generalbox webservicesui');
8074 $table = new html_table();
8075 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8076 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8077 $table->id = 'webserviceprotocols';
8078 $table->attributes['class'] = 'admintable generaltable';
8079 $table->data = array();
8081 // iterate through auth plugins and add to the display table
8082 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8083 foreach ($protocols_available as $protocol => $location) {
8084 $name = get_string('pluginname', 'webservice_'.$protocol);
8086 $plugin = new stdClass();
8087 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8088 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8090 $version = isset($plugin->version) ? $plugin->version : '';
8092 // hide/show link
8093 if (in_array($protocol, $active_protocols)) {
8094 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8095 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8096 $displayname = "<span>$name</span>";
8097 } else {
8098 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8099 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8100 $displayname = "<span class=\"dimmed_text\">$name</span>";
8103 // settings link
8104 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8105 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8106 } else {
8107 $settings = '';
8110 // add a row to the table
8111 $table->data[] = array($displayname, $version, $hideshow, $settings);
8113 $return .= html_writer::table($table);
8114 $return .= get_string('configwebserviceplugins', 'webservice');
8115 $return .= $OUTPUT->box_end();
8117 return highlight($query, $return);
8123 * Special class for web service token administration.
8125 * @author Jerome Mouneyrac
8127 class admin_setting_managewebservicetokens extends admin_setting {
8130 * Calls parent::__construct with specific arguments
8132 public function __construct() {
8133 $this->nosave = true;
8134 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8138 * Always returns true, does nothing
8140 * @return true
8142 public function get_setting() {
8143 return true;
8147 * Always returns true, does nothing
8149 * @return true
8151 public function get_defaultsetting() {
8152 return true;
8156 * Always returns '', does not write anything
8158 * @return string Always returns ''
8160 public function write_setting($data) {
8161 // do not write any setting
8162 return '';
8166 * Builds the XHTML to display the control
8168 * @param string $data Unused
8169 * @param string $query
8170 * @return string
8172 public function output_html($data, $query='') {
8173 global $CFG, $OUTPUT, $DB, $USER;
8175 // display strings
8176 $stroperation = get_string('operation', 'webservice');
8177 $strtoken = get_string('token', 'webservice');
8178 $strservice = get_string('service', 'webservice');
8179 $struser = get_string('user');
8180 $strcontext = get_string('context', 'webservice');
8181 $strvaliduntil = get_string('validuntil', 'webservice');
8182 $striprestriction = get_string('iprestriction', 'webservice');
8184 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8186 $table = new html_table();
8187 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8188 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8189 $table->id = 'webservicetokens';
8190 $table->attributes['class'] = 'admintable generaltable';
8191 $table->data = array();
8193 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8195 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8197 //here retrieve token list (including linked users firstname/lastname and linked services name)
8198 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8199 FROM {external_tokens} t, {user} u, {external_services} s
8200 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8201 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8202 if (!empty($tokens)) {
8203 foreach ($tokens as $token) {
8204 //TODO: retrieve context
8206 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8207 $delete .= get_string('delete')."</a>";
8209 $validuntil = '';
8210 if (!empty($token->validuntil)) {
8211 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8214 $iprestriction = '';
8215 if (!empty($token->iprestriction)) {
8216 $iprestriction = $token->iprestriction;
8219 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8220 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8221 $useratag .= $token->firstname." ".$token->lastname;
8222 $useratag .= html_writer::end_tag('a');
8224 //check user missing capabilities
8225 require_once($CFG->dirroot . '/webservice/lib.php');
8226 $webservicemanager = new webservice();
8227 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8228 array(array('id' => $token->userid)), $token->serviceid);
8230 if (!is_siteadmin($token->userid) and
8231 array_key_exists($token->userid, $usermissingcaps)) {
8232 $missingcapabilities = implode(', ',
8233 $usermissingcaps[$token->userid]);
8234 if (!empty($missingcapabilities)) {
8235 $useratag .= html_writer::tag('div',
8236 get_string('usermissingcaps', 'webservice',
8237 $missingcapabilities)
8238 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8239 array('class' => 'missingcaps'));
8243 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8246 $return .= html_writer::table($table);
8247 } else {
8248 $return .= get_string('notoken', 'webservice');
8251 $return .= $OUTPUT->box_end();
8252 // add a token to the table
8253 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8254 $return .= get_string('add')."</a>";
8256 return highlight($query, $return);
8262 * Colour picker
8264 * @copyright 2010 Sam Hemelryk
8265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8267 class admin_setting_configcolourpicker extends admin_setting {
8270 * Information for previewing the colour
8272 * @var array|null
8274 protected $previewconfig = null;
8277 * Use default when empty.
8279 protected $usedefaultwhenempty = true;
8283 * @param string $name
8284 * @param string $visiblename
8285 * @param string $description
8286 * @param string $defaultsetting
8287 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8289 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8290 $usedefaultwhenempty = true) {
8291 $this->previewconfig = $previewconfig;
8292 $this->usedefaultwhenempty = $usedefaultwhenempty;
8293 parent::__construct($name, $visiblename, $description, $defaultsetting);
8297 * Return the setting
8299 * @return mixed returns config if successful else null
8301 public function get_setting() {
8302 return $this->config_read($this->name);
8306 * Saves the setting
8308 * @param string $data
8309 * @return bool
8311 public function write_setting($data) {
8312 $data = $this->validate($data);
8313 if ($data === false) {
8314 return get_string('validateerror', 'admin');
8316 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8320 * Validates the colour that was entered by the user
8322 * @param string $data
8323 * @return string|false
8325 protected function validate($data) {
8327 * List of valid HTML colour names
8329 * @var array
8331 $colornames = array(
8332 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8333 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8334 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8335 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8336 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8337 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8338 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8339 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8340 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8341 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8342 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8343 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8344 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8345 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8346 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8347 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8348 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8349 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8350 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8351 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8352 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8353 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8354 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8355 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8356 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8357 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8358 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8359 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8360 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8361 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8362 'whitesmoke', 'yellow', 'yellowgreen'
8365 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8366 if (strpos($data, '#')!==0) {
8367 $data = '#'.$data;
8369 return $data;
8370 } else if (in_array(strtolower($data), $colornames)) {
8371 return $data;
8372 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8373 return $data;
8374 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8375 return $data;
8376 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8377 return $data;
8378 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8379 return $data;
8380 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8381 return $data;
8382 } else if (empty($data)) {
8383 if ($this->usedefaultwhenempty){
8384 return $this->defaultsetting;
8385 } else {
8386 return '';
8388 } else {
8389 return false;
8394 * Generates the HTML for the setting
8396 * @global moodle_page $PAGE
8397 * @global core_renderer $OUTPUT
8398 * @param string $data
8399 * @param string $query
8401 public function output_html($data, $query = '') {
8402 global $PAGE, $OUTPUT;
8403 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8404 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8405 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8406 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8407 if (!empty($this->previewconfig)) {
8408 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8410 $content .= html_writer::end_tag('div');
8411 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
8417 * Class used for uploading of one file into file storage,
8418 * the file name is stored in config table.
8420 * Please note you need to implement your own '_pluginfile' callback function,
8421 * this setting only stores the file, it does not deal with file serving.
8423 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8424 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8426 class admin_setting_configstoredfile extends admin_setting {
8427 /** @var array file area options - should be one file only */
8428 protected $options;
8429 /** @var string name of the file area */
8430 protected $filearea;
8431 /** @var int intemid */
8432 protected $itemid;
8433 /** @var string used for detection of changes */
8434 protected $oldhashes;
8437 * Create new stored file setting.
8439 * @param string $name low level setting name
8440 * @param string $visiblename human readable setting name
8441 * @param string $description description of setting
8442 * @param mixed $filearea file area for file storage
8443 * @param int $itemid itemid for file storage
8444 * @param array $options file area options
8446 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8447 parent::__construct($name, $visiblename, $description, '');
8448 $this->filearea = $filearea;
8449 $this->itemid = $itemid;
8450 $this->options = (array)$options;
8454 * Applies defaults and returns all options.
8455 * @return array
8457 protected function get_options() {
8458 global $CFG;
8460 require_once("$CFG->libdir/filelib.php");
8461 require_once("$CFG->dirroot/repository/lib.php");
8462 $defaults = array(
8463 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8464 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8465 'context' => context_system::instance());
8466 foreach($this->options as $k => $v) {
8467 $defaults[$k] = $v;
8470 return $defaults;
8473 public function get_setting() {
8474 return $this->config_read($this->name);
8477 public function write_setting($data) {
8478 global $USER;
8480 // Let's not deal with validation here, this is for admins only.
8481 $current = $this->get_setting();
8482 if (empty($data) && $current === null) {
8483 // This will be the case when applying default settings (installation).
8484 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8485 } else if (!is_number($data)) {
8486 // Draft item id is expected here!
8487 return get_string('errorsetting', 'admin');
8490 $options = $this->get_options();
8491 $fs = get_file_storage();
8492 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8494 $this->oldhashes = null;
8495 if ($current) {
8496 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8497 if ($file = $fs->get_file_by_hash($hash)) {
8498 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8500 unset($file);
8503 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8504 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8505 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8506 // with an error because the draft area does not exist, as he did not use it.
8507 $usercontext = context_user::instance($USER->id);
8508 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8509 return get_string('errorsetting', 'admin');
8513 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8514 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8516 $filepath = '';
8517 if ($files) {
8518 /** @var stored_file $file */
8519 $file = reset($files);
8520 $filepath = $file->get_filepath().$file->get_filename();
8523 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8526 public function post_write_settings($original) {
8527 $options = $this->get_options();
8528 $fs = get_file_storage();
8529 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8531 $current = $this->get_setting();
8532 $newhashes = null;
8533 if ($current) {
8534 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8535 if ($file = $fs->get_file_by_hash($hash)) {
8536 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8538 unset($file);
8541 if ($this->oldhashes === $newhashes) {
8542 $this->oldhashes = null;
8543 return false;
8545 $this->oldhashes = null;
8547 $callbackfunction = $this->updatedcallback;
8548 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8549 $callbackfunction($this->get_full_name());
8551 return true;
8554 public function output_html($data, $query = '') {
8555 global $PAGE, $CFG;
8557 $options = $this->get_options();
8558 $id = $this->get_id();
8559 $elname = $this->get_full_name();
8560 $draftitemid = file_get_submitted_draft_itemid($elname);
8561 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8562 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8564 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8565 require_once("$CFG->dirroot/lib/form/filemanager.php");
8567 $fmoptions = new stdClass();
8568 $fmoptions->mainfile = $options['mainfile'];
8569 $fmoptions->maxbytes = $options['maxbytes'];
8570 $fmoptions->maxfiles = $options['maxfiles'];
8571 $fmoptions->client_id = uniqid();
8572 $fmoptions->itemid = $draftitemid;
8573 $fmoptions->subdirs = $options['subdirs'];
8574 $fmoptions->target = $id;
8575 $fmoptions->accepted_types = $options['accepted_types'];
8576 $fmoptions->return_types = $options['return_types'];
8577 $fmoptions->context = $options['context'];
8578 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8580 $fm = new form_filemanager($fmoptions);
8581 $output = $PAGE->get_renderer('core', 'files');
8582 $html = $output->render($fm);
8584 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8585 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8587 return format_admin_setting($this, $this->visiblename,
8588 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8594 * Administration interface for user specified regular expressions for device detection.
8596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8598 class admin_setting_devicedetectregex extends admin_setting {
8601 * Calls parent::__construct with specific args
8603 * @param string $name
8604 * @param string $visiblename
8605 * @param string $description
8606 * @param mixed $defaultsetting
8608 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8609 global $CFG;
8610 parent::__construct($name, $visiblename, $description, $defaultsetting);
8614 * Return the current setting(s)
8616 * @return array Current settings array
8618 public function get_setting() {
8619 global $CFG;
8621 $config = $this->config_read($this->name);
8622 if (is_null($config)) {
8623 return null;
8626 return $this->prepare_form_data($config);
8630 * Save selected settings
8632 * @param array $data Array of settings to save
8633 * @return bool
8635 public function write_setting($data) {
8636 if (empty($data)) {
8637 $data = array();
8640 if ($this->config_write($this->name, $this->process_form_data($data))) {
8641 return ''; // success
8642 } else {
8643 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8648 * Return XHTML field(s) for regexes
8650 * @param array $data Array of options to set in HTML
8651 * @return string XHTML string for the fields and wrapping div(s)
8653 public function output_html($data, $query='') {
8654 global $OUTPUT;
8656 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8657 $out .= html_writer::start_tag('thead');
8658 $out .= html_writer::start_tag('tr');
8659 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8660 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8661 $out .= html_writer::end_tag('tr');
8662 $out .= html_writer::end_tag('thead');
8663 $out .= html_writer::start_tag('tbody');
8665 if (empty($data)) {
8666 $looplimit = 1;
8667 } else {
8668 $looplimit = (count($data)/2)+1;
8671 for ($i=0; $i<$looplimit; $i++) {
8672 $out .= html_writer::start_tag('tr');
8674 $expressionname = 'expression'.$i;
8676 if (!empty($data[$expressionname])){
8677 $expression = $data[$expressionname];
8678 } else {
8679 $expression = '';
8682 $out .= html_writer::tag('td',
8683 html_writer::empty_tag('input',
8684 array(
8685 'type' => 'text',
8686 'class' => 'form-text',
8687 'name' => $this->get_full_name().'[expression'.$i.']',
8688 'value' => $expression,
8690 ), array('class' => 'c'.$i)
8693 $valuename = 'value'.$i;
8695 if (!empty($data[$valuename])){
8696 $value = $data[$valuename];
8697 } else {
8698 $value= '';
8701 $out .= html_writer::tag('td',
8702 html_writer::empty_tag('input',
8703 array(
8704 'type' => 'text',
8705 'class' => 'form-text',
8706 'name' => $this->get_full_name().'[value'.$i.']',
8707 'value' => $value,
8709 ), array('class' => 'c'.$i)
8712 $out .= html_writer::end_tag('tr');
8715 $out .= html_writer::end_tag('tbody');
8716 $out .= html_writer::end_tag('table');
8718 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8722 * Converts the string of regexes
8724 * @see self::process_form_data()
8725 * @param $regexes string of regexes
8726 * @return array of form fields and their values
8728 protected function prepare_form_data($regexes) {
8730 $regexes = json_decode($regexes);
8732 $form = array();
8734 $i = 0;
8736 foreach ($regexes as $value => $regex) {
8737 $expressionname = 'expression'.$i;
8738 $valuename = 'value'.$i;
8740 $form[$expressionname] = $regex;
8741 $form[$valuename] = $value;
8742 $i++;
8745 return $form;
8749 * Converts the data from admin settings form into a string of regexes
8751 * @see self::prepare_form_data()
8752 * @param array $data array of admin form fields and values
8753 * @return false|string of regexes
8755 protected function process_form_data(array $form) {
8757 $count = count($form); // number of form field values
8759 if ($count % 2) {
8760 // we must get five fields per expression
8761 return false;
8764 $regexes = array();
8765 for ($i = 0; $i < $count / 2; $i++) {
8766 $expressionname = "expression".$i;
8767 $valuename = "value".$i;
8769 $expression = trim($form['expression'.$i]);
8770 $value = trim($form['value'.$i]);
8772 if (empty($expression)){
8773 continue;
8776 $regexes[$value] = $expression;
8779 $regexes = json_encode($regexes);
8781 return $regexes;
8786 * Multiselect for current modules
8788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8790 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8791 private $excludesystem;
8794 * Calls parent::__construct - note array $choices is not required
8796 * @param string $name setting name
8797 * @param string $visiblename localised setting name
8798 * @param string $description setting description
8799 * @param array $defaultsetting a plain array of default module ids
8800 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8802 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8803 $excludesystem = true) {
8804 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8805 $this->excludesystem = $excludesystem;
8809 * Loads an array of current module choices
8811 * @return bool always return true
8813 public function load_choices() {
8814 if (is_array($this->choices)) {
8815 return true;
8817 $this->choices = array();
8819 global $CFG, $DB;
8820 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8821 foreach ($records as $record) {
8822 // Exclude modules if the code doesn't exist
8823 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8824 // Also exclude system modules (if specified)
8825 if (!($this->excludesystem &&
8826 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8827 MOD_ARCHETYPE_SYSTEM)) {
8828 $this->choices[$record->id] = $record->name;
8832 return true;
8837 * Admin setting to show if a php extension is enabled or not.
8839 * @copyright 2013 Damyon Wiese
8840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8842 class admin_setting_php_extension_enabled extends admin_setting {
8844 /** @var string The name of the extension to check for */
8845 private $extension;
8848 * Calls parent::__construct with specific arguments
8850 public function __construct($name, $visiblename, $description, $extension) {
8851 $this->extension = $extension;
8852 $this->nosave = true;
8853 parent::__construct($name, $visiblename, $description, '');
8857 * Always returns true, does nothing
8859 * @return true
8861 public function get_setting() {
8862 return true;
8866 * Always returns true, does nothing
8868 * @return true
8870 public function get_defaultsetting() {
8871 return true;
8875 * Always returns '', does not write anything
8877 * @return string Always returns ''
8879 public function write_setting($data) {
8880 // Do not write any setting.
8881 return '';
8885 * Outputs the html for this setting.
8886 * @return string Returns an XHTML string
8888 public function output_html($data, $query='') {
8889 global $OUTPUT;
8891 $o = '';
8892 if (!extension_loaded($this->extension)) {
8893 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8895 $o .= format_admin_setting($this, $this->visiblename, $warning);
8897 return $o;