MDL-49418 core: partial revert of MDL-48804
[moodle.git] / lib / adminlib.php
blob5b72c07ca1a41d808df9d3a8eceeeb223a6e868d
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 global $CFG;
2429 $default = $this->get_defaultsetting();
2431 if ($data) {
2432 if (file_exists($data)) {
2433 $executable = '<span class="pathok">&#x2714;</span>';
2434 } else {
2435 $executable = '<span class="patherror">&#x2718;</span>';
2437 } else {
2438 $executable = '';
2440 $readonly = '';
2441 if (!empty($CFG->preventexecpath)) {
2442 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2443 $readonly = 'readonly="readonly"';
2446 return format_admin_setting($this, $this->visiblename,
2447 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2448 $this->description, true, '', $default, $query);
2452 * Checks if execpatch has been disabled in config.php
2454 public function write_setting($data) {
2455 global $CFG;
2456 if (!empty($CFG->preventexecpath)) {
2457 if ($this->get_setting() === null) {
2458 // Use default during installation.
2459 $data = $this->get_defaultsetting();
2460 if ($data === null) {
2461 $data = '';
2463 } else {
2464 return '';
2467 return parent::write_setting($data);
2473 * Path to executable file
2475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2477 class admin_setting_configexecutable extends admin_setting_configfile {
2480 * Returns an XHTML field
2482 * @param string $data This is the value for the field
2483 * @param string $query
2484 * @return string XHTML field
2486 public function output_html($data, $query='') {
2487 global $CFG;
2488 $default = $this->get_defaultsetting();
2490 if ($data) {
2491 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2492 $executable = '<span class="pathok">&#x2714;</span>';
2493 } else {
2494 $executable = '<span class="patherror">&#x2718;</span>';
2496 } else {
2497 $executable = '';
2499 $readonly = '';
2500 if (!empty($CFG->preventexecpath)) {
2501 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2502 $readonly = 'readonly="readonly"';
2505 return format_admin_setting($this, $this->visiblename,
2506 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2507 $this->description, true, '', $default, $query);
2513 * Path to directory
2515 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2517 class admin_setting_configdirectory extends admin_setting_configfile {
2520 * Returns an XHTML field
2522 * @param string $data This is the value for the field
2523 * @param string $query
2524 * @return string XHTML
2526 public function output_html($data, $query='') {
2527 global $CFG;
2528 $default = $this->get_defaultsetting();
2530 if ($data) {
2531 if (file_exists($data) and is_dir($data)) {
2532 $executable = '<span class="pathok">&#x2714;</span>';
2533 } else {
2534 $executable = '<span class="patherror">&#x2718;</span>';
2536 } else {
2537 $executable = '';
2539 $readonly = '';
2540 if (!empty($CFG->preventexecpath)) {
2541 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2542 $readonly = 'readonly="readonly"';
2545 return format_admin_setting($this, $this->visiblename,
2546 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2547 $this->description, true, '', $default, $query);
2553 * Checkbox
2555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2557 class admin_setting_configcheckbox extends admin_setting {
2558 /** @var string Value used when checked */
2559 public $yes;
2560 /** @var string Value used when not checked */
2561 public $no;
2564 * Constructor
2565 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2566 * @param string $visiblename localised
2567 * @param string $description long localised info
2568 * @param string $defaultsetting
2569 * @param string $yes value used when checked
2570 * @param string $no value used when not checked
2572 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2573 parent::__construct($name, $visiblename, $description, $defaultsetting);
2574 $this->yes = (string)$yes;
2575 $this->no = (string)$no;
2579 * Retrieves the current setting using the objects name
2581 * @return string
2583 public function get_setting() {
2584 return $this->config_read($this->name);
2588 * Sets the value for the setting
2590 * Sets the value for the setting to either the yes or no values
2591 * of the object by comparing $data to yes
2593 * @param mixed $data Gets converted to str for comparison against yes value
2594 * @return string empty string or error
2596 public function write_setting($data) {
2597 if ((string)$data === $this->yes) { // convert to strings before comparison
2598 $data = $this->yes;
2599 } else {
2600 $data = $this->no;
2602 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2606 * Returns an XHTML checkbox field
2608 * @param string $data If $data matches yes then checkbox is checked
2609 * @param string $query
2610 * @return string XHTML field
2612 public function output_html($data, $query='') {
2613 $default = $this->get_defaultsetting();
2615 if (!is_null($default)) {
2616 if ((string)$default === $this->yes) {
2617 $defaultinfo = get_string('checkboxyes', 'admin');
2618 } else {
2619 $defaultinfo = get_string('checkboxno', 'admin');
2621 } else {
2622 $defaultinfo = NULL;
2625 if ((string)$data === $this->yes) { // convert to strings before comparison
2626 $checked = 'checked="checked"';
2627 } else {
2628 $checked = '';
2631 return format_admin_setting($this, $this->visiblename,
2632 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2633 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2634 $this->description, true, '', $defaultinfo, $query);
2640 * Multiple checkboxes, each represents different value, stored in csv format
2642 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2644 class admin_setting_configmulticheckbox extends admin_setting {
2645 /** @var array Array of choices value=>label */
2646 public $choices;
2649 * Constructor: uses parent::__construct
2651 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2652 * @param string $visiblename localised
2653 * @param string $description long localised info
2654 * @param array $defaultsetting array of selected
2655 * @param array $choices array of $value=>$label for each checkbox
2657 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2658 $this->choices = $choices;
2659 parent::__construct($name, $visiblename, $description, $defaultsetting);
2663 * This public function may be used in ancestors for lazy loading of choices
2665 * @todo Check if this function is still required content commented out only returns true
2666 * @return bool true if loaded, false if error
2668 public function load_choices() {
2670 if (is_array($this->choices)) {
2671 return true;
2673 .... load choices here
2675 return true;
2679 * Is setting related to query text - used when searching
2681 * @param string $query
2682 * @return bool true on related, false on not or failure
2684 public function is_related($query) {
2685 if (!$this->load_choices() or empty($this->choices)) {
2686 return false;
2688 if (parent::is_related($query)) {
2689 return true;
2692 foreach ($this->choices as $desc) {
2693 if (strpos(core_text::strtolower($desc), $query) !== false) {
2694 return true;
2697 return false;
2701 * Returns the current setting if it is set
2703 * @return mixed null if null, else an array
2705 public function get_setting() {
2706 $result = $this->config_read($this->name);
2708 if (is_null($result)) {
2709 return NULL;
2711 if ($result === '') {
2712 return array();
2714 $enabled = explode(',', $result);
2715 $setting = array();
2716 foreach ($enabled as $option) {
2717 $setting[$option] = 1;
2719 return $setting;
2723 * Saves the setting(s) provided in $data
2725 * @param array $data An array of data, if not array returns empty str
2726 * @return mixed empty string on useless data or bool true=success, false=failed
2728 public function write_setting($data) {
2729 if (!is_array($data)) {
2730 return ''; // ignore it
2732 if (!$this->load_choices() or empty($this->choices)) {
2733 return '';
2735 unset($data['xxxxx']);
2736 $result = array();
2737 foreach ($data as $key => $value) {
2738 if ($value and array_key_exists($key, $this->choices)) {
2739 $result[] = $key;
2742 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2746 * Returns XHTML field(s) as required by choices
2748 * Relies on data being an array should data ever be another valid vartype with
2749 * acceptable value this may cause a warning/error
2750 * if (!is_array($data)) would fix the problem
2752 * @todo Add vartype handling to ensure $data is an array
2754 * @param array $data An array of checked values
2755 * @param string $query
2756 * @return string XHTML field
2758 public function output_html($data, $query='') {
2759 if (!$this->load_choices() or empty($this->choices)) {
2760 return '';
2762 $default = $this->get_defaultsetting();
2763 if (is_null($default)) {
2764 $default = array();
2766 if (is_null($data)) {
2767 $data = array();
2769 $options = array();
2770 $defaults = array();
2771 foreach ($this->choices as $key=>$description) {
2772 if (!empty($data[$key])) {
2773 $checked = 'checked="checked"';
2774 } else {
2775 $checked = '';
2777 if (!empty($default[$key])) {
2778 $defaults[] = $description;
2781 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2782 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2785 if (is_null($default)) {
2786 $defaultinfo = NULL;
2787 } else if (!empty($defaults)) {
2788 $defaultinfo = implode(', ', $defaults);
2789 } else {
2790 $defaultinfo = get_string('none');
2793 $return = '<div class="form-multicheckbox">';
2794 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2795 if ($options) {
2796 $return .= '<ul>';
2797 foreach ($options as $option) {
2798 $return .= '<li>'.$option.'</li>';
2800 $return .= '</ul>';
2802 $return .= '</div>';
2804 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2811 * Multiple checkboxes 2, value stored as string 00101011
2813 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2815 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2818 * Returns the setting if set
2820 * @return mixed null if not set, else an array of set settings
2822 public function get_setting() {
2823 $result = $this->config_read($this->name);
2824 if (is_null($result)) {
2825 return NULL;
2827 if (!$this->load_choices()) {
2828 return NULL;
2830 $result = str_pad($result, count($this->choices), '0');
2831 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2832 $setting = array();
2833 foreach ($this->choices as $key=>$unused) {
2834 $value = array_shift($result);
2835 if ($value) {
2836 $setting[$key] = 1;
2839 return $setting;
2843 * Save setting(s) provided in $data param
2845 * @param array $data An array of settings to save
2846 * @return mixed empty string for bad data or bool true=>success, false=>error
2848 public function write_setting($data) {
2849 if (!is_array($data)) {
2850 return ''; // ignore it
2852 if (!$this->load_choices() or empty($this->choices)) {
2853 return '';
2855 $result = '';
2856 foreach ($this->choices as $key=>$unused) {
2857 if (!empty($data[$key])) {
2858 $result .= '1';
2859 } else {
2860 $result .= '0';
2863 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2869 * Select one value from list
2871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2873 class admin_setting_configselect extends admin_setting {
2874 /** @var array Array of choices value=>label */
2875 public $choices;
2878 * Constructor
2879 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2880 * @param string $visiblename localised
2881 * @param string $description long localised info
2882 * @param string|int $defaultsetting
2883 * @param array $choices array of $value=>$label for each selection
2885 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2886 $this->choices = $choices;
2887 parent::__construct($name, $visiblename, $description, $defaultsetting);
2891 * This function may be used in ancestors for lazy loading of choices
2893 * Override this method if loading of choices is expensive, such
2894 * as when it requires multiple db requests.
2896 * @return bool true if loaded, false if error
2898 public function load_choices() {
2900 if (is_array($this->choices)) {
2901 return true;
2903 .... load choices here
2905 return true;
2909 * Check if this is $query is related to a choice
2911 * @param string $query
2912 * @return bool true if related, false if not
2914 public function is_related($query) {
2915 if (parent::is_related($query)) {
2916 return true;
2918 if (!$this->load_choices()) {
2919 return false;
2921 foreach ($this->choices as $key=>$value) {
2922 if (strpos(core_text::strtolower($key), $query) !== false) {
2923 return true;
2925 if (strpos(core_text::strtolower($value), $query) !== false) {
2926 return true;
2929 return false;
2933 * Return the setting
2935 * @return mixed returns config if successful else null
2937 public function get_setting() {
2938 return $this->config_read($this->name);
2942 * Save a setting
2944 * @param string $data
2945 * @return string empty of error string
2947 public function write_setting($data) {
2948 if (!$this->load_choices() or empty($this->choices)) {
2949 return '';
2951 if (!array_key_exists($data, $this->choices)) {
2952 return ''; // ignore it
2955 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2959 * Returns XHTML select field
2961 * Ensure the options are loaded, and generate the XHTML for the select
2962 * element and any warning message. Separating this out from output_html
2963 * makes it easier to subclass this class.
2965 * @param string $data the option to show as selected.
2966 * @param string $current the currently selected option in the database, null if none.
2967 * @param string $default the default selected option.
2968 * @return array the HTML for the select element, and a warning message.
2970 public function output_select_html($data, $current, $default, $extraname = '') {
2971 if (!$this->load_choices() or empty($this->choices)) {
2972 return array('', '');
2975 $warning = '';
2976 if (is_null($current)) {
2977 // first run
2978 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2979 // no warning
2980 } else if (!array_key_exists($current, $this->choices)) {
2981 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2982 if (!is_null($default) and $data == $current) {
2983 $data = $default; // use default instead of first value when showing the form
2987 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2988 foreach ($this->choices as $key => $value) {
2989 // the string cast is needed because key may be integer - 0 is equal to most strings!
2990 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2992 $selecthtml .= '</select>';
2993 return array($selecthtml, $warning);
2997 * Returns XHTML select field and wrapping div(s)
2999 * @see output_select_html()
3001 * @param string $data the option to show as selected
3002 * @param string $query
3003 * @return string XHTML field and wrapping div
3005 public function output_html($data, $query='') {
3006 $default = $this->get_defaultsetting();
3007 $current = $this->get_setting();
3009 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3010 if (!$selecthtml) {
3011 return '';
3014 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3015 $defaultinfo = $this->choices[$default];
3016 } else {
3017 $defaultinfo = NULL;
3020 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3022 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3028 * Select multiple items from list
3030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3032 class admin_setting_configmultiselect extends admin_setting_configselect {
3034 * Constructor
3035 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3036 * @param string $visiblename localised
3037 * @param string $description long localised info
3038 * @param array $defaultsetting array of selected items
3039 * @param array $choices array of $value=>$label for each list item
3041 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3042 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3046 * Returns the select setting(s)
3048 * @return mixed null or array. Null if no settings else array of setting(s)
3050 public function get_setting() {
3051 $result = $this->config_read($this->name);
3052 if (is_null($result)) {
3053 return NULL;
3055 if ($result === '') {
3056 return array();
3058 return explode(',', $result);
3062 * Saves setting(s) provided through $data
3064 * Potential bug in the works should anyone call with this function
3065 * using a vartype that is not an array
3067 * @param array $data
3069 public function write_setting($data) {
3070 if (!is_array($data)) {
3071 return ''; //ignore it
3073 if (!$this->load_choices() or empty($this->choices)) {
3074 return '';
3077 unset($data['xxxxx']);
3079 $save = array();
3080 foreach ($data as $value) {
3081 if (!array_key_exists($value, $this->choices)) {
3082 continue; // ignore it
3084 $save[] = $value;
3087 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3091 * Is setting related to query text - used when searching
3093 * @param string $query
3094 * @return bool true if related, false if not
3096 public function is_related($query) {
3097 if (!$this->load_choices() or empty($this->choices)) {
3098 return false;
3100 if (parent::is_related($query)) {
3101 return true;
3104 foreach ($this->choices as $desc) {
3105 if (strpos(core_text::strtolower($desc), $query) !== false) {
3106 return true;
3109 return false;
3113 * Returns XHTML multi-select field
3115 * @todo Add vartype handling to ensure $data is an array
3116 * @param array $data Array of values to select by default
3117 * @param string $query
3118 * @return string XHTML multi-select field
3120 public function output_html($data, $query='') {
3121 if (!$this->load_choices() or empty($this->choices)) {
3122 return '';
3124 $choices = $this->choices;
3125 $default = $this->get_defaultsetting();
3126 if (is_null($default)) {
3127 $default = array();
3129 if (is_null($data)) {
3130 $data = array();
3133 $defaults = array();
3134 $size = min(10, count($this->choices));
3135 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3136 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3137 foreach ($this->choices as $key => $description) {
3138 if (in_array($key, $data)) {
3139 $selected = 'selected="selected"';
3140 } else {
3141 $selected = '';
3143 if (in_array($key, $default)) {
3144 $defaults[] = $description;
3147 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3150 if (is_null($default)) {
3151 $defaultinfo = NULL;
3152 } if (!empty($defaults)) {
3153 $defaultinfo = implode(', ', $defaults);
3154 } else {
3155 $defaultinfo = get_string('none');
3158 $return .= '</select></div>';
3159 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3164 * Time selector
3166 * This is a liiitle bit messy. we're using two selects, but we're returning
3167 * them as an array named after $name (so we only use $name2 internally for the setting)
3169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3171 class admin_setting_configtime extends admin_setting {
3172 /** @var string Used for setting second select (minutes) */
3173 public $name2;
3176 * Constructor
3177 * @param string $hoursname setting for hours
3178 * @param string $minutesname setting for hours
3179 * @param string $visiblename localised
3180 * @param string $description long localised info
3181 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3183 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3184 $this->name2 = $minutesname;
3185 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3189 * Get the selected time
3191 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3193 public function get_setting() {
3194 $result1 = $this->config_read($this->name);
3195 $result2 = $this->config_read($this->name2);
3196 if (is_null($result1) or is_null($result2)) {
3197 return NULL;
3200 return array('h' => $result1, 'm' => $result2);
3204 * Store the time (hours and minutes)
3206 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3207 * @return bool true if success, false if not
3209 public function write_setting($data) {
3210 if (!is_array($data)) {
3211 return '';
3214 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3215 return ($result ? '' : get_string('errorsetting', 'admin'));
3219 * Returns XHTML time select fields
3221 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3222 * @param string $query
3223 * @return string XHTML time select fields and wrapping div(s)
3225 public function output_html($data, $query='') {
3226 $default = $this->get_defaultsetting();
3228 if (is_array($default)) {
3229 $defaultinfo = $default['h'].':'.$default['m'];
3230 } else {
3231 $defaultinfo = NULL;
3234 $return = '<div class="form-time defaultsnext">';
3235 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3236 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3237 for ($i = 0; $i < 24; $i++) {
3238 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3240 $return .= '</select>:';
3241 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3242 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3243 for ($i = 0; $i < 60; $i += 5) {
3244 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3246 $return .= '</select>';
3247 $return .= '</div>';
3248 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3255 * Seconds duration setting.
3257 * @copyright 2012 Petr Skoda (http://skodak.org)
3258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3260 class admin_setting_configduration extends admin_setting {
3262 /** @var int default duration unit */
3263 protected $defaultunit;
3266 * Constructor
3267 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3268 * or 'myplugin/mysetting' for ones in config_plugins.
3269 * @param string $visiblename localised name
3270 * @param string $description localised long description
3271 * @param mixed $defaultsetting string or array depending on implementation
3272 * @param int $defaultunit - day, week, etc. (in seconds)
3274 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3275 if (is_number($defaultsetting)) {
3276 $defaultsetting = self::parse_seconds($defaultsetting);
3278 $units = self::get_units();
3279 if (isset($units[$defaultunit])) {
3280 $this->defaultunit = $defaultunit;
3281 } else {
3282 $this->defaultunit = 86400;
3284 parent::__construct($name, $visiblename, $description, $defaultsetting);
3288 * Returns selectable units.
3289 * @static
3290 * @return array
3292 protected static function get_units() {
3293 return array(
3294 604800 => get_string('weeks'),
3295 86400 => get_string('days'),
3296 3600 => get_string('hours'),
3297 60 => get_string('minutes'),
3298 1 => get_string('seconds'),
3303 * Converts seconds to some more user friendly string.
3304 * @static
3305 * @param int $seconds
3306 * @return string
3308 protected static function get_duration_text($seconds) {
3309 if (empty($seconds)) {
3310 return get_string('none');
3312 $data = self::parse_seconds($seconds);
3313 switch ($data['u']) {
3314 case (60*60*24*7):
3315 return get_string('numweeks', '', $data['v']);
3316 case (60*60*24):
3317 return get_string('numdays', '', $data['v']);
3318 case (60*60):
3319 return get_string('numhours', '', $data['v']);
3320 case (60):
3321 return get_string('numminutes', '', $data['v']);
3322 default:
3323 return get_string('numseconds', '', $data['v']*$data['u']);
3328 * Finds suitable units for given duration.
3329 * @static
3330 * @param int $seconds
3331 * @return array
3333 protected static function parse_seconds($seconds) {
3334 foreach (self::get_units() as $unit => $unused) {
3335 if ($seconds % $unit === 0) {
3336 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3339 return array('v'=>(int)$seconds, 'u'=>1);
3343 * Get the selected duration as array.
3345 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3347 public function get_setting() {
3348 $seconds = $this->config_read($this->name);
3349 if (is_null($seconds)) {
3350 return null;
3353 return self::parse_seconds($seconds);
3357 * Store the duration as seconds.
3359 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3360 * @return bool true if success, false if not
3362 public function write_setting($data) {
3363 if (!is_array($data)) {
3364 return '';
3367 $seconds = (int)($data['v']*$data['u']);
3368 if ($seconds < 0) {
3369 return get_string('errorsetting', 'admin');
3372 $result = $this->config_write($this->name, $seconds);
3373 return ($result ? '' : get_string('errorsetting', 'admin'));
3377 * Returns duration text+select fields.
3379 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3380 * @param string $query
3381 * @return string duration text+select fields and wrapping div(s)
3383 public function output_html($data, $query='') {
3384 $default = $this->get_defaultsetting();
3386 if (is_number($default)) {
3387 $defaultinfo = self::get_duration_text($default);
3388 } else if (is_array($default)) {
3389 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3390 } else {
3391 $defaultinfo = null;
3394 $units = self::get_units();
3396 $return = '<div class="form-duration defaultsnext">';
3397 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3398 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3399 foreach ($units as $val => $text) {
3400 $selected = '';
3401 if ($data['v'] == 0) {
3402 if ($val == $this->defaultunit) {
3403 $selected = ' selected="selected"';
3405 } else if ($val == $data['u']) {
3406 $selected = ' selected="selected"';
3408 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3410 $return .= '</select></div>';
3411 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3417 * Used to validate a textarea used for ip addresses
3419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3421 class admin_setting_configiplist extends admin_setting_configtextarea {
3424 * Validate the contents of the textarea as IP addresses
3426 * Used to validate a new line separated list of IP addresses collected from
3427 * a textarea control
3429 * @param string $data A list of IP Addresses separated by new lines
3430 * @return mixed bool true for success or string:error on failure
3432 public function validate($data) {
3433 if(!empty($data)) {
3434 $ips = explode("\n", $data);
3435 } else {
3436 return true;
3438 $result = true;
3439 foreach($ips as $ip) {
3440 $ip = trim($ip);
3441 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3442 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3443 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3444 $result = true;
3445 } else {
3446 $result = false;
3447 break;
3450 if($result) {
3451 return true;
3452 } else {
3453 return get_string('validateerror', 'admin');
3460 * An admin setting for selecting one or more users who have a capability
3461 * in the system context
3463 * An admin setting for selecting one or more users, who have a particular capability
3464 * in the system context. Warning, make sure the list will never be too long. There is
3465 * no paging or searching of this list.
3467 * To correctly get a list of users from this config setting, you need to call the
3468 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3472 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3473 /** @var string The capabilities name */
3474 protected $capability;
3475 /** @var int include admin users too */
3476 protected $includeadmins;
3479 * Constructor.
3481 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3482 * @param string $visiblename localised name
3483 * @param string $description localised long description
3484 * @param array $defaultsetting array of usernames
3485 * @param string $capability string capability name.
3486 * @param bool $includeadmins include administrators
3488 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3489 $this->capability = $capability;
3490 $this->includeadmins = $includeadmins;
3491 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3495 * Load all of the uses who have the capability into choice array
3497 * @return bool Always returns true
3499 function load_choices() {
3500 if (is_array($this->choices)) {
3501 return true;
3503 list($sort, $sortparams) = users_order_by_sql('u');
3504 if (!empty($sortparams)) {
3505 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3506 'This is unexpected, and a problem because there is no way to pass these ' .
3507 'parameters to get_users_by_capability. See MDL-34657.');
3509 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3510 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3511 $this->choices = array(
3512 '$@NONE@$' => get_string('nobody'),
3513 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3515 if ($this->includeadmins) {
3516 $admins = get_admins();
3517 foreach ($admins as $user) {
3518 $this->choices[$user->id] = fullname($user);
3521 if (is_array($users)) {
3522 foreach ($users as $user) {
3523 $this->choices[$user->id] = fullname($user);
3526 return true;
3530 * Returns the default setting for class
3532 * @return mixed Array, or string. Empty string if no default
3534 public function get_defaultsetting() {
3535 $this->load_choices();
3536 $defaultsetting = parent::get_defaultsetting();
3537 if (empty($defaultsetting)) {
3538 return array('$@NONE@$');
3539 } else if (array_key_exists($defaultsetting, $this->choices)) {
3540 return $defaultsetting;
3541 } else {
3542 return '';
3547 * Returns the current setting
3549 * @return mixed array or string
3551 public function get_setting() {
3552 $result = parent::get_setting();
3553 if ($result === null) {
3554 // this is necessary for settings upgrade
3555 return null;
3557 if (empty($result)) {
3558 $result = array('$@NONE@$');
3560 return $result;
3564 * Save the chosen setting provided as $data
3566 * @param array $data
3567 * @return mixed string or array
3569 public function write_setting($data) {
3570 // If all is selected, remove any explicit options.
3571 if (in_array('$@ALL@$', $data)) {
3572 $data = array('$@ALL@$');
3574 // None never needs to be written to the DB.
3575 if (in_array('$@NONE@$', $data)) {
3576 unset($data[array_search('$@NONE@$', $data)]);
3578 return parent::write_setting($data);
3584 * Special checkbox for calendar - resets SESSION vars.
3586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3588 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3590 * Calls the parent::__construct with default values
3592 * name => calendar_adminseesall
3593 * visiblename => get_string('adminseesall', 'admin')
3594 * description => get_string('helpadminseesall', 'admin')
3595 * defaultsetting => 0
3597 public function __construct() {
3598 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3599 get_string('helpadminseesall', 'admin'), '0');
3603 * Stores the setting passed in $data
3605 * @param mixed gets converted to string for comparison
3606 * @return string empty string or error message
3608 public function write_setting($data) {
3609 global $SESSION;
3610 return parent::write_setting($data);
3615 * Special select for settings that are altered in setup.php and can not be altered on the fly
3617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3619 class admin_setting_special_selectsetup extends admin_setting_configselect {
3621 * Reads the setting directly from the database
3623 * @return mixed
3625 public function get_setting() {
3626 // read directly from db!
3627 return get_config(NULL, $this->name);
3631 * Save the setting passed in $data
3633 * @param string $data The setting to save
3634 * @return string empty or error message
3636 public function write_setting($data) {
3637 global $CFG;
3638 // do not change active CFG setting!
3639 $current = $CFG->{$this->name};
3640 $result = parent::write_setting($data);
3641 $CFG->{$this->name} = $current;
3642 return $result;
3648 * Special select for frontpage - stores data in course table
3650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3652 class admin_setting_sitesetselect extends admin_setting_configselect {
3654 * Returns the site name for the selected site
3656 * @see get_site()
3657 * @return string The site name of the selected site
3659 public function get_setting() {
3660 $site = course_get_format(get_site())->get_course();
3661 return $site->{$this->name};
3665 * Updates the database and save the setting
3667 * @param string data
3668 * @return string empty or error message
3670 public function write_setting($data) {
3671 global $DB, $SITE, $COURSE;
3672 if (!in_array($data, array_keys($this->choices))) {
3673 return get_string('errorsetting', 'admin');
3675 $record = new stdClass();
3676 $record->id = SITEID;
3677 $temp = $this->name;
3678 $record->$temp = $data;
3679 $record->timemodified = time();
3681 course_get_format($SITE)->update_course_format_options($record);
3682 $DB->update_record('course', $record);
3684 // Reset caches.
3685 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3686 if ($SITE->id == $COURSE->id) {
3687 $COURSE = $SITE;
3689 format_base::reset_course_cache($SITE->id);
3691 return '';
3698 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3699 * block to hidden.
3701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3703 class admin_setting_bloglevel extends admin_setting_configselect {
3705 * Updates the database and save the setting
3707 * @param string data
3708 * @return string empty or error message
3710 public function write_setting($data) {
3711 global $DB, $CFG;
3712 if ($data == 0) {
3713 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3714 foreach ($blogblocks as $block) {
3715 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3717 } else {
3718 // reenable all blocks only when switching from disabled blogs
3719 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3720 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3721 foreach ($blogblocks as $block) {
3722 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3726 return parent::write_setting($data);
3732 * Special select - lists on the frontpage - hacky
3734 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3736 class admin_setting_courselist_frontpage extends admin_setting {
3737 /** @var array Array of choices value=>label */
3738 public $choices;
3741 * Construct override, requires one param
3743 * @param bool $loggedin Is the user logged in
3745 public function __construct($loggedin) {
3746 global $CFG;
3747 require_once($CFG->dirroot.'/course/lib.php');
3748 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3749 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3750 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3751 $defaults = array(FRONTPAGEALLCOURSELIST);
3752 parent::__construct($name, $visiblename, $description, $defaults);
3756 * Loads the choices available
3758 * @return bool always returns true
3760 public function load_choices() {
3761 if (is_array($this->choices)) {
3762 return true;
3764 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3765 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3766 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3767 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3768 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3769 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3770 'none' => get_string('none'));
3771 if ($this->name === 'frontpage') {
3772 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3774 return true;
3778 * Returns the selected settings
3780 * @param mixed array or setting or null
3782 public function get_setting() {
3783 $result = $this->config_read($this->name);
3784 if (is_null($result)) {
3785 return NULL;
3787 if ($result === '') {
3788 return array();
3790 return explode(',', $result);
3794 * Save the selected options
3796 * @param array $data
3797 * @return mixed empty string (data is not an array) or bool true=success false=failure
3799 public function write_setting($data) {
3800 if (!is_array($data)) {
3801 return '';
3803 $this->load_choices();
3804 $save = array();
3805 foreach($data as $datum) {
3806 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3807 continue;
3809 $save[$datum] = $datum; // no duplicates
3811 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3815 * Return XHTML select field and wrapping div
3817 * @todo Add vartype handling to make sure $data is an array
3818 * @param array $data Array of elements to select by default
3819 * @return string XHTML select field and wrapping div
3821 public function output_html($data, $query='') {
3822 $this->load_choices();
3823 $currentsetting = array();
3824 foreach ($data as $key) {
3825 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3826 $currentsetting[] = $key; // already selected first
3830 $return = '<div class="form-group">';
3831 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3832 if (!array_key_exists($i, $currentsetting)) {
3833 $currentsetting[$i] = 'none'; //none
3835 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3836 foreach ($this->choices as $key => $value) {
3837 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3839 $return .= '</select>';
3840 if ($i !== count($this->choices) - 2) {
3841 $return .= '<br />';
3844 $return .= '</div>';
3846 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3852 * Special checkbox for frontpage - stores data in course table
3854 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3856 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3858 * Returns the current sites name
3860 * @return string
3862 public function get_setting() {
3863 $site = course_get_format(get_site())->get_course();
3864 return $site->{$this->name};
3868 * Save the selected setting
3870 * @param string $data The selected site
3871 * @return string empty string or error message
3873 public function write_setting($data) {
3874 global $DB, $SITE, $COURSE;
3875 $record = new stdClass();
3876 $record->id = $SITE->id;
3877 $record->{$this->name} = ($data == '1' ? 1 : 0);
3878 $record->timemodified = time();
3880 course_get_format($SITE)->update_course_format_options($record);
3881 $DB->update_record('course', $record);
3883 // Reset caches.
3884 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3885 if ($SITE->id == $COURSE->id) {
3886 $COURSE = $SITE;
3888 format_base::reset_course_cache($SITE->id);
3890 return '';
3895 * Special text for frontpage - stores data in course table.
3896 * Empty string means not set here. Manual setting is required.
3898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3900 class admin_setting_sitesettext extends admin_setting_configtext {
3902 * Return the current setting
3904 * @return mixed string or null
3906 public function get_setting() {
3907 $site = course_get_format(get_site())->get_course();
3908 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3912 * Validate the selected data
3914 * @param string $data The selected value to validate
3915 * @return mixed true or message string
3917 public function validate($data) {
3918 $cleaned = clean_param($data, PARAM_TEXT);
3919 if ($cleaned === '') {
3920 return get_string('required');
3922 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3923 return true;
3924 } else {
3925 return get_string('validateerror', 'admin');
3930 * Save the selected setting
3932 * @param string $data The selected value
3933 * @return string empty or error message
3935 public function write_setting($data) {
3936 global $DB, $SITE, $COURSE;
3937 $data = trim($data);
3938 $validated = $this->validate($data);
3939 if ($validated !== true) {
3940 return $validated;
3943 $record = new stdClass();
3944 $record->id = $SITE->id;
3945 $record->{$this->name} = $data;
3946 $record->timemodified = time();
3948 course_get_format($SITE)->update_course_format_options($record);
3949 $DB->update_record('course', $record);
3951 // Reset caches.
3952 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3953 if ($SITE->id == $COURSE->id) {
3954 $COURSE = $SITE;
3956 format_base::reset_course_cache($SITE->id);
3958 return '';
3964 * Special text editor for site description.
3966 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3968 class admin_setting_special_frontpagedesc extends admin_setting {
3970 * Calls parent::__construct with specific arguments
3972 public function __construct() {
3973 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3974 editors_head_setup();
3978 * Return the current setting
3979 * @return string The current setting
3981 public function get_setting() {
3982 $site = course_get_format(get_site())->get_course();
3983 return $site->{$this->name};
3987 * Save the new setting
3989 * @param string $data The new value to save
3990 * @return string empty or error message
3992 public function write_setting($data) {
3993 global $DB, $SITE, $COURSE;
3994 $record = new stdClass();
3995 $record->id = $SITE->id;
3996 $record->{$this->name} = $data;
3997 $record->timemodified = time();
3999 course_get_format($SITE)->update_course_format_options($record);
4000 $DB->update_record('course', $record);
4002 // Reset caches.
4003 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4004 if ($SITE->id == $COURSE->id) {
4005 $COURSE = $SITE;
4007 format_base::reset_course_cache($SITE->id);
4009 return '';
4013 * Returns XHTML for the field plus wrapping div
4015 * @param string $data The current value
4016 * @param string $query
4017 * @return string The XHTML output
4019 public function output_html($data, $query='') {
4020 global $CFG;
4022 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4024 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4030 * Administration interface for emoticon_manager settings.
4032 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4034 class admin_setting_emoticons extends admin_setting {
4037 * Calls parent::__construct with specific args
4039 public function __construct() {
4040 global $CFG;
4042 $manager = get_emoticon_manager();
4043 $defaults = $this->prepare_form_data($manager->default_emoticons());
4044 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4048 * Return the current setting(s)
4050 * @return array Current settings array
4052 public function get_setting() {
4053 global $CFG;
4055 $manager = get_emoticon_manager();
4057 $config = $this->config_read($this->name);
4058 if (is_null($config)) {
4059 return null;
4062 $config = $manager->decode_stored_config($config);
4063 if (is_null($config)) {
4064 return null;
4067 return $this->prepare_form_data($config);
4071 * Save selected settings
4073 * @param array $data Array of settings to save
4074 * @return bool
4076 public function write_setting($data) {
4078 $manager = get_emoticon_manager();
4079 $emoticons = $this->process_form_data($data);
4081 if ($emoticons === false) {
4082 return false;
4085 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4086 return ''; // success
4087 } else {
4088 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4093 * Return XHTML field(s) for options
4095 * @param array $data Array of options to set in HTML
4096 * @return string XHTML string for the fields and wrapping div(s)
4098 public function output_html($data, $query='') {
4099 global $OUTPUT;
4101 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4102 $out .= html_writer::start_tag('thead');
4103 $out .= html_writer::start_tag('tr');
4104 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4105 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4106 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4107 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4108 $out .= html_writer::tag('th', '');
4109 $out .= html_writer::end_tag('tr');
4110 $out .= html_writer::end_tag('thead');
4111 $out .= html_writer::start_tag('tbody');
4112 $i = 0;
4113 foreach($data as $field => $value) {
4114 switch ($i) {
4115 case 0:
4116 $out .= html_writer::start_tag('tr');
4117 $current_text = $value;
4118 $current_filename = '';
4119 $current_imagecomponent = '';
4120 $current_altidentifier = '';
4121 $current_altcomponent = '';
4122 case 1:
4123 $current_filename = $value;
4124 case 2:
4125 $current_imagecomponent = $value;
4126 case 3:
4127 $current_altidentifier = $value;
4128 case 4:
4129 $current_altcomponent = $value;
4132 $out .= html_writer::tag('td',
4133 html_writer::empty_tag('input',
4134 array(
4135 'type' => 'text',
4136 'class' => 'form-text',
4137 'name' => $this->get_full_name().'['.$field.']',
4138 'value' => $value,
4140 ), array('class' => 'c'.$i)
4143 if ($i == 4) {
4144 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4145 $alt = get_string($current_altidentifier, $current_altcomponent);
4146 } else {
4147 $alt = $current_text;
4149 if ($current_filename) {
4150 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4151 } else {
4152 $out .= html_writer::tag('td', '');
4154 $out .= html_writer::end_tag('tr');
4155 $i = 0;
4156 } else {
4157 $i++;
4161 $out .= html_writer::end_tag('tbody');
4162 $out .= html_writer::end_tag('table');
4163 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4164 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4166 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4170 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4172 * @see self::process_form_data()
4173 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4174 * @return array of form fields and their values
4176 protected function prepare_form_data(array $emoticons) {
4178 $form = array();
4179 $i = 0;
4180 foreach ($emoticons as $emoticon) {
4181 $form['text'.$i] = $emoticon->text;
4182 $form['imagename'.$i] = $emoticon->imagename;
4183 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4184 $form['altidentifier'.$i] = $emoticon->altidentifier;
4185 $form['altcomponent'.$i] = $emoticon->altcomponent;
4186 $i++;
4188 // add one more blank field set for new object
4189 $form['text'.$i] = '';
4190 $form['imagename'.$i] = '';
4191 $form['imagecomponent'.$i] = '';
4192 $form['altidentifier'.$i] = '';
4193 $form['altcomponent'.$i] = '';
4195 return $form;
4199 * Converts the data from admin settings form into an array of emoticon objects
4201 * @see self::prepare_form_data()
4202 * @param array $data array of admin form fields and values
4203 * @return false|array of emoticon objects
4205 protected function process_form_data(array $form) {
4207 $count = count($form); // number of form field values
4209 if ($count % 5) {
4210 // we must get five fields per emoticon object
4211 return false;
4214 $emoticons = array();
4215 for ($i = 0; $i < $count / 5; $i++) {
4216 $emoticon = new stdClass();
4217 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4218 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4219 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4220 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4221 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4223 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4224 // prevent from breaking http://url.addresses by accident
4225 $emoticon->text = '';
4228 if (strlen($emoticon->text) < 2) {
4229 // do not allow single character emoticons
4230 $emoticon->text = '';
4233 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4234 // emoticon text must contain some non-alphanumeric character to prevent
4235 // breaking HTML tags
4236 $emoticon->text = '';
4239 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4240 $emoticons[] = $emoticon;
4243 return $emoticons;
4249 * Special setting for limiting of the list of available languages.
4251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4253 class admin_setting_langlist extends admin_setting_configtext {
4255 * Calls parent::__construct with specific arguments
4257 public function __construct() {
4258 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4262 * Save the new setting
4264 * @param string $data The new setting
4265 * @return bool
4267 public function write_setting($data) {
4268 $return = parent::write_setting($data);
4269 get_string_manager()->reset_caches();
4270 return $return;
4276 * Selection of one of the recognised countries using the list
4277 * returned by {@link get_list_of_countries()}.
4279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4281 class admin_settings_country_select extends admin_setting_configselect {
4282 protected $includeall;
4283 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4284 $this->includeall = $includeall;
4285 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4289 * Lazy-load the available choices for the select box
4291 public function load_choices() {
4292 global $CFG;
4293 if (is_array($this->choices)) {
4294 return true;
4296 $this->choices = array_merge(
4297 array('0' => get_string('choosedots')),
4298 get_string_manager()->get_list_of_countries($this->includeall));
4299 return true;
4305 * admin_setting_configselect for the default number of sections in a course,
4306 * simply so we can lazy-load the choices.
4308 * @copyright 2011 The Open University
4309 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4311 class admin_settings_num_course_sections extends admin_setting_configselect {
4312 public function __construct($name, $visiblename, $description, $defaultsetting) {
4313 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4316 /** Lazy-load the available choices for the select box */
4317 public function load_choices() {
4318 $max = get_config('moodlecourse', 'maxsections');
4319 if (!isset($max) || !is_numeric($max)) {
4320 $max = 52;
4322 for ($i = 0; $i <= $max; $i++) {
4323 $this->choices[$i] = "$i";
4325 return true;
4331 * Course category selection
4333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4335 class admin_settings_coursecat_select extends admin_setting_configselect {
4337 * Calls parent::__construct with specific arguments
4339 public function __construct($name, $visiblename, $description, $defaultsetting) {
4340 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4344 * Load the available choices for the select box
4346 * @return bool
4348 public function load_choices() {
4349 global $CFG;
4350 require_once($CFG->dirroot.'/course/lib.php');
4351 if (is_array($this->choices)) {
4352 return true;
4354 $this->choices = make_categories_options();
4355 return true;
4361 * Special control for selecting days to backup
4363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4365 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4367 * Calls parent::__construct with specific arguments
4369 public function __construct() {
4370 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4371 $this->plugin = 'backup';
4375 * Load the available choices for the select box
4377 * @return bool Always returns true
4379 public function load_choices() {
4380 if (is_array($this->choices)) {
4381 return true;
4383 $this->choices = array();
4384 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4385 foreach ($days as $day) {
4386 $this->choices[$day] = get_string($day, 'calendar');
4388 return true;
4394 * Special debug setting
4396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4398 class admin_setting_special_debug extends admin_setting_configselect {
4400 * Calls parent::__construct with specific arguments
4402 public function __construct() {
4403 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4407 * Load the available choices for the select box
4409 * @return bool
4411 public function load_choices() {
4412 if (is_array($this->choices)) {
4413 return true;
4415 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4416 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4417 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4418 DEBUG_ALL => get_string('debugall', 'admin'),
4419 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4420 return true;
4426 * Special admin control
4428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4430 class admin_setting_special_calendar_weekend extends admin_setting {
4432 * Calls parent::__construct with specific arguments
4434 public function __construct() {
4435 $name = 'calendar_weekend';
4436 $visiblename = get_string('calendar_weekend', 'admin');
4437 $description = get_string('helpweekenddays', 'admin');
4438 $default = array ('0', '6'); // Saturdays and Sundays
4439 parent::__construct($name, $visiblename, $description, $default);
4443 * Gets the current settings as an array
4445 * @return mixed Null if none, else array of settings
4447 public function get_setting() {
4448 $result = $this->config_read($this->name);
4449 if (is_null($result)) {
4450 return NULL;
4452 if ($result === '') {
4453 return array();
4455 $settings = array();
4456 for ($i=0; $i<7; $i++) {
4457 if ($result & (1 << $i)) {
4458 $settings[] = $i;
4461 return $settings;
4465 * Save the new settings
4467 * @param array $data Array of new settings
4468 * @return bool
4470 public function write_setting($data) {
4471 if (!is_array($data)) {
4472 return '';
4474 unset($data['xxxxx']);
4475 $result = 0;
4476 foreach($data as $index) {
4477 $result |= 1 << $index;
4479 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4483 * Return XHTML to display the control
4485 * @param array $data array of selected days
4486 * @param string $query
4487 * @return string XHTML for display (field + wrapping div(s)
4489 public function output_html($data, $query='') {
4490 // The order matters very much because of the implied numeric keys
4491 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4492 $return = '<table><thead><tr>';
4493 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4494 foreach($days as $index => $day) {
4495 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4497 $return .= '</tr></thead><tbody><tr>';
4498 foreach($days as $index => $day) {
4499 $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>';
4501 $return .= '</tr></tbody></table>';
4503 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4510 * Admin setting that allows a user to pick a behaviour.
4512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4514 class admin_setting_question_behaviour extends admin_setting_configselect {
4516 * @param string $name name of config variable
4517 * @param string $visiblename display name
4518 * @param string $description description
4519 * @param string $default default.
4521 public function __construct($name, $visiblename, $description, $default) {
4522 parent::__construct($name, $visiblename, $description, $default, NULL);
4526 * Load list of behaviours as choices
4527 * @return bool true => success, false => error.
4529 public function load_choices() {
4530 global $CFG;
4531 require_once($CFG->dirroot . '/question/engine/lib.php');
4532 $this->choices = question_engine::get_behaviour_options('');
4533 return true;
4539 * Admin setting that allows a user to pick appropriate roles for something.
4541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4543 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4544 /** @var array Array of capabilities which identify roles */
4545 private $types;
4548 * @param string $name Name of config variable
4549 * @param string $visiblename Display name
4550 * @param string $description Description
4551 * @param array $types Array of archetypes which identify
4552 * roles that will be enabled by default.
4554 public function __construct($name, $visiblename, $description, $types) {
4555 parent::__construct($name, $visiblename, $description, NULL, NULL);
4556 $this->types = $types;
4560 * Load roles as choices
4562 * @return bool true=>success, false=>error
4564 public function load_choices() {
4565 global $CFG, $DB;
4566 if (during_initial_install()) {
4567 return false;
4569 if (is_array($this->choices)) {
4570 return true;
4572 if ($roles = get_all_roles()) {
4573 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4574 return true;
4575 } else {
4576 return false;
4581 * Return the default setting for this control
4583 * @return array Array of default settings
4585 public function get_defaultsetting() {
4586 global $CFG;
4588 if (during_initial_install()) {
4589 return null;
4591 $result = array();
4592 foreach($this->types as $archetype) {
4593 if ($caproles = get_archetype_roles($archetype)) {
4594 foreach ($caproles as $caprole) {
4595 $result[$caprole->id] = 1;
4599 return $result;
4605 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4609 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4611 * Constructor
4612 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4613 * @param string $visiblename localised
4614 * @param string $description long localised info
4615 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4616 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4617 * @param int $size default field size
4619 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4620 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4621 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4627 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4629 * @copyright 2009 Petr Skoda (http://skodak.org)
4630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4632 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4635 * Constructor
4636 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4637 * @param string $visiblename localised
4638 * @param string $description long localised info
4639 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4640 * @param string $yes value used when checked
4641 * @param string $no value used when not checked
4643 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4644 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4645 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4652 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4654 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4656 * @copyright 2010 Sam Hemelryk
4657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4659 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4661 * Constructor
4662 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4663 * @param string $visiblename localised
4664 * @param string $description long localised info
4665 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4666 * @param string $yes value used when checked
4667 * @param string $no value used when not checked
4669 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4670 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4671 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4678 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4682 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4684 * Calls parent::__construct with specific arguments
4686 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4687 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4688 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4695 * Graded roles in gradebook
4697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4699 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4701 * Calls parent::__construct with specific arguments
4703 public function __construct() {
4704 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4705 get_string('configgradebookroles', 'admin'),
4706 array('student'));
4713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4715 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4717 * Saves the new settings passed in $data
4719 * @param string $data
4720 * @return mixed string or Array
4722 public function write_setting($data) {
4723 global $CFG, $DB;
4725 $oldvalue = $this->config_read($this->name);
4726 $return = parent::write_setting($data);
4727 $newvalue = $this->config_read($this->name);
4729 if ($oldvalue !== $newvalue) {
4730 // force full regrading
4731 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4734 return $return;
4740 * Which roles to show on course description page
4742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4744 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4746 * Calls parent::__construct with specific arguments
4748 public function __construct() {
4749 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4750 get_string('coursecontact_desc', 'admin'),
4751 array('editingteacher'));
4758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4760 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4762 * Calls parent::__construct with specific arguments
4764 function admin_setting_special_gradelimiting() {
4765 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4766 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4770 * Force site regrading
4772 function regrade_all() {
4773 global $CFG;
4774 require_once("$CFG->libdir/gradelib.php");
4775 grade_force_site_regrading();
4779 * Saves the new settings
4781 * @param mixed $data
4782 * @return string empty string or error message
4784 function write_setting($data) {
4785 $previous = $this->get_setting();
4787 if ($previous === null) {
4788 if ($data) {
4789 $this->regrade_all();
4791 } else {
4792 if ($data != $previous) {
4793 $this->regrade_all();
4796 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4803 * Primary grade export plugin - has state tracking.
4805 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4807 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4809 * Calls parent::__construct with specific arguments
4811 public function __construct() {
4812 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4813 get_string('configgradeexport', 'admin'), array(), NULL);
4817 * Load the available choices for the multicheckbox
4819 * @return bool always returns true
4821 public function load_choices() {
4822 if (is_array($this->choices)) {
4823 return true;
4825 $this->choices = array();
4827 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4828 foreach($plugins as $plugin => $unused) {
4829 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4832 return true;
4838 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4842 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4844 * Config gradepointmax constructor
4846 * @param string $name Overidden by "gradepointmax"
4847 * @param string $visiblename Overridden by "gradepointmax" language string.
4848 * @param string $description Overridden by "gradepointmax_help" language string.
4849 * @param string $defaultsetting Not used, overridden by 100.
4850 * @param mixed $paramtype Overridden by PARAM_INT.
4851 * @param int $size Overridden by 5.
4853 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4854 $name = 'gradepointdefault';
4855 $visiblename = get_string('gradepointdefault', 'grades');
4856 $description = get_string('gradepointdefault_help', 'grades');
4857 $defaultsetting = 100;
4858 $paramtype = PARAM_INT;
4859 $size = 5;
4860 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4864 * Validate data before storage
4865 * @param string $data The submitted data
4866 * @return bool|string true if ok, string if error found
4868 public function validate($data) {
4869 global $CFG;
4870 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4871 return true;
4872 } else {
4873 return get_string('gradepointdefault_validateerror', 'grades');
4880 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4884 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4887 * Config gradepointmax constructor
4889 * @param string $name Overidden by "gradepointmax"
4890 * @param string $visiblename Overridden by "gradepointmax" language string.
4891 * @param string $description Overridden by "gradepointmax_help" language string.
4892 * @param string $defaultsetting Not used, overridden by 100.
4893 * @param mixed $paramtype Overridden by PARAM_INT.
4894 * @param int $size Overridden by 5.
4896 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4897 $name = 'gradepointmax';
4898 $visiblename = get_string('gradepointmax', 'grades');
4899 $description = get_string('gradepointmax_help', 'grades');
4900 $defaultsetting = 100;
4901 $paramtype = PARAM_INT;
4902 $size = 5;
4903 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4907 * Save the selected setting
4909 * @param string $data The selected site
4910 * @return string empty string or error message
4912 public function write_setting($data) {
4913 if ($data === '') {
4914 $data = (int)$this->defaultsetting;
4915 } else {
4916 $data = $data;
4918 return parent::write_setting($data);
4922 * Validate data before storage
4923 * @param string $data The submitted data
4924 * @return bool|string true if ok, string if error found
4926 public function validate($data) {
4927 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4928 return true;
4929 } else {
4930 return get_string('gradepointmax_validateerror', 'grades');
4935 * Return an XHTML string for the setting
4936 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4937 * @param string $query search query to be highlighted
4938 * @return string XHTML to display control
4940 public function output_html($data, $query = '') {
4941 $default = $this->get_defaultsetting();
4943 $attr = array(
4944 'type' => 'text',
4945 'size' => $this->size,
4946 'id' => $this->get_id(),
4947 'name' => $this->get_full_name(),
4948 'value' => s($data),
4949 'maxlength' => '5'
4951 $input = html_writer::empty_tag('input', $attr);
4953 $attr = array('class' => 'form-text defaultsnext');
4954 $div = html_writer::tag('div', $input, $attr);
4955 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
4961 * Grade category settings
4963 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4965 class admin_setting_gradecat_combo extends admin_setting {
4966 /** @var array Array of choices */
4967 public $choices;
4970 * Sets choices and calls parent::__construct with passed arguments
4971 * @param string $name
4972 * @param string $visiblename
4973 * @param string $description
4974 * @param mixed $defaultsetting string or array depending on implementation
4975 * @param array $choices An array of choices for the control
4977 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4978 $this->choices = $choices;
4979 parent::__construct($name, $visiblename, $description, $defaultsetting);
4983 * Return the current setting(s) array
4985 * @return array Array of value=>xx, forced=>xx, adv=>xx
4987 public function get_setting() {
4988 global $CFG;
4990 $value = $this->config_read($this->name);
4991 $flag = $this->config_read($this->name.'_flag');
4993 if (is_null($value) or is_null($flag)) {
4994 return NULL;
4997 $flag = (int)$flag;
4998 $forced = (boolean)(1 & $flag); // first bit
4999 $adv = (boolean)(2 & $flag); // second bit
5001 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5005 * Save the new settings passed in $data
5007 * @todo Add vartype handling to ensure $data is array
5008 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5009 * @return string empty or error message
5011 public function write_setting($data) {
5012 global $CFG;
5014 $value = $data['value'];
5015 $forced = empty($data['forced']) ? 0 : 1;
5016 $adv = empty($data['adv']) ? 0 : 2;
5017 $flag = ($forced | $adv); //bitwise or
5019 if (!in_array($value, array_keys($this->choices))) {
5020 return 'Error setting ';
5023 $oldvalue = $this->config_read($this->name);
5024 $oldflag = (int)$this->config_read($this->name.'_flag');
5025 $oldforced = (1 & $oldflag); // first bit
5027 $result1 = $this->config_write($this->name, $value);
5028 $result2 = $this->config_write($this->name.'_flag', $flag);
5030 // force regrade if needed
5031 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5032 require_once($CFG->libdir.'/gradelib.php');
5033 grade_category::updated_forced_settings();
5036 if ($result1 and $result2) {
5037 return '';
5038 } else {
5039 return get_string('errorsetting', 'admin');
5044 * Return XHTML to display the field and wrapping div
5046 * @todo Add vartype handling to ensure $data is array
5047 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5048 * @param string $query
5049 * @return string XHTML to display control
5051 public function output_html($data, $query='') {
5052 $value = $data['value'];
5053 $forced = !empty($data['forced']);
5054 $adv = !empty($data['adv']);
5056 $default = $this->get_defaultsetting();
5057 if (!is_null($default)) {
5058 $defaultinfo = array();
5059 if (isset($this->choices[$default['value']])) {
5060 $defaultinfo[] = $this->choices[$default['value']];
5062 if (!empty($default['forced'])) {
5063 $defaultinfo[] = get_string('force');
5065 if (!empty($default['adv'])) {
5066 $defaultinfo[] = get_string('advanced');
5068 $defaultinfo = implode(', ', $defaultinfo);
5070 } else {
5071 $defaultinfo = NULL;
5075 $return = '<div class="form-group">';
5076 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5077 foreach ($this->choices as $key => $val) {
5078 // the string cast is needed because key may be integer - 0 is equal to most strings!
5079 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5081 $return .= '</select>';
5082 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5083 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5084 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5085 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5086 $return .= '</div>';
5088 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5094 * Selection of grade report in user profiles
5096 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5098 class admin_setting_grade_profilereport extends admin_setting_configselect {
5100 * Calls parent::__construct with specific arguments
5102 public function __construct() {
5103 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5107 * Loads an array of choices for the configselect control
5109 * @return bool always return true
5111 public function load_choices() {
5112 if (is_array($this->choices)) {
5113 return true;
5115 $this->choices = array();
5117 global $CFG;
5118 require_once($CFG->libdir.'/gradelib.php');
5120 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5121 if (file_exists($plugindir.'/lib.php')) {
5122 require_once($plugindir.'/lib.php');
5123 $functionname = 'grade_report_'.$plugin.'_profilereport';
5124 if (function_exists($functionname)) {
5125 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5129 return true;
5135 * Special class for register auth selection
5137 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5139 class admin_setting_special_registerauth extends admin_setting_configselect {
5141 * Calls parent::__construct with specific arguments
5143 public function __construct() {
5144 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5148 * Returns the default option
5150 * @return string empty or default option
5152 public function get_defaultsetting() {
5153 $this->load_choices();
5154 $defaultsetting = parent::get_defaultsetting();
5155 if (array_key_exists($defaultsetting, $this->choices)) {
5156 return $defaultsetting;
5157 } else {
5158 return '';
5163 * Loads the possible choices for the array
5165 * @return bool always returns true
5167 public function load_choices() {
5168 global $CFG;
5170 if (is_array($this->choices)) {
5171 return true;
5173 $this->choices = array();
5174 $this->choices[''] = get_string('disable');
5176 $authsenabled = get_enabled_auth_plugins(true);
5178 foreach ($authsenabled as $auth) {
5179 $authplugin = get_auth_plugin($auth);
5180 if (!$authplugin->can_signup()) {
5181 continue;
5183 // Get the auth title (from core or own auth lang files)
5184 $authtitle = $authplugin->get_title();
5185 $this->choices[$auth] = $authtitle;
5187 return true;
5193 * General plugins manager
5195 class admin_page_pluginsoverview extends admin_externalpage {
5198 * Sets basic information about the external page
5200 public function __construct() {
5201 global $CFG;
5202 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5203 "$CFG->wwwroot/$CFG->admin/plugins.php");
5208 * Module manage page
5210 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5212 class admin_page_managemods extends admin_externalpage {
5214 * Calls parent::__construct with specific arguments
5216 public function __construct() {
5217 global $CFG;
5218 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5222 * Try to find the specified module
5224 * @param string $query The module to search for
5225 * @return array
5227 public function search($query) {
5228 global $CFG, $DB;
5229 if ($result = parent::search($query)) {
5230 return $result;
5233 $found = false;
5234 if ($modules = $DB->get_records('modules')) {
5235 foreach ($modules as $module) {
5236 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5237 continue;
5239 if (strpos($module->name, $query) !== false) {
5240 $found = true;
5241 break;
5243 $strmodulename = get_string('modulename', $module->name);
5244 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5245 $found = true;
5246 break;
5250 if ($found) {
5251 $result = new stdClass();
5252 $result->page = $this;
5253 $result->settings = array();
5254 return array($this->name => $result);
5255 } else {
5256 return array();
5263 * Special class for enrol plugins management.
5265 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5268 class admin_setting_manageenrols extends admin_setting {
5270 * Calls parent::__construct with specific arguments
5272 public function __construct() {
5273 $this->nosave = true;
5274 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5278 * Always returns true, does nothing
5280 * @return true
5282 public function get_setting() {
5283 return true;
5287 * Always returns true, does nothing
5289 * @return true
5291 public function get_defaultsetting() {
5292 return true;
5296 * Always returns '', does not write anything
5298 * @return string Always returns ''
5300 public function write_setting($data) {
5301 // do not write any setting
5302 return '';
5306 * Checks if $query is one of the available enrol plugins
5308 * @param string $query The string to search for
5309 * @return bool Returns true if found, false if not
5311 public function is_related($query) {
5312 if (parent::is_related($query)) {
5313 return true;
5316 $query = core_text::strtolower($query);
5317 $enrols = enrol_get_plugins(false);
5318 foreach ($enrols as $name=>$enrol) {
5319 $localised = get_string('pluginname', 'enrol_'.$name);
5320 if (strpos(core_text::strtolower($name), $query) !== false) {
5321 return true;
5323 if (strpos(core_text::strtolower($localised), $query) !== false) {
5324 return true;
5327 return false;
5331 * Builds the XHTML to display the control
5333 * @param string $data Unused
5334 * @param string $query
5335 * @return string
5337 public function output_html($data, $query='') {
5338 global $CFG, $OUTPUT, $DB, $PAGE;
5340 // Display strings.
5341 $strup = get_string('up');
5342 $strdown = get_string('down');
5343 $strsettings = get_string('settings');
5344 $strenable = get_string('enable');
5345 $strdisable = get_string('disable');
5346 $struninstall = get_string('uninstallplugin', 'core_admin');
5347 $strusage = get_string('enrolusage', 'enrol');
5348 $strversion = get_string('version');
5349 $strtest = get_string('testsettings', 'core_enrol');
5351 $pluginmanager = core_plugin_manager::instance();
5353 $enrols_available = enrol_get_plugins(false);
5354 $active_enrols = enrol_get_plugins(true);
5356 $allenrols = array();
5357 foreach ($active_enrols as $key=>$enrol) {
5358 $allenrols[$key] = true;
5360 foreach ($enrols_available as $key=>$enrol) {
5361 $allenrols[$key] = true;
5363 // Now find all borked plugins and at least allow then to uninstall.
5364 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5365 foreach ($condidates as $candidate) {
5366 if (empty($allenrols[$candidate])) {
5367 $allenrols[$candidate] = true;
5371 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5372 $return .= $OUTPUT->box_start('generalbox enrolsui');
5374 $table = new html_table();
5375 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5376 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5377 $table->id = 'courseenrolmentplugins';
5378 $table->attributes['class'] = 'admintable generaltable';
5379 $table->data = array();
5381 // Iterate through enrol plugins and add to the display table.
5382 $updowncount = 1;
5383 $enrolcount = count($active_enrols);
5384 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5385 $printed = array();
5386 foreach($allenrols as $enrol => $unused) {
5387 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5388 $version = get_config('enrol_'.$enrol, 'version');
5389 if ($version === false) {
5390 $version = '';
5393 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5394 $name = get_string('pluginname', 'enrol_'.$enrol);
5395 } else {
5396 $name = $enrol;
5398 // Usage.
5399 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5400 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5401 $usage = "$ci / $cp";
5403 // Hide/show links.
5404 $class = '';
5405 if (isset($active_enrols[$enrol])) {
5406 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5407 $hideshow = "<a href=\"$aurl\">";
5408 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5409 $enabled = true;
5410 $displayname = $name;
5411 } else if (isset($enrols_available[$enrol])) {
5412 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5413 $hideshow = "<a href=\"$aurl\">";
5414 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5415 $enabled = false;
5416 $displayname = $name;
5417 $class = 'dimmed_text';
5418 } else {
5419 $hideshow = '';
5420 $enabled = false;
5421 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5423 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5424 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5425 } else {
5426 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5429 // Up/down link (only if enrol is enabled).
5430 $updown = '';
5431 if ($enabled) {
5432 if ($updowncount > 1) {
5433 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5434 $updown .= "<a href=\"$aurl\">";
5435 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5436 } else {
5437 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5439 if ($updowncount < $enrolcount) {
5440 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5441 $updown .= "<a href=\"$aurl\">";
5442 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5443 } else {
5444 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5446 ++$updowncount;
5449 // Add settings link.
5450 if (!$version) {
5451 $settings = '';
5452 } else if ($surl = $plugininfo->get_settings_url()) {
5453 $settings = html_writer::link($surl, $strsettings);
5454 } else {
5455 $settings = '';
5458 // Add uninstall info.
5459 $uninstall = '';
5460 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5461 $uninstall = html_writer::link($uninstallurl, $struninstall);
5464 $test = '';
5465 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5466 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5467 $test = html_writer::link($testsettingsurl, $strtest);
5470 // Add a row to the table.
5471 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5472 if ($class) {
5473 $row->attributes['class'] = $class;
5475 $table->data[] = $row;
5477 $printed[$enrol] = true;
5480 $return .= html_writer::table($table);
5481 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5482 $return .= $OUTPUT->box_end();
5483 return highlight($query, $return);
5489 * Blocks manage page
5491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5493 class admin_page_manageblocks extends admin_externalpage {
5495 * Calls parent::__construct with specific arguments
5497 public function __construct() {
5498 global $CFG;
5499 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5503 * Search for a specific block
5505 * @param string $query The string to search for
5506 * @return array
5508 public function search($query) {
5509 global $CFG, $DB;
5510 if ($result = parent::search($query)) {
5511 return $result;
5514 $found = false;
5515 if ($blocks = $DB->get_records('block')) {
5516 foreach ($blocks as $block) {
5517 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5518 continue;
5520 if (strpos($block->name, $query) !== false) {
5521 $found = true;
5522 break;
5524 $strblockname = get_string('pluginname', 'block_'.$block->name);
5525 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5526 $found = true;
5527 break;
5531 if ($found) {
5532 $result = new stdClass();
5533 $result->page = $this;
5534 $result->settings = array();
5535 return array($this->name => $result);
5536 } else {
5537 return array();
5543 * Message outputs configuration
5545 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5547 class admin_page_managemessageoutputs extends admin_externalpage {
5549 * Calls parent::__construct with specific arguments
5551 public function __construct() {
5552 global $CFG;
5553 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5557 * Search for a specific message processor
5559 * @param string $query The string to search for
5560 * @return array
5562 public function search($query) {
5563 global $CFG, $DB;
5564 if ($result = parent::search($query)) {
5565 return $result;
5568 $found = false;
5569 if ($processors = get_message_processors()) {
5570 foreach ($processors as $processor) {
5571 if (!$processor->available) {
5572 continue;
5574 if (strpos($processor->name, $query) !== false) {
5575 $found = true;
5576 break;
5578 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5579 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5580 $found = true;
5581 break;
5585 if ($found) {
5586 $result = new stdClass();
5587 $result->page = $this;
5588 $result->settings = array();
5589 return array($this->name => $result);
5590 } else {
5591 return array();
5597 * Default message outputs configuration
5599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5601 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5603 * Calls parent::__construct with specific arguments
5605 public function __construct() {
5606 global $CFG;
5607 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5613 * Manage question behaviours page
5615 * @copyright 2011 The Open University
5616 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5618 class admin_page_manageqbehaviours extends admin_externalpage {
5620 * Constructor
5622 public function __construct() {
5623 global $CFG;
5624 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5625 new moodle_url('/admin/qbehaviours.php'));
5629 * Search question behaviours for the specified string
5631 * @param string $query The string to search for in question behaviours
5632 * @return array
5634 public function search($query) {
5635 global $CFG;
5636 if ($result = parent::search($query)) {
5637 return $result;
5640 $found = false;
5641 require_once($CFG->dirroot . '/question/engine/lib.php');
5642 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5643 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5644 $query) !== false) {
5645 $found = true;
5646 break;
5649 if ($found) {
5650 $result = new stdClass();
5651 $result->page = $this;
5652 $result->settings = array();
5653 return array($this->name => $result);
5654 } else {
5655 return array();
5662 * Question type manage page
5664 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5666 class admin_page_manageqtypes extends admin_externalpage {
5668 * Calls parent::__construct with specific arguments
5670 public function __construct() {
5671 global $CFG;
5672 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5673 new moodle_url('/admin/qtypes.php'));
5677 * Search question types for the specified string
5679 * @param string $query The string to search for in question types
5680 * @return array
5682 public function search($query) {
5683 global $CFG;
5684 if ($result = parent::search($query)) {
5685 return $result;
5688 $found = false;
5689 require_once($CFG->dirroot . '/question/engine/bank.php');
5690 foreach (question_bank::get_all_qtypes() as $qtype) {
5691 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5692 $found = true;
5693 break;
5696 if ($found) {
5697 $result = new stdClass();
5698 $result->page = $this;
5699 $result->settings = array();
5700 return array($this->name => $result);
5701 } else {
5702 return array();
5708 class admin_page_manageportfolios extends admin_externalpage {
5710 * Calls parent::__construct with specific arguments
5712 public function __construct() {
5713 global $CFG;
5714 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5715 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5719 * Searches page for the specified string.
5720 * @param string $query The string to search for
5721 * @return bool True if it is found on this page
5723 public function search($query) {
5724 global $CFG;
5725 if ($result = parent::search($query)) {
5726 return $result;
5729 $found = false;
5730 $portfolios = core_component::get_plugin_list('portfolio');
5731 foreach ($portfolios as $p => $dir) {
5732 if (strpos($p, $query) !== false) {
5733 $found = true;
5734 break;
5737 if (!$found) {
5738 foreach (portfolio_instances(false, false) as $instance) {
5739 $title = $instance->get('name');
5740 if (strpos(core_text::strtolower($title), $query) !== false) {
5741 $found = true;
5742 break;
5747 if ($found) {
5748 $result = new stdClass();
5749 $result->page = $this;
5750 $result->settings = array();
5751 return array($this->name => $result);
5752 } else {
5753 return array();
5759 class admin_page_managerepositories extends admin_externalpage {
5761 * Calls parent::__construct with specific arguments
5763 public function __construct() {
5764 global $CFG;
5765 parent::__construct('managerepositories', get_string('manage',
5766 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5770 * Searches page for the specified string.
5771 * @param string $query The string to search for
5772 * @return bool True if it is found on this page
5774 public function search($query) {
5775 global $CFG;
5776 if ($result = parent::search($query)) {
5777 return $result;
5780 $found = false;
5781 $repositories= core_component::get_plugin_list('repository');
5782 foreach ($repositories as $p => $dir) {
5783 if (strpos($p, $query) !== false) {
5784 $found = true;
5785 break;
5788 if (!$found) {
5789 foreach (repository::get_types() as $instance) {
5790 $title = $instance->get_typename();
5791 if (strpos(core_text::strtolower($title), $query) !== false) {
5792 $found = true;
5793 break;
5798 if ($found) {
5799 $result = new stdClass();
5800 $result->page = $this;
5801 $result->settings = array();
5802 return array($this->name => $result);
5803 } else {
5804 return array();
5811 * Special class for authentication administration.
5813 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5815 class admin_setting_manageauths extends admin_setting {
5817 * Calls parent::__construct with specific arguments
5819 public function __construct() {
5820 $this->nosave = true;
5821 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5825 * Always returns true
5827 * @return true
5829 public function get_setting() {
5830 return true;
5834 * Always returns true
5836 * @return true
5838 public function get_defaultsetting() {
5839 return true;
5843 * Always returns '' and doesn't write anything
5845 * @return string Always returns ''
5847 public function write_setting($data) {
5848 // do not write any setting
5849 return '';
5853 * Search to find if Query is related to auth plugin
5855 * @param string $query The string to search for
5856 * @return bool true for related false for not
5858 public function is_related($query) {
5859 if (parent::is_related($query)) {
5860 return true;
5863 $authsavailable = core_component::get_plugin_list('auth');
5864 foreach ($authsavailable as $auth => $dir) {
5865 if (strpos($auth, $query) !== false) {
5866 return true;
5868 $authplugin = get_auth_plugin($auth);
5869 $authtitle = $authplugin->get_title();
5870 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5871 return true;
5874 return false;
5878 * Return XHTML to display control
5880 * @param mixed $data Unused
5881 * @param string $query
5882 * @return string highlight
5884 public function output_html($data, $query='') {
5885 global $CFG, $OUTPUT, $DB;
5887 // display strings
5888 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5889 'settings', 'edit', 'name', 'enable', 'disable',
5890 'up', 'down', 'none', 'users'));
5891 $txt->updown = "$txt->up/$txt->down";
5892 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5893 $txt->testsettings = get_string('testsettings', 'core_auth');
5895 $authsavailable = core_component::get_plugin_list('auth');
5896 get_enabled_auth_plugins(true); // fix the list of enabled auths
5897 if (empty($CFG->auth)) {
5898 $authsenabled = array();
5899 } else {
5900 $authsenabled = explode(',', $CFG->auth);
5903 // construct the display array, with enabled auth plugins at the top, in order
5904 $displayauths = array();
5905 $registrationauths = array();
5906 $registrationauths[''] = $txt->disable;
5907 $authplugins = array();
5908 foreach ($authsenabled as $auth) {
5909 $authplugin = get_auth_plugin($auth);
5910 $authplugins[$auth] = $authplugin;
5911 /// Get the auth title (from core or own auth lang files)
5912 $authtitle = $authplugin->get_title();
5913 /// Apply titles
5914 $displayauths[$auth] = $authtitle;
5915 if ($authplugin->can_signup()) {
5916 $registrationauths[$auth] = $authtitle;
5920 foreach ($authsavailable as $auth => $dir) {
5921 if (array_key_exists($auth, $displayauths)) {
5922 continue; //already in the list
5924 $authplugin = get_auth_plugin($auth);
5925 $authplugins[$auth] = $authplugin;
5926 /// Get the auth title (from core or own auth lang files)
5927 $authtitle = $authplugin->get_title();
5928 /// Apply titles
5929 $displayauths[$auth] = $authtitle;
5930 if ($authplugin->can_signup()) {
5931 $registrationauths[$auth] = $authtitle;
5935 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5936 $return .= $OUTPUT->box_start('generalbox authsui');
5938 $table = new html_table();
5939 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5940 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5941 $table->data = array();
5942 $table->attributes['class'] = 'admintable generaltable';
5943 $table->id = 'manageauthtable';
5945 //add always enabled plugins first
5946 $displayname = $displayauths['manual'];
5947 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5948 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5949 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
5950 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5951 $displayname = $displayauths['nologin'];
5952 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5953 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
5954 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5957 // iterate through auth plugins and add to the display table
5958 $updowncount = 1;
5959 $authcount = count($authsenabled);
5960 $url = "auth.php?sesskey=" . sesskey();
5961 foreach ($displayauths as $auth => $name) {
5962 if ($auth == 'manual' or $auth == 'nologin') {
5963 continue;
5965 $class = '';
5966 // hide/show link
5967 if (in_array($auth, $authsenabled)) {
5968 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5969 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5970 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5971 $enabled = true;
5972 $displayname = $name;
5974 else {
5975 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5976 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5977 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5978 $enabled = false;
5979 $displayname = $name;
5980 $class = 'dimmed_text';
5983 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
5985 // up/down link (only if auth is enabled)
5986 $updown = '';
5987 if ($enabled) {
5988 if ($updowncount > 1) {
5989 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5990 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5992 else {
5993 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5995 if ($updowncount < $authcount) {
5996 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5997 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5999 else {
6000 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6002 ++ $updowncount;
6005 // settings link
6006 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6007 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6008 } else {
6009 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6012 // Uninstall link.
6013 $uninstall = '';
6014 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6015 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6018 $test = '';
6019 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6020 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6021 $test = html_writer::link($testurl, $txt->testsettings);
6024 // Add a row to the table.
6025 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6026 if ($class) {
6027 $row->attributes['class'] = $class;
6029 $table->data[] = $row;
6031 $return .= html_writer::table($table);
6032 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6033 $return .= $OUTPUT->box_end();
6034 return highlight($query, $return);
6040 * Special class for authentication administration.
6042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6044 class admin_setting_manageeditors extends admin_setting {
6046 * Calls parent::__construct with specific arguments
6048 public function __construct() {
6049 $this->nosave = true;
6050 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6054 * Always returns true, does nothing
6056 * @return true
6058 public function get_setting() {
6059 return true;
6063 * Always returns true, does nothing
6065 * @return true
6067 public function get_defaultsetting() {
6068 return true;
6072 * Always returns '', does not write anything
6074 * @return string Always returns ''
6076 public function write_setting($data) {
6077 // do not write any setting
6078 return '';
6082 * Checks if $query is one of the available editors
6084 * @param string $query The string to search for
6085 * @return bool Returns true if found, false if not
6087 public function is_related($query) {
6088 if (parent::is_related($query)) {
6089 return true;
6092 $editors_available = editors_get_available();
6093 foreach ($editors_available as $editor=>$editorstr) {
6094 if (strpos($editor, $query) !== false) {
6095 return true;
6097 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6098 return true;
6101 return false;
6105 * Builds the XHTML to display the control
6107 * @param string $data Unused
6108 * @param string $query
6109 * @return string
6111 public function output_html($data, $query='') {
6112 global $CFG, $OUTPUT;
6114 // display strings
6115 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6116 'up', 'down', 'none'));
6117 $struninstall = get_string('uninstallplugin', 'core_admin');
6119 $txt->updown = "$txt->up/$txt->down";
6121 $editors_available = editors_get_available();
6122 $active_editors = explode(',', $CFG->texteditors);
6124 $active_editors = array_reverse($active_editors);
6125 foreach ($active_editors as $key=>$editor) {
6126 if (empty($editors_available[$editor])) {
6127 unset($active_editors[$key]);
6128 } else {
6129 $name = $editors_available[$editor];
6130 unset($editors_available[$editor]);
6131 $editors_available[$editor] = $name;
6134 if (empty($active_editors)) {
6135 //$active_editors = array('textarea');
6137 $editors_available = array_reverse($editors_available, true);
6138 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6139 $return .= $OUTPUT->box_start('generalbox editorsui');
6141 $table = new html_table();
6142 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6143 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6144 $table->id = 'editormanagement';
6145 $table->attributes['class'] = 'admintable generaltable';
6146 $table->data = array();
6148 // iterate through auth plugins and add to the display table
6149 $updowncount = 1;
6150 $editorcount = count($active_editors);
6151 $url = "editors.php?sesskey=" . sesskey();
6152 foreach ($editors_available as $editor => $name) {
6153 // hide/show link
6154 $class = '';
6155 if (in_array($editor, $active_editors)) {
6156 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6157 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6158 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6159 $enabled = true;
6160 $displayname = $name;
6162 else {
6163 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6164 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6165 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6166 $enabled = false;
6167 $displayname = $name;
6168 $class = 'dimmed_text';
6171 // up/down link (only if auth is enabled)
6172 $updown = '';
6173 if ($enabled) {
6174 if ($updowncount > 1) {
6175 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6176 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6178 else {
6179 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6181 if ($updowncount < $editorcount) {
6182 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6183 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6185 else {
6186 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6188 ++ $updowncount;
6191 // settings link
6192 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6193 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6194 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6195 } else {
6196 $settings = '';
6199 $uninstall = '';
6200 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6201 $uninstall = html_writer::link($uninstallurl, $struninstall);
6204 // Add a row to the table.
6205 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6206 if ($class) {
6207 $row->attributes['class'] = $class;
6209 $table->data[] = $row;
6211 $return .= html_writer::table($table);
6212 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6213 $return .= $OUTPUT->box_end();
6214 return highlight($query, $return);
6220 * Special class for license administration.
6222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6224 class admin_setting_managelicenses extends admin_setting {
6226 * Calls parent::__construct with specific arguments
6228 public function __construct() {
6229 $this->nosave = true;
6230 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6234 * Always returns true, does nothing
6236 * @return true
6238 public function get_setting() {
6239 return true;
6243 * Always returns true, does nothing
6245 * @return true
6247 public function get_defaultsetting() {
6248 return true;
6252 * Always returns '', does not write anything
6254 * @return string Always returns ''
6256 public function write_setting($data) {
6257 // do not write any setting
6258 return '';
6262 * Builds the XHTML to display the control
6264 * @param string $data Unused
6265 * @param string $query
6266 * @return string
6268 public function output_html($data, $query='') {
6269 global $CFG, $OUTPUT;
6270 require_once($CFG->libdir . '/licenselib.php');
6271 $url = "licenses.php?sesskey=" . sesskey();
6273 // display strings
6274 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6275 $licenses = license_manager::get_licenses();
6277 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6279 $return .= $OUTPUT->box_start('generalbox editorsui');
6281 $table = new html_table();
6282 $table->head = array($txt->name, $txt->enable);
6283 $table->colclasses = array('leftalign', 'centeralign');
6284 $table->id = 'availablelicenses';
6285 $table->attributes['class'] = 'admintable generaltable';
6286 $table->data = array();
6288 foreach ($licenses as $value) {
6289 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6291 if ($value->enabled == 1) {
6292 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6293 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6294 } else {
6295 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6296 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6299 if ($value->shortname == $CFG->sitedefaultlicense) {
6300 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6301 $hideshow = '';
6304 $enabled = true;
6306 $table->data[] =array($displayname, $hideshow);
6308 $return .= html_writer::table($table);
6309 $return .= $OUTPUT->box_end();
6310 return highlight($query, $return);
6315 * Course formats manager. Allows to enable/disable formats and jump to settings
6317 class admin_setting_manageformats extends admin_setting {
6320 * Calls parent::__construct with specific arguments
6322 public function __construct() {
6323 $this->nosave = true;
6324 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6328 * Always returns true
6330 * @return true
6332 public function get_setting() {
6333 return true;
6337 * Always returns true
6339 * @return true
6341 public function get_defaultsetting() {
6342 return true;
6346 * Always returns '' and doesn't write anything
6348 * @param mixed $data string or array, must not be NULL
6349 * @return string Always returns ''
6351 public function write_setting($data) {
6352 // do not write any setting
6353 return '';
6357 * Search to find if Query is related to format plugin
6359 * @param string $query The string to search for
6360 * @return bool true for related false for not
6362 public function is_related($query) {
6363 if (parent::is_related($query)) {
6364 return true;
6366 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6367 foreach ($formats as $format) {
6368 if (strpos($format->component, $query) !== false ||
6369 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6370 return true;
6373 return false;
6377 * Return XHTML to display control
6379 * @param mixed $data Unused
6380 * @param string $query
6381 * @return string highlight
6383 public function output_html($data, $query='') {
6384 global $CFG, $OUTPUT;
6385 $return = '';
6386 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6387 $return .= $OUTPUT->box_start('generalbox formatsui');
6389 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6391 // display strings
6392 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6393 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6394 $txt->updown = "$txt->up/$txt->down";
6396 $table = new html_table();
6397 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6398 $table->align = array('left', 'center', 'center', 'center', 'center');
6399 $table->attributes['class'] = 'manageformattable generaltable admintable';
6400 $table->data = array();
6402 $cnt = 0;
6403 $defaultformat = get_config('moodlecourse', 'format');
6404 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6405 foreach ($formats as $format) {
6406 $url = new moodle_url('/admin/courseformats.php',
6407 array('sesskey' => sesskey(), 'format' => $format->name));
6408 $isdefault = '';
6409 $class = '';
6410 if ($format->is_enabled()) {
6411 $strformatname = $format->displayname;
6412 if ($defaultformat === $format->name) {
6413 $hideshow = $txt->default;
6414 } else {
6415 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6416 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6418 } else {
6419 $strformatname = $format->displayname;
6420 $class = 'dimmed_text';
6421 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6422 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6424 $updown = '';
6425 if ($cnt) {
6426 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6427 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6428 } else {
6429 $updown .= $spacer;
6431 if ($cnt < count($formats) - 1) {
6432 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6433 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6434 } else {
6435 $updown .= $spacer;
6437 $cnt++;
6438 $settings = '';
6439 if ($format->get_settings_url()) {
6440 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6442 $uninstall = '';
6443 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6444 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6446 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6447 if ($class) {
6448 $row->attributes['class'] = $class;
6450 $table->data[] = $row;
6452 $return .= html_writer::table($table);
6453 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6454 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6455 $return .= $OUTPUT->box_end();
6456 return highlight($query, $return);
6461 * Special class for filter administration.
6463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6465 class admin_page_managefilters extends admin_externalpage {
6467 * Calls parent::__construct with specific arguments
6469 public function __construct() {
6470 global $CFG;
6471 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6475 * Searches all installed filters for specified filter
6477 * @param string $query The filter(string) to search for
6478 * @param string $query
6480 public function search($query) {
6481 global $CFG;
6482 if ($result = parent::search($query)) {
6483 return $result;
6486 $found = false;
6487 $filternames = filter_get_all_installed();
6488 foreach ($filternames as $path => $strfiltername) {
6489 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6490 $found = true;
6491 break;
6493 if (strpos($path, $query) !== false) {
6494 $found = true;
6495 break;
6499 if ($found) {
6500 $result = new stdClass;
6501 $result->page = $this;
6502 $result->settings = array();
6503 return array($this->name => $result);
6504 } else {
6505 return array();
6512 * Initialise admin page - this function does require login and permission
6513 * checks specified in page definition.
6515 * This function must be called on each admin page before other code.
6517 * @global moodle_page $PAGE
6519 * @param string $section name of page
6520 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6521 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6522 * added to the turn blocks editing on/off form, so this page reloads correctly.
6523 * @param string $actualurl if the actual page being viewed is not the normal one for this
6524 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6525 * @param array $options Additional options that can be specified for page setup.
6526 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6528 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6529 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6531 $PAGE->set_context(null); // hack - set context to something, by default to system context
6533 $site = get_site();
6534 require_login();
6536 if (!empty($options['pagelayout'])) {
6537 // A specific page layout has been requested.
6538 $PAGE->set_pagelayout($options['pagelayout']);
6539 } else if ($section === 'upgradesettings') {
6540 $PAGE->set_pagelayout('maintenance');
6541 } else {
6542 $PAGE->set_pagelayout('admin');
6545 $adminroot = admin_get_root(false, false); // settings not required for external pages
6546 $extpage = $adminroot->locate($section, true);
6548 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6549 // The requested section isn't in the admin tree
6550 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6551 if (!has_capability('moodle/site:config', context_system::instance())) {
6552 // The requested section could depend on a different capability
6553 // but most likely the user has inadequate capabilities
6554 print_error('accessdenied', 'admin');
6555 } else {
6556 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6560 // this eliminates our need to authenticate on the actual pages
6561 if (!$extpage->check_access()) {
6562 print_error('accessdenied', 'admin');
6563 die;
6566 navigation_node::require_admin_tree();
6568 // $PAGE->set_extra_button($extrabutton); TODO
6570 if (!$actualurl) {
6571 $actualurl = $extpage->url;
6574 $PAGE->set_url($actualurl, $extraurlparams);
6575 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6576 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6579 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6580 // During initial install.
6581 $strinstallation = get_string('installation', 'install');
6582 $strsettings = get_string('settings');
6583 $PAGE->navbar->add($strsettings);
6584 $PAGE->set_title($strinstallation);
6585 $PAGE->set_heading($strinstallation);
6586 $PAGE->set_cacheable(false);
6587 return;
6590 // Locate the current item on the navigation and make it active when found.
6591 $path = $extpage->path;
6592 $node = $PAGE->settingsnav;
6593 while ($node && count($path) > 0) {
6594 $node = $node->get(array_pop($path));
6596 if ($node) {
6597 $node->make_active();
6600 // Normal case.
6601 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6602 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6603 $USER->editing = $adminediting;
6606 $visiblepathtosection = array_reverse($extpage->visiblepath);
6608 if ($PAGE->user_allowed_editing()) {
6609 if ($PAGE->user_is_editing()) {
6610 $caption = get_string('blockseditoff');
6611 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6612 } else {
6613 $caption = get_string('blocksediton');
6614 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6616 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6619 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6620 $PAGE->set_heading($SITE->fullname);
6622 // prevent caching in nav block
6623 $PAGE->navigation->clear_cache();
6627 * Returns the reference to admin tree root
6629 * @return object admin_root object
6631 function admin_get_root($reload=false, $requirefulltree=true) {
6632 global $CFG, $DB, $OUTPUT;
6634 static $ADMIN = NULL;
6636 if (is_null($ADMIN)) {
6637 // create the admin tree!
6638 $ADMIN = new admin_root($requirefulltree);
6641 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6642 $ADMIN->purge_children($requirefulltree);
6645 if (!$ADMIN->loaded) {
6646 // we process this file first to create categories first and in correct order
6647 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6649 // now we process all other files in admin/settings to build the admin tree
6650 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6651 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6652 continue;
6654 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6655 // plugins are loaded last - they may insert pages anywhere
6656 continue;
6658 require($file);
6660 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6662 $ADMIN->loaded = true;
6665 return $ADMIN;
6668 /// settings utility functions
6671 * This function applies default settings.
6673 * @param object $node, NULL means complete tree, null by default
6674 * @param bool $unconditional if true overrides all values with defaults, null buy default
6676 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6677 global $CFG;
6679 if (is_null($node)) {
6680 core_plugin_manager::reset_caches();
6681 $node = admin_get_root(true, true);
6684 if ($node instanceof admin_category) {
6685 $entries = array_keys($node->children);
6686 foreach ($entries as $entry) {
6687 admin_apply_default_settings($node->children[$entry], $unconditional);
6690 } else if ($node instanceof admin_settingpage) {
6691 foreach ($node->settings as $setting) {
6692 if (!$unconditional and !is_null($setting->get_setting())) {
6693 //do not override existing defaults
6694 continue;
6696 $defaultsetting = $setting->get_defaultsetting();
6697 if (is_null($defaultsetting)) {
6698 // no value yet - default maybe applied after admin user creation or in upgradesettings
6699 continue;
6701 $setting->write_setting($defaultsetting);
6702 $setting->write_setting_flags(null);
6705 // Just in case somebody modifies the list of active plugins directly.
6706 core_plugin_manager::reset_caches();
6710 * Store changed settings, this function updates the errors variable in $ADMIN
6712 * @param object $formdata from form
6713 * @return int number of changed settings
6715 function admin_write_settings($formdata) {
6716 global $CFG, $SITE, $DB;
6718 $olddbsessions = !empty($CFG->dbsessions);
6719 $formdata = (array)$formdata;
6721 $data = array();
6722 foreach ($formdata as $fullname=>$value) {
6723 if (strpos($fullname, 's_') !== 0) {
6724 continue; // not a config value
6726 $data[$fullname] = $value;
6729 $adminroot = admin_get_root();
6730 $settings = admin_find_write_settings($adminroot, $data);
6732 $count = 0;
6733 foreach ($settings as $fullname=>$setting) {
6734 /** @var $setting admin_setting */
6735 $original = $setting->get_setting();
6736 $error = $setting->write_setting($data[$fullname]);
6737 if ($error !== '') {
6738 $adminroot->errors[$fullname] = new stdClass();
6739 $adminroot->errors[$fullname]->data = $data[$fullname];
6740 $adminroot->errors[$fullname]->id = $setting->get_id();
6741 $adminroot->errors[$fullname]->error = $error;
6742 } else {
6743 $setting->write_setting_flags($data);
6745 if ($setting->post_write_settings($original)) {
6746 $count++;
6750 if ($olddbsessions != !empty($CFG->dbsessions)) {
6751 require_logout();
6754 // Now update $SITE - just update the fields, in case other people have a
6755 // a reference to it (e.g. $PAGE, $COURSE).
6756 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6757 foreach (get_object_vars($newsite) as $field => $value) {
6758 $SITE->$field = $value;
6761 // now reload all settings - some of them might depend on the changed
6762 admin_get_root(true);
6763 return $count;
6767 * Internal recursive function - finds all settings from submitted form
6769 * @param object $node Instance of admin_category, or admin_settingpage
6770 * @param array $data
6771 * @return array
6773 function admin_find_write_settings($node, $data) {
6774 $return = array();
6776 if (empty($data)) {
6777 return $return;
6780 if ($node instanceof admin_category) {
6781 $entries = array_keys($node->children);
6782 foreach ($entries as $entry) {
6783 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6786 } else if ($node instanceof admin_settingpage) {
6787 foreach ($node->settings as $setting) {
6788 $fullname = $setting->get_full_name();
6789 if (array_key_exists($fullname, $data)) {
6790 $return[$fullname] = $setting;
6796 return $return;
6800 * Internal function - prints the search results
6802 * @param string $query String to search for
6803 * @return string empty or XHTML
6805 function admin_search_settings_html($query) {
6806 global $CFG, $OUTPUT;
6808 if (core_text::strlen($query) < 2) {
6809 return '';
6811 $query = core_text::strtolower($query);
6813 $adminroot = admin_get_root();
6814 $findings = $adminroot->search($query);
6815 $return = '';
6816 $savebutton = false;
6818 foreach ($findings as $found) {
6819 $page = $found->page;
6820 $settings = $found->settings;
6821 if ($page->is_hidden()) {
6822 // hidden pages are not displayed in search results
6823 continue;
6825 if ($page instanceof admin_externalpage) {
6826 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6827 } else if ($page instanceof admin_settingpage) {
6828 $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');
6829 } else {
6830 continue;
6832 if (!empty($settings)) {
6833 $return .= '<fieldset class="adminsettings">'."\n";
6834 foreach ($settings as $setting) {
6835 if (empty($setting->nosave)) {
6836 $savebutton = true;
6838 $return .= '<div class="clearer"><!-- --></div>'."\n";
6839 $fullname = $setting->get_full_name();
6840 if (array_key_exists($fullname, $adminroot->errors)) {
6841 $data = $adminroot->errors[$fullname]->data;
6842 } else {
6843 $data = $setting->get_setting();
6844 // do not use defaults if settings not available - upgradesettings handles the defaults!
6846 $return .= $setting->output_html($data, $query);
6848 $return .= '</fieldset>';
6852 if ($savebutton) {
6853 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6856 return $return;
6860 * Internal function - returns arrays of html pages with uninitialised settings
6862 * @param object $node Instance of admin_category or admin_settingpage
6863 * @return array
6865 function admin_output_new_settings_by_page($node) {
6866 global $OUTPUT;
6867 $return = array();
6869 if ($node instanceof admin_category) {
6870 $entries = array_keys($node->children);
6871 foreach ($entries as $entry) {
6872 $return += admin_output_new_settings_by_page($node->children[$entry]);
6875 } else if ($node instanceof admin_settingpage) {
6876 $newsettings = array();
6877 foreach ($node->settings as $setting) {
6878 if (is_null($setting->get_setting())) {
6879 $newsettings[] = $setting;
6882 if (count($newsettings) > 0) {
6883 $adminroot = admin_get_root();
6884 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6885 $page .= '<fieldset class="adminsettings">'."\n";
6886 foreach ($newsettings as $setting) {
6887 $fullname = $setting->get_full_name();
6888 if (array_key_exists($fullname, $adminroot->errors)) {
6889 $data = $adminroot->errors[$fullname]->data;
6890 } else {
6891 $data = $setting->get_setting();
6892 if (is_null($data)) {
6893 $data = $setting->get_defaultsetting();
6896 $page .= '<div class="clearer"><!-- --></div>'."\n";
6897 $page .= $setting->output_html($data);
6899 $page .= '</fieldset>';
6900 $return[$node->name] = $page;
6904 return $return;
6908 * Format admin settings
6910 * @param object $setting
6911 * @param string $title label element
6912 * @param string $form form fragment, html code - not highlighted automatically
6913 * @param string $description
6914 * @param bool $label link label to id, true by default
6915 * @param string $warning warning text
6916 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6917 * @param string $query search query to be highlighted
6918 * @return string XHTML
6920 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6921 global $CFG;
6923 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6924 $fullname = $setting->get_full_name();
6926 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6927 if ($label) {
6928 $labelfor = 'for = "'.$setting->get_id().'"';
6929 } else {
6930 $labelfor = '';
6932 $form .= $setting->output_setting_flags();
6934 $override = '';
6935 if (empty($setting->plugin)) {
6936 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6937 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6939 } else {
6940 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6941 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6945 if ($warning !== '') {
6946 $warning = '<div class="form-warning">'.$warning.'</div>';
6949 $defaults = array();
6950 if (!is_null($defaultinfo)) {
6951 if ($defaultinfo === '') {
6952 $defaultinfo = get_string('emptysettingvalue', 'admin');
6954 $defaults[] = $defaultinfo;
6957 $setting->get_setting_flag_defaults($defaults);
6959 if (!empty($defaults)) {
6960 $defaultinfo = implode(', ', $defaults);
6961 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6962 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6966 $adminroot = admin_get_root();
6967 $error = '';
6968 if (array_key_exists($fullname, $adminroot->errors)) {
6969 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
6972 $str = '
6973 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6974 <div class="form-label">
6975 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6976 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6977 </div>
6978 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
6979 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6980 </div>';
6982 return $str;
6986 * Based on find_new_settings{@link ()} in upgradesettings.php
6987 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6989 * @param object $node Instance of admin_category, or admin_settingpage
6990 * @return boolean true if any settings haven't been initialised, false if they all have
6992 function any_new_admin_settings($node) {
6994 if ($node instanceof admin_category) {
6995 $entries = array_keys($node->children);
6996 foreach ($entries as $entry) {
6997 if (any_new_admin_settings($node->children[$entry])) {
6998 return true;
7002 } else if ($node instanceof admin_settingpage) {
7003 foreach ($node->settings as $setting) {
7004 if ($setting->get_setting() === NULL) {
7005 return true;
7010 return false;
7014 * Moved from admin/replace.php so that we can use this in cron
7016 * @param string $search string to look for
7017 * @param string $replace string to replace
7018 * @return bool success or fail
7020 function db_replace($search, $replace) {
7021 global $DB, $CFG, $OUTPUT;
7023 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7024 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7025 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7026 'block_instances', '');
7028 // Turn off time limits, sometimes upgrades can be slow.
7029 core_php_time_limit::raise();
7031 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7032 return false;
7034 foreach ($tables as $table) {
7036 if (in_array($table, $skiptables)) { // Don't process these
7037 continue;
7040 if ($columns = $DB->get_columns($table)) {
7041 $DB->set_debug(true);
7042 foreach ($columns as $column) {
7043 $DB->replace_all_text($table, $column, $search, $replace);
7045 $DB->set_debug(false);
7049 // delete modinfo caches
7050 rebuild_course_cache(0, true);
7052 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7053 $blocks = core_component::get_plugin_list('block');
7054 foreach ($blocks as $blockname=>$fullblock) {
7055 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7056 continue;
7059 if (!is_readable($fullblock.'/lib.php')) {
7060 continue;
7063 $function = 'block_'.$blockname.'_global_db_replace';
7064 include_once($fullblock.'/lib.php');
7065 if (!function_exists($function)) {
7066 continue;
7069 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7070 $function($search, $replace);
7071 echo $OUTPUT->notification("...finished", 'notifysuccess');
7074 purge_all_caches();
7076 return true;
7080 * Manage repository settings
7082 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7084 class admin_setting_managerepository extends admin_setting {
7085 /** @var string */
7086 private $baseurl;
7089 * calls parent::__construct with specific arguments
7091 public function __construct() {
7092 global $CFG;
7093 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7094 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7098 * Always returns true, does nothing
7100 * @return true
7102 public function get_setting() {
7103 return true;
7107 * Always returns true does nothing
7109 * @return true
7111 public function get_defaultsetting() {
7112 return true;
7116 * Always returns s_managerepository
7118 * @return string Always return 's_managerepository'
7120 public function get_full_name() {
7121 return 's_managerepository';
7125 * Always returns '' doesn't do anything
7127 public function write_setting($data) {
7128 $url = $this->baseurl . '&amp;new=' . $data;
7129 return '';
7130 // TODO
7131 // Should not use redirect and exit here
7132 // Find a better way to do this.
7133 // redirect($url);
7134 // exit;
7138 * Searches repository plugins for one that matches $query
7140 * @param string $query The string to search for
7141 * @return bool true if found, false if not
7143 public function is_related($query) {
7144 if (parent::is_related($query)) {
7145 return true;
7148 $repositories= core_component::get_plugin_list('repository');
7149 foreach ($repositories as $p => $dir) {
7150 if (strpos($p, $query) !== false) {
7151 return true;
7154 foreach (repository::get_types() as $instance) {
7155 $title = $instance->get_typename();
7156 if (strpos(core_text::strtolower($title), $query) !== false) {
7157 return true;
7160 return false;
7164 * Helper function that generates a moodle_url object
7165 * relevant to the repository
7168 function repository_action_url($repository) {
7169 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7173 * Builds XHTML to display the control
7175 * @param string $data Unused
7176 * @param string $query
7177 * @return string XHTML
7179 public function output_html($data, $query='') {
7180 global $CFG, $USER, $OUTPUT;
7182 // Get strings that are used
7183 $strshow = get_string('on', 'repository');
7184 $strhide = get_string('off', 'repository');
7185 $strdelete = get_string('disabled', 'repository');
7187 $actionchoicesforexisting = array(
7188 'show' => $strshow,
7189 'hide' => $strhide,
7190 'delete' => $strdelete
7193 $actionchoicesfornew = array(
7194 'newon' => $strshow,
7195 'newoff' => $strhide,
7196 'delete' => $strdelete
7199 $return = '';
7200 $return .= $OUTPUT->box_start('generalbox');
7202 // Set strings that are used multiple times
7203 $settingsstr = get_string('settings');
7204 $disablestr = get_string('disable');
7206 // Table to list plug-ins
7207 $table = new html_table();
7208 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7209 $table->align = array('left', 'center', 'center', 'center', 'center');
7210 $table->data = array();
7212 // Get list of used plug-ins
7213 $repositorytypes = repository::get_types();
7214 if (!empty($repositorytypes)) {
7215 // Array to store plugins being used
7216 $alreadyplugins = array();
7217 $totalrepositorytypes = count($repositorytypes);
7218 $updowncount = 1;
7219 foreach ($repositorytypes as $i) {
7220 $settings = '';
7221 $typename = $i->get_typename();
7222 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7223 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7224 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7226 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7227 // Calculate number of instances in order to display them for the Moodle administrator
7228 if (!empty($instanceoptionnames)) {
7229 $params = array();
7230 $params['context'] = array(context_system::instance());
7231 $params['onlyvisible'] = false;
7232 $params['type'] = $typename;
7233 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7234 // site instances
7235 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7236 $params['context'] = array();
7237 $instances = repository::static_function($typename, 'get_instances', $params);
7238 $courseinstances = array();
7239 $userinstances = array();
7241 foreach ($instances as $instance) {
7242 $repocontext = context::instance_by_id($instance->instance->contextid);
7243 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7244 $courseinstances[] = $instance;
7245 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7246 $userinstances[] = $instance;
7249 // course instances
7250 $instancenumber = count($courseinstances);
7251 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7253 // user private instances
7254 $instancenumber = count($userinstances);
7255 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7256 } else {
7257 $admininstancenumbertext = "";
7258 $courseinstancenumbertext = "";
7259 $userinstancenumbertext = "";
7262 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7264 $settings .= $OUTPUT->container_start('mdl-left');
7265 $settings .= '<br/>';
7266 $settings .= $admininstancenumbertext;
7267 $settings .= '<br/>';
7268 $settings .= $courseinstancenumbertext;
7269 $settings .= '<br/>';
7270 $settings .= $userinstancenumbertext;
7271 $settings .= $OUTPUT->container_end();
7273 // Get the current visibility
7274 if ($i->get_visible()) {
7275 $currentaction = 'show';
7276 } else {
7277 $currentaction = 'hide';
7280 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7282 // Display up/down link
7283 $updown = '';
7284 // Should be done with CSS instead.
7285 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7287 if ($updowncount > 1) {
7288 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7289 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7291 else {
7292 $updown .= $spacer;
7294 if ($updowncount < $totalrepositorytypes) {
7295 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7296 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7298 else {
7299 $updown .= $spacer;
7302 $updowncount++;
7304 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7306 if (!in_array($typename, $alreadyplugins)) {
7307 $alreadyplugins[] = $typename;
7312 // Get all the plugins that exist on disk
7313 $plugins = core_component::get_plugin_list('repository');
7314 if (!empty($plugins)) {
7315 foreach ($plugins as $plugin => $dir) {
7316 // Check that it has not already been listed
7317 if (!in_array($plugin, $alreadyplugins)) {
7318 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7319 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7324 $return .= html_writer::table($table);
7325 $return .= $OUTPUT->box_end();
7326 return highlight($query, $return);
7331 * Special checkbox for enable mobile web service
7332 * If enable then we store the service id of the mobile service into config table
7333 * If disable then we unstore the service id from the config table
7335 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7337 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7338 private $xmlrpcuse;
7339 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7340 private $restuse;
7343 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7345 * @return boolean
7347 private function is_protocol_cap_allowed() {
7348 global $DB, $CFG;
7350 // We keep xmlrpc enabled for backward compatibility.
7351 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7352 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7353 $params = array();
7354 $params['permission'] = CAP_ALLOW;
7355 $params['roleid'] = $CFG->defaultuserroleid;
7356 $params['capability'] = 'webservice/xmlrpc:use';
7357 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7360 // If the $this->restuse variable is not set, it needs to be set.
7361 if (empty($this->restuse) and $this->restuse!==false) {
7362 $params = array();
7363 $params['permission'] = CAP_ALLOW;
7364 $params['roleid'] = $CFG->defaultuserroleid;
7365 $params['capability'] = 'webservice/rest:use';
7366 $this->restuse = $DB->record_exists('role_capabilities', $params);
7369 return ($this->xmlrpcuse && $this->restuse);
7373 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7374 * @param type $status true to allow, false to not set
7376 private function set_protocol_cap($status) {
7377 global $CFG;
7378 if ($status and !$this->is_protocol_cap_allowed()) {
7379 //need to allow the cap
7380 $permission = CAP_ALLOW;
7381 $assign = true;
7382 } else if (!$status and $this->is_protocol_cap_allowed()){
7383 //need to disallow the cap
7384 $permission = CAP_INHERIT;
7385 $assign = true;
7387 if (!empty($assign)) {
7388 $systemcontext = context_system::instance();
7389 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7390 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7395 * Builds XHTML to display the control.
7396 * The main purpose of this overloading is to display a warning when https
7397 * is not supported by the server
7398 * @param string $data Unused
7399 * @param string $query
7400 * @return string XHTML
7402 public function output_html($data, $query='') {
7403 global $CFG, $OUTPUT;
7404 $html = parent::output_html($data, $query);
7406 if ((string)$data === $this->yes) {
7407 require_once($CFG->dirroot . "/lib/filelib.php");
7408 $curl = new curl();
7409 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7410 $curl->head($httpswwwroot . "/login/index.php");
7411 $info = $curl->get_info();
7412 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7413 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7417 return $html;
7421 * Retrieves the current setting using the objects name
7423 * @return string
7425 public function get_setting() {
7426 global $CFG;
7428 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7429 // Or if web services aren't enabled this can't be,
7430 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7431 return 0;
7434 require_once($CFG->dirroot . '/webservice/lib.php');
7435 $webservicemanager = new webservice();
7436 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7437 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7438 return $this->config_read($this->name); //same as returning 1
7439 } else {
7440 return 0;
7445 * Save the selected setting
7447 * @param string $data The selected site
7448 * @return string empty string or error message
7450 public function write_setting($data) {
7451 global $DB, $CFG;
7453 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7454 if (empty($CFG->defaultuserroleid)) {
7455 return '';
7458 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7460 require_once($CFG->dirroot . '/webservice/lib.php');
7461 $webservicemanager = new webservice();
7463 $updateprotocol = false;
7464 if ((string)$data === $this->yes) {
7465 //code run when enable mobile web service
7466 //enable web service systeme if necessary
7467 set_config('enablewebservices', true);
7469 //enable mobile service
7470 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7471 $mobileservice->enabled = 1;
7472 $webservicemanager->update_external_service($mobileservice);
7474 //enable xml-rpc server
7475 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7477 if (!in_array('xmlrpc', $activeprotocols)) {
7478 $activeprotocols[] = 'xmlrpc';
7479 $updateprotocol = true;
7482 if (!in_array('rest', $activeprotocols)) {
7483 $activeprotocols[] = 'rest';
7484 $updateprotocol = true;
7487 if ($updateprotocol) {
7488 set_config('webserviceprotocols', implode(',', $activeprotocols));
7491 //allow xml-rpc:use capability for authenticated user
7492 $this->set_protocol_cap(true);
7494 } else {
7495 //disable web service system if no other services are enabled
7496 $otherenabledservices = $DB->get_records_select('external_services',
7497 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7498 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7499 if (empty($otherenabledservices)) {
7500 set_config('enablewebservices', false);
7502 //also disable xml-rpc server
7503 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7504 $protocolkey = array_search('xmlrpc', $activeprotocols);
7505 if ($protocolkey !== false) {
7506 unset($activeprotocols[$protocolkey]);
7507 $updateprotocol = true;
7510 $protocolkey = array_search('rest', $activeprotocols);
7511 if ($protocolkey !== false) {
7512 unset($activeprotocols[$protocolkey]);
7513 $updateprotocol = true;
7516 if ($updateprotocol) {
7517 set_config('webserviceprotocols', implode(',', $activeprotocols));
7520 //disallow xml-rpc:use capability for authenticated user
7521 $this->set_protocol_cap(false);
7524 //disable the mobile service
7525 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7526 $mobileservice->enabled = 0;
7527 $webservicemanager->update_external_service($mobileservice);
7530 return (parent::write_setting($data));
7535 * Special class for management of external services
7537 * @author Petr Skoda (skodak)
7539 class admin_setting_manageexternalservices extends admin_setting {
7541 * Calls parent::__construct with specific arguments
7543 public function __construct() {
7544 $this->nosave = true;
7545 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7549 * Always returns true, does nothing
7551 * @return true
7553 public function get_setting() {
7554 return true;
7558 * Always returns true, does nothing
7560 * @return true
7562 public function get_defaultsetting() {
7563 return true;
7567 * Always returns '', does not write anything
7569 * @return string Always returns ''
7571 public function write_setting($data) {
7572 // do not write any setting
7573 return '';
7577 * Checks if $query is one of the available external services
7579 * @param string $query The string to search for
7580 * @return bool Returns true if found, false if not
7582 public function is_related($query) {
7583 global $DB;
7585 if (parent::is_related($query)) {
7586 return true;
7589 $services = $DB->get_records('external_services', array(), 'id, name');
7590 foreach ($services as $service) {
7591 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7592 return true;
7595 return false;
7599 * Builds the XHTML to display the control
7601 * @param string $data Unused
7602 * @param string $query
7603 * @return string
7605 public function output_html($data, $query='') {
7606 global $CFG, $OUTPUT, $DB;
7608 // display strings
7609 $stradministration = get_string('administration');
7610 $stredit = get_string('edit');
7611 $strservice = get_string('externalservice', 'webservice');
7612 $strdelete = get_string('delete');
7613 $strplugin = get_string('plugin', 'admin');
7614 $stradd = get_string('add');
7615 $strfunctions = get_string('functions', 'webservice');
7616 $strusers = get_string('users');
7617 $strserviceusers = get_string('serviceusers', 'webservice');
7619 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7620 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7621 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7623 // built in services
7624 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7625 $return = "";
7626 if (!empty($services)) {
7627 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7631 $table = new html_table();
7632 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7633 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7634 $table->id = 'builtinservices';
7635 $table->attributes['class'] = 'admintable externalservices generaltable';
7636 $table->data = array();
7638 // iterate through auth plugins and add to the display table
7639 foreach ($services as $service) {
7640 $name = $service->name;
7642 // hide/show link
7643 if ($service->enabled) {
7644 $displayname = "<span>$name</span>";
7645 } else {
7646 $displayname = "<span class=\"dimmed_text\">$name</span>";
7649 $plugin = $service->component;
7651 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7653 if ($service->restrictedusers) {
7654 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7655 } else {
7656 $users = get_string('allusers', 'webservice');
7659 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7661 // add a row to the table
7662 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7664 $return .= html_writer::table($table);
7667 // Custom services
7668 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7669 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7671 $table = new html_table();
7672 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7673 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7674 $table->id = 'customservices';
7675 $table->attributes['class'] = 'admintable externalservices generaltable';
7676 $table->data = array();
7678 // iterate through auth plugins and add to the display table
7679 foreach ($services as $service) {
7680 $name = $service->name;
7682 // hide/show link
7683 if ($service->enabled) {
7684 $displayname = "<span>$name</span>";
7685 } else {
7686 $displayname = "<span class=\"dimmed_text\">$name</span>";
7689 // delete link
7690 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7692 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7694 if ($service->restrictedusers) {
7695 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7696 } else {
7697 $users = get_string('allusers', 'webservice');
7700 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7702 // add a row to the table
7703 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7705 // add new custom service option
7706 $return .= html_writer::table($table);
7708 $return .= '<br />';
7709 // add a token to the table
7710 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7712 return highlight($query, $return);
7717 * Special class for overview of external services
7719 * @author Jerome Mouneyrac
7721 class admin_setting_webservicesoverview extends admin_setting {
7724 * Calls parent::__construct with specific arguments
7726 public function __construct() {
7727 $this->nosave = true;
7728 parent::__construct('webservicesoverviewui',
7729 get_string('webservicesoverview', 'webservice'), '', '');
7733 * Always returns true, does nothing
7735 * @return true
7737 public function get_setting() {
7738 return true;
7742 * Always returns true, does nothing
7744 * @return true
7746 public function get_defaultsetting() {
7747 return true;
7751 * Always returns '', does not write anything
7753 * @return string Always returns ''
7755 public function write_setting($data) {
7756 // do not write any setting
7757 return '';
7761 * Builds the XHTML to display the control
7763 * @param string $data Unused
7764 * @param string $query
7765 * @return string
7767 public function output_html($data, $query='') {
7768 global $CFG, $OUTPUT;
7770 $return = "";
7771 $brtag = html_writer::empty_tag('br');
7773 // Enable mobile web service
7774 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7775 get_string('enablemobilewebservice', 'admin'),
7776 get_string('configenablemobilewebservice',
7777 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7778 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
7779 $wsmobileparam = new stdClass();
7780 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7781 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7782 get_string('mobile', 'admin'));
7783 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7784 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7785 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7786 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7787 . $brtag . $brtag;
7789 /// One system controlling Moodle with Token
7790 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7791 $table = new html_table();
7792 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7793 get_string('description'));
7794 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7795 $table->id = 'onesystemcontrol';
7796 $table->attributes['class'] = 'admintable wsoverview generaltable';
7797 $table->data = array();
7799 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7800 . $brtag . $brtag;
7802 /// 1. Enable Web Services
7803 $row = array();
7804 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7805 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7806 array('href' => $url));
7807 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7808 if ($CFG->enablewebservices) {
7809 $status = get_string('yes');
7811 $row[1] = $status;
7812 $row[2] = get_string('enablewsdescription', 'webservice');
7813 $table->data[] = $row;
7815 /// 2. Enable protocols
7816 $row = array();
7817 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7818 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7819 array('href' => $url));
7820 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7821 //retrieve activated protocol
7822 $active_protocols = empty($CFG->webserviceprotocols) ?
7823 array() : explode(',', $CFG->webserviceprotocols);
7824 if (!empty($active_protocols)) {
7825 $status = "";
7826 foreach ($active_protocols as $protocol) {
7827 $status .= $protocol . $brtag;
7830 $row[1] = $status;
7831 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7832 $table->data[] = $row;
7834 /// 3. Create user account
7835 $row = array();
7836 $url = new moodle_url("/user/editadvanced.php?id=-1");
7837 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7838 array('href' => $url));
7839 $row[1] = "";
7840 $row[2] = get_string('createuserdescription', 'webservice');
7841 $table->data[] = $row;
7843 /// 4. Add capability to users
7844 $row = array();
7845 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7846 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7847 array('href' => $url));
7848 $row[1] = "";
7849 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7850 $table->data[] = $row;
7852 /// 5. Select a web service
7853 $row = array();
7854 $url = new moodle_url("/admin/settings.php?section=externalservices");
7855 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7856 array('href' => $url));
7857 $row[1] = "";
7858 $row[2] = get_string('createservicedescription', 'webservice');
7859 $table->data[] = $row;
7861 /// 6. Add functions
7862 $row = array();
7863 $url = new moodle_url("/admin/settings.php?section=externalservices");
7864 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7865 array('href' => $url));
7866 $row[1] = "";
7867 $row[2] = get_string('addfunctionsdescription', 'webservice');
7868 $table->data[] = $row;
7870 /// 7. Add the specific user
7871 $row = array();
7872 $url = new moodle_url("/admin/settings.php?section=externalservices");
7873 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7874 array('href' => $url));
7875 $row[1] = "";
7876 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7877 $table->data[] = $row;
7879 /// 8. Create token for the specific user
7880 $row = array();
7881 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7882 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7883 array('href' => $url));
7884 $row[1] = "";
7885 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7886 $table->data[] = $row;
7888 /// 9. Enable the documentation
7889 $row = array();
7890 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7891 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7892 array('href' => $url));
7893 $status = '<span class="warning">' . get_string('no') . '</span>';
7894 if ($CFG->enablewsdocumentation) {
7895 $status = get_string('yes');
7897 $row[1] = $status;
7898 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7899 $table->data[] = $row;
7901 /// 10. Test the service
7902 $row = array();
7903 $url = new moodle_url("/admin/webservice/testclient.php");
7904 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7905 array('href' => $url));
7906 $row[1] = "";
7907 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7908 $table->data[] = $row;
7910 $return .= html_writer::table($table);
7912 /// Users as clients with token
7913 $return .= $brtag . $brtag . $brtag;
7914 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7915 $table = new html_table();
7916 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7917 get_string('description'));
7918 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7919 $table->id = 'userasclients';
7920 $table->attributes['class'] = 'admintable wsoverview generaltable';
7921 $table->data = array();
7923 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7924 $brtag . $brtag;
7926 /// 1. Enable Web Services
7927 $row = array();
7928 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7929 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7930 array('href' => $url));
7931 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7932 if ($CFG->enablewebservices) {
7933 $status = get_string('yes');
7935 $row[1] = $status;
7936 $row[2] = get_string('enablewsdescription', 'webservice');
7937 $table->data[] = $row;
7939 /// 2. Enable protocols
7940 $row = array();
7941 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7942 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7943 array('href' => $url));
7944 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7945 //retrieve activated protocol
7946 $active_protocols = empty($CFG->webserviceprotocols) ?
7947 array() : explode(',', $CFG->webserviceprotocols);
7948 if (!empty($active_protocols)) {
7949 $status = "";
7950 foreach ($active_protocols as $protocol) {
7951 $status .= $protocol . $brtag;
7954 $row[1] = $status;
7955 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7956 $table->data[] = $row;
7959 /// 3. Select a web service
7960 $row = array();
7961 $url = new moodle_url("/admin/settings.php?section=externalservices");
7962 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7963 array('href' => $url));
7964 $row[1] = "";
7965 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7966 $table->data[] = $row;
7968 /// 4. Add functions
7969 $row = array();
7970 $url = new moodle_url("/admin/settings.php?section=externalservices");
7971 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7972 array('href' => $url));
7973 $row[1] = "";
7974 $row[2] = get_string('addfunctionsdescription', 'webservice');
7975 $table->data[] = $row;
7977 /// 5. Add capability to users
7978 $row = array();
7979 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7980 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7981 array('href' => $url));
7982 $row[1] = "";
7983 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7984 $table->data[] = $row;
7986 /// 6. Test the service
7987 $row = array();
7988 $url = new moodle_url("/admin/webservice/testclient.php");
7989 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7990 array('href' => $url));
7991 $row[1] = "";
7992 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7993 $table->data[] = $row;
7995 $return .= html_writer::table($table);
7997 return highlight($query, $return);
8004 * Special class for web service protocol administration.
8006 * @author Petr Skoda (skodak)
8008 class admin_setting_managewebserviceprotocols extends admin_setting {
8011 * Calls parent::__construct with specific arguments
8013 public function __construct() {
8014 $this->nosave = true;
8015 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8019 * Always returns true, does nothing
8021 * @return true
8023 public function get_setting() {
8024 return true;
8028 * Always returns true, does nothing
8030 * @return true
8032 public function get_defaultsetting() {
8033 return true;
8037 * Always returns '', does not write anything
8039 * @return string Always returns ''
8041 public function write_setting($data) {
8042 // do not write any setting
8043 return '';
8047 * Checks if $query is one of the available webservices
8049 * @param string $query The string to search for
8050 * @return bool Returns true if found, false if not
8052 public function is_related($query) {
8053 if (parent::is_related($query)) {
8054 return true;
8057 $protocols = core_component::get_plugin_list('webservice');
8058 foreach ($protocols as $protocol=>$location) {
8059 if (strpos($protocol, $query) !== false) {
8060 return true;
8062 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8063 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8064 return true;
8067 return false;
8071 * Builds the XHTML to display the control
8073 * @param string $data Unused
8074 * @param string $query
8075 * @return string
8077 public function output_html($data, $query='') {
8078 global $CFG, $OUTPUT;
8080 // display strings
8081 $stradministration = get_string('administration');
8082 $strsettings = get_string('settings');
8083 $stredit = get_string('edit');
8084 $strprotocol = get_string('protocol', 'webservice');
8085 $strenable = get_string('enable');
8086 $strdisable = get_string('disable');
8087 $strversion = get_string('version');
8089 $protocols_available = core_component::get_plugin_list('webservice');
8090 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8091 ksort($protocols_available);
8093 foreach ($active_protocols as $key=>$protocol) {
8094 if (empty($protocols_available[$protocol])) {
8095 unset($active_protocols[$key]);
8099 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8100 $return .= $OUTPUT->box_start('generalbox webservicesui');
8102 $table = new html_table();
8103 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8104 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8105 $table->id = 'webserviceprotocols';
8106 $table->attributes['class'] = 'admintable generaltable';
8107 $table->data = array();
8109 // iterate through auth plugins and add to the display table
8110 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8111 foreach ($protocols_available as $protocol => $location) {
8112 $name = get_string('pluginname', 'webservice_'.$protocol);
8114 $plugin = new stdClass();
8115 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8116 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8118 $version = isset($plugin->version) ? $plugin->version : '';
8120 // hide/show link
8121 if (in_array($protocol, $active_protocols)) {
8122 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8123 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8124 $displayname = "<span>$name</span>";
8125 } else {
8126 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8127 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8128 $displayname = "<span class=\"dimmed_text\">$name</span>";
8131 // settings link
8132 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8133 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8134 } else {
8135 $settings = '';
8138 // add a row to the table
8139 $table->data[] = array($displayname, $version, $hideshow, $settings);
8141 $return .= html_writer::table($table);
8142 $return .= get_string('configwebserviceplugins', 'webservice');
8143 $return .= $OUTPUT->box_end();
8145 return highlight($query, $return);
8151 * Special class for web service token administration.
8153 * @author Jerome Mouneyrac
8155 class admin_setting_managewebservicetokens extends admin_setting {
8158 * Calls parent::__construct with specific arguments
8160 public function __construct() {
8161 $this->nosave = true;
8162 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8166 * Always returns true, does nothing
8168 * @return true
8170 public function get_setting() {
8171 return true;
8175 * Always returns true, does nothing
8177 * @return true
8179 public function get_defaultsetting() {
8180 return true;
8184 * Always returns '', does not write anything
8186 * @return string Always returns ''
8188 public function write_setting($data) {
8189 // do not write any setting
8190 return '';
8194 * Builds the XHTML to display the control
8196 * @param string $data Unused
8197 * @param string $query
8198 * @return string
8200 public function output_html($data, $query='') {
8201 global $CFG, $OUTPUT, $DB, $USER;
8203 // display strings
8204 $stroperation = get_string('operation', 'webservice');
8205 $strtoken = get_string('token', 'webservice');
8206 $strservice = get_string('service', 'webservice');
8207 $struser = get_string('user');
8208 $strcontext = get_string('context', 'webservice');
8209 $strvaliduntil = get_string('validuntil', 'webservice');
8210 $striprestriction = get_string('iprestriction', 'webservice');
8212 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8214 $table = new html_table();
8215 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8216 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8217 $table->id = 'webservicetokens';
8218 $table->attributes['class'] = 'admintable generaltable';
8219 $table->data = array();
8221 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8223 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8225 //here retrieve token list (including linked users firstname/lastname and linked services name)
8226 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8227 FROM {external_tokens} t, {user} u, {external_services} s
8228 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8229 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8230 if (!empty($tokens)) {
8231 foreach ($tokens as $token) {
8232 //TODO: retrieve context
8234 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8235 $delete .= get_string('delete')."</a>";
8237 $validuntil = '';
8238 if (!empty($token->validuntil)) {
8239 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8242 $iprestriction = '';
8243 if (!empty($token->iprestriction)) {
8244 $iprestriction = $token->iprestriction;
8247 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8248 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8249 $useratag .= $token->firstname." ".$token->lastname;
8250 $useratag .= html_writer::end_tag('a');
8252 //check user missing capabilities
8253 require_once($CFG->dirroot . '/webservice/lib.php');
8254 $webservicemanager = new webservice();
8255 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8256 array(array('id' => $token->userid)), $token->serviceid);
8258 if (!is_siteadmin($token->userid) and
8259 array_key_exists($token->userid, $usermissingcaps)) {
8260 $missingcapabilities = implode(', ',
8261 $usermissingcaps[$token->userid]);
8262 if (!empty($missingcapabilities)) {
8263 $useratag .= html_writer::tag('div',
8264 get_string('usermissingcaps', 'webservice',
8265 $missingcapabilities)
8266 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8267 array('class' => 'missingcaps'));
8271 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8274 $return .= html_writer::table($table);
8275 } else {
8276 $return .= get_string('notoken', 'webservice');
8279 $return .= $OUTPUT->box_end();
8280 // add a token to the table
8281 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8282 $return .= get_string('add')."</a>";
8284 return highlight($query, $return);
8290 * Colour picker
8292 * @copyright 2010 Sam Hemelryk
8293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8295 class admin_setting_configcolourpicker extends admin_setting {
8298 * Information for previewing the colour
8300 * @var array|null
8302 protected $previewconfig = null;
8305 * Use default when empty.
8307 protected $usedefaultwhenempty = true;
8311 * @param string $name
8312 * @param string $visiblename
8313 * @param string $description
8314 * @param string $defaultsetting
8315 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8317 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8318 $usedefaultwhenempty = true) {
8319 $this->previewconfig = $previewconfig;
8320 $this->usedefaultwhenempty = $usedefaultwhenempty;
8321 parent::__construct($name, $visiblename, $description, $defaultsetting);
8325 * Return the setting
8327 * @return mixed returns config if successful else null
8329 public function get_setting() {
8330 return $this->config_read($this->name);
8334 * Saves the setting
8336 * @param string $data
8337 * @return bool
8339 public function write_setting($data) {
8340 $data = $this->validate($data);
8341 if ($data === false) {
8342 return get_string('validateerror', 'admin');
8344 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8348 * Validates the colour that was entered by the user
8350 * @param string $data
8351 * @return string|false
8353 protected function validate($data) {
8355 * List of valid HTML colour names
8357 * @var array
8359 $colornames = array(
8360 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8361 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8362 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8363 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8364 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8365 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8366 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8367 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8368 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8369 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8370 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8371 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8372 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8373 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8374 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8375 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8376 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8377 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8378 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8379 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8380 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8381 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8382 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8383 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8384 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8385 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8386 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8387 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8388 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8389 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8390 'whitesmoke', 'yellow', 'yellowgreen'
8393 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8394 if (strpos($data, '#')!==0) {
8395 $data = '#'.$data;
8397 return $data;
8398 } else if (in_array(strtolower($data), $colornames)) {
8399 return $data;
8400 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8401 return $data;
8402 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8403 return $data;
8404 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8405 return $data;
8406 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8407 return $data;
8408 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8409 return $data;
8410 } else if (empty($data)) {
8411 if ($this->usedefaultwhenempty){
8412 return $this->defaultsetting;
8413 } else {
8414 return '';
8416 } else {
8417 return false;
8422 * Generates the HTML for the setting
8424 * @global moodle_page $PAGE
8425 * @global core_renderer $OUTPUT
8426 * @param string $data
8427 * @param string $query
8429 public function output_html($data, $query = '') {
8430 global $PAGE, $OUTPUT;
8431 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8432 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8433 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8434 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8435 if (!empty($this->previewconfig)) {
8436 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8438 $content .= html_writer::end_tag('div');
8439 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8445 * Class used for uploading of one file into file storage,
8446 * the file name is stored in config table.
8448 * Please note you need to implement your own '_pluginfile' callback function,
8449 * this setting only stores the file, it does not deal with file serving.
8451 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8452 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8454 class admin_setting_configstoredfile extends admin_setting {
8455 /** @var array file area options - should be one file only */
8456 protected $options;
8457 /** @var string name of the file area */
8458 protected $filearea;
8459 /** @var int intemid */
8460 protected $itemid;
8461 /** @var string used for detection of changes */
8462 protected $oldhashes;
8465 * Create new stored file setting.
8467 * @param string $name low level setting name
8468 * @param string $visiblename human readable setting name
8469 * @param string $description description of setting
8470 * @param mixed $filearea file area for file storage
8471 * @param int $itemid itemid for file storage
8472 * @param array $options file area options
8474 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8475 parent::__construct($name, $visiblename, $description, '');
8476 $this->filearea = $filearea;
8477 $this->itemid = $itemid;
8478 $this->options = (array)$options;
8482 * Applies defaults and returns all options.
8483 * @return array
8485 protected function get_options() {
8486 global $CFG;
8488 require_once("$CFG->libdir/filelib.php");
8489 require_once("$CFG->dirroot/repository/lib.php");
8490 $defaults = array(
8491 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8492 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8493 'context' => context_system::instance());
8494 foreach($this->options as $k => $v) {
8495 $defaults[$k] = $v;
8498 return $defaults;
8501 public function get_setting() {
8502 return $this->config_read($this->name);
8505 public function write_setting($data) {
8506 global $USER;
8508 // Let's not deal with validation here, this is for admins only.
8509 $current = $this->get_setting();
8510 if (empty($data) && $current === null) {
8511 // This will be the case when applying default settings (installation).
8512 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8513 } else if (!is_number($data)) {
8514 // Draft item id is expected here!
8515 return get_string('errorsetting', 'admin');
8518 $options = $this->get_options();
8519 $fs = get_file_storage();
8520 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8522 $this->oldhashes = null;
8523 if ($current) {
8524 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8525 if ($file = $fs->get_file_by_hash($hash)) {
8526 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8528 unset($file);
8531 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8532 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8533 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8534 // with an error because the draft area does not exist, as he did not use it.
8535 $usercontext = context_user::instance($USER->id);
8536 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8537 return get_string('errorsetting', 'admin');
8541 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8542 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8544 $filepath = '';
8545 if ($files) {
8546 /** @var stored_file $file */
8547 $file = reset($files);
8548 $filepath = $file->get_filepath().$file->get_filename();
8551 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8554 public function post_write_settings($original) {
8555 $options = $this->get_options();
8556 $fs = get_file_storage();
8557 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8559 $current = $this->get_setting();
8560 $newhashes = null;
8561 if ($current) {
8562 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8563 if ($file = $fs->get_file_by_hash($hash)) {
8564 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8566 unset($file);
8569 if ($this->oldhashes === $newhashes) {
8570 $this->oldhashes = null;
8571 return false;
8573 $this->oldhashes = null;
8575 $callbackfunction = $this->updatedcallback;
8576 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8577 $callbackfunction($this->get_full_name());
8579 return true;
8582 public function output_html($data, $query = '') {
8583 global $PAGE, $CFG;
8585 $options = $this->get_options();
8586 $id = $this->get_id();
8587 $elname = $this->get_full_name();
8588 $draftitemid = file_get_submitted_draft_itemid($elname);
8589 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8590 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8592 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8593 require_once("$CFG->dirroot/lib/form/filemanager.php");
8595 $fmoptions = new stdClass();
8596 $fmoptions->mainfile = $options['mainfile'];
8597 $fmoptions->maxbytes = $options['maxbytes'];
8598 $fmoptions->maxfiles = $options['maxfiles'];
8599 $fmoptions->client_id = uniqid();
8600 $fmoptions->itemid = $draftitemid;
8601 $fmoptions->subdirs = $options['subdirs'];
8602 $fmoptions->target = $id;
8603 $fmoptions->accepted_types = $options['accepted_types'];
8604 $fmoptions->return_types = $options['return_types'];
8605 $fmoptions->context = $options['context'];
8606 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8608 $fm = new form_filemanager($fmoptions);
8609 $output = $PAGE->get_renderer('core', 'files');
8610 $html = $output->render($fm);
8612 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8613 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8615 return format_admin_setting($this, $this->visiblename,
8616 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8622 * Administration interface for user specified regular expressions for device detection.
8624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8626 class admin_setting_devicedetectregex extends admin_setting {
8629 * Calls parent::__construct with specific args
8631 * @param string $name
8632 * @param string $visiblename
8633 * @param string $description
8634 * @param mixed $defaultsetting
8636 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8637 global $CFG;
8638 parent::__construct($name, $visiblename, $description, $defaultsetting);
8642 * Return the current setting(s)
8644 * @return array Current settings array
8646 public function get_setting() {
8647 global $CFG;
8649 $config = $this->config_read($this->name);
8650 if (is_null($config)) {
8651 return null;
8654 return $this->prepare_form_data($config);
8658 * Save selected settings
8660 * @param array $data Array of settings to save
8661 * @return bool
8663 public function write_setting($data) {
8664 if (empty($data)) {
8665 $data = array();
8668 if ($this->config_write($this->name, $this->process_form_data($data))) {
8669 return ''; // success
8670 } else {
8671 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8676 * Return XHTML field(s) for regexes
8678 * @param array $data Array of options to set in HTML
8679 * @return string XHTML string for the fields and wrapping div(s)
8681 public function output_html($data, $query='') {
8682 global $OUTPUT;
8684 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8685 $out .= html_writer::start_tag('thead');
8686 $out .= html_writer::start_tag('tr');
8687 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8688 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8689 $out .= html_writer::end_tag('tr');
8690 $out .= html_writer::end_tag('thead');
8691 $out .= html_writer::start_tag('tbody');
8693 if (empty($data)) {
8694 $looplimit = 1;
8695 } else {
8696 $looplimit = (count($data)/2)+1;
8699 for ($i=0; $i<$looplimit; $i++) {
8700 $out .= html_writer::start_tag('tr');
8702 $expressionname = 'expression'.$i;
8704 if (!empty($data[$expressionname])){
8705 $expression = $data[$expressionname];
8706 } else {
8707 $expression = '';
8710 $out .= html_writer::tag('td',
8711 html_writer::empty_tag('input',
8712 array(
8713 'type' => 'text',
8714 'class' => 'form-text',
8715 'name' => $this->get_full_name().'[expression'.$i.']',
8716 'value' => $expression,
8718 ), array('class' => 'c'.$i)
8721 $valuename = 'value'.$i;
8723 if (!empty($data[$valuename])){
8724 $value = $data[$valuename];
8725 } else {
8726 $value= '';
8729 $out .= html_writer::tag('td',
8730 html_writer::empty_tag('input',
8731 array(
8732 'type' => 'text',
8733 'class' => 'form-text',
8734 'name' => $this->get_full_name().'[value'.$i.']',
8735 'value' => $value,
8737 ), array('class' => 'c'.$i)
8740 $out .= html_writer::end_tag('tr');
8743 $out .= html_writer::end_tag('tbody');
8744 $out .= html_writer::end_tag('table');
8746 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8750 * Converts the string of regexes
8752 * @see self::process_form_data()
8753 * @param $regexes string of regexes
8754 * @return array of form fields and their values
8756 protected function prepare_form_data($regexes) {
8758 $regexes = json_decode($regexes);
8760 $form = array();
8762 $i = 0;
8764 foreach ($regexes as $value => $regex) {
8765 $expressionname = 'expression'.$i;
8766 $valuename = 'value'.$i;
8768 $form[$expressionname] = $regex;
8769 $form[$valuename] = $value;
8770 $i++;
8773 return $form;
8777 * Converts the data from admin settings form into a string of regexes
8779 * @see self::prepare_form_data()
8780 * @param array $data array of admin form fields and values
8781 * @return false|string of regexes
8783 protected function process_form_data(array $form) {
8785 $count = count($form); // number of form field values
8787 if ($count % 2) {
8788 // we must get five fields per expression
8789 return false;
8792 $regexes = array();
8793 for ($i = 0; $i < $count / 2; $i++) {
8794 $expressionname = "expression".$i;
8795 $valuename = "value".$i;
8797 $expression = trim($form['expression'.$i]);
8798 $value = trim($form['value'.$i]);
8800 if (empty($expression)){
8801 continue;
8804 $regexes[$value] = $expression;
8807 $regexes = json_encode($regexes);
8809 return $regexes;
8814 * Multiselect for current modules
8816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8818 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8819 private $excludesystem;
8822 * Calls parent::__construct - note array $choices is not required
8824 * @param string $name setting name
8825 * @param string $visiblename localised setting name
8826 * @param string $description setting description
8827 * @param array $defaultsetting a plain array of default module ids
8828 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8830 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8831 $excludesystem = true) {
8832 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8833 $this->excludesystem = $excludesystem;
8837 * Loads an array of current module choices
8839 * @return bool always return true
8841 public function load_choices() {
8842 if (is_array($this->choices)) {
8843 return true;
8845 $this->choices = array();
8847 global $CFG, $DB;
8848 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8849 foreach ($records as $record) {
8850 // Exclude modules if the code doesn't exist
8851 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8852 // Also exclude system modules (if specified)
8853 if (!($this->excludesystem &&
8854 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8855 MOD_ARCHETYPE_SYSTEM)) {
8856 $this->choices[$record->id] = $record->name;
8860 return true;
8865 * Admin setting to show if a php extension is enabled or not.
8867 * @copyright 2013 Damyon Wiese
8868 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8870 class admin_setting_php_extension_enabled extends admin_setting {
8872 /** @var string The name of the extension to check for */
8873 private $extension;
8876 * Calls parent::__construct with specific arguments
8878 public function __construct($name, $visiblename, $description, $extension) {
8879 $this->extension = $extension;
8880 $this->nosave = true;
8881 parent::__construct($name, $visiblename, $description, '');
8885 * Always returns true, does nothing
8887 * @return true
8889 public function get_setting() {
8890 return true;
8894 * Always returns true, does nothing
8896 * @return true
8898 public function get_defaultsetting() {
8899 return true;
8903 * Always returns '', does not write anything
8905 * @return string Always returns ''
8907 public function write_setting($data) {
8908 // Do not write any setting.
8909 return '';
8913 * Outputs the html for this setting.
8914 * @return string Returns an XHTML string
8916 public function output_html($data, $query='') {
8917 global $OUTPUT;
8919 $o = '';
8920 if (!extension_loaded($this->extension)) {
8921 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8923 $o .= format_admin_setting($this, $this->visiblename, $warning);
8925 return $o;