Merge branch 'MDL-47713-master-fix1' of http://github.com/damyon/moodle
[moodle.git] / lib / adminlib.php
blobbe24d9e2afed8ed715ea7ab234cd96251c0d7fdc
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // Delete Inbound Message datakeys.
206 $DB->delete_records_select('messageinbound_datakeys',
207 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($pluginname));
209 // Delete Inbound Message handlers.
210 $DB->delete_records('messageinbound_handlers', array('component' => $pluginname));
212 // delete all the logs
213 $DB->delete_records('log', array('module' => $pluginname));
215 // delete log_display information
216 $DB->delete_records('log_display', array('component' => $component));
218 // delete the module configuration records
219 unset_all_config_for_plugin($component);
220 if ($type === 'mod') {
221 unset_all_config_for_plugin($pluginname);
224 // delete message provider
225 message_provider_uninstall($component);
227 // delete the plugin tables
228 $xmldbfilepath = $plugindirectory . '/db/install.xml';
229 drop_plugin_tables($component, $xmldbfilepath, false);
230 if ($type === 'mod' or $type === 'block') {
231 // non-frankenstyle table prefixes
232 drop_plugin_tables($name, $xmldbfilepath, false);
235 // delete the capabilities that were defined by this module
236 capabilities_cleanup($component);
238 // remove event handlers and dequeue pending events
239 events_uninstall($component);
241 // Delete all remaining files in the filepool owned by the component.
242 $fs = get_file_storage();
243 $fs->delete_component_files($component);
245 // Finally purge all caches.
246 purge_all_caches();
248 // Invalidate the hash used for upgrade detections.
249 set_config('allversionshash', '');
251 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
255 * Returns the version of installed component
257 * @param string $component component name
258 * @param string $source either 'disk' or 'installed' - where to get the version information from
259 * @return string|bool version number or false if the component is not found
261 function get_component_version($component, $source='installed') {
262 global $CFG, $DB;
264 list($type, $name) = core_component::normalize_component($component);
266 // moodle core or a core subsystem
267 if ($type === 'core') {
268 if ($source === 'installed') {
269 if (empty($CFG->version)) {
270 return false;
271 } else {
272 return $CFG->version;
274 } else {
275 if (!is_readable($CFG->dirroot.'/version.php')) {
276 return false;
277 } else {
278 $version = null; //initialize variable for IDEs
279 include($CFG->dirroot.'/version.php');
280 return $version;
285 // activity module
286 if ($type === 'mod') {
287 if ($source === 'installed') {
288 if ($CFG->version < 2013092001.02) {
289 return $DB->get_field('modules', 'version', array('name'=>$name));
290 } else {
291 return get_config('mod_'.$name, 'version');
294 } else {
295 $mods = core_component::get_plugin_list('mod');
296 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
297 return false;
298 } else {
299 $plugin = new stdClass();
300 $plugin->version = null;
301 $module = $plugin;
302 include($mods[$name].'/version.php');
303 return $plugin->version;
308 // block
309 if ($type === 'block') {
310 if ($source === 'installed') {
311 if ($CFG->version < 2013092001.02) {
312 return $DB->get_field('block', 'version', array('name'=>$name));
313 } else {
314 return get_config('block_'.$name, 'version');
316 } else {
317 $blocks = core_component::get_plugin_list('block');
318 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
319 return false;
320 } else {
321 $plugin = new stdclass();
322 include($blocks[$name].'/version.php');
323 return $plugin->version;
328 // all other plugin types
329 if ($source === 'installed') {
330 return get_config($type.'_'.$name, 'version');
331 } else {
332 $plugins = core_component::get_plugin_list($type);
333 if (empty($plugins[$name])) {
334 return false;
335 } else {
336 $plugin = new stdclass();
337 include($plugins[$name].'/version.php');
338 return $plugin->version;
344 * Delete all plugin tables
346 * @param string $name Name of plugin, used as table prefix
347 * @param string $file Path to install.xml file
348 * @param bool $feedback defaults to true
349 * @return bool Always returns true
351 function drop_plugin_tables($name, $file, $feedback=true) {
352 global $CFG, $DB;
354 // first try normal delete
355 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
356 return true;
359 // then try to find all tables that start with name and are not in any xml file
360 $used_tables = get_used_table_names();
362 $tables = $DB->get_tables();
364 /// Iterate over, fixing id fields as necessary
365 foreach ($tables as $table) {
366 if (in_array($table, $used_tables)) {
367 continue;
370 if (strpos($table, $name) !== 0) {
371 continue;
374 // found orphan table --> delete it
375 if ($DB->get_manager()->table_exists($table)) {
376 $xmldb_table = new xmldb_table($table);
377 $DB->get_manager()->drop_table($xmldb_table);
381 return true;
385 * Returns names of all known tables == tables that moodle knows about.
387 * @return array Array of lowercase table names
389 function get_used_table_names() {
390 $table_names = array();
391 $dbdirs = get_db_directories();
393 foreach ($dbdirs as $dbdir) {
394 $file = $dbdir.'/install.xml';
396 $xmldb_file = new xmldb_file($file);
398 if (!$xmldb_file->fileExists()) {
399 continue;
402 $loaded = $xmldb_file->loadXMLStructure();
403 $structure = $xmldb_file->getStructure();
405 if ($loaded and $tables = $structure->getTables()) {
406 foreach($tables as $table) {
407 $table_names[] = strtolower($table->getName());
412 return $table_names;
416 * Returns list of all directories where we expect install.xml files
417 * @return array Array of paths
419 function get_db_directories() {
420 global $CFG;
422 $dbdirs = array();
424 /// First, the main one (lib/db)
425 $dbdirs[] = $CFG->libdir.'/db';
427 /// Then, all the ones defined by core_component::get_plugin_types()
428 $plugintypes = core_component::get_plugin_types();
429 foreach ($plugintypes as $plugintype => $pluginbasedir) {
430 if ($plugins = core_component::get_plugin_list($plugintype)) {
431 foreach ($plugins as $plugin => $plugindir) {
432 $dbdirs[] = $plugindir.'/db';
437 return $dbdirs;
441 * Try to obtain or release the cron lock.
442 * @param string $name name of lock
443 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
444 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
445 * @return bool true if lock obtained
447 function set_cron_lock($name, $until, $ignorecurrent=false) {
448 global $DB;
449 if (empty($name)) {
450 debugging("Tried to get a cron lock for a null fieldname");
451 return false;
454 // remove lock by force == remove from config table
455 if (is_null($until)) {
456 set_config($name, null);
457 return true;
460 if (!$ignorecurrent) {
461 // read value from db - other processes might have changed it
462 $value = $DB->get_field('config', 'value', array('name'=>$name));
464 if ($value and $value > time()) {
465 //lock active
466 return false;
470 set_config($name, $until);
471 return true;
475 * Test if and critical warnings are present
476 * @return bool
478 function admin_critical_warnings_present() {
479 global $SESSION;
481 if (!has_capability('moodle/site:config', context_system::instance())) {
482 return 0;
485 if (!isset($SESSION->admin_critical_warning)) {
486 $SESSION->admin_critical_warning = 0;
487 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
488 $SESSION->admin_critical_warning = 1;
492 return $SESSION->admin_critical_warning;
496 * Detects if float supports at least 10 decimal digits
498 * Detects if float supports at least 10 decimal digits
499 * and also if float-->string conversion works as expected.
501 * @return bool true if problem found
503 function is_float_problem() {
504 $num1 = 2009010200.01;
505 $num2 = 2009010200.02;
507 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
511 * Try to verify that dataroot is not accessible from web.
513 * Try to verify that dataroot is not accessible from web.
514 * It is not 100% correct but might help to reduce number of vulnerable sites.
515 * Protection from httpd.conf and .htaccess is not detected properly.
517 * @uses INSECURE_DATAROOT_WARNING
518 * @uses INSECURE_DATAROOT_ERROR
519 * @param bool $fetchtest try to test public access by fetching file, default false
520 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
522 function is_dataroot_insecure($fetchtest=false) {
523 global $CFG;
525 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
527 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
528 $rp = strrev(trim($rp, '/'));
529 $rp = explode('/', $rp);
530 foreach($rp as $r) {
531 if (strpos($siteroot, '/'.$r.'/') === 0) {
532 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
533 } else {
534 break; // probably alias root
538 $siteroot = strrev($siteroot);
539 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
541 if (strpos($dataroot, $siteroot) !== 0) {
542 return false;
545 if (!$fetchtest) {
546 return INSECURE_DATAROOT_WARNING;
549 // now try all methods to fetch a test file using http protocol
551 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
552 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
553 $httpdocroot = $matches[1];
554 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
555 make_upload_directory('diag');
556 $testfile = $CFG->dataroot.'/diag/public.txt';
557 if (!file_exists($testfile)) {
558 file_put_contents($testfile, 'test file, do not delete');
559 @chmod($testfile, $CFG->filepermissions);
561 $teststr = trim(file_get_contents($testfile));
562 if (empty($teststr)) {
563 // hmm, strange
564 return INSECURE_DATAROOT_WARNING;
567 $testurl = $datarooturl.'/diag/public.txt';
568 if (extension_loaded('curl') and
569 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
570 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
571 ($ch = @curl_init($testurl)) !== false) {
572 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
573 curl_setopt($ch, CURLOPT_HEADER, false);
574 $data = curl_exec($ch);
575 if (!curl_errno($ch)) {
576 $data = trim($data);
577 if ($data === $teststr) {
578 curl_close($ch);
579 return INSECURE_DATAROOT_ERROR;
582 curl_close($ch);
585 if ($data = @file_get_contents($testurl)) {
586 $data = trim($data);
587 if ($data === $teststr) {
588 return INSECURE_DATAROOT_ERROR;
592 preg_match('|https?://([^/]+)|i', $testurl, $matches);
593 $sitename = $matches[1];
594 $error = 0;
595 if ($fp = @fsockopen($sitename, 80, $error)) {
596 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
597 $localurl = $matches[1];
598 $out = "GET $localurl HTTP/1.1\r\n";
599 $out .= "Host: $sitename\r\n";
600 $out .= "Connection: Close\r\n\r\n";
601 fwrite($fp, $out);
602 $data = '';
603 $incoming = false;
604 while (!feof($fp)) {
605 if ($incoming) {
606 $data .= fgets($fp, 1024);
607 } else if (@fgets($fp, 1024) === "\r\n") {
608 $incoming = true;
611 fclose($fp);
612 $data = trim($data);
613 if ($data === $teststr) {
614 return INSECURE_DATAROOT_ERROR;
618 return INSECURE_DATAROOT_WARNING;
622 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
624 function enable_cli_maintenance_mode() {
625 global $CFG;
627 if (file_exists("$CFG->dataroot/climaintenance.html")) {
628 unlink("$CFG->dataroot/climaintenance.html");
631 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
632 $data = $CFG->maintenance_message;
633 $data = bootstrap_renderer::early_error_content($data, null, null, null);
634 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
636 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
637 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
639 } else {
640 $data = get_string('sitemaintenance', 'admin');
641 $data = bootstrap_renderer::early_error_content($data, null, null, null);
642 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
645 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
646 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
649 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
653 * Interface for anything appearing in the admin tree
655 * The interface that is implemented by anything that appears in the admin tree
656 * block. It forces inheriting classes to define a method for checking user permissions
657 * and methods for finding something in the admin tree.
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
661 interface part_of_admin_tree {
664 * Finds a named part_of_admin_tree.
666 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
667 * and not parentable_part_of_admin_tree, then this function should only check if
668 * $this->name matches $name. If it does, it should return a reference to $this,
669 * otherwise, it should return a reference to NULL.
671 * If a class inherits parentable_part_of_admin_tree, this method should be called
672 * recursively on all child objects (assuming, of course, the parent object's name
673 * doesn't match the search criterion).
675 * @param string $name The internal name of the part_of_admin_tree we're searching for.
676 * @return mixed An object reference or a NULL reference.
678 public function locate($name);
681 * Removes named part_of_admin_tree.
683 * @param string $name The internal name of the part_of_admin_tree we want to remove.
684 * @return bool success.
686 public function prune($name);
689 * Search using query
690 * @param string $query
691 * @return mixed array-object structure of found settings and pages
693 public function search($query);
696 * Verifies current user's access to this part_of_admin_tree.
698 * Used to check if the current user has access to this part of the admin tree or
699 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
700 * then this method is usually just a call to has_capability() in the site context.
702 * If a class inherits parentable_part_of_admin_tree, this method should return the
703 * logical OR of the return of check_access() on all child objects.
705 * @return bool True if the user has access, false if she doesn't.
707 public function check_access();
710 * Mostly useful for removing of some parts of the tree in admin tree block.
712 * @return True is hidden from normal list view
714 public function is_hidden();
717 * Show we display Save button at the page bottom?
718 * @return bool
720 public function show_save();
725 * Interface implemented by any part_of_admin_tree that has children.
727 * The interface implemented by any part_of_admin_tree that can be a parent
728 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
729 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
730 * include an add method for adding other part_of_admin_tree objects as children.
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 interface parentable_part_of_admin_tree extends part_of_admin_tree {
737 * Adds a part_of_admin_tree object to the admin tree.
739 * Used to add a part_of_admin_tree object to this object or a child of this
740 * object. $something should only be added if $destinationname matches
741 * $this->name. If it doesn't, add should be called on child objects that are
742 * also parentable_part_of_admin_tree's.
744 * $something should be appended as the last child in the $destinationname. If the
745 * $beforesibling is specified, $something should be prepended to it. If the given
746 * sibling is not found, $something should be appended to the end of $destinationname
747 * and a developer debugging message should be displayed.
749 * @param string $destinationname The internal name of the new parent for $something.
750 * @param part_of_admin_tree $something The object to be added.
751 * @return bool True on success, false on failure.
753 public function add($destinationname, $something, $beforesibling = null);
759 * The object used to represent folders (a.k.a. categories) in the admin tree block.
761 * Each admin_category object contains a number of part_of_admin_tree objects.
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class admin_category implements parentable_part_of_admin_tree {
767 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
768 protected $children;
769 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
770 public $name;
771 /** @var string The displayed name for this category. Usually obtained through get_string() */
772 public $visiblename;
773 /** @var bool Should this category be hidden in admin tree block? */
774 public $hidden;
775 /** @var mixed Either a string or an array or strings */
776 public $path;
777 /** @var mixed Either a string or an array or strings */
778 public $visiblepath;
780 /** @var array fast lookup category cache, all categories of one tree point to one cache */
781 protected $category_cache;
783 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
784 protected $sort = false;
785 /** @var bool If set to true children will be sorted in ascending order. */
786 protected $sortasc = true;
787 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
788 protected $sortsplit = true;
789 /** @var bool $sorted True if the children have been sorted and don't need resorting */
790 protected $sorted = false;
793 * Constructor for an empty admin category
795 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
796 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
797 * @param bool $hidden hide category in admin tree block, defaults to false
799 public function __construct($name, $visiblename, $hidden=false) {
800 $this->children = array();
801 $this->name = $name;
802 $this->visiblename = $visiblename;
803 $this->hidden = $hidden;
807 * Returns a reference to the part_of_admin_tree object with internal name $name.
809 * @param string $name The internal name of the object we want.
810 * @param bool $findpath initialize path and visiblepath arrays
811 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
812 * defaults to false
814 public function locate($name, $findpath=false) {
815 if (!isset($this->category_cache[$this->name])) {
816 // somebody much have purged the cache
817 $this->category_cache[$this->name] = $this;
820 if ($this->name == $name) {
821 if ($findpath) {
822 $this->visiblepath[] = $this->visiblename;
823 $this->path[] = $this->name;
825 return $this;
828 // quick category lookup
829 if (!$findpath and isset($this->category_cache[$name])) {
830 return $this->category_cache[$name];
833 $return = NULL;
834 foreach($this->children as $childid=>$unused) {
835 if ($return = $this->children[$childid]->locate($name, $findpath)) {
836 break;
840 if (!is_null($return) and $findpath) {
841 $return->visiblepath[] = $this->visiblename;
842 $return->path[] = $this->name;
845 return $return;
849 * Search using query
851 * @param string query
852 * @return mixed array-object structure of found settings and pages
854 public function search($query) {
855 $result = array();
856 foreach ($this->get_children() as $child) {
857 $subsearch = $child->search($query);
858 if (!is_array($subsearch)) {
859 debugging('Incorrect search result from '.$child->name);
860 continue;
862 $result = array_merge($result, $subsearch);
864 return $result;
868 * Removes part_of_admin_tree object with internal name $name.
870 * @param string $name The internal name of the object we want to remove.
871 * @return bool success
873 public function prune($name) {
875 if ($this->name == $name) {
876 return false; //can not remove itself
879 foreach($this->children as $precedence => $child) {
880 if ($child->name == $name) {
881 // clear cache and delete self
882 while($this->category_cache) {
883 // delete the cache, but keep the original array address
884 array_pop($this->category_cache);
886 unset($this->children[$precedence]);
887 return true;
888 } else if ($this->children[$precedence]->prune($name)) {
889 return true;
892 return false;
896 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
898 * By default the new part of the tree is appended as the last child of the parent. You
899 * can specify a sibling node that the new part should be prepended to. If the given
900 * sibling is not found, the part is appended to the end (as it would be by default) and
901 * a developer debugging message is displayed.
903 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
904 * @param string $destinationame The internal name of the immediate parent that we want for $something.
905 * @param mixed $something A part_of_admin_tree or setting instance to be added.
906 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something, $beforesibling = null) {
910 global $CFG;
912 $parent = $this->locate($parentname);
913 if (is_null($parent)) {
914 debugging('parent does not exist!');
915 return false;
918 if ($something instanceof part_of_admin_tree) {
919 if (!($parent instanceof parentable_part_of_admin_tree)) {
920 debugging('error - parts of tree can be inserted only into parentable parts');
921 return false;
923 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
924 // The name of the node is already used, simply warn the developer that this should not happen.
925 // It is intentional to check for the debug level before performing the check.
926 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
928 if (is_null($beforesibling)) {
929 // Append $something as the parent's last child.
930 $parent->children[] = $something;
931 } else {
932 if (!is_string($beforesibling) or trim($beforesibling) === '') {
933 throw new coding_exception('Unexpected value of the beforesibling parameter');
935 // Try to find the position of the sibling.
936 $siblingposition = null;
937 foreach ($parent->children as $childposition => $child) {
938 if ($child->name === $beforesibling) {
939 $siblingposition = $childposition;
940 break;
943 if (is_null($siblingposition)) {
944 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
945 $parent->children[] = $something;
946 } else {
947 $parent->children = array_merge(
948 array_slice($parent->children, 0, $siblingposition),
949 array($something),
950 array_slice($parent->children, $siblingposition)
954 if ($something instanceof admin_category) {
955 if (isset($this->category_cache[$something->name])) {
956 debugging('Duplicate admin category name: '.$something->name);
957 } else {
958 $this->category_cache[$something->name] = $something;
959 $something->category_cache =& $this->category_cache;
960 foreach ($something->children as $child) {
961 // just in case somebody already added subcategories
962 if ($child instanceof admin_category) {
963 if (isset($this->category_cache[$child->name])) {
964 debugging('Duplicate admin category name: '.$child->name);
965 } else {
966 $this->category_cache[$child->name] = $child;
967 $child->category_cache =& $this->category_cache;
973 return true;
975 } else {
976 debugging('error - can not add this element');
977 return false;
983 * Checks if the user has access to anything in this category.
985 * @return bool True if the user has access to at least one child in this category, false otherwise.
987 public function check_access() {
988 foreach ($this->children as $child) {
989 if ($child->check_access()) {
990 return true;
993 return false;
997 * Is this category hidden in admin tree block?
999 * @return bool True if hidden
1001 public function is_hidden() {
1002 return $this->hidden;
1006 * Show we display Save button at the page bottom?
1007 * @return bool
1009 public function show_save() {
1010 foreach ($this->children as $child) {
1011 if ($child->show_save()) {
1012 return true;
1015 return false;
1019 * Sets sorting on this category.
1021 * Please note this function doesn't actually do the sorting.
1022 * It can be called anytime.
1023 * Sorting occurs when the user calls get_children.
1024 * Code using the children array directly won't see the sorted results.
1026 * @param bool $sort If set to true children will be sorted, if false they won't be.
1027 * @param bool $asc If true sorting will be ascending, otherwise descending.
1028 * @param bool $split If true we sort pages and sub categories separately.
1030 public function set_sorting($sort, $asc = true, $split = true) {
1031 $this->sort = (bool)$sort;
1032 $this->sortasc = (bool)$asc;
1033 $this->sortsplit = (bool)$split;
1037 * Returns the children associated with this category.
1039 * @return part_of_admin_tree[]
1041 public function get_children() {
1042 // If we should sort and it hasn't already been sorted.
1043 if ($this->sort && !$this->sorted) {
1044 if ($this->sortsplit) {
1045 $categories = array();
1046 $pages = array();
1047 foreach ($this->children as $child) {
1048 if ($child instanceof admin_category) {
1049 $categories[] = $child;
1050 } else {
1051 $pages[] = $child;
1054 core_collator::asort_objects_by_property($categories, 'visiblename');
1055 core_collator::asort_objects_by_property($pages, 'visiblename');
1056 if (!$this->sortasc) {
1057 $categories = array_reverse($categories);
1058 $pages = array_reverse($pages);
1060 $this->children = array_merge($pages, $categories);
1061 } else {
1062 core_collator::asort_objects_by_property($this->children, 'visiblename');
1063 if (!$this->sortasc) {
1064 $this->children = array_reverse($this->children);
1067 $this->sorted = true;
1069 return $this->children;
1073 * Magically gets a property from this object.
1075 * @param $property
1076 * @return part_of_admin_tree[]
1077 * @throws coding_exception
1079 public function __get($property) {
1080 if ($property === 'children') {
1081 return $this->get_children();
1083 throw new coding_exception('Invalid property requested.');
1087 * Magically sets a property against this object.
1089 * @param string $property
1090 * @param mixed $value
1091 * @throws coding_exception
1093 public function __set($property, $value) {
1094 if ($property === 'children') {
1095 $this->sorted = false;
1096 $this->children = $value;
1097 } else {
1098 throw new coding_exception('Invalid property requested.');
1103 * Checks if an inaccessible property is set.
1105 * @param string $property
1106 * @return bool
1107 * @throws coding_exception
1109 public function __isset($property) {
1110 if ($property === 'children') {
1111 return isset($this->children);
1113 throw new coding_exception('Invalid property requested.');
1119 * Root of admin settings tree, does not have any parent.
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class admin_root extends admin_category {
1124 /** @var array List of errors */
1125 public $errors;
1126 /** @var string search query */
1127 public $search;
1128 /** @var bool full tree flag - true means all settings required, false only pages required */
1129 public $fulltree;
1130 /** @var bool flag indicating loaded tree */
1131 public $loaded;
1132 /** @var mixed site custom defaults overriding defaults in settings files*/
1133 public $custom_defaults;
1136 * @param bool $fulltree true means all settings required,
1137 * false only pages required
1139 public function __construct($fulltree) {
1140 global $CFG;
1142 parent::__construct('root', get_string('administration'), false);
1143 $this->errors = array();
1144 $this->search = '';
1145 $this->fulltree = $fulltree;
1146 $this->loaded = false;
1148 $this->category_cache = array();
1150 // load custom defaults if found
1151 $this->custom_defaults = null;
1152 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1153 if (is_readable($defaultsfile)) {
1154 $defaults = array();
1155 include($defaultsfile);
1156 if (is_array($defaults) and count($defaults)) {
1157 $this->custom_defaults = $defaults;
1163 * Empties children array, and sets loaded to false
1165 * @param bool $requirefulltree
1167 public function purge_children($requirefulltree) {
1168 $this->children = array();
1169 $this->fulltree = ($requirefulltree || $this->fulltree);
1170 $this->loaded = false;
1171 //break circular dependencies - this helps PHP 5.2
1172 while($this->category_cache) {
1173 array_pop($this->category_cache);
1175 $this->category_cache = array();
1181 * Links external PHP pages into the admin tree.
1183 * See detailed usage example at the top of this document (adminlib.php)
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1187 class admin_externalpage implements part_of_admin_tree {
1189 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1190 public $name;
1192 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1193 public $visiblename;
1195 /** @var string The external URL that we should link to when someone requests this external page. */
1196 public $url;
1198 /** @var string The role capability/permission a user must have to access this external page. */
1199 public $req_capability;
1201 /** @var object The context in which capability/permission should be checked, default is site context. */
1202 public $context;
1204 /** @var bool hidden in admin tree block. */
1205 public $hidden;
1207 /** @var mixed either string or array of string */
1208 public $path;
1210 /** @var array list of visible names of page parents */
1211 public $visiblepath;
1214 * Constructor for adding an external page into the admin tree.
1216 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1217 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1218 * @param string $url The external URL that we should link to when someone requests this external page.
1219 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1220 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1221 * @param stdClass $context The context the page relates to. Not sure what happens
1222 * if you specify something other than system or front page. Defaults to system.
1224 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1225 $this->name = $name;
1226 $this->visiblename = $visiblename;
1227 $this->url = $url;
1228 if (is_array($req_capability)) {
1229 $this->req_capability = $req_capability;
1230 } else {
1231 $this->req_capability = array($req_capability);
1233 $this->hidden = $hidden;
1234 $this->context = $context;
1238 * Returns a reference to the part_of_admin_tree object with internal name $name.
1240 * @param string $name The internal name of the object we want.
1241 * @param bool $findpath defaults to false
1242 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1244 public function locate($name, $findpath=false) {
1245 if ($this->name == $name) {
1246 if ($findpath) {
1247 $this->visiblepath = array($this->visiblename);
1248 $this->path = array($this->name);
1250 return $this;
1251 } else {
1252 $return = NULL;
1253 return $return;
1258 * This function always returns false, required function by interface
1260 * @param string $name
1261 * @return false
1263 public function prune($name) {
1264 return false;
1268 * Search using query
1270 * @param string $query
1271 * @return mixed array-object structure of found settings and pages
1273 public function search($query) {
1274 $found = false;
1275 if (strpos(strtolower($this->name), $query) !== false) {
1276 $found = true;
1277 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1278 $found = true;
1280 if ($found) {
1281 $result = new stdClass();
1282 $result->page = $this;
1283 $result->settings = array();
1284 return array($this->name => $result);
1285 } else {
1286 return array();
1291 * Determines if the current user has access to this external page based on $this->req_capability.
1293 * @return bool True if user has access, false otherwise.
1295 public function check_access() {
1296 global $CFG;
1297 $context = empty($this->context) ? context_system::instance() : $this->context;
1298 foreach($this->req_capability as $cap) {
1299 if (has_capability($cap, $context)) {
1300 return true;
1303 return false;
1307 * Is this external page hidden in admin tree block?
1309 * @return bool True if hidden
1311 public function is_hidden() {
1312 return $this->hidden;
1316 * Show we display Save button at the page bottom?
1317 * @return bool
1319 public function show_save() {
1320 return false;
1326 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 class admin_settingpage implements part_of_admin_tree {
1332 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1333 public $name;
1335 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1336 public $visiblename;
1338 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1339 public $settings;
1341 /** @var string The role capability/permission a user must have to access this external page. */
1342 public $req_capability;
1344 /** @var object The context in which capability/permission should be checked, default is site context. */
1345 public $context;
1347 /** @var bool hidden in admin tree block. */
1348 public $hidden;
1350 /** @var mixed string of paths or array of strings of paths */
1351 public $path;
1353 /** @var array list of visible names of page parents */
1354 public $visiblepath;
1357 * see admin_settingpage for details of this function
1359 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1360 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1361 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1362 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1363 * @param stdClass $context The context the page relates to. Not sure what happens
1364 * if you specify something other than system or front page. Defaults to system.
1366 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1367 $this->settings = new stdClass();
1368 $this->name = $name;
1369 $this->visiblename = $visiblename;
1370 if (is_array($req_capability)) {
1371 $this->req_capability = $req_capability;
1372 } else {
1373 $this->req_capability = array($req_capability);
1375 $this->hidden = $hidden;
1376 $this->context = $context;
1380 * see admin_category
1382 * @param string $name
1383 * @param bool $findpath
1384 * @return mixed Object (this) if name == this->name, else returns null
1386 public function locate($name, $findpath=false) {
1387 if ($this->name == $name) {
1388 if ($findpath) {
1389 $this->visiblepath = array($this->visiblename);
1390 $this->path = array($this->name);
1392 return $this;
1393 } else {
1394 $return = NULL;
1395 return $return;
1400 * Search string in settings page.
1402 * @param string $query
1403 * @return array
1405 public function search($query) {
1406 $found = array();
1408 foreach ($this->settings as $setting) {
1409 if ($setting->is_related($query)) {
1410 $found[] = $setting;
1414 if ($found) {
1415 $result = new stdClass();
1416 $result->page = $this;
1417 $result->settings = $found;
1418 return array($this->name => $result);
1421 $found = false;
1422 if (strpos(strtolower($this->name), $query) !== false) {
1423 $found = true;
1424 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1425 $found = true;
1427 if ($found) {
1428 $result = new stdClass();
1429 $result->page = $this;
1430 $result->settings = array();
1431 return array($this->name => $result);
1432 } else {
1433 return array();
1438 * This function always returns false, required by interface
1440 * @param string $name
1441 * @return bool Always false
1443 public function prune($name) {
1444 return false;
1448 * adds an admin_setting to this admin_settingpage
1450 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1451 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1453 * @param object $setting is the admin_setting object you want to add
1454 * @return bool true if successful, false if not
1456 public function add($setting) {
1457 if (!($setting instanceof admin_setting)) {
1458 debugging('error - not a setting instance');
1459 return false;
1462 $this->settings->{$setting->name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1554 * Constructor
1555 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1556 * or 'myplugin/mysetting' for ones in config_plugins.
1557 * @param string $visiblename localised name
1558 * @param string $description localised long description
1559 * @param mixed $defaultsetting string or array depending on implementation
1561 public function __construct($name, $visiblename, $description, $defaultsetting) {
1562 $this->parse_setting_name($name);
1563 $this->visiblename = $visiblename;
1564 $this->description = $description;
1565 $this->defaultsetting = $defaultsetting;
1569 * Generic function to add a flag to this admin setting.
1571 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1572 * @param bool $default - The default for the flag
1573 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1574 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1576 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1577 if (empty($this->flags[$shortname])) {
1578 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1579 } else {
1580 $this->flags[$shortname]->set_options($enabled, $default);
1585 * Set the enabled options flag on this admin setting.
1587 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1588 * @param bool $default - The default for the flag
1590 public function set_enabled_flag_options($enabled, $default) {
1591 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1595 * Set the advanced options flag on this admin setting.
1597 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1598 * @param bool $default - The default for the flag
1600 public function set_advanced_flag_options($enabled, $default) {
1601 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1606 * Set the locked options flag on this admin setting.
1608 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1609 * @param bool $default - The default for the flag
1611 public function set_locked_flag_options($enabled, $default) {
1612 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1616 * Get the currently saved value for a setting flag
1618 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1619 * @return bool
1621 public function get_setting_flag_value(admin_setting_flag $flag) {
1622 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1623 if (!isset($value)) {
1624 $value = $flag->get_default();
1627 return !empty($value);
1631 * Get the list of defaults for the flags on this setting.
1633 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1635 public function get_setting_flag_defaults(& $defaults) {
1636 foreach ($this->flags as $flag) {
1637 if ($flag->is_enabled() && $flag->get_default()) {
1638 $defaults[] = $flag->get_displayname();
1644 * Output the input fields for the advanced and locked flags on this setting.
1646 * @param bool $adv - The current value of the advanced flag.
1647 * @param bool $locked - The current value of the locked flag.
1648 * @return string $output - The html for the flags.
1650 public function output_setting_flags() {
1651 $output = '';
1653 foreach ($this->flags as $flag) {
1654 if ($flag->is_enabled()) {
1655 $output .= $flag->output_setting_flag($this);
1659 if (!empty($output)) {
1660 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1662 return $output;
1666 * Write the values of the flags for this admin setting.
1668 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1669 * @return bool - true if successful.
1671 public function write_setting_flags($data) {
1672 $result = true;
1673 foreach ($this->flags as $flag) {
1674 $result = $result && $flag->write_setting_flag($this, $data);
1676 return $result;
1680 * Set up $this->name and potentially $this->plugin
1682 * Set up $this->name and possibly $this->plugin based on whether $name looks
1683 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1684 * on the names, that is, output a developer debug warning if the name
1685 * contains anything other than [a-zA-Z0-9_]+.
1687 * @param string $name the setting name passed in to the constructor.
1689 private function parse_setting_name($name) {
1690 $bits = explode('/', $name);
1691 if (count($bits) > 2) {
1692 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1694 $this->name = array_pop($bits);
1695 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1698 if (!empty($bits)) {
1699 $this->plugin = array_pop($bits);
1700 if ($this->plugin === 'moodle') {
1701 $this->plugin = null;
1702 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1703 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1709 * Returns the fullname prefixed by the plugin
1710 * @return string
1712 public function get_full_name() {
1713 return 's_'.$this->plugin.'_'.$this->name;
1717 * Returns the ID string based on plugin and name
1718 * @return string
1720 public function get_id() {
1721 return 'id_s_'.$this->plugin.'_'.$this->name;
1725 * @param bool $affectsmodinfo If true, changes to this setting will
1726 * cause the course cache to be rebuilt
1728 public function set_affects_modinfo($affectsmodinfo) {
1729 $this->affectsmodinfo = $affectsmodinfo;
1733 * Returns the config if possible
1735 * @return mixed returns config if successful else null
1737 public function config_read($name) {
1738 global $CFG;
1739 if (!empty($this->plugin)) {
1740 $value = get_config($this->plugin, $name);
1741 return $value === false ? NULL : $value;
1743 } else {
1744 if (isset($CFG->$name)) {
1745 return $CFG->$name;
1746 } else {
1747 return NULL;
1753 * Used to set a config pair and log change
1755 * @param string $name
1756 * @param mixed $value Gets converted to string if not null
1757 * @return bool Write setting to config table
1759 public function config_write($name, $value) {
1760 global $DB, $USER, $CFG;
1762 if ($this->nosave) {
1763 return true;
1766 // make sure it is a real change
1767 $oldvalue = get_config($this->plugin, $name);
1768 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1769 $value = is_null($value) ? null : (string)$value;
1771 if ($oldvalue === $value) {
1772 return true;
1775 // store change
1776 set_config($name, $value, $this->plugin);
1778 // Some admin settings affect course modinfo
1779 if ($this->affectsmodinfo) {
1780 // Clear course cache for all courses
1781 rebuild_course_cache(0, true);
1784 $this->add_to_config_log($name, $oldvalue, $value);
1786 return true; // BC only
1790 * Log config changes if necessary.
1791 * @param string $name
1792 * @param string $oldvalue
1793 * @param string $value
1795 protected function add_to_config_log($name, $oldvalue, $value) {
1796 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1800 * Returns current value of this setting
1801 * @return mixed array or string depending on instance, NULL means not set yet
1803 public abstract function get_setting();
1806 * Returns default setting if exists
1807 * @return mixed array or string depending on instance; NULL means no default, user must supply
1809 public function get_defaultsetting() {
1810 $adminroot = admin_get_root(false, false);
1811 if (!empty($adminroot->custom_defaults)) {
1812 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1813 if (isset($adminroot->custom_defaults[$plugin])) {
1814 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1815 return $adminroot->custom_defaults[$plugin][$this->name];
1819 return $this->defaultsetting;
1823 * Store new setting
1825 * @param mixed $data string or array, must not be NULL
1826 * @return string empty string if ok, string error message otherwise
1828 public abstract function write_setting($data);
1831 * Return part of form with setting
1832 * This function should always be overwritten
1834 * @param mixed $data array or string depending on setting
1835 * @param string $query
1836 * @return string
1838 public function output_html($data, $query='') {
1839 // should be overridden
1840 return;
1844 * Function called if setting updated - cleanup, cache reset, etc.
1845 * @param string $functionname Sets the function name
1846 * @return void
1848 public function set_updatedcallback($functionname) {
1849 $this->updatedcallback = $functionname;
1853 * Execute postupdatecallback if necessary.
1854 * @param mixed $original original value before write_setting()
1855 * @return bool true if changed, false if not.
1857 public function post_write_settings($original) {
1858 // Comparison must work for arrays too.
1859 if (serialize($original) === serialize($this->get_setting())) {
1860 return false;
1863 $callbackfunction = $this->updatedcallback;
1864 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1865 $callbackfunction($this->get_full_name());
1867 return true;
1871 * Is setting related to query text - used when searching
1872 * @param string $query
1873 * @return bool
1875 public function is_related($query) {
1876 if (strpos(strtolower($this->name), $query) !== false) {
1877 return true;
1879 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1883 return true;
1885 $current = $this->get_setting();
1886 if (!is_null($current)) {
1887 if (is_string($current)) {
1888 if (strpos(core_text::strtolower($current), $query) !== false) {
1889 return true;
1893 $default = $this->get_defaultsetting();
1894 if (!is_null($default)) {
1895 if (is_string($default)) {
1896 if (strpos(core_text::strtolower($default), $query) !== false) {
1897 return true;
1901 return false;
1906 * An additional option that can be applied to an admin setting.
1907 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class admin_setting_flag {
1912 /** @var bool Flag to indicate if this option can be toggled for this setting */
1913 private $enabled = false;
1914 /** @var bool Flag to indicate if this option defaults to true or false */
1915 private $default = false;
1916 /** @var string Short string used to create setting name - e.g. 'adv' */
1917 private $shortname = '';
1918 /** @var string String used as the label for this flag */
1919 private $displayname = '';
1920 /** @const Checkbox for this flag is displayed in admin page */
1921 const ENABLED = true;
1922 /** @const Checkbox for this flag is not displayed in admin page */
1923 const DISABLED = false;
1926 * Constructor
1928 * @param bool $enabled Can this option can be toggled.
1929 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1930 * @param bool $default The default checked state for this setting option.
1931 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1932 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1934 public function __construct($enabled, $default, $shortname, $displayname) {
1935 $this->shortname = $shortname;
1936 $this->displayname = $displayname;
1937 $this->set_options($enabled, $default);
1941 * Update the values of this setting options class
1943 * @param bool $enabled Can this option can be toggled.
1944 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1945 * @param bool $default The default checked state for this setting option.
1947 public function set_options($enabled, $default) {
1948 $this->enabled = $enabled;
1949 $this->default = $default;
1953 * Should this option appear in the interface and be toggleable?
1955 * @return bool Is it enabled?
1957 public function is_enabled() {
1958 return $this->enabled;
1962 * Should this option be checked by default?
1964 * @return bool Is it on by default?
1966 public function get_default() {
1967 return $this->default;
1971 * Return the short name for this flag. e.g. 'adv' or 'locked'
1973 * @return string
1975 public function get_shortname() {
1976 return $this->shortname;
1980 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1982 * @return string
1984 public function get_displayname() {
1985 return $this->displayname;
1989 * Save the submitted data for this flag - or set it to the default if $data is null.
1991 * @param admin_setting $setting - The admin setting for this flag
1992 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1993 * @return bool
1995 public function write_setting_flag(admin_setting $setting, $data) {
1996 $result = true;
1997 if ($this->is_enabled()) {
1998 if (!isset($data)) {
1999 $value = $this->get_default();
2000 } else {
2001 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2003 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2006 return $result;
2011 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2013 * @param admin_setting $setting - The admin setting for this flag
2014 * @return string - The html for the checkbox.
2016 public function output_setting_flag(admin_setting $setting) {
2017 $value = $setting->get_setting_flag_value($this);
2018 $output = ' <input type="checkbox" class="form-checkbox" ' .
2019 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2020 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2021 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2022 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2023 $this->get_displayname() .
2024 ' </label> ';
2025 return $output;
2031 * No setting - just heading and text.
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class admin_setting_heading extends admin_setting {
2038 * not a setting, just text
2039 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2040 * @param string $heading heading
2041 * @param string $information text in box
2043 public function __construct($name, $heading, $information) {
2044 $this->nosave = true;
2045 parent::__construct($name, $heading, $information, '');
2049 * Always returns true
2050 * @return bool Always returns true
2052 public function get_setting() {
2053 return true;
2057 * Always returns true
2058 * @return bool Always returns true
2060 public function get_defaultsetting() {
2061 return true;
2065 * Never write settings
2066 * @return string Always returns an empty string
2068 public function write_setting($data) {
2069 // do not write any setting
2070 return '';
2074 * Returns an HTML string
2075 * @return string Returns an HTML string
2077 public function output_html($data, $query='') {
2078 global $OUTPUT;
2079 $return = '';
2080 if ($this->visiblename != '') {
2081 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2083 if ($this->description != '') {
2084 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2086 return $return;
2092 * The most flexibly setting, user is typing text
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configtext extends admin_setting {
2098 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2099 public $paramtype;
2100 /** @var int default field size */
2101 public $size;
2104 * Config text constructor
2106 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2107 * @param string $visiblename localised
2108 * @param string $description long localised info
2109 * @param string $defaultsetting
2110 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2111 * @param int $size default field size
2113 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2114 $this->paramtype = $paramtype;
2115 if (!is_null($size)) {
2116 $this->size = $size;
2117 } else {
2118 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2120 parent::__construct($name, $visiblename, $description, $defaultsetting);
2124 * Return the setting
2126 * @return mixed returns config if successful else null
2128 public function get_setting() {
2129 return $this->config_read($this->name);
2132 public function write_setting($data) {
2133 if ($this->paramtype === PARAM_INT and $data === '') {
2134 // do not complain if '' used instead of 0
2135 $data = 0;
2137 // $data is a string
2138 $validated = $this->validate($data);
2139 if ($validated !== true) {
2140 return $validated;
2142 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2146 * Validate data before storage
2147 * @param string data
2148 * @return mixed true if ok string if error found
2150 public function validate($data) {
2151 // allow paramtype to be a custom regex if it is the form of /pattern/
2152 if (preg_match('#^/.*/$#', $this->paramtype)) {
2153 if (preg_match($this->paramtype, $data)) {
2154 return true;
2155 } else {
2156 return get_string('validateerror', 'admin');
2159 } else if ($this->paramtype === PARAM_RAW) {
2160 return true;
2162 } else {
2163 $cleaned = clean_param($data, $this->paramtype);
2164 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2165 return true;
2166 } else {
2167 return get_string('validateerror', 'admin');
2173 * Return an XHTML string for the setting
2174 * @return string Returns an XHTML string
2176 public function output_html($data, $query='') {
2177 $default = $this->get_defaultsetting();
2179 return format_admin_setting($this, $this->visiblename,
2180 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2181 $this->description, true, '', $default, $query);
2187 * General text area without html editor.
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtextarea extends admin_setting_configtext {
2192 private $rows;
2193 private $cols;
2196 * @param string $name
2197 * @param string $visiblename
2198 * @param string $description
2199 * @param mixed $defaultsetting string or array
2200 * @param mixed $paramtype
2201 * @param string $cols The number of columns to make the editor
2202 * @param string $rows The number of rows to make the editor
2204 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2205 $this->rows = $rows;
2206 $this->cols = $cols;
2207 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2211 * Returns an XHTML string for the editor
2213 * @param string $data
2214 * @param string $query
2215 * @return string XHTML string for the editor
2217 public function output_html($data, $query='') {
2218 $default = $this->get_defaultsetting();
2220 $defaultinfo = $default;
2221 if (!is_null($default) and $default !== '') {
2222 $defaultinfo = "\n".$default;
2225 return format_admin_setting($this, $this->visiblename,
2226 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2227 $this->description, true, '', $defaultinfo, $query);
2233 * General text area with html editor.
2235 class admin_setting_confightmleditor extends admin_setting_configtext {
2236 private $rows;
2237 private $cols;
2240 * @param string $name
2241 * @param string $visiblename
2242 * @param string $description
2243 * @param mixed $defaultsetting string or array
2244 * @param mixed $paramtype
2246 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2247 $this->rows = $rows;
2248 $this->cols = $cols;
2249 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2250 editors_head_setup();
2254 * Returns an XHTML string for the editor
2256 * @param string $data
2257 * @param string $query
2258 * @return string XHTML string for the editor
2260 public function output_html($data, $query='') {
2261 $default = $this->get_defaultsetting();
2263 $defaultinfo = $default;
2264 if (!is_null($default) and $default !== '') {
2265 $defaultinfo = "\n".$default;
2268 $editor = editors_get_preferred_editor(FORMAT_HTML);
2269 $editor->use_editor($this->get_id(), array('noclean'=>true));
2271 return format_admin_setting($this, $this->visiblename,
2272 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2273 $this->description, true, '', $defaultinfo, $query);
2279 * Password field, allows unmasking of password
2281 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2283 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2285 * Constructor
2286 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2287 * @param string $visiblename localised
2288 * @param string $description long localised info
2289 * @param string $defaultsetting default password
2291 public function __construct($name, $visiblename, $description, $defaultsetting) {
2292 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2296 * Log config changes if necessary.
2297 * @param string $name
2298 * @param string $oldvalue
2299 * @param string $value
2301 protected function add_to_config_log($name, $oldvalue, $value) {
2302 if ($value !== '') {
2303 $value = '********';
2305 if ($oldvalue !== '' and $oldvalue !== null) {
2306 $oldvalue = '********';
2308 parent::add_to_config_log($name, $oldvalue, $value);
2312 * Returns XHTML for the field
2313 * Writes Javascript into the HTML below right before the last div
2315 * @todo Make javascript available through newer methods if possible
2316 * @param string $data Value for the field
2317 * @param string $query Passed as final argument for format_admin_setting
2318 * @return string XHTML field
2320 public function output_html($data, $query='') {
2321 $id = $this->get_id();
2322 $unmask = get_string('unmaskpassword', 'form');
2323 $unmaskjs = '<script type="text/javascript">
2324 //<![CDATA[
2325 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2327 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2329 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2331 var unmaskchb = document.createElement("input");
2332 unmaskchb.setAttribute("type", "checkbox");
2333 unmaskchb.setAttribute("id", "'.$id.'unmask");
2334 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2335 unmaskdiv.appendChild(unmaskchb);
2337 var unmasklbl = document.createElement("label");
2338 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2339 if (is_ie) {
2340 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2341 } else {
2342 unmasklbl.setAttribute("for", "'.$id.'unmask");
2344 unmaskdiv.appendChild(unmasklbl);
2346 if (is_ie) {
2347 // ugly hack to work around the famous onchange IE bug
2348 unmaskchb.onclick = function() {this.blur();};
2349 unmaskdiv.onclick = function() {this.blur();};
2351 //]]>
2352 </script>';
2353 return format_admin_setting($this, $this->visiblename,
2354 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
2355 $this->description, true, '', NULL, $query);
2360 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2361 * Note: Only advanced makes sense right now - locked does not.
2363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2365 class admin_setting_configempty extends admin_setting_configtext {
2368 * @param string $name
2369 * @param string $visiblename
2370 * @param string $description
2372 public function __construct($name, $visiblename, $description) {
2373 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2377 * Returns an XHTML string for the hidden field
2379 * @param string $data
2380 * @param string $query
2381 * @return string XHTML string for the editor
2383 public function output_html($data, $query='') {
2384 return format_admin_setting($this,
2385 $this->visiblename,
2386 '<div class="form-empty" >' .
2387 '<input type="hidden"' .
2388 ' id="'. $this->get_id() .'"' .
2389 ' name="'. $this->get_full_name() .'"' .
2390 ' value=""/></div>',
2391 $this->description,
2392 true,
2394 get_string('none'),
2395 $query);
2401 * Path to directory
2403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2405 class admin_setting_configfile extends admin_setting_configtext {
2407 * Constructor
2408 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2409 * @param string $visiblename localised
2410 * @param string $description long localised info
2411 * @param string $defaultdirectory default directory location
2413 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2414 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2418 * Returns XHTML for the field
2420 * Returns XHTML for the field and also checks whether the file
2421 * specified in $data exists using file_exists()
2423 * @param string $data File name and path to use in value attr
2424 * @param string $query
2425 * @return string XHTML field
2427 public function output_html($data, $query='') {
2428 $default = $this->get_defaultsetting();
2430 if ($data) {
2431 if (file_exists($data)) {
2432 $executable = '<span class="pathok">&#x2714;</span>';
2433 } else {
2434 $executable = '<span class="patherror">&#x2718;</span>';
2436 } else {
2437 $executable = '';
2440 return format_admin_setting($this, $this->visiblename,
2441 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2442 $this->description, true, '', $default, $query);
2446 * Checks if execpatch has been disabled in config.php
2448 public function write_setting($data) {
2449 global $CFG;
2450 if (!empty($CFG->preventexecpath)) {
2451 if ($this->get_setting() === null) {
2452 // Use default during installation.
2453 $data = $this->get_defaultsetting();
2454 if ($data === null) {
2455 $data = '';
2457 } else {
2458 return '';
2461 return parent::write_setting($data);
2467 * Path to executable file
2469 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2471 class admin_setting_configexecutable extends admin_setting_configfile {
2474 * Returns an XHTML field
2476 * @param string $data This is the value for the field
2477 * @param string $query
2478 * @return string XHTML field
2480 public function output_html($data, $query='') {
2481 global $CFG;
2482 $default = $this->get_defaultsetting();
2484 if ($data) {
2485 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2486 $executable = '<span class="pathok">&#x2714;</span>';
2487 } else {
2488 $executable = '<span class="patherror">&#x2718;</span>';
2490 } else {
2491 $executable = '';
2493 if (!empty($CFG->preventexecpath)) {
2494 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2497 return format_admin_setting($this, $this->visiblename,
2498 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2499 $this->description, true, '', $default, $query);
2505 * Path to directory
2507 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2509 class admin_setting_configdirectory extends admin_setting_configfile {
2512 * Returns an XHTML field
2514 * @param string $data This is the value for the field
2515 * @param string $query
2516 * @return string XHTML
2518 public function output_html($data, $query='') {
2519 $default = $this->get_defaultsetting();
2521 if ($data) {
2522 if (file_exists($data) and is_dir($data)) {
2523 $executable = '<span class="pathok">&#x2714;</span>';
2524 } else {
2525 $executable = '<span class="patherror">&#x2718;</span>';
2527 } else {
2528 $executable = '';
2531 return format_admin_setting($this, $this->visiblename,
2532 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2533 $this->description, true, '', $default, $query);
2539 * Checkbox
2541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2543 class admin_setting_configcheckbox extends admin_setting {
2544 /** @var string Value used when checked */
2545 public $yes;
2546 /** @var string Value used when not checked */
2547 public $no;
2550 * Constructor
2551 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2552 * @param string $visiblename localised
2553 * @param string $description long localised info
2554 * @param string $defaultsetting
2555 * @param string $yes value used when checked
2556 * @param string $no value used when not checked
2558 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2559 parent::__construct($name, $visiblename, $description, $defaultsetting);
2560 $this->yes = (string)$yes;
2561 $this->no = (string)$no;
2565 * Retrieves the current setting using the objects name
2567 * @return string
2569 public function get_setting() {
2570 return $this->config_read($this->name);
2574 * Sets the value for the setting
2576 * Sets the value for the setting to either the yes or no values
2577 * of the object by comparing $data to yes
2579 * @param mixed $data Gets converted to str for comparison against yes value
2580 * @return string empty string or error
2582 public function write_setting($data) {
2583 if ((string)$data === $this->yes) { // convert to strings before comparison
2584 $data = $this->yes;
2585 } else {
2586 $data = $this->no;
2588 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2592 * Returns an XHTML checkbox field
2594 * @param string $data If $data matches yes then checkbox is checked
2595 * @param string $query
2596 * @return string XHTML field
2598 public function output_html($data, $query='') {
2599 $default = $this->get_defaultsetting();
2601 if (!is_null($default)) {
2602 if ((string)$default === $this->yes) {
2603 $defaultinfo = get_string('checkboxyes', 'admin');
2604 } else {
2605 $defaultinfo = get_string('checkboxno', 'admin');
2607 } else {
2608 $defaultinfo = NULL;
2611 if ((string)$data === $this->yes) { // convert to strings before comparison
2612 $checked = 'checked="checked"';
2613 } else {
2614 $checked = '';
2617 return format_admin_setting($this, $this->visiblename,
2618 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2619 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2620 $this->description, true, '', $defaultinfo, $query);
2626 * Multiple checkboxes, each represents different value, stored in csv format
2628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2630 class admin_setting_configmulticheckbox extends admin_setting {
2631 /** @var array Array of choices value=>label */
2632 public $choices;
2635 * Constructor: uses parent::__construct
2637 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2638 * @param string $visiblename localised
2639 * @param string $description long localised info
2640 * @param array $defaultsetting array of selected
2641 * @param array $choices array of $value=>$label for each checkbox
2643 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2644 $this->choices = $choices;
2645 parent::__construct($name, $visiblename, $description, $defaultsetting);
2649 * This public function may be used in ancestors for lazy loading of choices
2651 * @todo Check if this function is still required content commented out only returns true
2652 * @return bool true if loaded, false if error
2654 public function load_choices() {
2656 if (is_array($this->choices)) {
2657 return true;
2659 .... load choices here
2661 return true;
2665 * Is setting related to query text - used when searching
2667 * @param string $query
2668 * @return bool true on related, false on not or failure
2670 public function is_related($query) {
2671 if (!$this->load_choices() or empty($this->choices)) {
2672 return false;
2674 if (parent::is_related($query)) {
2675 return true;
2678 foreach ($this->choices as $desc) {
2679 if (strpos(core_text::strtolower($desc), $query) !== false) {
2680 return true;
2683 return false;
2687 * Returns the current setting if it is set
2689 * @return mixed null if null, else an array
2691 public function get_setting() {
2692 $result = $this->config_read($this->name);
2694 if (is_null($result)) {
2695 return NULL;
2697 if ($result === '') {
2698 return array();
2700 $enabled = explode(',', $result);
2701 $setting = array();
2702 foreach ($enabled as $option) {
2703 $setting[$option] = 1;
2705 return $setting;
2709 * Saves the setting(s) provided in $data
2711 * @param array $data An array of data, if not array returns empty str
2712 * @return mixed empty string on useless data or bool true=success, false=failed
2714 public function write_setting($data) {
2715 if (!is_array($data)) {
2716 return ''; // ignore it
2718 if (!$this->load_choices() or empty($this->choices)) {
2719 return '';
2721 unset($data['xxxxx']);
2722 $result = array();
2723 foreach ($data as $key => $value) {
2724 if ($value and array_key_exists($key, $this->choices)) {
2725 $result[] = $key;
2728 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2732 * Returns XHTML field(s) as required by choices
2734 * Relies on data being an array should data ever be another valid vartype with
2735 * acceptable value this may cause a warning/error
2736 * if (!is_array($data)) would fix the problem
2738 * @todo Add vartype handling to ensure $data is an array
2740 * @param array $data An array of checked values
2741 * @param string $query
2742 * @return string XHTML field
2744 public function output_html($data, $query='') {
2745 if (!$this->load_choices() or empty($this->choices)) {
2746 return '';
2748 $default = $this->get_defaultsetting();
2749 if (is_null($default)) {
2750 $default = array();
2752 if (is_null($data)) {
2753 $data = array();
2755 $options = array();
2756 $defaults = array();
2757 foreach ($this->choices as $key=>$description) {
2758 if (!empty($data[$key])) {
2759 $checked = 'checked="checked"';
2760 } else {
2761 $checked = '';
2763 if (!empty($default[$key])) {
2764 $defaults[] = $description;
2767 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2768 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2771 if (is_null($default)) {
2772 $defaultinfo = NULL;
2773 } else if (!empty($defaults)) {
2774 $defaultinfo = implode(', ', $defaults);
2775 } else {
2776 $defaultinfo = get_string('none');
2779 $return = '<div class="form-multicheckbox">';
2780 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2781 if ($options) {
2782 $return .= '<ul>';
2783 foreach ($options as $option) {
2784 $return .= '<li>'.$option.'</li>';
2786 $return .= '</ul>';
2788 $return .= '</div>';
2790 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2797 * Multiple checkboxes 2, value stored as string 00101011
2799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2801 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2804 * Returns the setting if set
2806 * @return mixed null if not set, else an array of set settings
2808 public function get_setting() {
2809 $result = $this->config_read($this->name);
2810 if (is_null($result)) {
2811 return NULL;
2813 if (!$this->load_choices()) {
2814 return NULL;
2816 $result = str_pad($result, count($this->choices), '0');
2817 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2818 $setting = array();
2819 foreach ($this->choices as $key=>$unused) {
2820 $value = array_shift($result);
2821 if ($value) {
2822 $setting[$key] = 1;
2825 return $setting;
2829 * Save setting(s) provided in $data param
2831 * @param array $data An array of settings to save
2832 * @return mixed empty string for bad data or bool true=>success, false=>error
2834 public function write_setting($data) {
2835 if (!is_array($data)) {
2836 return ''; // ignore it
2838 if (!$this->load_choices() or empty($this->choices)) {
2839 return '';
2841 $result = '';
2842 foreach ($this->choices as $key=>$unused) {
2843 if (!empty($data[$key])) {
2844 $result .= '1';
2845 } else {
2846 $result .= '0';
2849 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2855 * Select one value from list
2857 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859 class admin_setting_configselect extends admin_setting {
2860 /** @var array Array of choices value=>label */
2861 public $choices;
2864 * Constructor
2865 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2866 * @param string $visiblename localised
2867 * @param string $description long localised info
2868 * @param string|int $defaultsetting
2869 * @param array $choices array of $value=>$label for each selection
2871 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2872 $this->choices = $choices;
2873 parent::__construct($name, $visiblename, $description, $defaultsetting);
2877 * This function may be used in ancestors for lazy loading of choices
2879 * Override this method if loading of choices is expensive, such
2880 * as when it requires multiple db requests.
2882 * @return bool true if loaded, false if error
2884 public function load_choices() {
2886 if (is_array($this->choices)) {
2887 return true;
2889 .... load choices here
2891 return true;
2895 * Check if this is $query is related to a choice
2897 * @param string $query
2898 * @return bool true if related, false if not
2900 public function is_related($query) {
2901 if (parent::is_related($query)) {
2902 return true;
2904 if (!$this->load_choices()) {
2905 return false;
2907 foreach ($this->choices as $key=>$value) {
2908 if (strpos(core_text::strtolower($key), $query) !== false) {
2909 return true;
2911 if (strpos(core_text::strtolower($value), $query) !== false) {
2912 return true;
2915 return false;
2919 * Return the setting
2921 * @return mixed returns config if successful else null
2923 public function get_setting() {
2924 return $this->config_read($this->name);
2928 * Save a setting
2930 * @param string $data
2931 * @return string empty of error string
2933 public function write_setting($data) {
2934 if (!$this->load_choices() or empty($this->choices)) {
2935 return '';
2937 if (!array_key_exists($data, $this->choices)) {
2938 return ''; // ignore it
2941 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2945 * Returns XHTML select field
2947 * Ensure the options are loaded, and generate the XHTML for the select
2948 * element and any warning message. Separating this out from output_html
2949 * makes it easier to subclass this class.
2951 * @param string $data the option to show as selected.
2952 * @param string $current the currently selected option in the database, null if none.
2953 * @param string $default the default selected option.
2954 * @return array the HTML for the select element, and a warning message.
2956 public function output_select_html($data, $current, $default, $extraname = '') {
2957 if (!$this->load_choices() or empty($this->choices)) {
2958 return array('', '');
2961 $warning = '';
2962 if (is_null($current)) {
2963 // first run
2964 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2965 // no warning
2966 } else if (!array_key_exists($current, $this->choices)) {
2967 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2968 if (!is_null($default) and $data == $current) {
2969 $data = $default; // use default instead of first value when showing the form
2973 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2974 foreach ($this->choices as $key => $value) {
2975 // the string cast is needed because key may be integer - 0 is equal to most strings!
2976 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2978 $selecthtml .= '</select>';
2979 return array($selecthtml, $warning);
2983 * Returns XHTML select field and wrapping div(s)
2985 * @see output_select_html()
2987 * @param string $data the option to show as selected
2988 * @param string $query
2989 * @return string XHTML field and wrapping div
2991 public function output_html($data, $query='') {
2992 $default = $this->get_defaultsetting();
2993 $current = $this->get_setting();
2995 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2996 if (!$selecthtml) {
2997 return '';
3000 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3001 $defaultinfo = $this->choices[$default];
3002 } else {
3003 $defaultinfo = NULL;
3006 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3008 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3014 * Select multiple items from list
3016 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3018 class admin_setting_configmultiselect extends admin_setting_configselect {
3020 * Constructor
3021 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3022 * @param string $visiblename localised
3023 * @param string $description long localised info
3024 * @param array $defaultsetting array of selected items
3025 * @param array $choices array of $value=>$label for each list item
3027 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3028 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3032 * Returns the select setting(s)
3034 * @return mixed null or array. Null if no settings else array of setting(s)
3036 public function get_setting() {
3037 $result = $this->config_read($this->name);
3038 if (is_null($result)) {
3039 return NULL;
3041 if ($result === '') {
3042 return array();
3044 return explode(',', $result);
3048 * Saves setting(s) provided through $data
3050 * Potential bug in the works should anyone call with this function
3051 * using a vartype that is not an array
3053 * @param array $data
3055 public function write_setting($data) {
3056 if (!is_array($data)) {
3057 return ''; //ignore it
3059 if (!$this->load_choices() or empty($this->choices)) {
3060 return '';
3063 unset($data['xxxxx']);
3065 $save = array();
3066 foreach ($data as $value) {
3067 if (!array_key_exists($value, $this->choices)) {
3068 continue; // ignore it
3070 $save[] = $value;
3073 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3077 * Is setting related to query text - used when searching
3079 * @param string $query
3080 * @return bool true if related, false if not
3082 public function is_related($query) {
3083 if (!$this->load_choices() or empty($this->choices)) {
3084 return false;
3086 if (parent::is_related($query)) {
3087 return true;
3090 foreach ($this->choices as $desc) {
3091 if (strpos(core_text::strtolower($desc), $query) !== false) {
3092 return true;
3095 return false;
3099 * Returns XHTML multi-select field
3101 * @todo Add vartype handling to ensure $data is an array
3102 * @param array $data Array of values to select by default
3103 * @param string $query
3104 * @return string XHTML multi-select field
3106 public function output_html($data, $query='') {
3107 if (!$this->load_choices() or empty($this->choices)) {
3108 return '';
3110 $choices = $this->choices;
3111 $default = $this->get_defaultsetting();
3112 if (is_null($default)) {
3113 $default = array();
3115 if (is_null($data)) {
3116 $data = array();
3119 $defaults = array();
3120 $size = min(10, count($this->choices));
3121 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3122 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3123 foreach ($this->choices as $key => $description) {
3124 if (in_array($key, $data)) {
3125 $selected = 'selected="selected"';
3126 } else {
3127 $selected = '';
3129 if (in_array($key, $default)) {
3130 $defaults[] = $description;
3133 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3136 if (is_null($default)) {
3137 $defaultinfo = NULL;
3138 } if (!empty($defaults)) {
3139 $defaultinfo = implode(', ', $defaults);
3140 } else {
3141 $defaultinfo = get_string('none');
3144 $return .= '</select></div>';
3145 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3150 * Time selector
3152 * This is a liiitle bit messy. we're using two selects, but we're returning
3153 * them as an array named after $name (so we only use $name2 internally for the setting)
3155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3157 class admin_setting_configtime extends admin_setting {
3158 /** @var string Used for setting second select (minutes) */
3159 public $name2;
3162 * Constructor
3163 * @param string $hoursname setting for hours
3164 * @param string $minutesname setting for hours
3165 * @param string $visiblename localised
3166 * @param string $description long localised info
3167 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3169 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3170 $this->name2 = $minutesname;
3171 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3175 * Get the selected time
3177 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3179 public function get_setting() {
3180 $result1 = $this->config_read($this->name);
3181 $result2 = $this->config_read($this->name2);
3182 if (is_null($result1) or is_null($result2)) {
3183 return NULL;
3186 return array('h' => $result1, 'm' => $result2);
3190 * Store the time (hours and minutes)
3192 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3193 * @return bool true if success, false if not
3195 public function write_setting($data) {
3196 if (!is_array($data)) {
3197 return '';
3200 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3201 return ($result ? '' : get_string('errorsetting', 'admin'));
3205 * Returns XHTML time select fields
3207 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3208 * @param string $query
3209 * @return string XHTML time select fields and wrapping div(s)
3211 public function output_html($data, $query='') {
3212 $default = $this->get_defaultsetting();
3214 if (is_array($default)) {
3215 $defaultinfo = $default['h'].':'.$default['m'];
3216 } else {
3217 $defaultinfo = NULL;
3220 $return = '<div class="form-time defaultsnext">'.
3221 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
3222 for ($i = 0; $i < 24; $i++) {
3223 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3225 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
3226 for ($i = 0; $i < 60; $i += 5) {
3227 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
3229 $return .= '</select></div>';
3230 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3237 * Seconds duration setting.
3239 * @copyright 2012 Petr Skoda (http://skodak.org)
3240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3242 class admin_setting_configduration extends admin_setting {
3244 /** @var int default duration unit */
3245 protected $defaultunit;
3248 * Constructor
3249 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3250 * or 'myplugin/mysetting' for ones in config_plugins.
3251 * @param string $visiblename localised name
3252 * @param string $description localised long description
3253 * @param mixed $defaultsetting string or array depending on implementation
3254 * @param int $defaultunit - day, week, etc. (in seconds)
3256 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3257 if (is_number($defaultsetting)) {
3258 $defaultsetting = self::parse_seconds($defaultsetting);
3260 $units = self::get_units();
3261 if (isset($units[$defaultunit])) {
3262 $this->defaultunit = $defaultunit;
3263 } else {
3264 $this->defaultunit = 86400;
3266 parent::__construct($name, $visiblename, $description, $defaultsetting);
3270 * Returns selectable units.
3271 * @static
3272 * @return array
3274 protected static function get_units() {
3275 return array(
3276 604800 => get_string('weeks'),
3277 86400 => get_string('days'),
3278 3600 => get_string('hours'),
3279 60 => get_string('minutes'),
3280 1 => get_string('seconds'),
3285 * Converts seconds to some more user friendly string.
3286 * @static
3287 * @param int $seconds
3288 * @return string
3290 protected static function get_duration_text($seconds) {
3291 if (empty($seconds)) {
3292 return get_string('none');
3294 $data = self::parse_seconds($seconds);
3295 switch ($data['u']) {
3296 case (60*60*24*7):
3297 return get_string('numweeks', '', $data['v']);
3298 case (60*60*24):
3299 return get_string('numdays', '', $data['v']);
3300 case (60*60):
3301 return get_string('numhours', '', $data['v']);
3302 case (60):
3303 return get_string('numminutes', '', $data['v']);
3304 default:
3305 return get_string('numseconds', '', $data['v']*$data['u']);
3310 * Finds suitable units for given duration.
3311 * @static
3312 * @param int $seconds
3313 * @return array
3315 protected static function parse_seconds($seconds) {
3316 foreach (self::get_units() as $unit => $unused) {
3317 if ($seconds % $unit === 0) {
3318 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3321 return array('v'=>(int)$seconds, 'u'=>1);
3325 * Get the selected duration as array.
3327 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3329 public function get_setting() {
3330 $seconds = $this->config_read($this->name);
3331 if (is_null($seconds)) {
3332 return null;
3335 return self::parse_seconds($seconds);
3339 * Store the duration as seconds.
3341 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3342 * @return bool true if success, false if not
3344 public function write_setting($data) {
3345 if (!is_array($data)) {
3346 return '';
3349 $seconds = (int)($data['v']*$data['u']);
3350 if ($seconds < 0) {
3351 return get_string('errorsetting', 'admin');
3354 $result = $this->config_write($this->name, $seconds);
3355 return ($result ? '' : get_string('errorsetting', 'admin'));
3359 * Returns duration text+select fields.
3361 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3362 * @param string $query
3363 * @return string duration text+select fields and wrapping div(s)
3365 public function output_html($data, $query='') {
3366 $default = $this->get_defaultsetting();
3368 if (is_number($default)) {
3369 $defaultinfo = self::get_duration_text($default);
3370 } else if (is_array($default)) {
3371 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3372 } else {
3373 $defaultinfo = null;
3376 $units = self::get_units();
3378 $return = '<div class="form-duration defaultsnext">';
3379 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3380 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3381 foreach ($units as $val => $text) {
3382 $selected = '';
3383 if ($data['v'] == 0) {
3384 if ($val == $this->defaultunit) {
3385 $selected = ' selected="selected"';
3387 } else if ($val == $data['u']) {
3388 $selected = ' selected="selected"';
3390 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3392 $return .= '</select></div>';
3393 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3399 * Used to validate a textarea used for ip addresses
3401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3403 class admin_setting_configiplist extends admin_setting_configtextarea {
3406 * Validate the contents of the textarea as IP addresses
3408 * Used to validate a new line separated list of IP addresses collected from
3409 * a textarea control
3411 * @param string $data A list of IP Addresses separated by new lines
3412 * @return mixed bool true for success or string:error on failure
3414 public function validate($data) {
3415 if(!empty($data)) {
3416 $ips = explode("\n", $data);
3417 } else {
3418 return true;
3420 $result = true;
3421 foreach($ips as $ip) {
3422 $ip = trim($ip);
3423 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3424 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3425 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3426 $result = true;
3427 } else {
3428 $result = false;
3429 break;
3432 if($result) {
3433 return true;
3434 } else {
3435 return get_string('validateerror', 'admin');
3442 * An admin setting for selecting one or more users who have a capability
3443 * in the system context
3445 * An admin setting for selecting one or more users, who have a particular capability
3446 * in the system context. Warning, make sure the list will never be too long. There is
3447 * no paging or searching of this list.
3449 * To correctly get a list of users from this config setting, you need to call the
3450 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3452 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3454 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3455 /** @var string The capabilities name */
3456 protected $capability;
3457 /** @var int include admin users too */
3458 protected $includeadmins;
3461 * Constructor.
3463 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3464 * @param string $visiblename localised name
3465 * @param string $description localised long description
3466 * @param array $defaultsetting array of usernames
3467 * @param string $capability string capability name.
3468 * @param bool $includeadmins include administrators
3470 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3471 $this->capability = $capability;
3472 $this->includeadmins = $includeadmins;
3473 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3477 * Load all of the uses who have the capability into choice array
3479 * @return bool Always returns true
3481 function load_choices() {
3482 if (is_array($this->choices)) {
3483 return true;
3485 list($sort, $sortparams) = users_order_by_sql('u');
3486 if (!empty($sortparams)) {
3487 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3488 'This is unexpected, and a problem because there is no way to pass these ' .
3489 'parameters to get_users_by_capability. See MDL-34657.');
3491 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3492 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3493 $this->choices = array(
3494 '$@NONE@$' => get_string('nobody'),
3495 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3497 if ($this->includeadmins) {
3498 $admins = get_admins();
3499 foreach ($admins as $user) {
3500 $this->choices[$user->id] = fullname($user);
3503 if (is_array($users)) {
3504 foreach ($users as $user) {
3505 $this->choices[$user->id] = fullname($user);
3508 return true;
3512 * Returns the default setting for class
3514 * @return mixed Array, or string. Empty string if no default
3516 public function get_defaultsetting() {
3517 $this->load_choices();
3518 $defaultsetting = parent::get_defaultsetting();
3519 if (empty($defaultsetting)) {
3520 return array('$@NONE@$');
3521 } else if (array_key_exists($defaultsetting, $this->choices)) {
3522 return $defaultsetting;
3523 } else {
3524 return '';
3529 * Returns the current setting
3531 * @return mixed array or string
3533 public function get_setting() {
3534 $result = parent::get_setting();
3535 if ($result === null) {
3536 // this is necessary for settings upgrade
3537 return null;
3539 if (empty($result)) {
3540 $result = array('$@NONE@$');
3542 return $result;
3546 * Save the chosen setting provided as $data
3548 * @param array $data
3549 * @return mixed string or array
3551 public function write_setting($data) {
3552 // If all is selected, remove any explicit options.
3553 if (in_array('$@ALL@$', $data)) {
3554 $data = array('$@ALL@$');
3556 // None never needs to be written to the DB.
3557 if (in_array('$@NONE@$', $data)) {
3558 unset($data[array_search('$@NONE@$', $data)]);
3560 return parent::write_setting($data);
3566 * Special checkbox for calendar - resets SESSION vars.
3568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3570 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3572 * Calls the parent::__construct with default values
3574 * name => calendar_adminseesall
3575 * visiblename => get_string('adminseesall', 'admin')
3576 * description => get_string('helpadminseesall', 'admin')
3577 * defaultsetting => 0
3579 public function __construct() {
3580 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3581 get_string('helpadminseesall', 'admin'), '0');
3585 * Stores the setting passed in $data
3587 * @param mixed gets converted to string for comparison
3588 * @return string empty string or error message
3590 public function write_setting($data) {
3591 global $SESSION;
3592 return parent::write_setting($data);
3597 * Special select for settings that are altered in setup.php and can not be altered on the fly
3599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3601 class admin_setting_special_selectsetup extends admin_setting_configselect {
3603 * Reads the setting directly from the database
3605 * @return mixed
3607 public function get_setting() {
3608 // read directly from db!
3609 return get_config(NULL, $this->name);
3613 * Save the setting passed in $data
3615 * @param string $data The setting to save
3616 * @return string empty or error message
3618 public function write_setting($data) {
3619 global $CFG;
3620 // do not change active CFG setting!
3621 $current = $CFG->{$this->name};
3622 $result = parent::write_setting($data);
3623 $CFG->{$this->name} = $current;
3624 return $result;
3630 * Special select for frontpage - stores data in course table
3632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3634 class admin_setting_sitesetselect extends admin_setting_configselect {
3636 * Returns the site name for the selected site
3638 * @see get_site()
3639 * @return string The site name of the selected site
3641 public function get_setting() {
3642 $site = course_get_format(get_site())->get_course();
3643 return $site->{$this->name};
3647 * Updates the database and save the setting
3649 * @param string data
3650 * @return string empty or error message
3652 public function write_setting($data) {
3653 global $DB, $SITE, $COURSE;
3654 if (!in_array($data, array_keys($this->choices))) {
3655 return get_string('errorsetting', 'admin');
3657 $record = new stdClass();
3658 $record->id = SITEID;
3659 $temp = $this->name;
3660 $record->$temp = $data;
3661 $record->timemodified = time();
3663 course_get_format($SITE)->update_course_format_options($record);
3664 $DB->update_record('course', $record);
3666 // Reset caches.
3667 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3668 if ($SITE->id == $COURSE->id) {
3669 $COURSE = $SITE;
3671 format_base::reset_course_cache($SITE->id);
3673 return '';
3680 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3681 * block to hidden.
3683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3685 class admin_setting_bloglevel extends admin_setting_configselect {
3687 * Updates the database and save the setting
3689 * @param string data
3690 * @return string empty or error message
3692 public function write_setting($data) {
3693 global $DB, $CFG;
3694 if ($data == 0) {
3695 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3696 foreach ($blogblocks as $block) {
3697 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3699 } else {
3700 // reenable all blocks only when switching from disabled blogs
3701 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3702 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3703 foreach ($blogblocks as $block) {
3704 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3708 return parent::write_setting($data);
3714 * Special select - lists on the frontpage - hacky
3716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3718 class admin_setting_courselist_frontpage extends admin_setting {
3719 /** @var array Array of choices value=>label */
3720 public $choices;
3723 * Construct override, requires one param
3725 * @param bool $loggedin Is the user logged in
3727 public function __construct($loggedin) {
3728 global $CFG;
3729 require_once($CFG->dirroot.'/course/lib.php');
3730 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3731 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3732 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3733 $defaults = array(FRONTPAGEALLCOURSELIST);
3734 parent::__construct($name, $visiblename, $description, $defaults);
3738 * Loads the choices available
3740 * @return bool always returns true
3742 public function load_choices() {
3743 if (is_array($this->choices)) {
3744 return true;
3746 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3747 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3748 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3749 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3750 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3751 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3752 'none' => get_string('none'));
3753 if ($this->name === 'frontpage') {
3754 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3756 return true;
3760 * Returns the selected settings
3762 * @param mixed array or setting or null
3764 public function get_setting() {
3765 $result = $this->config_read($this->name);
3766 if (is_null($result)) {
3767 return NULL;
3769 if ($result === '') {
3770 return array();
3772 return explode(',', $result);
3776 * Save the selected options
3778 * @param array $data
3779 * @return mixed empty string (data is not an array) or bool true=success false=failure
3781 public function write_setting($data) {
3782 if (!is_array($data)) {
3783 return '';
3785 $this->load_choices();
3786 $save = array();
3787 foreach($data as $datum) {
3788 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3789 continue;
3791 $save[$datum] = $datum; // no duplicates
3793 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3797 * Return XHTML select field and wrapping div
3799 * @todo Add vartype handling to make sure $data is an array
3800 * @param array $data Array of elements to select by default
3801 * @return string XHTML select field and wrapping div
3803 public function output_html($data, $query='') {
3804 $this->load_choices();
3805 $currentsetting = array();
3806 foreach ($data as $key) {
3807 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3808 $currentsetting[] = $key; // already selected first
3812 $return = '<div class="form-group">';
3813 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3814 if (!array_key_exists($i, $currentsetting)) {
3815 $currentsetting[$i] = 'none'; //none
3817 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3818 foreach ($this->choices as $key => $value) {
3819 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3821 $return .= '</select>';
3822 if ($i !== count($this->choices) - 2) {
3823 $return .= '<br />';
3826 $return .= '</div>';
3828 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3834 * Special checkbox for frontpage - stores data in course table
3836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3838 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3840 * Returns the current sites name
3842 * @return string
3844 public function get_setting() {
3845 $site = course_get_format(get_site())->get_course();
3846 return $site->{$this->name};
3850 * Save the selected setting
3852 * @param string $data The selected site
3853 * @return string empty string or error message
3855 public function write_setting($data) {
3856 global $DB, $SITE, $COURSE;
3857 $record = new stdClass();
3858 $record->id = $SITE->id;
3859 $record->{$this->name} = ($data == '1' ? 1 : 0);
3860 $record->timemodified = time();
3862 course_get_format($SITE)->update_course_format_options($record);
3863 $DB->update_record('course', $record);
3865 // Reset caches.
3866 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3867 if ($SITE->id == $COURSE->id) {
3868 $COURSE = $SITE;
3870 format_base::reset_course_cache($SITE->id);
3872 return '';
3877 * Special text for frontpage - stores data in course table.
3878 * Empty string means not set here. Manual setting is required.
3880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3882 class admin_setting_sitesettext extends admin_setting_configtext {
3884 * Return the current setting
3886 * @return mixed string or null
3888 public function get_setting() {
3889 $site = course_get_format(get_site())->get_course();
3890 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3894 * Validate the selected data
3896 * @param string $data The selected value to validate
3897 * @return mixed true or message string
3899 public function validate($data) {
3900 $cleaned = clean_param($data, PARAM_TEXT);
3901 if ($cleaned === '') {
3902 return get_string('required');
3904 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3905 return true;
3906 } else {
3907 return get_string('validateerror', 'admin');
3912 * Save the selected setting
3914 * @param string $data The selected value
3915 * @return string empty or error message
3917 public function write_setting($data) {
3918 global $DB, $SITE, $COURSE;
3919 $data = trim($data);
3920 $validated = $this->validate($data);
3921 if ($validated !== true) {
3922 return $validated;
3925 $record = new stdClass();
3926 $record->id = $SITE->id;
3927 $record->{$this->name} = $data;
3928 $record->timemodified = time();
3930 course_get_format($SITE)->update_course_format_options($record);
3931 $DB->update_record('course', $record);
3933 // Reset caches.
3934 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3935 if ($SITE->id == $COURSE->id) {
3936 $COURSE = $SITE;
3938 format_base::reset_course_cache($SITE->id);
3940 return '';
3946 * Special text editor for site description.
3948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3950 class admin_setting_special_frontpagedesc extends admin_setting {
3952 * Calls parent::__construct with specific arguments
3954 public function __construct() {
3955 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3956 editors_head_setup();
3960 * Return the current setting
3961 * @return string The current setting
3963 public function get_setting() {
3964 $site = course_get_format(get_site())->get_course();
3965 return $site->{$this->name};
3969 * Save the new setting
3971 * @param string $data The new value to save
3972 * @return string empty or error message
3974 public function write_setting($data) {
3975 global $DB, $SITE, $COURSE;
3976 $record = new stdClass();
3977 $record->id = $SITE->id;
3978 $record->{$this->name} = $data;
3979 $record->timemodified = time();
3981 course_get_format($SITE)->update_course_format_options($record);
3982 $DB->update_record('course', $record);
3984 // Reset caches.
3985 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3986 if ($SITE->id == $COURSE->id) {
3987 $COURSE = $SITE;
3989 format_base::reset_course_cache($SITE->id);
3991 return '';
3995 * Returns XHTML for the field plus wrapping div
3997 * @param string $data The current value
3998 * @param string $query
3999 * @return string The XHTML output
4001 public function output_html($data, $query='') {
4002 global $CFG;
4004 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4006 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4012 * Administration interface for emoticon_manager settings.
4014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4016 class admin_setting_emoticons extends admin_setting {
4019 * Calls parent::__construct with specific args
4021 public function __construct() {
4022 global $CFG;
4024 $manager = get_emoticon_manager();
4025 $defaults = $this->prepare_form_data($manager->default_emoticons());
4026 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4030 * Return the current setting(s)
4032 * @return array Current settings array
4034 public function get_setting() {
4035 global $CFG;
4037 $manager = get_emoticon_manager();
4039 $config = $this->config_read($this->name);
4040 if (is_null($config)) {
4041 return null;
4044 $config = $manager->decode_stored_config($config);
4045 if (is_null($config)) {
4046 return null;
4049 return $this->prepare_form_data($config);
4053 * Save selected settings
4055 * @param array $data Array of settings to save
4056 * @return bool
4058 public function write_setting($data) {
4060 $manager = get_emoticon_manager();
4061 $emoticons = $this->process_form_data($data);
4063 if ($emoticons === false) {
4064 return false;
4067 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4068 return ''; // success
4069 } else {
4070 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4075 * Return XHTML field(s) for options
4077 * @param array $data Array of options to set in HTML
4078 * @return string XHTML string for the fields and wrapping div(s)
4080 public function output_html($data, $query='') {
4081 global $OUTPUT;
4083 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4084 $out .= html_writer::start_tag('thead');
4085 $out .= html_writer::start_tag('tr');
4086 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4087 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4088 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4089 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4090 $out .= html_writer::tag('th', '');
4091 $out .= html_writer::end_tag('tr');
4092 $out .= html_writer::end_tag('thead');
4093 $out .= html_writer::start_tag('tbody');
4094 $i = 0;
4095 foreach($data as $field => $value) {
4096 switch ($i) {
4097 case 0:
4098 $out .= html_writer::start_tag('tr');
4099 $current_text = $value;
4100 $current_filename = '';
4101 $current_imagecomponent = '';
4102 $current_altidentifier = '';
4103 $current_altcomponent = '';
4104 case 1:
4105 $current_filename = $value;
4106 case 2:
4107 $current_imagecomponent = $value;
4108 case 3:
4109 $current_altidentifier = $value;
4110 case 4:
4111 $current_altcomponent = $value;
4114 $out .= html_writer::tag('td',
4115 html_writer::empty_tag('input',
4116 array(
4117 'type' => 'text',
4118 'class' => 'form-text',
4119 'name' => $this->get_full_name().'['.$field.']',
4120 'value' => $value,
4122 ), array('class' => 'c'.$i)
4125 if ($i == 4) {
4126 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4127 $alt = get_string($current_altidentifier, $current_altcomponent);
4128 } else {
4129 $alt = $current_text;
4131 if ($current_filename) {
4132 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4133 } else {
4134 $out .= html_writer::tag('td', '');
4136 $out .= html_writer::end_tag('tr');
4137 $i = 0;
4138 } else {
4139 $i++;
4143 $out .= html_writer::end_tag('tbody');
4144 $out .= html_writer::end_tag('table');
4145 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4146 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4148 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4152 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4154 * @see self::process_form_data()
4155 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4156 * @return array of form fields and their values
4158 protected function prepare_form_data(array $emoticons) {
4160 $form = array();
4161 $i = 0;
4162 foreach ($emoticons as $emoticon) {
4163 $form['text'.$i] = $emoticon->text;
4164 $form['imagename'.$i] = $emoticon->imagename;
4165 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4166 $form['altidentifier'.$i] = $emoticon->altidentifier;
4167 $form['altcomponent'.$i] = $emoticon->altcomponent;
4168 $i++;
4170 // add one more blank field set for new object
4171 $form['text'.$i] = '';
4172 $form['imagename'.$i] = '';
4173 $form['imagecomponent'.$i] = '';
4174 $form['altidentifier'.$i] = '';
4175 $form['altcomponent'.$i] = '';
4177 return $form;
4181 * Converts the data from admin settings form into an array of emoticon objects
4183 * @see self::prepare_form_data()
4184 * @param array $data array of admin form fields and values
4185 * @return false|array of emoticon objects
4187 protected function process_form_data(array $form) {
4189 $count = count($form); // number of form field values
4191 if ($count % 5) {
4192 // we must get five fields per emoticon object
4193 return false;
4196 $emoticons = array();
4197 for ($i = 0; $i < $count / 5; $i++) {
4198 $emoticon = new stdClass();
4199 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4200 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4201 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4202 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4203 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4205 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4206 // prevent from breaking http://url.addresses by accident
4207 $emoticon->text = '';
4210 if (strlen($emoticon->text) < 2) {
4211 // do not allow single character emoticons
4212 $emoticon->text = '';
4215 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4216 // emoticon text must contain some non-alphanumeric character to prevent
4217 // breaking HTML tags
4218 $emoticon->text = '';
4221 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4222 $emoticons[] = $emoticon;
4225 return $emoticons;
4231 * Special setting for limiting of the list of available languages.
4233 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4235 class admin_setting_langlist extends admin_setting_configtext {
4237 * Calls parent::__construct with specific arguments
4239 public function __construct() {
4240 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4244 * Save the new setting
4246 * @param string $data The new setting
4247 * @return bool
4249 public function write_setting($data) {
4250 $return = parent::write_setting($data);
4251 get_string_manager()->reset_caches();
4252 return $return;
4258 * Selection of one of the recognised countries using the list
4259 * returned by {@link get_list_of_countries()}.
4261 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4263 class admin_settings_country_select extends admin_setting_configselect {
4264 protected $includeall;
4265 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4266 $this->includeall = $includeall;
4267 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4271 * Lazy-load the available choices for the select box
4273 public function load_choices() {
4274 global $CFG;
4275 if (is_array($this->choices)) {
4276 return true;
4278 $this->choices = array_merge(
4279 array('0' => get_string('choosedots')),
4280 get_string_manager()->get_list_of_countries($this->includeall));
4281 return true;
4287 * admin_setting_configselect for the default number of sections in a course,
4288 * simply so we can lazy-load the choices.
4290 * @copyright 2011 The Open University
4291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4293 class admin_settings_num_course_sections extends admin_setting_configselect {
4294 public function __construct($name, $visiblename, $description, $defaultsetting) {
4295 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4298 /** Lazy-load the available choices for the select box */
4299 public function load_choices() {
4300 $max = get_config('moodlecourse', 'maxsections');
4301 if (!isset($max) || !is_numeric($max)) {
4302 $max = 52;
4304 for ($i = 0; $i <= $max; $i++) {
4305 $this->choices[$i] = "$i";
4307 return true;
4313 * Course category selection
4315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4317 class admin_settings_coursecat_select extends admin_setting_configselect {
4319 * Calls parent::__construct with specific arguments
4321 public function __construct($name, $visiblename, $description, $defaultsetting) {
4322 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4326 * Load the available choices for the select box
4328 * @return bool
4330 public function load_choices() {
4331 global $CFG;
4332 require_once($CFG->dirroot.'/course/lib.php');
4333 if (is_array($this->choices)) {
4334 return true;
4336 $this->choices = make_categories_options();
4337 return true;
4343 * Special control for selecting days to backup
4345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4347 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4349 * Calls parent::__construct with specific arguments
4351 public function __construct() {
4352 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4353 $this->plugin = 'backup';
4357 * Load the available choices for the select box
4359 * @return bool Always returns true
4361 public function load_choices() {
4362 if (is_array($this->choices)) {
4363 return true;
4365 $this->choices = array();
4366 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4367 foreach ($days as $day) {
4368 $this->choices[$day] = get_string($day, 'calendar');
4370 return true;
4376 * Special debug setting
4378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4380 class admin_setting_special_debug extends admin_setting_configselect {
4382 * Calls parent::__construct with specific arguments
4384 public function __construct() {
4385 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4389 * Load the available choices for the select box
4391 * @return bool
4393 public function load_choices() {
4394 if (is_array($this->choices)) {
4395 return true;
4397 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4398 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4399 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4400 DEBUG_ALL => get_string('debugall', 'admin'),
4401 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4402 return true;
4408 * Special admin control
4410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4412 class admin_setting_special_calendar_weekend extends admin_setting {
4414 * Calls parent::__construct with specific arguments
4416 public function __construct() {
4417 $name = 'calendar_weekend';
4418 $visiblename = get_string('calendar_weekend', 'admin');
4419 $description = get_string('helpweekenddays', 'admin');
4420 $default = array ('0', '6'); // Saturdays and Sundays
4421 parent::__construct($name, $visiblename, $description, $default);
4425 * Gets the current settings as an array
4427 * @return mixed Null if none, else array of settings
4429 public function get_setting() {
4430 $result = $this->config_read($this->name);
4431 if (is_null($result)) {
4432 return NULL;
4434 if ($result === '') {
4435 return array();
4437 $settings = array();
4438 for ($i=0; $i<7; $i++) {
4439 if ($result & (1 << $i)) {
4440 $settings[] = $i;
4443 return $settings;
4447 * Save the new settings
4449 * @param array $data Array of new settings
4450 * @return bool
4452 public function write_setting($data) {
4453 if (!is_array($data)) {
4454 return '';
4456 unset($data['xxxxx']);
4457 $result = 0;
4458 foreach($data as $index) {
4459 $result |= 1 << $index;
4461 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4465 * Return XHTML to display the control
4467 * @param array $data array of selected days
4468 * @param string $query
4469 * @return string XHTML for display (field + wrapping div(s)
4471 public function output_html($data, $query='') {
4472 // The order matters very much because of the implied numeric keys
4473 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4474 $return = '<table><thead><tr>';
4475 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4476 foreach($days as $index => $day) {
4477 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4479 $return .= '</tr></thead><tbody><tr>';
4480 foreach($days as $index => $day) {
4481 $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>';
4483 $return .= '</tr></tbody></table>';
4485 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4492 * Admin setting that allows a user to pick a behaviour.
4494 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4496 class admin_setting_question_behaviour extends admin_setting_configselect {
4498 * @param string $name name of config variable
4499 * @param string $visiblename display name
4500 * @param string $description description
4501 * @param string $default default.
4503 public function __construct($name, $visiblename, $description, $default) {
4504 parent::__construct($name, $visiblename, $description, $default, NULL);
4508 * Load list of behaviours as choices
4509 * @return bool true => success, false => error.
4511 public function load_choices() {
4512 global $CFG;
4513 require_once($CFG->dirroot . '/question/engine/lib.php');
4514 $this->choices = question_engine::get_behaviour_options('');
4515 return true;
4521 * Admin setting that allows a user to pick appropriate roles for something.
4523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4525 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4526 /** @var array Array of capabilities which identify roles */
4527 private $types;
4530 * @param string $name Name of config variable
4531 * @param string $visiblename Display name
4532 * @param string $description Description
4533 * @param array $types Array of archetypes which identify
4534 * roles that will be enabled by default.
4536 public function __construct($name, $visiblename, $description, $types) {
4537 parent::__construct($name, $visiblename, $description, NULL, NULL);
4538 $this->types = $types;
4542 * Load roles as choices
4544 * @return bool true=>success, false=>error
4546 public function load_choices() {
4547 global $CFG, $DB;
4548 if (during_initial_install()) {
4549 return false;
4551 if (is_array($this->choices)) {
4552 return true;
4554 if ($roles = get_all_roles()) {
4555 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4556 return true;
4557 } else {
4558 return false;
4563 * Return the default setting for this control
4565 * @return array Array of default settings
4567 public function get_defaultsetting() {
4568 global $CFG;
4570 if (during_initial_install()) {
4571 return null;
4573 $result = array();
4574 foreach($this->types as $archetype) {
4575 if ($caproles = get_archetype_roles($archetype)) {
4576 foreach ($caproles as $caprole) {
4577 $result[$caprole->id] = 1;
4581 return $result;
4587 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4591 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4593 * Constructor
4594 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4595 * @param string $visiblename localised
4596 * @param string $description long localised info
4597 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4598 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4599 * @param int $size default field size
4601 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4602 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4603 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4609 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4611 * @copyright 2009 Petr Skoda (http://skodak.org)
4612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4614 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4617 * Constructor
4618 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4619 * @param string $visiblename localised
4620 * @param string $description long localised info
4621 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4622 * @param string $yes value used when checked
4623 * @param string $no value used when not checked
4625 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4626 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4627 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4634 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4636 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4638 * @copyright 2010 Sam Hemelryk
4639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4641 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4643 * Constructor
4644 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4645 * @param string $visiblename localised
4646 * @param string $description long localised info
4647 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4648 * @param string $yes value used when checked
4649 * @param string $no value used when not checked
4651 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4652 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4653 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4660 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4662 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4664 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4666 * Calls parent::__construct with specific arguments
4668 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4669 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4670 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4677 * Graded roles in gradebook
4679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4681 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4683 * Calls parent::__construct with specific arguments
4685 public function __construct() {
4686 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4687 get_string('configgradebookroles', 'admin'),
4688 array('student'));
4695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4697 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4699 * Saves the new settings passed in $data
4701 * @param string $data
4702 * @return mixed string or Array
4704 public function write_setting($data) {
4705 global $CFG, $DB;
4707 $oldvalue = $this->config_read($this->name);
4708 $return = parent::write_setting($data);
4709 $newvalue = $this->config_read($this->name);
4711 if ($oldvalue !== $newvalue) {
4712 // force full regrading
4713 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4716 return $return;
4722 * Which roles to show on course description page
4724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4726 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4728 * Calls parent::__construct with specific arguments
4730 public function __construct() {
4731 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4732 get_string('coursecontact_desc', 'admin'),
4733 array('editingteacher'));
4740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4742 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4744 * Calls parent::__construct with specific arguments
4746 function admin_setting_special_gradelimiting() {
4747 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4748 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4752 * Force site regrading
4754 function regrade_all() {
4755 global $CFG;
4756 require_once("$CFG->libdir/gradelib.php");
4757 grade_force_site_regrading();
4761 * Saves the new settings
4763 * @param mixed $data
4764 * @return string empty string or error message
4766 function write_setting($data) {
4767 $previous = $this->get_setting();
4769 if ($previous === null) {
4770 if ($data) {
4771 $this->regrade_all();
4773 } else {
4774 if ($data != $previous) {
4775 $this->regrade_all();
4778 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4785 * Primary grade export plugin - has state tracking.
4787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4789 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4791 * Calls parent::__construct with specific arguments
4793 public function __construct() {
4794 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4795 get_string('configgradeexport', 'admin'), array(), NULL);
4799 * Load the available choices for the multicheckbox
4801 * @return bool always returns true
4803 public function load_choices() {
4804 if (is_array($this->choices)) {
4805 return true;
4807 $this->choices = array();
4809 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4810 foreach($plugins as $plugin => $unused) {
4811 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4814 return true;
4820 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4824 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4826 * Config gradepointmax constructor
4828 * @param string $name Overidden by "gradepointmax"
4829 * @param string $visiblename Overridden by "gradepointmax" language string.
4830 * @param string $description Overridden by "gradepointmax_help" language string.
4831 * @param string $defaultsetting Not used, overridden by 100.
4832 * @param mixed $paramtype Overridden by PARAM_INT.
4833 * @param int $size Overridden by 5.
4835 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4836 $name = 'gradepointdefault';
4837 $visiblename = get_string('gradepointdefault', 'grades');
4838 $description = get_string('gradepointdefault_help', 'grades');
4839 $defaultsetting = 100;
4840 $paramtype = PARAM_INT;
4841 $size = 5;
4842 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4846 * Validate data before storage
4847 * @param string $data The submitted data
4848 * @return bool|string true if ok, string if error found
4850 public function validate($data) {
4851 global $CFG;
4852 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4853 return true;
4854 } else {
4855 return get_string('gradepointdefault_validateerror', 'grades');
4862 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4866 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4869 * Config gradepointmax constructor
4871 * @param string $name Overidden by "gradepointmax"
4872 * @param string $visiblename Overridden by "gradepointmax" language string.
4873 * @param string $description Overridden by "gradepointmax_help" language string.
4874 * @param string $defaultsetting Not used, overridden by 100.
4875 * @param mixed $paramtype Overridden by PARAM_INT.
4876 * @param int $size Overridden by 5.
4878 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4879 $name = 'gradepointmax';
4880 $visiblename = get_string('gradepointmax', 'grades');
4881 $description = get_string('gradepointmax_help', 'grades');
4882 $defaultsetting = 100;
4883 $paramtype = PARAM_INT;
4884 $size = 5;
4885 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4889 * Save the selected setting
4891 * @param string $data The selected site
4892 * @return string empty string or error message
4894 public function write_setting($data) {
4895 if ($data === '') {
4896 $data = (int)$this->defaultsetting;
4897 } else {
4898 $data = $data;
4900 return parent::write_setting($data);
4904 * Validate data before storage
4905 * @param string $data The submitted data
4906 * @return bool|string true if ok, string if error found
4908 public function validate($data) {
4909 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4910 return true;
4911 } else {
4912 return get_string('gradepointmax_validateerror', 'grades');
4917 * Return an XHTML string for the setting
4918 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4919 * @param string $query search query to be highlighted
4920 * @return string XHTML to display control
4922 public function output_html($data, $query = '') {
4923 $default = $this->get_defaultsetting();
4925 $attr = array(
4926 'type' => 'text',
4927 'size' => $this->size,
4928 'id' => $this->get_id(),
4929 'name' => $this->get_full_name(),
4930 'value' => s($data),
4931 'maxlength' => '5'
4933 $input = html_writer::empty_tag('input', $attr);
4935 $attr = array('class' => 'form-text defaultsnext');
4936 $div = html_writer::tag('div', $input, $attr);
4937 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
4943 * Grade category settings
4945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4947 class admin_setting_gradecat_combo extends admin_setting {
4948 /** @var array Array of choices */
4949 public $choices;
4952 * Sets choices and calls parent::__construct with passed arguments
4953 * @param string $name
4954 * @param string $visiblename
4955 * @param string $description
4956 * @param mixed $defaultsetting string or array depending on implementation
4957 * @param array $choices An array of choices for the control
4959 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4960 $this->choices = $choices;
4961 parent::__construct($name, $visiblename, $description, $defaultsetting);
4965 * Return the current setting(s) array
4967 * @return array Array of value=>xx, forced=>xx, adv=>xx
4969 public function get_setting() {
4970 global $CFG;
4972 $value = $this->config_read($this->name);
4973 $flag = $this->config_read($this->name.'_flag');
4975 if (is_null($value) or is_null($flag)) {
4976 return NULL;
4979 $flag = (int)$flag;
4980 $forced = (boolean)(1 & $flag); // first bit
4981 $adv = (boolean)(2 & $flag); // second bit
4983 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4987 * Save the new settings passed in $data
4989 * @todo Add vartype handling to ensure $data is array
4990 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4991 * @return string empty or error message
4993 public function write_setting($data) {
4994 global $CFG;
4996 $value = $data['value'];
4997 $forced = empty($data['forced']) ? 0 : 1;
4998 $adv = empty($data['adv']) ? 0 : 2;
4999 $flag = ($forced | $adv); //bitwise or
5001 if (!in_array($value, array_keys($this->choices))) {
5002 return 'Error setting ';
5005 $oldvalue = $this->config_read($this->name);
5006 $oldflag = (int)$this->config_read($this->name.'_flag');
5007 $oldforced = (1 & $oldflag); // first bit
5009 $result1 = $this->config_write($this->name, $value);
5010 $result2 = $this->config_write($this->name.'_flag', $flag);
5012 // force regrade if needed
5013 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5014 require_once($CFG->libdir.'/gradelib.php');
5015 grade_category::updated_forced_settings();
5018 if ($result1 and $result2) {
5019 return '';
5020 } else {
5021 return get_string('errorsetting', 'admin');
5026 * Return XHTML to display the field and wrapping div
5028 * @todo Add vartype handling to ensure $data is array
5029 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5030 * @param string $query
5031 * @return string XHTML to display control
5033 public function output_html($data, $query='') {
5034 $value = $data['value'];
5035 $forced = !empty($data['forced']);
5036 $adv = !empty($data['adv']);
5038 $default = $this->get_defaultsetting();
5039 if (!is_null($default)) {
5040 $defaultinfo = array();
5041 if (isset($this->choices[$default['value']])) {
5042 $defaultinfo[] = $this->choices[$default['value']];
5044 if (!empty($default['forced'])) {
5045 $defaultinfo[] = get_string('force');
5047 if (!empty($default['adv'])) {
5048 $defaultinfo[] = get_string('advanced');
5050 $defaultinfo = implode(', ', $defaultinfo);
5052 } else {
5053 $defaultinfo = NULL;
5057 $return = '<div class="form-group">';
5058 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5059 foreach ($this->choices as $key => $val) {
5060 // the string cast is needed because key may be integer - 0 is equal to most strings!
5061 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5063 $return .= '</select>';
5064 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5065 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5066 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5067 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5068 $return .= '</div>';
5070 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5076 * Selection of grade report in user profiles
5078 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5080 class admin_setting_grade_profilereport extends admin_setting_configselect {
5082 * Calls parent::__construct with specific arguments
5084 public function __construct() {
5085 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5089 * Loads an array of choices for the configselect control
5091 * @return bool always return true
5093 public function load_choices() {
5094 if (is_array($this->choices)) {
5095 return true;
5097 $this->choices = array();
5099 global $CFG;
5100 require_once($CFG->libdir.'/gradelib.php');
5102 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5103 if (file_exists($plugindir.'/lib.php')) {
5104 require_once($plugindir.'/lib.php');
5105 $functionname = 'grade_report_'.$plugin.'_profilereport';
5106 if (function_exists($functionname)) {
5107 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5111 return true;
5117 * Special class for register auth selection
5119 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5121 class admin_setting_special_registerauth extends admin_setting_configselect {
5123 * Calls parent::__construct with specific arguments
5125 public function __construct() {
5126 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5130 * Returns the default option
5132 * @return string empty or default option
5134 public function get_defaultsetting() {
5135 $this->load_choices();
5136 $defaultsetting = parent::get_defaultsetting();
5137 if (array_key_exists($defaultsetting, $this->choices)) {
5138 return $defaultsetting;
5139 } else {
5140 return '';
5145 * Loads the possible choices for the array
5147 * @return bool always returns true
5149 public function load_choices() {
5150 global $CFG;
5152 if (is_array($this->choices)) {
5153 return true;
5155 $this->choices = array();
5156 $this->choices[''] = get_string('disable');
5158 $authsenabled = get_enabled_auth_plugins(true);
5160 foreach ($authsenabled as $auth) {
5161 $authplugin = get_auth_plugin($auth);
5162 if (!$authplugin->can_signup()) {
5163 continue;
5165 // Get the auth title (from core or own auth lang files)
5166 $authtitle = $authplugin->get_title();
5167 $this->choices[$auth] = $authtitle;
5169 return true;
5175 * General plugins manager
5177 class admin_page_pluginsoverview extends admin_externalpage {
5180 * Sets basic information about the external page
5182 public function __construct() {
5183 global $CFG;
5184 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5185 "$CFG->wwwroot/$CFG->admin/plugins.php");
5190 * Module manage page
5192 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5194 class admin_page_managemods extends admin_externalpage {
5196 * Calls parent::__construct with specific arguments
5198 public function __construct() {
5199 global $CFG;
5200 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5204 * Try to find the specified module
5206 * @param string $query The module to search for
5207 * @return array
5209 public function search($query) {
5210 global $CFG, $DB;
5211 if ($result = parent::search($query)) {
5212 return $result;
5215 $found = false;
5216 if ($modules = $DB->get_records('modules')) {
5217 foreach ($modules as $module) {
5218 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5219 continue;
5221 if (strpos($module->name, $query) !== false) {
5222 $found = true;
5223 break;
5225 $strmodulename = get_string('modulename', $module->name);
5226 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5227 $found = true;
5228 break;
5232 if ($found) {
5233 $result = new stdClass();
5234 $result->page = $this;
5235 $result->settings = array();
5236 return array($this->name => $result);
5237 } else {
5238 return array();
5245 * Special class for enrol plugins management.
5247 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5250 class admin_setting_manageenrols extends admin_setting {
5252 * Calls parent::__construct with specific arguments
5254 public function __construct() {
5255 $this->nosave = true;
5256 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5260 * Always returns true, does nothing
5262 * @return true
5264 public function get_setting() {
5265 return true;
5269 * Always returns true, does nothing
5271 * @return true
5273 public function get_defaultsetting() {
5274 return true;
5278 * Always returns '', does not write anything
5280 * @return string Always returns ''
5282 public function write_setting($data) {
5283 // do not write any setting
5284 return '';
5288 * Checks if $query is one of the available enrol plugins
5290 * @param string $query The string to search for
5291 * @return bool Returns true if found, false if not
5293 public function is_related($query) {
5294 if (parent::is_related($query)) {
5295 return true;
5298 $query = core_text::strtolower($query);
5299 $enrols = enrol_get_plugins(false);
5300 foreach ($enrols as $name=>$enrol) {
5301 $localised = get_string('pluginname', 'enrol_'.$name);
5302 if (strpos(core_text::strtolower($name), $query) !== false) {
5303 return true;
5305 if (strpos(core_text::strtolower($localised), $query) !== false) {
5306 return true;
5309 return false;
5313 * Builds the XHTML to display the control
5315 * @param string $data Unused
5316 * @param string $query
5317 * @return string
5319 public function output_html($data, $query='') {
5320 global $CFG, $OUTPUT, $DB, $PAGE;
5322 // Display strings.
5323 $strup = get_string('up');
5324 $strdown = get_string('down');
5325 $strsettings = get_string('settings');
5326 $strenable = get_string('enable');
5327 $strdisable = get_string('disable');
5328 $struninstall = get_string('uninstallplugin', 'core_admin');
5329 $strusage = get_string('enrolusage', 'enrol');
5330 $strversion = get_string('version');
5331 $strtest = get_string('testsettings', 'core_enrol');
5333 $pluginmanager = core_plugin_manager::instance();
5335 $enrols_available = enrol_get_plugins(false);
5336 $active_enrols = enrol_get_plugins(true);
5338 $allenrols = array();
5339 foreach ($active_enrols as $key=>$enrol) {
5340 $allenrols[$key] = true;
5342 foreach ($enrols_available as $key=>$enrol) {
5343 $allenrols[$key] = true;
5345 // Now find all borked plugins and at least allow then to uninstall.
5346 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5347 foreach ($condidates as $candidate) {
5348 if (empty($allenrols[$candidate])) {
5349 $allenrols[$candidate] = true;
5353 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5354 $return .= $OUTPUT->box_start('generalbox enrolsui');
5356 $table = new html_table();
5357 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5358 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5359 $table->id = 'courseenrolmentplugins';
5360 $table->attributes['class'] = 'admintable generaltable';
5361 $table->data = array();
5363 // Iterate through enrol plugins and add to the display table.
5364 $updowncount = 1;
5365 $enrolcount = count($active_enrols);
5366 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5367 $printed = array();
5368 foreach($allenrols as $enrol => $unused) {
5369 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5370 $version = get_config('enrol_'.$enrol, 'version');
5371 if ($version === false) {
5372 $version = '';
5375 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5376 $name = get_string('pluginname', 'enrol_'.$enrol);
5377 } else {
5378 $name = $enrol;
5380 // Usage.
5381 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5382 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5383 $usage = "$ci / $cp";
5385 // Hide/show links.
5386 $class = '';
5387 if (isset($active_enrols[$enrol])) {
5388 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5389 $hideshow = "<a href=\"$aurl\">";
5390 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5391 $enabled = true;
5392 $displayname = $name;
5393 } else if (isset($enrols_available[$enrol])) {
5394 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5395 $hideshow = "<a href=\"$aurl\">";
5396 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5397 $enabled = false;
5398 $displayname = $name;
5399 $class = 'dimmed_text';
5400 } else {
5401 $hideshow = '';
5402 $enabled = false;
5403 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5405 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5406 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5407 } else {
5408 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5411 // Up/down link (only if enrol is enabled).
5412 $updown = '';
5413 if ($enabled) {
5414 if ($updowncount > 1) {
5415 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5416 $updown .= "<a href=\"$aurl\">";
5417 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5418 } else {
5419 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5421 if ($updowncount < $enrolcount) {
5422 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5423 $updown .= "<a href=\"$aurl\">";
5424 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5425 } else {
5426 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5428 ++$updowncount;
5431 // Add settings link.
5432 if (!$version) {
5433 $settings = '';
5434 } else if ($surl = $plugininfo->get_settings_url()) {
5435 $settings = html_writer::link($surl, $strsettings);
5436 } else {
5437 $settings = '';
5440 // Add uninstall info.
5441 $uninstall = '';
5442 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5443 $uninstall = html_writer::link($uninstallurl, $struninstall);
5446 $test = '';
5447 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5448 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5449 $test = html_writer::link($testsettingsurl, $strtest);
5452 // Add a row to the table.
5453 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5454 if ($class) {
5455 $row->attributes['class'] = $class;
5457 $table->data[] = $row;
5459 $printed[$enrol] = true;
5462 $return .= html_writer::table($table);
5463 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5464 $return .= $OUTPUT->box_end();
5465 return highlight($query, $return);
5471 * Blocks manage page
5473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5475 class admin_page_manageblocks extends admin_externalpage {
5477 * Calls parent::__construct with specific arguments
5479 public function __construct() {
5480 global $CFG;
5481 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5485 * Search for a specific block
5487 * @param string $query The string to search for
5488 * @return array
5490 public function search($query) {
5491 global $CFG, $DB;
5492 if ($result = parent::search($query)) {
5493 return $result;
5496 $found = false;
5497 if ($blocks = $DB->get_records('block')) {
5498 foreach ($blocks as $block) {
5499 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5500 continue;
5502 if (strpos($block->name, $query) !== false) {
5503 $found = true;
5504 break;
5506 $strblockname = get_string('pluginname', 'block_'.$block->name);
5507 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5508 $found = true;
5509 break;
5513 if ($found) {
5514 $result = new stdClass();
5515 $result->page = $this;
5516 $result->settings = array();
5517 return array($this->name => $result);
5518 } else {
5519 return array();
5525 * Message outputs configuration
5527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5529 class admin_page_managemessageoutputs extends admin_externalpage {
5531 * Calls parent::__construct with specific arguments
5533 public function __construct() {
5534 global $CFG;
5535 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5539 * Search for a specific message processor
5541 * @param string $query The string to search for
5542 * @return array
5544 public function search($query) {
5545 global $CFG, $DB;
5546 if ($result = parent::search($query)) {
5547 return $result;
5550 $found = false;
5551 if ($processors = get_message_processors()) {
5552 foreach ($processors as $processor) {
5553 if (!$processor->available) {
5554 continue;
5556 if (strpos($processor->name, $query) !== false) {
5557 $found = true;
5558 break;
5560 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5561 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5562 $found = true;
5563 break;
5567 if ($found) {
5568 $result = new stdClass();
5569 $result->page = $this;
5570 $result->settings = array();
5571 return array($this->name => $result);
5572 } else {
5573 return array();
5579 * Default message outputs configuration
5581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5583 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5585 * Calls parent::__construct with specific arguments
5587 public function __construct() {
5588 global $CFG;
5589 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5595 * Manage question behaviours page
5597 * @copyright 2011 The Open University
5598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5600 class admin_page_manageqbehaviours extends admin_externalpage {
5602 * Constructor
5604 public function __construct() {
5605 global $CFG;
5606 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5607 new moodle_url('/admin/qbehaviours.php'));
5611 * Search question behaviours for the specified string
5613 * @param string $query The string to search for in question behaviours
5614 * @return array
5616 public function search($query) {
5617 global $CFG;
5618 if ($result = parent::search($query)) {
5619 return $result;
5622 $found = false;
5623 require_once($CFG->dirroot . '/question/engine/lib.php');
5624 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5625 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5626 $query) !== false) {
5627 $found = true;
5628 break;
5631 if ($found) {
5632 $result = new stdClass();
5633 $result->page = $this;
5634 $result->settings = array();
5635 return array($this->name => $result);
5636 } else {
5637 return array();
5644 * Question type manage page
5646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5648 class admin_page_manageqtypes extends admin_externalpage {
5650 * Calls parent::__construct with specific arguments
5652 public function __construct() {
5653 global $CFG;
5654 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5655 new moodle_url('/admin/qtypes.php'));
5659 * Search question types for the specified string
5661 * @param string $query The string to search for in question types
5662 * @return array
5664 public function search($query) {
5665 global $CFG;
5666 if ($result = parent::search($query)) {
5667 return $result;
5670 $found = false;
5671 require_once($CFG->dirroot . '/question/engine/bank.php');
5672 foreach (question_bank::get_all_qtypes() as $qtype) {
5673 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5674 $found = true;
5675 break;
5678 if ($found) {
5679 $result = new stdClass();
5680 $result->page = $this;
5681 $result->settings = array();
5682 return array($this->name => $result);
5683 } else {
5684 return array();
5690 class admin_page_manageportfolios extends admin_externalpage {
5692 * Calls parent::__construct with specific arguments
5694 public function __construct() {
5695 global $CFG;
5696 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5697 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5701 * Searches page for the specified string.
5702 * @param string $query The string to search for
5703 * @return bool True if it is found on this page
5705 public function search($query) {
5706 global $CFG;
5707 if ($result = parent::search($query)) {
5708 return $result;
5711 $found = false;
5712 $portfolios = core_component::get_plugin_list('portfolio');
5713 foreach ($portfolios as $p => $dir) {
5714 if (strpos($p, $query) !== false) {
5715 $found = true;
5716 break;
5719 if (!$found) {
5720 foreach (portfolio_instances(false, false) as $instance) {
5721 $title = $instance->get('name');
5722 if (strpos(core_text::strtolower($title), $query) !== false) {
5723 $found = true;
5724 break;
5729 if ($found) {
5730 $result = new stdClass();
5731 $result->page = $this;
5732 $result->settings = array();
5733 return array($this->name => $result);
5734 } else {
5735 return array();
5741 class admin_page_managerepositories extends admin_externalpage {
5743 * Calls parent::__construct with specific arguments
5745 public function __construct() {
5746 global $CFG;
5747 parent::__construct('managerepositories', get_string('manage',
5748 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5752 * Searches page for the specified string.
5753 * @param string $query The string to search for
5754 * @return bool True if it is found on this page
5756 public function search($query) {
5757 global $CFG;
5758 if ($result = parent::search($query)) {
5759 return $result;
5762 $found = false;
5763 $repositories= core_component::get_plugin_list('repository');
5764 foreach ($repositories as $p => $dir) {
5765 if (strpos($p, $query) !== false) {
5766 $found = true;
5767 break;
5770 if (!$found) {
5771 foreach (repository::get_types() as $instance) {
5772 $title = $instance->get_typename();
5773 if (strpos(core_text::strtolower($title), $query) !== false) {
5774 $found = true;
5775 break;
5780 if ($found) {
5781 $result = new stdClass();
5782 $result->page = $this;
5783 $result->settings = array();
5784 return array($this->name => $result);
5785 } else {
5786 return array();
5793 * Special class for authentication administration.
5795 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5797 class admin_setting_manageauths extends admin_setting {
5799 * Calls parent::__construct with specific arguments
5801 public function __construct() {
5802 $this->nosave = true;
5803 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5807 * Always returns true
5809 * @return true
5811 public function get_setting() {
5812 return true;
5816 * Always returns true
5818 * @return true
5820 public function get_defaultsetting() {
5821 return true;
5825 * Always returns '' and doesn't write anything
5827 * @return string Always returns ''
5829 public function write_setting($data) {
5830 // do not write any setting
5831 return '';
5835 * Search to find if Query is related to auth plugin
5837 * @param string $query The string to search for
5838 * @return bool true for related false for not
5840 public function is_related($query) {
5841 if (parent::is_related($query)) {
5842 return true;
5845 $authsavailable = core_component::get_plugin_list('auth');
5846 foreach ($authsavailable as $auth => $dir) {
5847 if (strpos($auth, $query) !== false) {
5848 return true;
5850 $authplugin = get_auth_plugin($auth);
5851 $authtitle = $authplugin->get_title();
5852 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5853 return true;
5856 return false;
5860 * Return XHTML to display control
5862 * @param mixed $data Unused
5863 * @param string $query
5864 * @return string highlight
5866 public function output_html($data, $query='') {
5867 global $CFG, $OUTPUT, $DB;
5869 // display strings
5870 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5871 'settings', 'edit', 'name', 'enable', 'disable',
5872 'up', 'down', 'none', 'users'));
5873 $txt->updown = "$txt->up/$txt->down";
5874 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5875 $txt->testsettings = get_string('testsettings', 'core_auth');
5877 $authsavailable = core_component::get_plugin_list('auth');
5878 get_enabled_auth_plugins(true); // fix the list of enabled auths
5879 if (empty($CFG->auth)) {
5880 $authsenabled = array();
5881 } else {
5882 $authsenabled = explode(',', $CFG->auth);
5885 // construct the display array, with enabled auth plugins at the top, in order
5886 $displayauths = array();
5887 $registrationauths = array();
5888 $registrationauths[''] = $txt->disable;
5889 $authplugins = array();
5890 foreach ($authsenabled as $auth) {
5891 $authplugin = get_auth_plugin($auth);
5892 $authplugins[$auth] = $authplugin;
5893 /// Get the auth title (from core or own auth lang files)
5894 $authtitle = $authplugin->get_title();
5895 /// Apply titles
5896 $displayauths[$auth] = $authtitle;
5897 if ($authplugin->can_signup()) {
5898 $registrationauths[$auth] = $authtitle;
5902 foreach ($authsavailable as $auth => $dir) {
5903 if (array_key_exists($auth, $displayauths)) {
5904 continue; //already in the list
5906 $authplugin = get_auth_plugin($auth);
5907 $authplugins[$auth] = $authplugin;
5908 /// Get the auth title (from core or own auth lang files)
5909 $authtitle = $authplugin->get_title();
5910 /// Apply titles
5911 $displayauths[$auth] = $authtitle;
5912 if ($authplugin->can_signup()) {
5913 $registrationauths[$auth] = $authtitle;
5917 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5918 $return .= $OUTPUT->box_start('generalbox authsui');
5920 $table = new html_table();
5921 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5922 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5923 $table->data = array();
5924 $table->attributes['class'] = 'admintable generaltable';
5925 $table->id = 'manageauthtable';
5927 //add always enabled plugins first
5928 $displayname = $displayauths['manual'];
5929 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5930 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5931 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
5932 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5933 $displayname = $displayauths['nologin'];
5934 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5935 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
5936 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5939 // iterate through auth plugins and add to the display table
5940 $updowncount = 1;
5941 $authcount = count($authsenabled);
5942 $url = "auth.php?sesskey=" . sesskey();
5943 foreach ($displayauths as $auth => $name) {
5944 if ($auth == 'manual' or $auth == 'nologin') {
5945 continue;
5947 $class = '';
5948 // hide/show link
5949 if (in_array($auth, $authsenabled)) {
5950 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5951 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5952 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5953 $enabled = true;
5954 $displayname = $name;
5956 else {
5957 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5958 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5959 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5960 $enabled = false;
5961 $displayname = $name;
5962 $class = 'dimmed_text';
5965 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
5967 // up/down link (only if auth is enabled)
5968 $updown = '';
5969 if ($enabled) {
5970 if ($updowncount > 1) {
5971 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5972 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5974 else {
5975 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5977 if ($updowncount < $authcount) {
5978 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5979 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5981 else {
5982 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5984 ++ $updowncount;
5987 // settings link
5988 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5989 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5990 } else {
5991 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5994 // Uninstall link.
5995 $uninstall = '';
5996 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
5997 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6000 $test = '';
6001 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6002 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6003 $test = html_writer::link($testurl, $txt->testsettings);
6006 // Add a row to the table.
6007 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6008 if ($class) {
6009 $row->attributes['class'] = $class;
6011 $table->data[] = $row;
6013 $return .= html_writer::table($table);
6014 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6015 $return .= $OUTPUT->box_end();
6016 return highlight($query, $return);
6022 * Special class for authentication administration.
6024 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6026 class admin_setting_manageeditors extends admin_setting {
6028 * Calls parent::__construct with specific arguments
6030 public function __construct() {
6031 $this->nosave = true;
6032 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6036 * Always returns true, does nothing
6038 * @return true
6040 public function get_setting() {
6041 return true;
6045 * Always returns true, does nothing
6047 * @return true
6049 public function get_defaultsetting() {
6050 return true;
6054 * Always returns '', does not write anything
6056 * @return string Always returns ''
6058 public function write_setting($data) {
6059 // do not write any setting
6060 return '';
6064 * Checks if $query is one of the available editors
6066 * @param string $query The string to search for
6067 * @return bool Returns true if found, false if not
6069 public function is_related($query) {
6070 if (parent::is_related($query)) {
6071 return true;
6074 $editors_available = editors_get_available();
6075 foreach ($editors_available as $editor=>$editorstr) {
6076 if (strpos($editor, $query) !== false) {
6077 return true;
6079 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6080 return true;
6083 return false;
6087 * Builds the XHTML to display the control
6089 * @param string $data Unused
6090 * @param string $query
6091 * @return string
6093 public function output_html($data, $query='') {
6094 global $CFG, $OUTPUT;
6096 // display strings
6097 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6098 'up', 'down', 'none'));
6099 $struninstall = get_string('uninstallplugin', 'core_admin');
6101 $txt->updown = "$txt->up/$txt->down";
6103 $editors_available = editors_get_available();
6104 $active_editors = explode(',', $CFG->texteditors);
6106 $active_editors = array_reverse($active_editors);
6107 foreach ($active_editors as $key=>$editor) {
6108 if (empty($editors_available[$editor])) {
6109 unset($active_editors[$key]);
6110 } else {
6111 $name = $editors_available[$editor];
6112 unset($editors_available[$editor]);
6113 $editors_available[$editor] = $name;
6116 if (empty($active_editors)) {
6117 //$active_editors = array('textarea');
6119 $editors_available = array_reverse($editors_available, true);
6120 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6121 $return .= $OUTPUT->box_start('generalbox editorsui');
6123 $table = new html_table();
6124 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6125 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6126 $table->id = 'editormanagement';
6127 $table->attributes['class'] = 'admintable generaltable';
6128 $table->data = array();
6130 // iterate through auth plugins and add to the display table
6131 $updowncount = 1;
6132 $editorcount = count($active_editors);
6133 $url = "editors.php?sesskey=" . sesskey();
6134 foreach ($editors_available as $editor => $name) {
6135 // hide/show link
6136 $class = '';
6137 if (in_array($editor, $active_editors)) {
6138 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6139 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6140 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6141 $enabled = true;
6142 $displayname = $name;
6144 else {
6145 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6146 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6147 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6148 $enabled = false;
6149 $displayname = $name;
6150 $class = 'dimmed_text';
6153 // up/down link (only if auth is enabled)
6154 $updown = '';
6155 if ($enabled) {
6156 if ($updowncount > 1) {
6157 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6158 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6160 else {
6161 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6163 if ($updowncount < $editorcount) {
6164 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6165 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6167 else {
6168 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6170 ++ $updowncount;
6173 // settings link
6174 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6175 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6176 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6177 } else {
6178 $settings = '';
6181 $uninstall = '';
6182 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6183 $uninstall = html_writer::link($uninstallurl, $struninstall);
6186 // Add a row to the table.
6187 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6188 if ($class) {
6189 $row->attributes['class'] = $class;
6191 $table->data[] = $row;
6193 $return .= html_writer::table($table);
6194 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6195 $return .= $OUTPUT->box_end();
6196 return highlight($query, $return);
6202 * Special class for license administration.
6204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6206 class admin_setting_managelicenses extends admin_setting {
6208 * Calls parent::__construct with specific arguments
6210 public function __construct() {
6211 $this->nosave = true;
6212 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6216 * Always returns true, does nothing
6218 * @return true
6220 public function get_setting() {
6221 return true;
6225 * Always returns true, does nothing
6227 * @return true
6229 public function get_defaultsetting() {
6230 return true;
6234 * Always returns '', does not write anything
6236 * @return string Always returns ''
6238 public function write_setting($data) {
6239 // do not write any setting
6240 return '';
6244 * Builds the XHTML to display the control
6246 * @param string $data Unused
6247 * @param string $query
6248 * @return string
6250 public function output_html($data, $query='') {
6251 global $CFG, $OUTPUT;
6252 require_once($CFG->libdir . '/licenselib.php');
6253 $url = "licenses.php?sesskey=" . sesskey();
6255 // display strings
6256 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6257 $licenses = license_manager::get_licenses();
6259 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6261 $return .= $OUTPUT->box_start('generalbox editorsui');
6263 $table = new html_table();
6264 $table->head = array($txt->name, $txt->enable);
6265 $table->colclasses = array('leftalign', 'centeralign');
6266 $table->id = 'availablelicenses';
6267 $table->attributes['class'] = 'admintable generaltable';
6268 $table->data = array();
6270 foreach ($licenses as $value) {
6271 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6273 if ($value->enabled == 1) {
6274 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6275 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6276 } else {
6277 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6278 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6281 if ($value->shortname == $CFG->sitedefaultlicense) {
6282 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6283 $hideshow = '';
6286 $enabled = true;
6288 $table->data[] =array($displayname, $hideshow);
6290 $return .= html_writer::table($table);
6291 $return .= $OUTPUT->box_end();
6292 return highlight($query, $return);
6297 * Course formats manager. Allows to enable/disable formats and jump to settings
6299 class admin_setting_manageformats extends admin_setting {
6302 * Calls parent::__construct with specific arguments
6304 public function __construct() {
6305 $this->nosave = true;
6306 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6310 * Always returns true
6312 * @return true
6314 public function get_setting() {
6315 return true;
6319 * Always returns true
6321 * @return true
6323 public function get_defaultsetting() {
6324 return true;
6328 * Always returns '' and doesn't write anything
6330 * @param mixed $data string or array, must not be NULL
6331 * @return string Always returns ''
6333 public function write_setting($data) {
6334 // do not write any setting
6335 return '';
6339 * Search to find if Query is related to format plugin
6341 * @param string $query The string to search for
6342 * @return bool true for related false for not
6344 public function is_related($query) {
6345 if (parent::is_related($query)) {
6346 return true;
6348 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6349 foreach ($formats as $format) {
6350 if (strpos($format->component, $query) !== false ||
6351 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6352 return true;
6355 return false;
6359 * Return XHTML to display control
6361 * @param mixed $data Unused
6362 * @param string $query
6363 * @return string highlight
6365 public function output_html($data, $query='') {
6366 global $CFG, $OUTPUT;
6367 $return = '';
6368 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6369 $return .= $OUTPUT->box_start('generalbox formatsui');
6371 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6373 // display strings
6374 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6375 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6376 $txt->updown = "$txt->up/$txt->down";
6378 $table = new html_table();
6379 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6380 $table->align = array('left', 'center', 'center', 'center', 'center');
6381 $table->attributes['class'] = 'manageformattable generaltable admintable';
6382 $table->data = array();
6384 $cnt = 0;
6385 $defaultformat = get_config('moodlecourse', 'format');
6386 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6387 foreach ($formats as $format) {
6388 $url = new moodle_url('/admin/courseformats.php',
6389 array('sesskey' => sesskey(), 'format' => $format->name));
6390 $isdefault = '';
6391 $class = '';
6392 if ($format->is_enabled()) {
6393 $strformatname = $format->displayname;
6394 if ($defaultformat === $format->name) {
6395 $hideshow = $txt->default;
6396 } else {
6397 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6398 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6400 } else {
6401 $strformatname = $format->displayname;
6402 $class = 'dimmed_text';
6403 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6404 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6406 $updown = '';
6407 if ($cnt) {
6408 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6409 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6410 } else {
6411 $updown .= $spacer;
6413 if ($cnt < count($formats) - 1) {
6414 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6415 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6416 } else {
6417 $updown .= $spacer;
6419 $cnt++;
6420 $settings = '';
6421 if ($format->get_settings_url()) {
6422 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6424 $uninstall = '';
6425 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6426 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6428 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6429 if ($class) {
6430 $row->attributes['class'] = $class;
6432 $table->data[] = $row;
6434 $return .= html_writer::table($table);
6435 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6436 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6437 $return .= $OUTPUT->box_end();
6438 return highlight($query, $return);
6443 * Special class for filter administration.
6445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6447 class admin_page_managefilters extends admin_externalpage {
6449 * Calls parent::__construct with specific arguments
6451 public function __construct() {
6452 global $CFG;
6453 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6457 * Searches all installed filters for specified filter
6459 * @param string $query The filter(string) to search for
6460 * @param string $query
6462 public function search($query) {
6463 global $CFG;
6464 if ($result = parent::search($query)) {
6465 return $result;
6468 $found = false;
6469 $filternames = filter_get_all_installed();
6470 foreach ($filternames as $path => $strfiltername) {
6471 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6472 $found = true;
6473 break;
6475 if (strpos($path, $query) !== false) {
6476 $found = true;
6477 break;
6481 if ($found) {
6482 $result = new stdClass;
6483 $result->page = $this;
6484 $result->settings = array();
6485 return array($this->name => $result);
6486 } else {
6487 return array();
6494 * Initialise admin page - this function does require login and permission
6495 * checks specified in page definition.
6497 * This function must be called on each admin page before other code.
6499 * @global moodle_page $PAGE
6501 * @param string $section name of page
6502 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6503 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6504 * added to the turn blocks editing on/off form, so this page reloads correctly.
6505 * @param string $actualurl if the actual page being viewed is not the normal one for this
6506 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6507 * @param array $options Additional options that can be specified for page setup.
6508 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6510 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6511 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6513 $PAGE->set_context(null); // hack - set context to something, by default to system context
6515 $site = get_site();
6516 require_login();
6518 if (!empty($options['pagelayout'])) {
6519 // A specific page layout has been requested.
6520 $PAGE->set_pagelayout($options['pagelayout']);
6521 } else if ($section === 'upgradesettings') {
6522 $PAGE->set_pagelayout('maintenance');
6523 } else {
6524 $PAGE->set_pagelayout('admin');
6527 $adminroot = admin_get_root(false, false); // settings not required for external pages
6528 $extpage = $adminroot->locate($section, true);
6530 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6531 // The requested section isn't in the admin tree
6532 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6533 if (!has_capability('moodle/site:config', context_system::instance())) {
6534 // The requested section could depend on a different capability
6535 // but most likely the user has inadequate capabilities
6536 print_error('accessdenied', 'admin');
6537 } else {
6538 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6542 // this eliminates our need to authenticate on the actual pages
6543 if (!$extpage->check_access()) {
6544 print_error('accessdenied', 'admin');
6545 die;
6548 navigation_node::require_admin_tree();
6550 // $PAGE->set_extra_button($extrabutton); TODO
6552 if (!$actualurl) {
6553 $actualurl = $extpage->url;
6556 $PAGE->set_url($actualurl, $extraurlparams);
6557 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6558 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6561 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6562 // During initial install.
6563 $strinstallation = get_string('installation', 'install');
6564 $strsettings = get_string('settings');
6565 $PAGE->navbar->add($strsettings);
6566 $PAGE->set_title($strinstallation);
6567 $PAGE->set_heading($strinstallation);
6568 $PAGE->set_cacheable(false);
6569 return;
6572 // Locate the current item on the navigation and make it active when found.
6573 $path = $extpage->path;
6574 $node = $PAGE->settingsnav;
6575 while ($node && count($path) > 0) {
6576 $node = $node->get(array_pop($path));
6578 if ($node) {
6579 $node->make_active();
6582 // Normal case.
6583 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6584 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6585 $USER->editing = $adminediting;
6588 $visiblepathtosection = array_reverse($extpage->visiblepath);
6590 if ($PAGE->user_allowed_editing()) {
6591 if ($PAGE->user_is_editing()) {
6592 $caption = get_string('blockseditoff');
6593 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6594 } else {
6595 $caption = get_string('blocksediton');
6596 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6598 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6601 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6602 $PAGE->set_heading($SITE->fullname);
6604 // prevent caching in nav block
6605 $PAGE->navigation->clear_cache();
6609 * Returns the reference to admin tree root
6611 * @return object admin_root object
6613 function admin_get_root($reload=false, $requirefulltree=true) {
6614 global $CFG, $DB, $OUTPUT;
6616 static $ADMIN = NULL;
6618 if (is_null($ADMIN)) {
6619 // create the admin tree!
6620 $ADMIN = new admin_root($requirefulltree);
6623 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6624 $ADMIN->purge_children($requirefulltree);
6627 if (!$ADMIN->loaded) {
6628 // we process this file first to create categories first and in correct order
6629 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6631 // now we process all other files in admin/settings to build the admin tree
6632 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6633 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6634 continue;
6636 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6637 // plugins are loaded last - they may insert pages anywhere
6638 continue;
6640 require($file);
6642 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6644 $ADMIN->loaded = true;
6647 return $ADMIN;
6650 /// settings utility functions
6653 * This function applies default settings.
6655 * @param object $node, NULL means complete tree, null by default
6656 * @param bool $unconditional if true overrides all values with defaults, null buy default
6658 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6659 global $CFG;
6661 if (is_null($node)) {
6662 core_plugin_manager::reset_caches();
6663 $node = admin_get_root(true, true);
6666 if ($node instanceof admin_category) {
6667 $entries = array_keys($node->children);
6668 foreach ($entries as $entry) {
6669 admin_apply_default_settings($node->children[$entry], $unconditional);
6672 } else if ($node instanceof admin_settingpage) {
6673 foreach ($node->settings as $setting) {
6674 if (!$unconditional and !is_null($setting->get_setting())) {
6675 //do not override existing defaults
6676 continue;
6678 $defaultsetting = $setting->get_defaultsetting();
6679 if (is_null($defaultsetting)) {
6680 // no value yet - default maybe applied after admin user creation or in upgradesettings
6681 continue;
6683 $setting->write_setting($defaultsetting);
6684 $setting->write_setting_flags(null);
6687 // Just in case somebody modifies the list of active plugins directly.
6688 core_plugin_manager::reset_caches();
6692 * Store changed settings, this function updates the errors variable in $ADMIN
6694 * @param object $formdata from form
6695 * @return int number of changed settings
6697 function admin_write_settings($formdata) {
6698 global $CFG, $SITE, $DB;
6700 $olddbsessions = !empty($CFG->dbsessions);
6701 $formdata = (array)$formdata;
6703 $data = array();
6704 foreach ($formdata as $fullname=>$value) {
6705 if (strpos($fullname, 's_') !== 0) {
6706 continue; // not a config value
6708 $data[$fullname] = $value;
6711 $adminroot = admin_get_root();
6712 $settings = admin_find_write_settings($adminroot, $data);
6714 $count = 0;
6715 foreach ($settings as $fullname=>$setting) {
6716 /** @var $setting admin_setting */
6717 $original = $setting->get_setting();
6718 $error = $setting->write_setting($data[$fullname]);
6719 if ($error !== '') {
6720 $adminroot->errors[$fullname] = new stdClass();
6721 $adminroot->errors[$fullname]->data = $data[$fullname];
6722 $adminroot->errors[$fullname]->id = $setting->get_id();
6723 $adminroot->errors[$fullname]->error = $error;
6724 } else {
6725 $setting->write_setting_flags($data);
6727 if ($setting->post_write_settings($original)) {
6728 $count++;
6732 if ($olddbsessions != !empty($CFG->dbsessions)) {
6733 require_logout();
6736 // Now update $SITE - just update the fields, in case other people have a
6737 // a reference to it (e.g. $PAGE, $COURSE).
6738 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6739 foreach (get_object_vars($newsite) as $field => $value) {
6740 $SITE->$field = $value;
6743 // now reload all settings - some of them might depend on the changed
6744 admin_get_root(true);
6745 return $count;
6749 * Internal recursive function - finds all settings from submitted form
6751 * @param object $node Instance of admin_category, or admin_settingpage
6752 * @param array $data
6753 * @return array
6755 function admin_find_write_settings($node, $data) {
6756 $return = array();
6758 if (empty($data)) {
6759 return $return;
6762 if ($node instanceof admin_category) {
6763 $entries = array_keys($node->children);
6764 foreach ($entries as $entry) {
6765 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6768 } else if ($node instanceof admin_settingpage) {
6769 foreach ($node->settings as $setting) {
6770 $fullname = $setting->get_full_name();
6771 if (array_key_exists($fullname, $data)) {
6772 $return[$fullname] = $setting;
6778 return $return;
6782 * Internal function - prints the search results
6784 * @param string $query String to search for
6785 * @return string empty or XHTML
6787 function admin_search_settings_html($query) {
6788 global $CFG, $OUTPUT;
6790 if (core_text::strlen($query) < 2) {
6791 return '';
6793 $query = core_text::strtolower($query);
6795 $adminroot = admin_get_root();
6796 $findings = $adminroot->search($query);
6797 $return = '';
6798 $savebutton = false;
6800 foreach ($findings as $found) {
6801 $page = $found->page;
6802 $settings = $found->settings;
6803 if ($page->is_hidden()) {
6804 // hidden pages are not displayed in search results
6805 continue;
6807 if ($page instanceof admin_externalpage) {
6808 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6809 } else if ($page instanceof admin_settingpage) {
6810 $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');
6811 } else {
6812 continue;
6814 if (!empty($settings)) {
6815 $return .= '<fieldset class="adminsettings">'."\n";
6816 foreach ($settings as $setting) {
6817 if (empty($setting->nosave)) {
6818 $savebutton = true;
6820 $return .= '<div class="clearer"><!-- --></div>'."\n";
6821 $fullname = $setting->get_full_name();
6822 if (array_key_exists($fullname, $adminroot->errors)) {
6823 $data = $adminroot->errors[$fullname]->data;
6824 } else {
6825 $data = $setting->get_setting();
6826 // do not use defaults if settings not available - upgradesettings handles the defaults!
6828 $return .= $setting->output_html($data, $query);
6830 $return .= '</fieldset>';
6834 if ($savebutton) {
6835 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6838 return $return;
6842 * Internal function - returns arrays of html pages with uninitialised settings
6844 * @param object $node Instance of admin_category or admin_settingpage
6845 * @return array
6847 function admin_output_new_settings_by_page($node) {
6848 global $OUTPUT;
6849 $return = array();
6851 if ($node instanceof admin_category) {
6852 $entries = array_keys($node->children);
6853 foreach ($entries as $entry) {
6854 $return += admin_output_new_settings_by_page($node->children[$entry]);
6857 } else if ($node instanceof admin_settingpage) {
6858 $newsettings = array();
6859 foreach ($node->settings as $setting) {
6860 if (is_null($setting->get_setting())) {
6861 $newsettings[] = $setting;
6864 if (count($newsettings) > 0) {
6865 $adminroot = admin_get_root();
6866 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6867 $page .= '<fieldset class="adminsettings">'."\n";
6868 foreach ($newsettings as $setting) {
6869 $fullname = $setting->get_full_name();
6870 if (array_key_exists($fullname, $adminroot->errors)) {
6871 $data = $adminroot->errors[$fullname]->data;
6872 } else {
6873 $data = $setting->get_setting();
6874 if (is_null($data)) {
6875 $data = $setting->get_defaultsetting();
6878 $page .= '<div class="clearer"><!-- --></div>'."\n";
6879 $page .= $setting->output_html($data);
6881 $page .= '</fieldset>';
6882 $return[$node->name] = $page;
6886 return $return;
6890 * Format admin settings
6892 * @param object $setting
6893 * @param string $title label element
6894 * @param string $form form fragment, html code - not highlighted automatically
6895 * @param string $description
6896 * @param bool $label link label to id, true by default
6897 * @param string $warning warning text
6898 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6899 * @param string $query search query to be highlighted
6900 * @return string XHTML
6902 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6903 global $CFG;
6905 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6906 $fullname = $setting->get_full_name();
6908 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6909 if ($label) {
6910 $labelfor = 'for = "'.$setting->get_id().'"';
6911 } else {
6912 $labelfor = '';
6914 $form .= $setting->output_setting_flags();
6916 $override = '';
6917 if (empty($setting->plugin)) {
6918 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6919 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6921 } else {
6922 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6923 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6927 if ($warning !== '') {
6928 $warning = '<div class="form-warning">'.$warning.'</div>';
6931 $defaults = array();
6932 if (!is_null($defaultinfo)) {
6933 if ($defaultinfo === '') {
6934 $defaultinfo = get_string('emptysettingvalue', 'admin');
6936 $defaults[] = $defaultinfo;
6939 $setting->get_setting_flag_defaults($defaults);
6941 if (!empty($defaults)) {
6942 $defaultinfo = implode(', ', $defaults);
6943 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6944 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6948 $str = '
6949 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6950 <div class="form-label">
6951 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6952 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6953 </div>
6954 <div class="form-setting">'.$form.$defaultinfo.'</div>
6955 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6956 </div>';
6958 $adminroot = admin_get_root();
6959 if (array_key_exists($fullname, $adminroot->errors)) {
6960 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6963 return $str;
6967 * Based on find_new_settings{@link ()} in upgradesettings.php
6968 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6970 * @param object $node Instance of admin_category, or admin_settingpage
6971 * @return boolean true if any settings haven't been initialised, false if they all have
6973 function any_new_admin_settings($node) {
6975 if ($node instanceof admin_category) {
6976 $entries = array_keys($node->children);
6977 foreach ($entries as $entry) {
6978 if (any_new_admin_settings($node->children[$entry])) {
6979 return true;
6983 } else if ($node instanceof admin_settingpage) {
6984 foreach ($node->settings as $setting) {
6985 if ($setting->get_setting() === NULL) {
6986 return true;
6991 return false;
6995 * Moved from admin/replace.php so that we can use this in cron
6997 * @param string $search string to look for
6998 * @param string $replace string to replace
6999 * @return bool success or fail
7001 function db_replace($search, $replace) {
7002 global $DB, $CFG, $OUTPUT;
7004 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7005 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7006 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7007 'block_instances', '');
7009 // Turn off time limits, sometimes upgrades can be slow.
7010 core_php_time_limit::raise();
7012 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7013 return false;
7015 foreach ($tables as $table) {
7017 if (in_array($table, $skiptables)) { // Don't process these
7018 continue;
7021 if ($columns = $DB->get_columns($table)) {
7022 $DB->set_debug(true);
7023 foreach ($columns as $column) {
7024 $DB->replace_all_text($table, $column, $search, $replace);
7026 $DB->set_debug(false);
7030 // delete modinfo caches
7031 rebuild_course_cache(0, true);
7033 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7034 $blocks = core_component::get_plugin_list('block');
7035 foreach ($blocks as $blockname=>$fullblock) {
7036 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7037 continue;
7040 if (!is_readable($fullblock.'/lib.php')) {
7041 continue;
7044 $function = 'block_'.$blockname.'_global_db_replace';
7045 include_once($fullblock.'/lib.php');
7046 if (!function_exists($function)) {
7047 continue;
7050 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7051 $function($search, $replace);
7052 echo $OUTPUT->notification("...finished", 'notifysuccess');
7055 purge_all_caches();
7057 return true;
7061 * Manage repository settings
7063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7065 class admin_setting_managerepository extends admin_setting {
7066 /** @var string */
7067 private $baseurl;
7070 * calls parent::__construct with specific arguments
7072 public function __construct() {
7073 global $CFG;
7074 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7075 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7079 * Always returns true, does nothing
7081 * @return true
7083 public function get_setting() {
7084 return true;
7088 * Always returns true does nothing
7090 * @return true
7092 public function get_defaultsetting() {
7093 return true;
7097 * Always returns s_managerepository
7099 * @return string Always return 's_managerepository'
7101 public function get_full_name() {
7102 return 's_managerepository';
7106 * Always returns '' doesn't do anything
7108 public function write_setting($data) {
7109 $url = $this->baseurl . '&amp;new=' . $data;
7110 return '';
7111 // TODO
7112 // Should not use redirect and exit here
7113 // Find a better way to do this.
7114 // redirect($url);
7115 // exit;
7119 * Searches repository plugins for one that matches $query
7121 * @param string $query The string to search for
7122 * @return bool true if found, false if not
7124 public function is_related($query) {
7125 if (parent::is_related($query)) {
7126 return true;
7129 $repositories= core_component::get_plugin_list('repository');
7130 foreach ($repositories as $p => $dir) {
7131 if (strpos($p, $query) !== false) {
7132 return true;
7135 foreach (repository::get_types() as $instance) {
7136 $title = $instance->get_typename();
7137 if (strpos(core_text::strtolower($title), $query) !== false) {
7138 return true;
7141 return false;
7145 * Helper function that generates a moodle_url object
7146 * relevant to the repository
7149 function repository_action_url($repository) {
7150 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7154 * Builds XHTML to display the control
7156 * @param string $data Unused
7157 * @param string $query
7158 * @return string XHTML
7160 public function output_html($data, $query='') {
7161 global $CFG, $USER, $OUTPUT;
7163 // Get strings that are used
7164 $strshow = get_string('on', 'repository');
7165 $strhide = get_string('off', 'repository');
7166 $strdelete = get_string('disabled', 'repository');
7168 $actionchoicesforexisting = array(
7169 'show' => $strshow,
7170 'hide' => $strhide,
7171 'delete' => $strdelete
7174 $actionchoicesfornew = array(
7175 'newon' => $strshow,
7176 'newoff' => $strhide,
7177 'delete' => $strdelete
7180 $return = '';
7181 $return .= $OUTPUT->box_start('generalbox');
7183 // Set strings that are used multiple times
7184 $settingsstr = get_string('settings');
7185 $disablestr = get_string('disable');
7187 // Table to list plug-ins
7188 $table = new html_table();
7189 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7190 $table->align = array('left', 'center', 'center', 'center', 'center');
7191 $table->data = array();
7193 // Get list of used plug-ins
7194 $repositorytypes = repository::get_types();
7195 if (!empty($repositorytypes)) {
7196 // Array to store plugins being used
7197 $alreadyplugins = array();
7198 $totalrepositorytypes = count($repositorytypes);
7199 $updowncount = 1;
7200 foreach ($repositorytypes as $i) {
7201 $settings = '';
7202 $typename = $i->get_typename();
7203 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7204 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7205 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7207 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7208 // Calculate number of instances in order to display them for the Moodle administrator
7209 if (!empty($instanceoptionnames)) {
7210 $params = array();
7211 $params['context'] = array(context_system::instance());
7212 $params['onlyvisible'] = false;
7213 $params['type'] = $typename;
7214 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7215 // site instances
7216 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7217 $params['context'] = array();
7218 $instances = repository::static_function($typename, 'get_instances', $params);
7219 $courseinstances = array();
7220 $userinstances = array();
7222 foreach ($instances as $instance) {
7223 $repocontext = context::instance_by_id($instance->instance->contextid);
7224 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7225 $courseinstances[] = $instance;
7226 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7227 $userinstances[] = $instance;
7230 // course instances
7231 $instancenumber = count($courseinstances);
7232 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7234 // user private instances
7235 $instancenumber = count($userinstances);
7236 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7237 } else {
7238 $admininstancenumbertext = "";
7239 $courseinstancenumbertext = "";
7240 $userinstancenumbertext = "";
7243 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7245 $settings .= $OUTPUT->container_start('mdl-left');
7246 $settings .= '<br/>';
7247 $settings .= $admininstancenumbertext;
7248 $settings .= '<br/>';
7249 $settings .= $courseinstancenumbertext;
7250 $settings .= '<br/>';
7251 $settings .= $userinstancenumbertext;
7252 $settings .= $OUTPUT->container_end();
7254 // Get the current visibility
7255 if ($i->get_visible()) {
7256 $currentaction = 'show';
7257 } else {
7258 $currentaction = 'hide';
7261 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7263 // Display up/down link
7264 $updown = '';
7265 // Should be done with CSS instead.
7266 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7268 if ($updowncount > 1) {
7269 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7270 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7272 else {
7273 $updown .= $spacer;
7275 if ($updowncount < $totalrepositorytypes) {
7276 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7277 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7279 else {
7280 $updown .= $spacer;
7283 $updowncount++;
7285 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7287 if (!in_array($typename, $alreadyplugins)) {
7288 $alreadyplugins[] = $typename;
7293 // Get all the plugins that exist on disk
7294 $plugins = core_component::get_plugin_list('repository');
7295 if (!empty($plugins)) {
7296 foreach ($plugins as $plugin => $dir) {
7297 // Check that it has not already been listed
7298 if (!in_array($plugin, $alreadyplugins)) {
7299 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7300 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7305 $return .= html_writer::table($table);
7306 $return .= $OUTPUT->box_end();
7307 return highlight($query, $return);
7312 * Special checkbox for enable mobile web service
7313 * If enable then we store the service id of the mobile service into config table
7314 * If disable then we unstore the service id from the config table
7316 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7318 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7319 private $xmlrpcuse;
7320 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7321 private $restuse;
7324 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7326 * @return boolean
7328 private function is_protocol_cap_allowed() {
7329 global $DB, $CFG;
7331 // We keep xmlrpc enabled for backward compatibility.
7332 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7333 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7334 $params = array();
7335 $params['permission'] = CAP_ALLOW;
7336 $params['roleid'] = $CFG->defaultuserroleid;
7337 $params['capability'] = 'webservice/xmlrpc:use';
7338 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7341 // If the $this->restuse variable is not set, it needs to be set.
7342 if (empty($this->restuse) and $this->restuse!==false) {
7343 $params = array();
7344 $params['permission'] = CAP_ALLOW;
7345 $params['roleid'] = $CFG->defaultuserroleid;
7346 $params['capability'] = 'webservice/rest:use';
7347 $this->restuse = $DB->record_exists('role_capabilities', $params);
7350 return ($this->xmlrpcuse && $this->restuse);
7354 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7355 * @param type $status true to allow, false to not set
7357 private function set_protocol_cap($status) {
7358 global $CFG;
7359 if ($status and !$this->is_protocol_cap_allowed()) {
7360 //need to allow the cap
7361 $permission = CAP_ALLOW;
7362 $assign = true;
7363 } else if (!$status and $this->is_protocol_cap_allowed()){
7364 //need to disallow the cap
7365 $permission = CAP_INHERIT;
7366 $assign = true;
7368 if (!empty($assign)) {
7369 $systemcontext = context_system::instance();
7370 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7371 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7376 * Builds XHTML to display the control.
7377 * The main purpose of this overloading is to display a warning when https
7378 * is not supported by the server
7379 * @param string $data Unused
7380 * @param string $query
7381 * @return string XHTML
7383 public function output_html($data, $query='') {
7384 global $CFG, $OUTPUT;
7385 $html = parent::output_html($data, $query);
7387 if ((string)$data === $this->yes) {
7388 require_once($CFG->dirroot . "/lib/filelib.php");
7389 $curl = new curl();
7390 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7391 $curl->head($httpswwwroot . "/login/index.php");
7392 $info = $curl->get_info();
7393 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7394 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7398 return $html;
7402 * Retrieves the current setting using the objects name
7404 * @return string
7406 public function get_setting() {
7407 global $CFG;
7409 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7410 // Or if web services aren't enabled this can't be,
7411 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7412 return 0;
7415 require_once($CFG->dirroot . '/webservice/lib.php');
7416 $webservicemanager = new webservice();
7417 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7418 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7419 return $this->config_read($this->name); //same as returning 1
7420 } else {
7421 return 0;
7426 * Save the selected setting
7428 * @param string $data The selected site
7429 * @return string empty string or error message
7431 public function write_setting($data) {
7432 global $DB, $CFG;
7434 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7435 if (empty($CFG->defaultuserroleid)) {
7436 return '';
7439 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7441 require_once($CFG->dirroot . '/webservice/lib.php');
7442 $webservicemanager = new webservice();
7444 $updateprotocol = false;
7445 if ((string)$data === $this->yes) {
7446 //code run when enable mobile web service
7447 //enable web service systeme if necessary
7448 set_config('enablewebservices', true);
7450 //enable mobile service
7451 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7452 $mobileservice->enabled = 1;
7453 $webservicemanager->update_external_service($mobileservice);
7455 //enable xml-rpc server
7456 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7458 if (!in_array('xmlrpc', $activeprotocols)) {
7459 $activeprotocols[] = 'xmlrpc';
7460 $updateprotocol = true;
7463 if (!in_array('rest', $activeprotocols)) {
7464 $activeprotocols[] = 'rest';
7465 $updateprotocol = true;
7468 if ($updateprotocol) {
7469 set_config('webserviceprotocols', implode(',', $activeprotocols));
7472 //allow xml-rpc:use capability for authenticated user
7473 $this->set_protocol_cap(true);
7475 } else {
7476 //disable web service system if no other services are enabled
7477 $otherenabledservices = $DB->get_records_select('external_services',
7478 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7479 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7480 if (empty($otherenabledservices)) {
7481 set_config('enablewebservices', false);
7483 //also disable xml-rpc server
7484 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7485 $protocolkey = array_search('xmlrpc', $activeprotocols);
7486 if ($protocolkey !== false) {
7487 unset($activeprotocols[$protocolkey]);
7488 $updateprotocol = true;
7491 $protocolkey = array_search('rest', $activeprotocols);
7492 if ($protocolkey !== false) {
7493 unset($activeprotocols[$protocolkey]);
7494 $updateprotocol = true;
7497 if ($updateprotocol) {
7498 set_config('webserviceprotocols', implode(',', $activeprotocols));
7501 //disallow xml-rpc:use capability for authenticated user
7502 $this->set_protocol_cap(false);
7505 //disable the mobile service
7506 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7507 $mobileservice->enabled = 0;
7508 $webservicemanager->update_external_service($mobileservice);
7511 return (parent::write_setting($data));
7516 * Special class for management of external services
7518 * @author Petr Skoda (skodak)
7520 class admin_setting_manageexternalservices extends admin_setting {
7522 * Calls parent::__construct with specific arguments
7524 public function __construct() {
7525 $this->nosave = true;
7526 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7530 * Always returns true, does nothing
7532 * @return true
7534 public function get_setting() {
7535 return true;
7539 * Always returns true, does nothing
7541 * @return true
7543 public function get_defaultsetting() {
7544 return true;
7548 * Always returns '', does not write anything
7550 * @return string Always returns ''
7552 public function write_setting($data) {
7553 // do not write any setting
7554 return '';
7558 * Checks if $query is one of the available external services
7560 * @param string $query The string to search for
7561 * @return bool Returns true if found, false if not
7563 public function is_related($query) {
7564 global $DB;
7566 if (parent::is_related($query)) {
7567 return true;
7570 $services = $DB->get_records('external_services', array(), 'id, name');
7571 foreach ($services as $service) {
7572 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7573 return true;
7576 return false;
7580 * Builds the XHTML to display the control
7582 * @param string $data Unused
7583 * @param string $query
7584 * @return string
7586 public function output_html($data, $query='') {
7587 global $CFG, $OUTPUT, $DB;
7589 // display strings
7590 $stradministration = get_string('administration');
7591 $stredit = get_string('edit');
7592 $strservice = get_string('externalservice', 'webservice');
7593 $strdelete = get_string('delete');
7594 $strplugin = get_string('plugin', 'admin');
7595 $stradd = get_string('add');
7596 $strfunctions = get_string('functions', 'webservice');
7597 $strusers = get_string('users');
7598 $strserviceusers = get_string('serviceusers', 'webservice');
7600 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7601 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7602 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7604 // built in services
7605 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7606 $return = "";
7607 if (!empty($services)) {
7608 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7612 $table = new html_table();
7613 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7614 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7615 $table->id = 'builtinservices';
7616 $table->attributes['class'] = 'admintable externalservices generaltable';
7617 $table->data = array();
7619 // iterate through auth plugins and add to the display table
7620 foreach ($services as $service) {
7621 $name = $service->name;
7623 // hide/show link
7624 if ($service->enabled) {
7625 $displayname = "<span>$name</span>";
7626 } else {
7627 $displayname = "<span class=\"dimmed_text\">$name</span>";
7630 $plugin = $service->component;
7632 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7634 if ($service->restrictedusers) {
7635 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7636 } else {
7637 $users = get_string('allusers', 'webservice');
7640 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7642 // add a row to the table
7643 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7645 $return .= html_writer::table($table);
7648 // Custom services
7649 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7650 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7652 $table = new html_table();
7653 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7654 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7655 $table->id = 'customservices';
7656 $table->attributes['class'] = 'admintable externalservices generaltable';
7657 $table->data = array();
7659 // iterate through auth plugins and add to the display table
7660 foreach ($services as $service) {
7661 $name = $service->name;
7663 // hide/show link
7664 if ($service->enabled) {
7665 $displayname = "<span>$name</span>";
7666 } else {
7667 $displayname = "<span class=\"dimmed_text\">$name</span>";
7670 // delete link
7671 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7673 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7675 if ($service->restrictedusers) {
7676 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7677 } else {
7678 $users = get_string('allusers', 'webservice');
7681 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7683 // add a row to the table
7684 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7686 // add new custom service option
7687 $return .= html_writer::table($table);
7689 $return .= '<br />';
7690 // add a token to the table
7691 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7693 return highlight($query, $return);
7698 * Special class for overview of external services
7700 * @author Jerome Mouneyrac
7702 class admin_setting_webservicesoverview extends admin_setting {
7705 * Calls parent::__construct with specific arguments
7707 public function __construct() {
7708 $this->nosave = true;
7709 parent::__construct('webservicesoverviewui',
7710 get_string('webservicesoverview', 'webservice'), '', '');
7714 * Always returns true, does nothing
7716 * @return true
7718 public function get_setting() {
7719 return true;
7723 * Always returns true, does nothing
7725 * @return true
7727 public function get_defaultsetting() {
7728 return true;
7732 * Always returns '', does not write anything
7734 * @return string Always returns ''
7736 public function write_setting($data) {
7737 // do not write any setting
7738 return '';
7742 * Builds the XHTML to display the control
7744 * @param string $data Unused
7745 * @param string $query
7746 * @return string
7748 public function output_html($data, $query='') {
7749 global $CFG, $OUTPUT;
7751 $return = "";
7752 $brtag = html_writer::empty_tag('br');
7754 // Enable mobile web service
7755 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7756 get_string('enablemobilewebservice', 'admin'),
7757 get_string('configenablemobilewebservice',
7758 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7759 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7760 $wsmobileparam = new stdClass();
7761 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7762 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7763 get_string('externalservices', 'webservice'));
7764 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7765 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7766 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7767 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7768 . $brtag . $brtag;
7770 /// One system controlling Moodle with Token
7771 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7772 $table = new html_table();
7773 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7774 get_string('description'));
7775 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7776 $table->id = 'onesystemcontrol';
7777 $table->attributes['class'] = 'admintable wsoverview generaltable';
7778 $table->data = array();
7780 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7781 . $brtag . $brtag;
7783 /// 1. Enable Web Services
7784 $row = array();
7785 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7786 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7787 array('href' => $url));
7788 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7789 if ($CFG->enablewebservices) {
7790 $status = get_string('yes');
7792 $row[1] = $status;
7793 $row[2] = get_string('enablewsdescription', 'webservice');
7794 $table->data[] = $row;
7796 /// 2. Enable protocols
7797 $row = array();
7798 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7799 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7800 array('href' => $url));
7801 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7802 //retrieve activated protocol
7803 $active_protocols = empty($CFG->webserviceprotocols) ?
7804 array() : explode(',', $CFG->webserviceprotocols);
7805 if (!empty($active_protocols)) {
7806 $status = "";
7807 foreach ($active_protocols as $protocol) {
7808 $status .= $protocol . $brtag;
7811 $row[1] = $status;
7812 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7813 $table->data[] = $row;
7815 /// 3. Create user account
7816 $row = array();
7817 $url = new moodle_url("/user/editadvanced.php?id=-1");
7818 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7819 array('href' => $url));
7820 $row[1] = "";
7821 $row[2] = get_string('createuserdescription', 'webservice');
7822 $table->data[] = $row;
7824 /// 4. Add capability to users
7825 $row = array();
7826 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7827 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7828 array('href' => $url));
7829 $row[1] = "";
7830 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7831 $table->data[] = $row;
7833 /// 5. Select a web service
7834 $row = array();
7835 $url = new moodle_url("/admin/settings.php?section=externalservices");
7836 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7837 array('href' => $url));
7838 $row[1] = "";
7839 $row[2] = get_string('createservicedescription', 'webservice');
7840 $table->data[] = $row;
7842 /// 6. Add functions
7843 $row = array();
7844 $url = new moodle_url("/admin/settings.php?section=externalservices");
7845 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7846 array('href' => $url));
7847 $row[1] = "";
7848 $row[2] = get_string('addfunctionsdescription', 'webservice');
7849 $table->data[] = $row;
7851 /// 7. Add the specific user
7852 $row = array();
7853 $url = new moodle_url("/admin/settings.php?section=externalservices");
7854 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7855 array('href' => $url));
7856 $row[1] = "";
7857 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7858 $table->data[] = $row;
7860 /// 8. Create token for the specific user
7861 $row = array();
7862 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7863 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7864 array('href' => $url));
7865 $row[1] = "";
7866 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7867 $table->data[] = $row;
7869 /// 9. Enable the documentation
7870 $row = array();
7871 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7872 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7873 array('href' => $url));
7874 $status = '<span class="warning">' . get_string('no') . '</span>';
7875 if ($CFG->enablewsdocumentation) {
7876 $status = get_string('yes');
7878 $row[1] = $status;
7879 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7880 $table->data[] = $row;
7882 /// 10. Test the service
7883 $row = array();
7884 $url = new moodle_url("/admin/webservice/testclient.php");
7885 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7886 array('href' => $url));
7887 $row[1] = "";
7888 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7889 $table->data[] = $row;
7891 $return .= html_writer::table($table);
7893 /// Users as clients with token
7894 $return .= $brtag . $brtag . $brtag;
7895 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7896 $table = new html_table();
7897 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7898 get_string('description'));
7899 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7900 $table->id = 'userasclients';
7901 $table->attributes['class'] = 'admintable wsoverview generaltable';
7902 $table->data = array();
7904 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7905 $brtag . $brtag;
7907 /// 1. Enable Web Services
7908 $row = array();
7909 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7910 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7911 array('href' => $url));
7912 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7913 if ($CFG->enablewebservices) {
7914 $status = get_string('yes');
7916 $row[1] = $status;
7917 $row[2] = get_string('enablewsdescription', 'webservice');
7918 $table->data[] = $row;
7920 /// 2. Enable protocols
7921 $row = array();
7922 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7923 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7924 array('href' => $url));
7925 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7926 //retrieve activated protocol
7927 $active_protocols = empty($CFG->webserviceprotocols) ?
7928 array() : explode(',', $CFG->webserviceprotocols);
7929 if (!empty($active_protocols)) {
7930 $status = "";
7931 foreach ($active_protocols as $protocol) {
7932 $status .= $protocol . $brtag;
7935 $row[1] = $status;
7936 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7937 $table->data[] = $row;
7940 /// 3. Select a web service
7941 $row = array();
7942 $url = new moodle_url("/admin/settings.php?section=externalservices");
7943 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7944 array('href' => $url));
7945 $row[1] = "";
7946 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7947 $table->data[] = $row;
7949 /// 4. Add functions
7950 $row = array();
7951 $url = new moodle_url("/admin/settings.php?section=externalservices");
7952 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7953 array('href' => $url));
7954 $row[1] = "";
7955 $row[2] = get_string('addfunctionsdescription', 'webservice');
7956 $table->data[] = $row;
7958 /// 5. Add capability to users
7959 $row = array();
7960 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7961 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7962 array('href' => $url));
7963 $row[1] = "";
7964 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7965 $table->data[] = $row;
7967 /// 6. Test the service
7968 $row = array();
7969 $url = new moodle_url("/admin/webservice/testclient.php");
7970 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7971 array('href' => $url));
7972 $row[1] = "";
7973 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7974 $table->data[] = $row;
7976 $return .= html_writer::table($table);
7978 return highlight($query, $return);
7985 * Special class for web service protocol administration.
7987 * @author Petr Skoda (skodak)
7989 class admin_setting_managewebserviceprotocols extends admin_setting {
7992 * Calls parent::__construct with specific arguments
7994 public function __construct() {
7995 $this->nosave = true;
7996 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8000 * Always returns true, does nothing
8002 * @return true
8004 public function get_setting() {
8005 return true;
8009 * Always returns true, does nothing
8011 * @return true
8013 public function get_defaultsetting() {
8014 return true;
8018 * Always returns '', does not write anything
8020 * @return string Always returns ''
8022 public function write_setting($data) {
8023 // do not write any setting
8024 return '';
8028 * Checks if $query is one of the available webservices
8030 * @param string $query The string to search for
8031 * @return bool Returns true if found, false if not
8033 public function is_related($query) {
8034 if (parent::is_related($query)) {
8035 return true;
8038 $protocols = core_component::get_plugin_list('webservice');
8039 foreach ($protocols as $protocol=>$location) {
8040 if (strpos($protocol, $query) !== false) {
8041 return true;
8043 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8044 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8045 return true;
8048 return false;
8052 * Builds the XHTML to display the control
8054 * @param string $data Unused
8055 * @param string $query
8056 * @return string
8058 public function output_html($data, $query='') {
8059 global $CFG, $OUTPUT;
8061 // display strings
8062 $stradministration = get_string('administration');
8063 $strsettings = get_string('settings');
8064 $stredit = get_string('edit');
8065 $strprotocol = get_string('protocol', 'webservice');
8066 $strenable = get_string('enable');
8067 $strdisable = get_string('disable');
8068 $strversion = get_string('version');
8070 $protocols_available = core_component::get_plugin_list('webservice');
8071 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8072 ksort($protocols_available);
8074 foreach ($active_protocols as $key=>$protocol) {
8075 if (empty($protocols_available[$protocol])) {
8076 unset($active_protocols[$key]);
8080 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8081 $return .= $OUTPUT->box_start('generalbox webservicesui');
8083 $table = new html_table();
8084 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8085 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8086 $table->id = 'webserviceprotocols';
8087 $table->attributes['class'] = 'admintable generaltable';
8088 $table->data = array();
8090 // iterate through auth plugins and add to the display table
8091 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8092 foreach ($protocols_available as $protocol => $location) {
8093 $name = get_string('pluginname', 'webservice_'.$protocol);
8095 $plugin = new stdClass();
8096 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8097 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8099 $version = isset($plugin->version) ? $plugin->version : '';
8101 // hide/show link
8102 if (in_array($protocol, $active_protocols)) {
8103 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8104 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8105 $displayname = "<span>$name</span>";
8106 } else {
8107 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8108 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8109 $displayname = "<span class=\"dimmed_text\">$name</span>";
8112 // settings link
8113 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8114 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8115 } else {
8116 $settings = '';
8119 // add a row to the table
8120 $table->data[] = array($displayname, $version, $hideshow, $settings);
8122 $return .= html_writer::table($table);
8123 $return .= get_string('configwebserviceplugins', 'webservice');
8124 $return .= $OUTPUT->box_end();
8126 return highlight($query, $return);
8132 * Special class for web service token administration.
8134 * @author Jerome Mouneyrac
8136 class admin_setting_managewebservicetokens extends admin_setting {
8139 * Calls parent::__construct with specific arguments
8141 public function __construct() {
8142 $this->nosave = true;
8143 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8147 * Always returns true, does nothing
8149 * @return true
8151 public function get_setting() {
8152 return true;
8156 * Always returns true, does nothing
8158 * @return true
8160 public function get_defaultsetting() {
8161 return true;
8165 * Always returns '', does not write anything
8167 * @return string Always returns ''
8169 public function write_setting($data) {
8170 // do not write any setting
8171 return '';
8175 * Builds the XHTML to display the control
8177 * @param string $data Unused
8178 * @param string $query
8179 * @return string
8181 public function output_html($data, $query='') {
8182 global $CFG, $OUTPUT, $DB, $USER;
8184 // display strings
8185 $stroperation = get_string('operation', 'webservice');
8186 $strtoken = get_string('token', 'webservice');
8187 $strservice = get_string('service', 'webservice');
8188 $struser = get_string('user');
8189 $strcontext = get_string('context', 'webservice');
8190 $strvaliduntil = get_string('validuntil', 'webservice');
8191 $striprestriction = get_string('iprestriction', 'webservice');
8193 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8195 $table = new html_table();
8196 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8197 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8198 $table->id = 'webservicetokens';
8199 $table->attributes['class'] = 'admintable generaltable';
8200 $table->data = array();
8202 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8204 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8206 //here retrieve token list (including linked users firstname/lastname and linked services name)
8207 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8208 FROM {external_tokens} t, {user} u, {external_services} s
8209 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8210 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8211 if (!empty($tokens)) {
8212 foreach ($tokens as $token) {
8213 //TODO: retrieve context
8215 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8216 $delete .= get_string('delete')."</a>";
8218 $validuntil = '';
8219 if (!empty($token->validuntil)) {
8220 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8223 $iprestriction = '';
8224 if (!empty($token->iprestriction)) {
8225 $iprestriction = $token->iprestriction;
8228 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8229 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8230 $useratag .= $token->firstname." ".$token->lastname;
8231 $useratag .= html_writer::end_tag('a');
8233 //check user missing capabilities
8234 require_once($CFG->dirroot . '/webservice/lib.php');
8235 $webservicemanager = new webservice();
8236 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8237 array(array('id' => $token->userid)), $token->serviceid);
8239 if (!is_siteadmin($token->userid) and
8240 array_key_exists($token->userid, $usermissingcaps)) {
8241 $missingcapabilities = implode(', ',
8242 $usermissingcaps[$token->userid]);
8243 if (!empty($missingcapabilities)) {
8244 $useratag .= html_writer::tag('div',
8245 get_string('usermissingcaps', 'webservice',
8246 $missingcapabilities)
8247 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8248 array('class' => 'missingcaps'));
8252 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8255 $return .= html_writer::table($table);
8256 } else {
8257 $return .= get_string('notoken', 'webservice');
8260 $return .= $OUTPUT->box_end();
8261 // add a token to the table
8262 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8263 $return .= get_string('add')."</a>";
8265 return highlight($query, $return);
8271 * Colour picker
8273 * @copyright 2010 Sam Hemelryk
8274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8276 class admin_setting_configcolourpicker extends admin_setting {
8279 * Information for previewing the colour
8281 * @var array|null
8283 protected $previewconfig = null;
8286 * Use default when empty.
8288 protected $usedefaultwhenempty = true;
8292 * @param string $name
8293 * @param string $visiblename
8294 * @param string $description
8295 * @param string $defaultsetting
8296 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8298 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8299 $usedefaultwhenempty = true) {
8300 $this->previewconfig = $previewconfig;
8301 $this->usedefaultwhenempty = $usedefaultwhenempty;
8302 parent::__construct($name, $visiblename, $description, $defaultsetting);
8306 * Return the setting
8308 * @return mixed returns config if successful else null
8310 public function get_setting() {
8311 return $this->config_read($this->name);
8315 * Saves the setting
8317 * @param string $data
8318 * @return bool
8320 public function write_setting($data) {
8321 $data = $this->validate($data);
8322 if ($data === false) {
8323 return get_string('validateerror', 'admin');
8325 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8329 * Validates the colour that was entered by the user
8331 * @param string $data
8332 * @return string|false
8334 protected function validate($data) {
8336 * List of valid HTML colour names
8338 * @var array
8340 $colornames = array(
8341 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8342 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8343 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8344 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8345 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8346 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8347 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8348 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8349 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8350 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8351 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8352 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8353 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8354 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8355 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8356 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8357 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8358 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8359 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8360 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8361 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8362 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8363 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8364 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8365 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8366 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8367 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8368 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8369 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8370 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8371 'whitesmoke', 'yellow', 'yellowgreen'
8374 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8375 if (strpos($data, '#')!==0) {
8376 $data = '#'.$data;
8378 return $data;
8379 } else if (in_array(strtolower($data), $colornames)) {
8380 return $data;
8381 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8382 return $data;
8383 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8384 return $data;
8385 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8386 return $data;
8387 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8388 return $data;
8389 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8390 return $data;
8391 } else if (empty($data)) {
8392 if ($this->usedefaultwhenempty){
8393 return $this->defaultsetting;
8394 } else {
8395 return '';
8397 } else {
8398 return false;
8403 * Generates the HTML for the setting
8405 * @global moodle_page $PAGE
8406 * @global core_renderer $OUTPUT
8407 * @param string $data
8408 * @param string $query
8410 public function output_html($data, $query = '') {
8411 global $PAGE, $OUTPUT;
8412 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8413 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8414 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8415 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8416 if (!empty($this->previewconfig)) {
8417 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8419 $content .= html_writer::end_tag('div');
8420 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
8426 * Class used for uploading of one file into file storage,
8427 * the file name is stored in config table.
8429 * Please note you need to implement your own '_pluginfile' callback function,
8430 * this setting only stores the file, it does not deal with file serving.
8432 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8433 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8435 class admin_setting_configstoredfile extends admin_setting {
8436 /** @var array file area options - should be one file only */
8437 protected $options;
8438 /** @var string name of the file area */
8439 protected $filearea;
8440 /** @var int intemid */
8441 protected $itemid;
8442 /** @var string used for detection of changes */
8443 protected $oldhashes;
8446 * Create new stored file setting.
8448 * @param string $name low level setting name
8449 * @param string $visiblename human readable setting name
8450 * @param string $description description of setting
8451 * @param mixed $filearea file area for file storage
8452 * @param int $itemid itemid for file storage
8453 * @param array $options file area options
8455 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8456 parent::__construct($name, $visiblename, $description, '');
8457 $this->filearea = $filearea;
8458 $this->itemid = $itemid;
8459 $this->options = (array)$options;
8463 * Applies defaults and returns all options.
8464 * @return array
8466 protected function get_options() {
8467 global $CFG;
8469 require_once("$CFG->libdir/filelib.php");
8470 require_once("$CFG->dirroot/repository/lib.php");
8471 $defaults = array(
8472 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8473 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8474 'context' => context_system::instance());
8475 foreach($this->options as $k => $v) {
8476 $defaults[$k] = $v;
8479 return $defaults;
8482 public function get_setting() {
8483 return $this->config_read($this->name);
8486 public function write_setting($data) {
8487 global $USER;
8489 // Let's not deal with validation here, this is for admins only.
8490 $current = $this->get_setting();
8491 if (empty($data) && $current === null) {
8492 // This will be the case when applying default settings (installation).
8493 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8494 } else if (!is_number($data)) {
8495 // Draft item id is expected here!
8496 return get_string('errorsetting', 'admin');
8499 $options = $this->get_options();
8500 $fs = get_file_storage();
8501 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8503 $this->oldhashes = null;
8504 if ($current) {
8505 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8506 if ($file = $fs->get_file_by_hash($hash)) {
8507 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8509 unset($file);
8512 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8513 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8514 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8515 // with an error because the draft area does not exist, as he did not use it.
8516 $usercontext = context_user::instance($USER->id);
8517 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8518 return get_string('errorsetting', 'admin');
8522 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8523 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8525 $filepath = '';
8526 if ($files) {
8527 /** @var stored_file $file */
8528 $file = reset($files);
8529 $filepath = $file->get_filepath().$file->get_filename();
8532 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8535 public function post_write_settings($original) {
8536 $options = $this->get_options();
8537 $fs = get_file_storage();
8538 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8540 $current = $this->get_setting();
8541 $newhashes = null;
8542 if ($current) {
8543 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8544 if ($file = $fs->get_file_by_hash($hash)) {
8545 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8547 unset($file);
8550 if ($this->oldhashes === $newhashes) {
8551 $this->oldhashes = null;
8552 return false;
8554 $this->oldhashes = null;
8556 $callbackfunction = $this->updatedcallback;
8557 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8558 $callbackfunction($this->get_full_name());
8560 return true;
8563 public function output_html($data, $query = '') {
8564 global $PAGE, $CFG;
8566 $options = $this->get_options();
8567 $id = $this->get_id();
8568 $elname = $this->get_full_name();
8569 $draftitemid = file_get_submitted_draft_itemid($elname);
8570 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8571 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8573 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8574 require_once("$CFG->dirroot/lib/form/filemanager.php");
8576 $fmoptions = new stdClass();
8577 $fmoptions->mainfile = $options['mainfile'];
8578 $fmoptions->maxbytes = $options['maxbytes'];
8579 $fmoptions->maxfiles = $options['maxfiles'];
8580 $fmoptions->client_id = uniqid();
8581 $fmoptions->itemid = $draftitemid;
8582 $fmoptions->subdirs = $options['subdirs'];
8583 $fmoptions->target = $id;
8584 $fmoptions->accepted_types = $options['accepted_types'];
8585 $fmoptions->return_types = $options['return_types'];
8586 $fmoptions->context = $options['context'];
8587 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8589 $fm = new form_filemanager($fmoptions);
8590 $output = $PAGE->get_renderer('core', 'files');
8591 $html = $output->render($fm);
8593 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8594 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8596 return format_admin_setting($this, $this->visiblename,
8597 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8603 * Administration interface for user specified regular expressions for device detection.
8605 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8607 class admin_setting_devicedetectregex extends admin_setting {
8610 * Calls parent::__construct with specific args
8612 * @param string $name
8613 * @param string $visiblename
8614 * @param string $description
8615 * @param mixed $defaultsetting
8617 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8618 global $CFG;
8619 parent::__construct($name, $visiblename, $description, $defaultsetting);
8623 * Return the current setting(s)
8625 * @return array Current settings array
8627 public function get_setting() {
8628 global $CFG;
8630 $config = $this->config_read($this->name);
8631 if (is_null($config)) {
8632 return null;
8635 return $this->prepare_form_data($config);
8639 * Save selected settings
8641 * @param array $data Array of settings to save
8642 * @return bool
8644 public function write_setting($data) {
8645 if (empty($data)) {
8646 $data = array();
8649 if ($this->config_write($this->name, $this->process_form_data($data))) {
8650 return ''; // success
8651 } else {
8652 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8657 * Return XHTML field(s) for regexes
8659 * @param array $data Array of options to set in HTML
8660 * @return string XHTML string for the fields and wrapping div(s)
8662 public function output_html($data, $query='') {
8663 global $OUTPUT;
8665 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8666 $out .= html_writer::start_tag('thead');
8667 $out .= html_writer::start_tag('tr');
8668 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8669 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8670 $out .= html_writer::end_tag('tr');
8671 $out .= html_writer::end_tag('thead');
8672 $out .= html_writer::start_tag('tbody');
8674 if (empty($data)) {
8675 $looplimit = 1;
8676 } else {
8677 $looplimit = (count($data)/2)+1;
8680 for ($i=0; $i<$looplimit; $i++) {
8681 $out .= html_writer::start_tag('tr');
8683 $expressionname = 'expression'.$i;
8685 if (!empty($data[$expressionname])){
8686 $expression = $data[$expressionname];
8687 } else {
8688 $expression = '';
8691 $out .= html_writer::tag('td',
8692 html_writer::empty_tag('input',
8693 array(
8694 'type' => 'text',
8695 'class' => 'form-text',
8696 'name' => $this->get_full_name().'[expression'.$i.']',
8697 'value' => $expression,
8699 ), array('class' => 'c'.$i)
8702 $valuename = 'value'.$i;
8704 if (!empty($data[$valuename])){
8705 $value = $data[$valuename];
8706 } else {
8707 $value= '';
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().'[value'.$i.']',
8716 'value' => $value,
8718 ), array('class' => 'c'.$i)
8721 $out .= html_writer::end_tag('tr');
8724 $out .= html_writer::end_tag('tbody');
8725 $out .= html_writer::end_tag('table');
8727 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8731 * Converts the string of regexes
8733 * @see self::process_form_data()
8734 * @param $regexes string of regexes
8735 * @return array of form fields and their values
8737 protected function prepare_form_data($regexes) {
8739 $regexes = json_decode($regexes);
8741 $form = array();
8743 $i = 0;
8745 foreach ($regexes as $value => $regex) {
8746 $expressionname = 'expression'.$i;
8747 $valuename = 'value'.$i;
8749 $form[$expressionname] = $regex;
8750 $form[$valuename] = $value;
8751 $i++;
8754 return $form;
8758 * Converts the data from admin settings form into a string of regexes
8760 * @see self::prepare_form_data()
8761 * @param array $data array of admin form fields and values
8762 * @return false|string of regexes
8764 protected function process_form_data(array $form) {
8766 $count = count($form); // number of form field values
8768 if ($count % 2) {
8769 // we must get five fields per expression
8770 return false;
8773 $regexes = array();
8774 for ($i = 0; $i < $count / 2; $i++) {
8775 $expressionname = "expression".$i;
8776 $valuename = "value".$i;
8778 $expression = trim($form['expression'.$i]);
8779 $value = trim($form['value'.$i]);
8781 if (empty($expression)){
8782 continue;
8785 $regexes[$value] = $expression;
8788 $regexes = json_encode($regexes);
8790 return $regexes;
8795 * Multiselect for current modules
8797 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8799 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8800 private $excludesystem;
8803 * Calls parent::__construct - note array $choices is not required
8805 * @param string $name setting name
8806 * @param string $visiblename localised setting name
8807 * @param string $description setting description
8808 * @param array $defaultsetting a plain array of default module ids
8809 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8811 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8812 $excludesystem = true) {
8813 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8814 $this->excludesystem = $excludesystem;
8818 * Loads an array of current module choices
8820 * @return bool always return true
8822 public function load_choices() {
8823 if (is_array($this->choices)) {
8824 return true;
8826 $this->choices = array();
8828 global $CFG, $DB;
8829 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8830 foreach ($records as $record) {
8831 // Exclude modules if the code doesn't exist
8832 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8833 // Also exclude system modules (if specified)
8834 if (!($this->excludesystem &&
8835 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8836 MOD_ARCHETYPE_SYSTEM)) {
8837 $this->choices[$record->id] = $record->name;
8841 return true;
8846 * Admin setting to show if a php extension is enabled or not.
8848 * @copyright 2013 Damyon Wiese
8849 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8851 class admin_setting_php_extension_enabled extends admin_setting {
8853 /** @var string The name of the extension to check for */
8854 private $extension;
8857 * Calls parent::__construct with specific arguments
8859 public function __construct($name, $visiblename, $description, $extension) {
8860 $this->extension = $extension;
8861 $this->nosave = true;
8862 parent::__construct($name, $visiblename, $description, '');
8866 * Always returns true, does nothing
8868 * @return true
8870 public function get_setting() {
8871 return true;
8875 * Always returns true, does nothing
8877 * @return true
8879 public function get_defaultsetting() {
8880 return true;
8884 * Always returns '', does not write anything
8886 * @return string Always returns ''
8888 public function write_setting($data) {
8889 // Do not write any setting.
8890 return '';
8894 * Outputs the html for this setting.
8895 * @return string Returns an XHTML string
8897 public function output_html($data, $query='') {
8898 global $OUTPUT;
8900 $o = '';
8901 if (!extension_loaded($this->extension)) {
8902 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8904 $o .= format_admin_setting($this, $this->visiblename, $warning);
8906 return $o;