MDL-49294 logging: Improve cleanup tests
[moodle.git] / lib / adminlib.php
blob532f64c397095c32c87bb5db34535ddfa4774aa3
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // delete all the logs
206 $DB->delete_records('log', array('module' => $pluginname));
208 // delete log_display information
209 $DB->delete_records('log_display', array('component' => $component));
211 // delete the module configuration records
212 unset_all_config_for_plugin($component);
213 if ($type === 'mod') {
214 unset_all_config_for_plugin($pluginname);
217 // delete message provider
218 message_provider_uninstall($component);
220 // delete the plugin tables
221 $xmldbfilepath = $plugindirectory . '/db/install.xml';
222 drop_plugin_tables($component, $xmldbfilepath, false);
223 if ($type === 'mod' or $type === 'block') {
224 // non-frankenstyle table prefixes
225 drop_plugin_tables($name, $xmldbfilepath, false);
228 // delete the capabilities that were defined by this module
229 capabilities_cleanup($component);
231 // remove event handlers and dequeue pending events
232 events_uninstall($component);
234 // Delete all remaining files in the filepool owned by the component.
235 $fs = get_file_storage();
236 $fs->delete_component_files($component);
238 // Finally purge all caches.
239 purge_all_caches();
241 // Invalidate the hash used for upgrade detections.
242 set_config('allversionshash', '');
244 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
248 * Returns the version of installed component
250 * @param string $component component name
251 * @param string $source either 'disk' or 'installed' - where to get the version information from
252 * @return string|bool version number or false if the component is not found
254 function get_component_version($component, $source='installed') {
255 global $CFG, $DB;
257 list($type, $name) = core_component::normalize_component($component);
259 // moodle core or a core subsystem
260 if ($type === 'core') {
261 if ($source === 'installed') {
262 if (empty($CFG->version)) {
263 return false;
264 } else {
265 return $CFG->version;
267 } else {
268 if (!is_readable($CFG->dirroot.'/version.php')) {
269 return false;
270 } else {
271 $version = null; //initialize variable for IDEs
272 include($CFG->dirroot.'/version.php');
273 return $version;
278 // activity module
279 if ($type === 'mod') {
280 if ($source === 'installed') {
281 if ($CFG->version < 2013092001.02) {
282 return $DB->get_field('modules', 'version', array('name'=>$name));
283 } else {
284 return get_config('mod_'.$name, 'version');
287 } else {
288 $mods = core_component::get_plugin_list('mod');
289 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
290 return false;
291 } else {
292 $plugin = new stdClass();
293 $plugin->version = null;
294 $module = $plugin;
295 include($mods[$name].'/version.php');
296 return $plugin->version;
301 // block
302 if ($type === 'block') {
303 if ($source === 'installed') {
304 if ($CFG->version < 2013092001.02) {
305 return $DB->get_field('block', 'version', array('name'=>$name));
306 } else {
307 return get_config('block_'.$name, 'version');
309 } else {
310 $blocks = core_component::get_plugin_list('block');
311 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
312 return false;
313 } else {
314 $plugin = new stdclass();
315 include($blocks[$name].'/version.php');
316 return $plugin->version;
321 // all other plugin types
322 if ($source === 'installed') {
323 return get_config($type.'_'.$name, 'version');
324 } else {
325 $plugins = core_component::get_plugin_list($type);
326 if (empty($plugins[$name])) {
327 return false;
328 } else {
329 $plugin = new stdclass();
330 include($plugins[$name].'/version.php');
331 return $plugin->version;
337 * Delete all plugin tables
339 * @param string $name Name of plugin, used as table prefix
340 * @param string $file Path to install.xml file
341 * @param bool $feedback defaults to true
342 * @return bool Always returns true
344 function drop_plugin_tables($name, $file, $feedback=true) {
345 global $CFG, $DB;
347 // first try normal delete
348 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
349 return true;
352 // then try to find all tables that start with name and are not in any xml file
353 $used_tables = get_used_table_names();
355 $tables = $DB->get_tables();
357 /// Iterate over, fixing id fields as necessary
358 foreach ($tables as $table) {
359 if (in_array($table, $used_tables)) {
360 continue;
363 if (strpos($table, $name) !== 0) {
364 continue;
367 // found orphan table --> delete it
368 if ($DB->get_manager()->table_exists($table)) {
369 $xmldb_table = new xmldb_table($table);
370 $DB->get_manager()->drop_table($xmldb_table);
374 return true;
378 * Returns names of all known tables == tables that moodle knows about.
380 * @return array Array of lowercase table names
382 function get_used_table_names() {
383 $table_names = array();
384 $dbdirs = get_db_directories();
386 foreach ($dbdirs as $dbdir) {
387 $file = $dbdir.'/install.xml';
389 $xmldb_file = new xmldb_file($file);
391 if (!$xmldb_file->fileExists()) {
392 continue;
395 $loaded = $xmldb_file->loadXMLStructure();
396 $structure = $xmldb_file->getStructure();
398 if ($loaded and $tables = $structure->getTables()) {
399 foreach($tables as $table) {
400 $table_names[] = strtolower($table->getName());
405 return $table_names;
409 * Returns list of all directories where we expect install.xml files
410 * @return array Array of paths
412 function get_db_directories() {
413 global $CFG;
415 $dbdirs = array();
417 /// First, the main one (lib/db)
418 $dbdirs[] = $CFG->libdir.'/db';
420 /// Then, all the ones defined by core_component::get_plugin_types()
421 $plugintypes = core_component::get_plugin_types();
422 foreach ($plugintypes as $plugintype => $pluginbasedir) {
423 if ($plugins = core_component::get_plugin_list($plugintype)) {
424 foreach ($plugins as $plugin => $plugindir) {
425 $dbdirs[] = $plugindir.'/db';
430 return $dbdirs;
434 * Try to obtain or release the cron lock.
435 * @param string $name name of lock
436 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
437 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
438 * @return bool true if lock obtained
440 function set_cron_lock($name, $until, $ignorecurrent=false) {
441 global $DB;
442 if (empty($name)) {
443 debugging("Tried to get a cron lock for a null fieldname");
444 return false;
447 // remove lock by force == remove from config table
448 if (is_null($until)) {
449 set_config($name, null);
450 return true;
453 if (!$ignorecurrent) {
454 // read value from db - other processes might have changed it
455 $value = $DB->get_field('config', 'value', array('name'=>$name));
457 if ($value and $value > time()) {
458 //lock active
459 return false;
463 set_config($name, $until);
464 return true;
468 * Test if and critical warnings are present
469 * @return bool
471 function admin_critical_warnings_present() {
472 global $SESSION;
474 if (!has_capability('moodle/site:config', context_system::instance())) {
475 return 0;
478 if (!isset($SESSION->admin_critical_warning)) {
479 $SESSION->admin_critical_warning = 0;
480 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
481 $SESSION->admin_critical_warning = 1;
485 return $SESSION->admin_critical_warning;
489 * Detects if float supports at least 10 decimal digits
491 * Detects if float supports at least 10 decimal digits
492 * and also if float-->string conversion works as expected.
494 * @return bool true if problem found
496 function is_float_problem() {
497 $num1 = 2009010200.01;
498 $num2 = 2009010200.02;
500 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
504 * Try to verify that dataroot is not accessible from web.
506 * Try to verify that dataroot is not accessible from web.
507 * It is not 100% correct but might help to reduce number of vulnerable sites.
508 * Protection from httpd.conf and .htaccess is not detected properly.
510 * @uses INSECURE_DATAROOT_WARNING
511 * @uses INSECURE_DATAROOT_ERROR
512 * @param bool $fetchtest try to test public access by fetching file, default false
513 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
515 function is_dataroot_insecure($fetchtest=false) {
516 global $CFG;
518 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
520 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
521 $rp = strrev(trim($rp, '/'));
522 $rp = explode('/', $rp);
523 foreach($rp as $r) {
524 if (strpos($siteroot, '/'.$r.'/') === 0) {
525 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
526 } else {
527 break; // probably alias root
531 $siteroot = strrev($siteroot);
532 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
534 if (strpos($dataroot, $siteroot) !== 0) {
535 return false;
538 if (!$fetchtest) {
539 return INSECURE_DATAROOT_WARNING;
542 // now try all methods to fetch a test file using http protocol
544 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
545 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
546 $httpdocroot = $matches[1];
547 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
548 make_upload_directory('diag');
549 $testfile = $CFG->dataroot.'/diag/public.txt';
550 if (!file_exists($testfile)) {
551 file_put_contents($testfile, 'test file, do not delete');
552 @chmod($testfile, $CFG->filepermissions);
554 $teststr = trim(file_get_contents($testfile));
555 if (empty($teststr)) {
556 // hmm, strange
557 return INSECURE_DATAROOT_WARNING;
560 $testurl = $datarooturl.'/diag/public.txt';
561 if (extension_loaded('curl') and
562 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
563 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
564 ($ch = @curl_init($testurl)) !== false) {
565 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
566 curl_setopt($ch, CURLOPT_HEADER, false);
567 $data = curl_exec($ch);
568 if (!curl_errno($ch)) {
569 $data = trim($data);
570 if ($data === $teststr) {
571 curl_close($ch);
572 return INSECURE_DATAROOT_ERROR;
575 curl_close($ch);
578 if ($data = @file_get_contents($testurl)) {
579 $data = trim($data);
580 if ($data === $teststr) {
581 return INSECURE_DATAROOT_ERROR;
585 preg_match('|https?://([^/]+)|i', $testurl, $matches);
586 $sitename = $matches[1];
587 $error = 0;
588 if ($fp = @fsockopen($sitename, 80, $error)) {
589 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
590 $localurl = $matches[1];
591 $out = "GET $localurl HTTP/1.1\r\n";
592 $out .= "Host: $sitename\r\n";
593 $out .= "Connection: Close\r\n\r\n";
594 fwrite($fp, $out);
595 $data = '';
596 $incoming = false;
597 while (!feof($fp)) {
598 if ($incoming) {
599 $data .= fgets($fp, 1024);
600 } else if (@fgets($fp, 1024) === "\r\n") {
601 $incoming = true;
604 fclose($fp);
605 $data = trim($data);
606 if ($data === $teststr) {
607 return INSECURE_DATAROOT_ERROR;
611 return INSECURE_DATAROOT_WARNING;
615 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
617 function enable_cli_maintenance_mode() {
618 global $CFG;
620 if (file_exists("$CFG->dataroot/climaintenance.html")) {
621 unlink("$CFG->dataroot/climaintenance.html");
624 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
625 $data = $CFG->maintenance_message;
626 $data = bootstrap_renderer::early_error_content($data, null, null, null);
627 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
629 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
630 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
632 } else {
633 $data = get_string('sitemaintenance', 'admin');
634 $data = bootstrap_renderer::early_error_content($data, null, null, null);
635 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
638 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
639 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
642 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
646 * Interface for anything appearing in the admin tree
648 * The interface that is implemented by anything that appears in the admin tree
649 * block. It forces inheriting classes to define a method for checking user permissions
650 * and methods for finding something in the admin tree.
652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
654 interface part_of_admin_tree {
657 * Finds a named part_of_admin_tree.
659 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
660 * and not parentable_part_of_admin_tree, then this function should only check if
661 * $this->name matches $name. If it does, it should return a reference to $this,
662 * otherwise, it should return a reference to NULL.
664 * If a class inherits parentable_part_of_admin_tree, this method should be called
665 * recursively on all child objects (assuming, of course, the parent object's name
666 * doesn't match the search criterion).
668 * @param string $name The internal name of the part_of_admin_tree we're searching for.
669 * @return mixed An object reference or a NULL reference.
671 public function locate($name);
674 * Removes named part_of_admin_tree.
676 * @param string $name The internal name of the part_of_admin_tree we want to remove.
677 * @return bool success.
679 public function prune($name);
682 * Search using query
683 * @param string $query
684 * @return mixed array-object structure of found settings and pages
686 public function search($query);
689 * Verifies current user's access to this part_of_admin_tree.
691 * Used to check if the current user has access to this part of the admin tree or
692 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
693 * then this method is usually just a call to has_capability() in the site context.
695 * If a class inherits parentable_part_of_admin_tree, this method should return the
696 * logical OR of the return of check_access() on all child objects.
698 * @return bool True if the user has access, false if she doesn't.
700 public function check_access();
703 * Mostly useful for removing of some parts of the tree in admin tree block.
705 * @return True is hidden from normal list view
707 public function is_hidden();
710 * Show we display Save button at the page bottom?
711 * @return bool
713 public function show_save();
718 * Interface implemented by any part_of_admin_tree that has children.
720 * The interface implemented by any part_of_admin_tree that can be a parent
721 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
722 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
723 * include an add method for adding other part_of_admin_tree objects as children.
725 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
727 interface parentable_part_of_admin_tree extends part_of_admin_tree {
730 * Adds a part_of_admin_tree object to the admin tree.
732 * Used to add a part_of_admin_tree object to this object or a child of this
733 * object. $something should only be added if $destinationname matches
734 * $this->name. If it doesn't, add should be called on child objects that are
735 * also parentable_part_of_admin_tree's.
737 * $something should be appended as the last child in the $destinationname. If the
738 * $beforesibling is specified, $something should be prepended to it. If the given
739 * sibling is not found, $something should be appended to the end of $destinationname
740 * and a developer debugging message should be displayed.
742 * @param string $destinationname The internal name of the new parent for $something.
743 * @param part_of_admin_tree $something The object to be added.
744 * @return bool True on success, false on failure.
746 public function add($destinationname, $something, $beforesibling = null);
752 * The object used to represent folders (a.k.a. categories) in the admin tree block.
754 * Each admin_category object contains a number of part_of_admin_tree objects.
756 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
758 class admin_category implements parentable_part_of_admin_tree {
760 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
761 protected $children;
762 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
763 public $name;
764 /** @var string The displayed name for this category. Usually obtained through get_string() */
765 public $visiblename;
766 /** @var bool Should this category be hidden in admin tree block? */
767 public $hidden;
768 /** @var mixed Either a string or an array or strings */
769 public $path;
770 /** @var mixed Either a string or an array or strings */
771 public $visiblepath;
773 /** @var array fast lookup category cache, all categories of one tree point to one cache */
774 protected $category_cache;
776 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
777 protected $sort = false;
778 /** @var bool If set to true children will be sorted in ascending order. */
779 protected $sortasc = true;
780 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
781 protected $sortsplit = true;
782 /** @var bool $sorted True if the children have been sorted and don't need resorting */
783 protected $sorted = false;
786 * Constructor for an empty admin category
788 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
789 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
790 * @param bool $hidden hide category in admin tree block, defaults to false
792 public function __construct($name, $visiblename, $hidden=false) {
793 $this->children = array();
794 $this->name = $name;
795 $this->visiblename = $visiblename;
796 $this->hidden = $hidden;
800 * Returns a reference to the part_of_admin_tree object with internal name $name.
802 * @param string $name The internal name of the object we want.
803 * @param bool $findpath initialize path and visiblepath arrays
804 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
805 * defaults to false
807 public function locate($name, $findpath=false) {
808 if (!isset($this->category_cache[$this->name])) {
809 // somebody much have purged the cache
810 $this->category_cache[$this->name] = $this;
813 if ($this->name == $name) {
814 if ($findpath) {
815 $this->visiblepath[] = $this->visiblename;
816 $this->path[] = $this->name;
818 return $this;
821 // quick category lookup
822 if (!$findpath and isset($this->category_cache[$name])) {
823 return $this->category_cache[$name];
826 $return = NULL;
827 foreach($this->children as $childid=>$unused) {
828 if ($return = $this->children[$childid]->locate($name, $findpath)) {
829 break;
833 if (!is_null($return) and $findpath) {
834 $return->visiblepath[] = $this->visiblename;
835 $return->path[] = $this->name;
838 return $return;
842 * Search using query
844 * @param string query
845 * @return mixed array-object structure of found settings and pages
847 public function search($query) {
848 $result = array();
849 foreach ($this->get_children() as $child) {
850 $subsearch = $child->search($query);
851 if (!is_array($subsearch)) {
852 debugging('Incorrect search result from '.$child->name);
853 continue;
855 $result = array_merge($result, $subsearch);
857 return $result;
861 * Removes part_of_admin_tree object with internal name $name.
863 * @param string $name The internal name of the object we want to remove.
864 * @return bool success
866 public function prune($name) {
868 if ($this->name == $name) {
869 return false; //can not remove itself
872 foreach($this->children as $precedence => $child) {
873 if ($child->name == $name) {
874 // clear cache and delete self
875 while($this->category_cache) {
876 // delete the cache, but keep the original array address
877 array_pop($this->category_cache);
879 unset($this->children[$precedence]);
880 return true;
881 } else if ($this->children[$precedence]->prune($name)) {
882 return true;
885 return false;
889 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
891 * By default the new part of the tree is appended as the last child of the parent. You
892 * can specify a sibling node that the new part should be prepended to. If the given
893 * sibling is not found, the part is appended to the end (as it would be by default) and
894 * a developer debugging message is displayed.
896 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
897 * @param string $destinationame The internal name of the immediate parent that we want for $something.
898 * @param mixed $something A part_of_admin_tree or setting instance to be added.
899 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
900 * @return bool True if successfully added, false if $something can not be added.
902 public function add($parentname, $something, $beforesibling = null) {
903 global $CFG;
905 $parent = $this->locate($parentname);
906 if (is_null($parent)) {
907 debugging('parent does not exist!');
908 return false;
911 if ($something instanceof part_of_admin_tree) {
912 if (!($parent instanceof parentable_part_of_admin_tree)) {
913 debugging('error - parts of tree can be inserted only into parentable parts');
914 return false;
916 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
917 // The name of the node is already used, simply warn the developer that this should not happen.
918 // It is intentional to check for the debug level before performing the check.
919 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
921 if (is_null($beforesibling)) {
922 // Append $something as the parent's last child.
923 $parent->children[] = $something;
924 } else {
925 if (!is_string($beforesibling) or trim($beforesibling) === '') {
926 throw new coding_exception('Unexpected value of the beforesibling parameter');
928 // Try to find the position of the sibling.
929 $siblingposition = null;
930 foreach ($parent->children as $childposition => $child) {
931 if ($child->name === $beforesibling) {
932 $siblingposition = $childposition;
933 break;
936 if (is_null($siblingposition)) {
937 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
938 $parent->children[] = $something;
939 } else {
940 $parent->children = array_merge(
941 array_slice($parent->children, 0, $siblingposition),
942 array($something),
943 array_slice($parent->children, $siblingposition)
947 if ($something instanceof admin_category) {
948 if (isset($this->category_cache[$something->name])) {
949 debugging('Duplicate admin category name: '.$something->name);
950 } else {
951 $this->category_cache[$something->name] = $something;
952 $something->category_cache =& $this->category_cache;
953 foreach ($something->children as $child) {
954 // just in case somebody already added subcategories
955 if ($child instanceof admin_category) {
956 if (isset($this->category_cache[$child->name])) {
957 debugging('Duplicate admin category name: '.$child->name);
958 } else {
959 $this->category_cache[$child->name] = $child;
960 $child->category_cache =& $this->category_cache;
966 return true;
968 } else {
969 debugging('error - can not add this element');
970 return false;
976 * Checks if the user has access to anything in this category.
978 * @return bool True if the user has access to at least one child in this category, false otherwise.
980 public function check_access() {
981 foreach ($this->children as $child) {
982 if ($child->check_access()) {
983 return true;
986 return false;
990 * Is this category hidden in admin tree block?
992 * @return bool True if hidden
994 public function is_hidden() {
995 return $this->hidden;
999 * Show we display Save button at the page bottom?
1000 * @return bool
1002 public function show_save() {
1003 foreach ($this->children as $child) {
1004 if ($child->show_save()) {
1005 return true;
1008 return false;
1012 * Sets sorting on this category.
1014 * Please note this function doesn't actually do the sorting.
1015 * It can be called anytime.
1016 * Sorting occurs when the user calls get_children.
1017 * Code using the children array directly won't see the sorted results.
1019 * @param bool $sort If set to true children will be sorted, if false they won't be.
1020 * @param bool $asc If true sorting will be ascending, otherwise descending.
1021 * @param bool $split If true we sort pages and sub categories separately.
1023 public function set_sorting($sort, $asc = true, $split = true) {
1024 $this->sort = (bool)$sort;
1025 $this->sortasc = (bool)$asc;
1026 $this->sortsplit = (bool)$split;
1030 * Returns the children associated with this category.
1032 * @return part_of_admin_tree[]
1034 public function get_children() {
1035 // If we should sort and it hasn't already been sorted.
1036 if ($this->sort && !$this->sorted) {
1037 if ($this->sortsplit) {
1038 $categories = array();
1039 $pages = array();
1040 foreach ($this->children as $child) {
1041 if ($child instanceof admin_category) {
1042 $categories[] = $child;
1043 } else {
1044 $pages[] = $child;
1047 core_collator::asort_objects_by_property($categories, 'visiblename');
1048 core_collator::asort_objects_by_property($pages, 'visiblename');
1049 if (!$this->sortasc) {
1050 $categories = array_reverse($categories);
1051 $pages = array_reverse($pages);
1053 $this->children = array_merge($pages, $categories);
1054 } else {
1055 core_collator::asort_objects_by_property($this->children, 'visiblename');
1056 if (!$this->sortasc) {
1057 $this->children = array_reverse($this->children);
1060 $this->sorted = true;
1062 return $this->children;
1066 * Magically gets a property from this object.
1068 * @param $property
1069 * @return part_of_admin_tree[]
1070 * @throws coding_exception
1072 public function __get($property) {
1073 if ($property === 'children') {
1074 return $this->get_children();
1076 throw new coding_exception('Invalid property requested.');
1080 * Magically sets a property against this object.
1082 * @param string $property
1083 * @param mixed $value
1084 * @throws coding_exception
1086 public function __set($property, $value) {
1087 if ($property === 'children') {
1088 $this->sorted = false;
1089 $this->children = $value;
1090 } else {
1091 throw new coding_exception('Invalid property requested.');
1096 * Checks if an inaccessible property is set.
1098 * @param string $property
1099 * @return bool
1100 * @throws coding_exception
1102 public function __isset($property) {
1103 if ($property === 'children') {
1104 return isset($this->children);
1106 throw new coding_exception('Invalid property requested.');
1112 * Root of admin settings tree, does not have any parent.
1114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1116 class admin_root extends admin_category {
1117 /** @var array List of errors */
1118 public $errors;
1119 /** @var string search query */
1120 public $search;
1121 /** @var bool full tree flag - true means all settings required, false only pages required */
1122 public $fulltree;
1123 /** @var bool flag indicating loaded tree */
1124 public $loaded;
1125 /** @var mixed site custom defaults overriding defaults in settings files*/
1126 public $custom_defaults;
1129 * @param bool $fulltree true means all settings required,
1130 * false only pages required
1132 public function __construct($fulltree) {
1133 global $CFG;
1135 parent::__construct('root', get_string('administration'), false);
1136 $this->errors = array();
1137 $this->search = '';
1138 $this->fulltree = $fulltree;
1139 $this->loaded = false;
1141 $this->category_cache = array();
1143 // load custom defaults if found
1144 $this->custom_defaults = null;
1145 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1146 if (is_readable($defaultsfile)) {
1147 $defaults = array();
1148 include($defaultsfile);
1149 if (is_array($defaults) and count($defaults)) {
1150 $this->custom_defaults = $defaults;
1156 * Empties children array, and sets loaded to false
1158 * @param bool $requirefulltree
1160 public function purge_children($requirefulltree) {
1161 $this->children = array();
1162 $this->fulltree = ($requirefulltree || $this->fulltree);
1163 $this->loaded = false;
1164 //break circular dependencies - this helps PHP 5.2
1165 while($this->category_cache) {
1166 array_pop($this->category_cache);
1168 $this->category_cache = array();
1174 * Links external PHP pages into the admin tree.
1176 * See detailed usage example at the top of this document (adminlib.php)
1178 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1180 class admin_externalpage implements part_of_admin_tree {
1182 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1183 public $name;
1185 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1186 public $visiblename;
1188 /** @var string The external URL that we should link to when someone requests this external page. */
1189 public $url;
1191 /** @var string The role capability/permission a user must have to access this external page. */
1192 public $req_capability;
1194 /** @var object The context in which capability/permission should be checked, default is site context. */
1195 public $context;
1197 /** @var bool hidden in admin tree block. */
1198 public $hidden;
1200 /** @var mixed either string or array of string */
1201 public $path;
1203 /** @var array list of visible names of page parents */
1204 public $visiblepath;
1207 * Constructor for adding an external page into the admin tree.
1209 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1210 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1211 * @param string $url The external URL that we should link to when someone requests this external page.
1212 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1213 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1214 * @param stdClass $context The context the page relates to. Not sure what happens
1215 * if you specify something other than system or front page. Defaults to system.
1217 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1218 $this->name = $name;
1219 $this->visiblename = $visiblename;
1220 $this->url = $url;
1221 if (is_array($req_capability)) {
1222 $this->req_capability = $req_capability;
1223 } else {
1224 $this->req_capability = array($req_capability);
1226 $this->hidden = $hidden;
1227 $this->context = $context;
1231 * Returns a reference to the part_of_admin_tree object with internal name $name.
1233 * @param string $name The internal name of the object we want.
1234 * @param bool $findpath defaults to false
1235 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1237 public function locate($name, $findpath=false) {
1238 if ($this->name == $name) {
1239 if ($findpath) {
1240 $this->visiblepath = array($this->visiblename);
1241 $this->path = array($this->name);
1243 return $this;
1244 } else {
1245 $return = NULL;
1246 return $return;
1251 * This function always returns false, required function by interface
1253 * @param string $name
1254 * @return false
1256 public function prune($name) {
1257 return false;
1261 * Search using query
1263 * @param string $query
1264 * @return mixed array-object structure of found settings and pages
1266 public function search($query) {
1267 $found = false;
1268 if (strpos(strtolower($this->name), $query) !== false) {
1269 $found = true;
1270 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1271 $found = true;
1273 if ($found) {
1274 $result = new stdClass();
1275 $result->page = $this;
1276 $result->settings = array();
1277 return array($this->name => $result);
1278 } else {
1279 return array();
1284 * Determines if the current user has access to this external page based on $this->req_capability.
1286 * @return bool True if user has access, false otherwise.
1288 public function check_access() {
1289 global $CFG;
1290 $context = empty($this->context) ? context_system::instance() : $this->context;
1291 foreach($this->req_capability as $cap) {
1292 if (has_capability($cap, $context)) {
1293 return true;
1296 return false;
1300 * Is this external page hidden in admin tree block?
1302 * @return bool True if hidden
1304 public function is_hidden() {
1305 return $this->hidden;
1309 * Show we display Save button at the page bottom?
1310 * @return bool
1312 public function show_save() {
1313 return false;
1319 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1323 class admin_settingpage implements part_of_admin_tree {
1325 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1326 public $name;
1328 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1329 public $visiblename;
1331 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1332 public $settings;
1334 /** @var string The role capability/permission a user must have to access this external page. */
1335 public $req_capability;
1337 /** @var object The context in which capability/permission should be checked, default is site context. */
1338 public $context;
1340 /** @var bool hidden in admin tree block. */
1341 public $hidden;
1343 /** @var mixed string of paths or array of strings of paths */
1344 public $path;
1346 /** @var array list of visible names of page parents */
1347 public $visiblepath;
1350 * see admin_settingpage for details of this function
1352 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1353 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1354 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1355 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1356 * @param stdClass $context The context the page relates to. Not sure what happens
1357 * if you specify something other than system or front page. Defaults to system.
1359 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1360 $this->settings = new stdClass();
1361 $this->name = $name;
1362 $this->visiblename = $visiblename;
1363 if (is_array($req_capability)) {
1364 $this->req_capability = $req_capability;
1365 } else {
1366 $this->req_capability = array($req_capability);
1368 $this->hidden = $hidden;
1369 $this->context = $context;
1373 * see admin_category
1375 * @param string $name
1376 * @param bool $findpath
1377 * @return mixed Object (this) if name == this->name, else returns null
1379 public function locate($name, $findpath=false) {
1380 if ($this->name == $name) {
1381 if ($findpath) {
1382 $this->visiblepath = array($this->visiblename);
1383 $this->path = array($this->name);
1385 return $this;
1386 } else {
1387 $return = NULL;
1388 return $return;
1393 * Search string in settings page.
1395 * @param string $query
1396 * @return array
1398 public function search($query) {
1399 $found = array();
1401 foreach ($this->settings as $setting) {
1402 if ($setting->is_related($query)) {
1403 $found[] = $setting;
1407 if ($found) {
1408 $result = new stdClass();
1409 $result->page = $this;
1410 $result->settings = $found;
1411 return array($this->name => $result);
1414 $found = false;
1415 if (strpos(strtolower($this->name), $query) !== false) {
1416 $found = true;
1417 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1418 $found = true;
1420 if ($found) {
1421 $result = new stdClass();
1422 $result->page = $this;
1423 $result->settings = array();
1424 return array($this->name => $result);
1425 } else {
1426 return array();
1431 * This function always returns false, required by interface
1433 * @param string $name
1434 * @return bool Always false
1436 public function prune($name) {
1437 return false;
1441 * adds an admin_setting to this admin_settingpage
1443 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1444 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1446 * @param object $setting is the admin_setting object you want to add
1447 * @return bool true if successful, false if not
1449 public function add($setting) {
1450 if (!($setting instanceof admin_setting)) {
1451 debugging('error - not a setting instance');
1452 return false;
1455 $this->settings->{$setting->name} = $setting;
1456 return true;
1460 * see admin_externalpage
1462 * @return bool Returns true for yes false for no
1464 public function check_access() {
1465 global $CFG;
1466 $context = empty($this->context) ? context_system::instance() : $this->context;
1467 foreach($this->req_capability as $cap) {
1468 if (has_capability($cap, $context)) {
1469 return true;
1472 return false;
1476 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1477 * @return string Returns an XHTML string
1479 public function output_html() {
1480 $adminroot = admin_get_root();
1481 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1482 foreach($this->settings as $setting) {
1483 $fullname = $setting->get_full_name();
1484 if (array_key_exists($fullname, $adminroot->errors)) {
1485 $data = $adminroot->errors[$fullname]->data;
1486 } else {
1487 $data = $setting->get_setting();
1488 // do not use defaults if settings not available - upgrade settings handles the defaults!
1490 $return .= $setting->output_html($data);
1492 $return .= '</fieldset>';
1493 return $return;
1497 * Is this settings page hidden in admin tree block?
1499 * @return bool True if hidden
1501 public function is_hidden() {
1502 return $this->hidden;
1506 * Show we display Save button at the page bottom?
1507 * @return bool
1509 public function show_save() {
1510 foreach($this->settings as $setting) {
1511 if (empty($setting->nosave)) {
1512 return true;
1515 return false;
1521 * Admin settings class. Only exists on setting pages.
1522 * Read & write happens at this level; no authentication.
1524 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1526 abstract class admin_setting {
1527 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1528 public $name;
1529 /** @var string localised name */
1530 public $visiblename;
1531 /** @var string localised long description in Markdown format */
1532 public $description;
1533 /** @var mixed Can be string or array of string */
1534 public $defaultsetting;
1535 /** @var string */
1536 public $updatedcallback;
1537 /** @var mixed can be String or Null. Null means main config table */
1538 public $plugin; // null means main config table
1539 /** @var bool true indicates this setting does not actually save anything, just information */
1540 public $nosave = false;
1541 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1542 public $affectsmodinfo = false;
1543 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1544 private $flags = array();
1547 * Constructor
1548 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1549 * or 'myplugin/mysetting' for ones in config_plugins.
1550 * @param string $visiblename localised name
1551 * @param string $description localised long description
1552 * @param mixed $defaultsetting string or array depending on implementation
1554 public function __construct($name, $visiblename, $description, $defaultsetting) {
1555 $this->parse_setting_name($name);
1556 $this->visiblename = $visiblename;
1557 $this->description = $description;
1558 $this->defaultsetting = $defaultsetting;
1562 * Generic function to add a flag to this admin setting.
1564 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1565 * @param bool $default - The default for the flag
1566 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1567 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1569 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1570 if (empty($this->flags[$shortname])) {
1571 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1572 } else {
1573 $this->flags[$shortname]->set_options($enabled, $default);
1578 * Set the enabled options flag on this admin setting.
1580 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1581 * @param bool $default - The default for the flag
1583 public function set_enabled_flag_options($enabled, $default) {
1584 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1588 * Set the advanced options flag on this admin setting.
1590 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1591 * @param bool $default - The default for the flag
1593 public function set_advanced_flag_options($enabled, $default) {
1594 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1599 * Set the locked options flag on this admin setting.
1601 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1602 * @param bool $default - The default for the flag
1604 public function set_locked_flag_options($enabled, $default) {
1605 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1609 * Get the currently saved value for a setting flag
1611 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1612 * @return bool
1614 public function get_setting_flag_value(admin_setting_flag $flag) {
1615 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1616 if (!isset($value)) {
1617 $value = $flag->get_default();
1620 return !empty($value);
1624 * Get the list of defaults for the flags on this setting.
1626 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1628 public function get_setting_flag_defaults(& $defaults) {
1629 foreach ($this->flags as $flag) {
1630 if ($flag->is_enabled() && $flag->get_default()) {
1631 $defaults[] = $flag->get_displayname();
1637 * Output the input fields for the advanced and locked flags on this setting.
1639 * @param bool $adv - The current value of the advanced flag.
1640 * @param bool $locked - The current value of the locked flag.
1641 * @return string $output - The html for the flags.
1643 public function output_setting_flags() {
1644 $output = '';
1646 foreach ($this->flags as $flag) {
1647 if ($flag->is_enabled()) {
1648 $output .= $flag->output_setting_flag($this);
1652 if (!empty($output)) {
1653 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1655 return $output;
1659 * Write the values of the flags for this admin setting.
1661 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1662 * @return bool - true if successful.
1664 public function write_setting_flags($data) {
1665 $result = true;
1666 foreach ($this->flags as $flag) {
1667 $result = $result && $flag->write_setting_flag($this, $data);
1669 return $result;
1673 * Set up $this->name and potentially $this->plugin
1675 * Set up $this->name and possibly $this->plugin based on whether $name looks
1676 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1677 * on the names, that is, output a developer debug warning if the name
1678 * contains anything other than [a-zA-Z0-9_]+.
1680 * @param string $name the setting name passed in to the constructor.
1682 private function parse_setting_name($name) {
1683 $bits = explode('/', $name);
1684 if (count($bits) > 2) {
1685 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1687 $this->name = array_pop($bits);
1688 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1689 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1691 if (!empty($bits)) {
1692 $this->plugin = array_pop($bits);
1693 if ($this->plugin === 'moodle') {
1694 $this->plugin = null;
1695 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1702 * Returns the fullname prefixed by the plugin
1703 * @return string
1705 public function get_full_name() {
1706 return 's_'.$this->plugin.'_'.$this->name;
1710 * Returns the ID string based on plugin and name
1711 * @return string
1713 public function get_id() {
1714 return 'id_s_'.$this->plugin.'_'.$this->name;
1718 * @param bool $affectsmodinfo If true, changes to this setting will
1719 * cause the course cache to be rebuilt
1721 public function set_affects_modinfo($affectsmodinfo) {
1722 $this->affectsmodinfo = $affectsmodinfo;
1726 * Returns the config if possible
1728 * @return mixed returns config if successful else null
1730 public function config_read($name) {
1731 global $CFG;
1732 if (!empty($this->plugin)) {
1733 $value = get_config($this->plugin, $name);
1734 return $value === false ? NULL : $value;
1736 } else {
1737 if (isset($CFG->$name)) {
1738 return $CFG->$name;
1739 } else {
1740 return NULL;
1746 * Used to set a config pair and log change
1748 * @param string $name
1749 * @param mixed $value Gets converted to string if not null
1750 * @return bool Write setting to config table
1752 public function config_write($name, $value) {
1753 global $DB, $USER, $CFG;
1755 if ($this->nosave) {
1756 return true;
1759 // make sure it is a real change
1760 $oldvalue = get_config($this->plugin, $name);
1761 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1762 $value = is_null($value) ? null : (string)$value;
1764 if ($oldvalue === $value) {
1765 return true;
1768 // store change
1769 set_config($name, $value, $this->plugin);
1771 // Some admin settings affect course modinfo
1772 if ($this->affectsmodinfo) {
1773 // Clear course cache for all courses
1774 rebuild_course_cache(0, true);
1777 $this->add_to_config_log($name, $oldvalue, $value);
1779 return true; // BC only
1783 * Log config changes if necessary.
1784 * @param string $name
1785 * @param string $oldvalue
1786 * @param string $value
1788 protected function add_to_config_log($name, $oldvalue, $value) {
1789 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1793 * Returns current value of this setting
1794 * @return mixed array or string depending on instance, NULL means not set yet
1796 public abstract function get_setting();
1799 * Returns default setting if exists
1800 * @return mixed array or string depending on instance; NULL means no default, user must supply
1802 public function get_defaultsetting() {
1803 $adminroot = admin_get_root(false, false);
1804 if (!empty($adminroot->custom_defaults)) {
1805 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1806 if (isset($adminroot->custom_defaults[$plugin])) {
1807 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1808 return $adminroot->custom_defaults[$plugin][$this->name];
1812 return $this->defaultsetting;
1816 * Store new setting
1818 * @param mixed $data string or array, must not be NULL
1819 * @return string empty string if ok, string error message otherwise
1821 public abstract function write_setting($data);
1824 * Return part of form with setting
1825 * This function should always be overwritten
1827 * @param mixed $data array or string depending on setting
1828 * @param string $query
1829 * @return string
1831 public function output_html($data, $query='') {
1832 // should be overridden
1833 return;
1837 * Function called if setting updated - cleanup, cache reset, etc.
1838 * @param string $functionname Sets the function name
1839 * @return void
1841 public function set_updatedcallback($functionname) {
1842 $this->updatedcallback = $functionname;
1846 * Execute postupdatecallback if necessary.
1847 * @param mixed $original original value before write_setting()
1848 * @return bool true if changed, false if not.
1850 public function post_write_settings($original) {
1851 // Comparison must work for arrays too.
1852 if (serialize($original) === serialize($this->get_setting())) {
1853 return false;
1856 $callbackfunction = $this->updatedcallback;
1857 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1858 $callbackfunction($this->get_full_name());
1860 return true;
1864 * Is setting related to query text - used when searching
1865 * @param string $query
1866 * @return bool
1868 public function is_related($query) {
1869 if (strpos(strtolower($this->name), $query) !== false) {
1870 return true;
1872 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1873 return true;
1875 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1876 return true;
1878 $current = $this->get_setting();
1879 if (!is_null($current)) {
1880 if (is_string($current)) {
1881 if (strpos(core_text::strtolower($current), $query) !== false) {
1882 return true;
1886 $default = $this->get_defaultsetting();
1887 if (!is_null($default)) {
1888 if (is_string($default)) {
1889 if (strpos(core_text::strtolower($default), $query) !== false) {
1890 return true;
1894 return false;
1899 * An additional option that can be applied to an admin setting.
1900 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1904 class admin_setting_flag {
1905 /** @var bool Flag to indicate if this option can be toggled for this setting */
1906 private $enabled = false;
1907 /** @var bool Flag to indicate if this option defaults to true or false */
1908 private $default = false;
1909 /** @var string Short string used to create setting name - e.g. 'adv' */
1910 private $shortname = '';
1911 /** @var string String used as the label for this flag */
1912 private $displayname = '';
1913 /** @const Checkbox for this flag is displayed in admin page */
1914 const ENABLED = true;
1915 /** @const Checkbox for this flag is not displayed in admin page */
1916 const DISABLED = false;
1919 * Constructor
1921 * @param bool $enabled Can this option can be toggled.
1922 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1923 * @param bool $default The default checked state for this setting option.
1924 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1925 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1927 public function __construct($enabled, $default, $shortname, $displayname) {
1928 $this->shortname = $shortname;
1929 $this->displayname = $displayname;
1930 $this->set_options($enabled, $default);
1934 * Update the values of this setting options class
1936 * @param bool $enabled Can this option can be toggled.
1937 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1938 * @param bool $default The default checked state for this setting option.
1940 public function set_options($enabled, $default) {
1941 $this->enabled = $enabled;
1942 $this->default = $default;
1946 * Should this option appear in the interface and be toggleable?
1948 * @return bool Is it enabled?
1950 public function is_enabled() {
1951 return $this->enabled;
1955 * Should this option be checked by default?
1957 * @return bool Is it on by default?
1959 public function get_default() {
1960 return $this->default;
1964 * Return the short name for this flag. e.g. 'adv' or 'locked'
1966 * @return string
1968 public function get_shortname() {
1969 return $this->shortname;
1973 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1975 * @return string
1977 public function get_displayname() {
1978 return $this->displayname;
1982 * Save the submitted data for this flag - or set it to the default if $data is null.
1984 * @param admin_setting $setting - The admin setting for this flag
1985 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1986 * @return bool
1988 public function write_setting_flag(admin_setting $setting, $data) {
1989 $result = true;
1990 if ($this->is_enabled()) {
1991 if (!isset($data)) {
1992 $value = $this->get_default();
1993 } else {
1994 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
1996 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
1999 return $result;
2004 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2006 * @param admin_setting $setting - The admin setting for this flag
2007 * @return string - The html for the checkbox.
2009 public function output_setting_flag(admin_setting $setting) {
2010 $value = $setting->get_setting_flag_value($this);
2011 $output = ' <input type="checkbox" class="form-checkbox" ' .
2012 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2013 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2014 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2015 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2016 $this->get_displayname() .
2017 ' </label> ';
2018 return $output;
2024 * No setting - just heading and text.
2026 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2028 class admin_setting_heading extends admin_setting {
2031 * not a setting, just text
2032 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2033 * @param string $heading heading
2034 * @param string $information text in box
2036 public function __construct($name, $heading, $information) {
2037 $this->nosave = true;
2038 parent::__construct($name, $heading, $information, '');
2042 * Always returns true
2043 * @return bool Always returns true
2045 public function get_setting() {
2046 return true;
2050 * Always returns true
2051 * @return bool Always returns true
2053 public function get_defaultsetting() {
2054 return true;
2058 * Never write settings
2059 * @return string Always returns an empty string
2061 public function write_setting($data) {
2062 // do not write any setting
2063 return '';
2067 * Returns an HTML string
2068 * @return string Returns an HTML string
2070 public function output_html($data, $query='') {
2071 global $OUTPUT;
2072 $return = '';
2073 if ($this->visiblename != '') {
2074 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2076 if ($this->description != '') {
2077 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2079 return $return;
2085 * The most flexibly setting, user is typing text
2087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2089 class admin_setting_configtext extends admin_setting {
2091 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2092 public $paramtype;
2093 /** @var int default field size */
2094 public $size;
2097 * Config text constructor
2099 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2100 * @param string $visiblename localised
2101 * @param string $description long localised info
2102 * @param string $defaultsetting
2103 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2104 * @param int $size default field size
2106 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2107 $this->paramtype = $paramtype;
2108 if (!is_null($size)) {
2109 $this->size = $size;
2110 } else {
2111 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2113 parent::__construct($name, $visiblename, $description, $defaultsetting);
2117 * Return the setting
2119 * @return mixed returns config if successful else null
2121 public function get_setting() {
2122 return $this->config_read($this->name);
2125 public function write_setting($data) {
2126 if ($this->paramtype === PARAM_INT and $data === '') {
2127 // do not complain if '' used instead of 0
2128 $data = 0;
2130 // $data is a string
2131 $validated = $this->validate($data);
2132 if ($validated !== true) {
2133 return $validated;
2135 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2139 * Validate data before storage
2140 * @param string data
2141 * @return mixed true if ok string if error found
2143 public function validate($data) {
2144 // allow paramtype to be a custom regex if it is the form of /pattern/
2145 if (preg_match('#^/.*/$#', $this->paramtype)) {
2146 if (preg_match($this->paramtype, $data)) {
2147 return true;
2148 } else {
2149 return get_string('validateerror', 'admin');
2152 } else if ($this->paramtype === PARAM_RAW) {
2153 return true;
2155 } else {
2156 $cleaned = clean_param($data, $this->paramtype);
2157 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2158 return true;
2159 } else {
2160 return get_string('validateerror', 'admin');
2166 * Return an XHTML string for the setting
2167 * @return string Returns an XHTML string
2169 public function output_html($data, $query='') {
2170 $default = $this->get_defaultsetting();
2172 return format_admin_setting($this, $this->visiblename,
2173 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2174 $this->description, true, '', $default, $query);
2180 * General text area without html editor.
2182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2184 class admin_setting_configtextarea extends admin_setting_configtext {
2185 private $rows;
2186 private $cols;
2189 * @param string $name
2190 * @param string $visiblename
2191 * @param string $description
2192 * @param mixed $defaultsetting string or array
2193 * @param mixed $paramtype
2194 * @param string $cols The number of columns to make the editor
2195 * @param string $rows The number of rows to make the editor
2197 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2198 $this->rows = $rows;
2199 $this->cols = $cols;
2200 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2204 * Returns an XHTML string for the editor
2206 * @param string $data
2207 * @param string $query
2208 * @return string XHTML string for the editor
2210 public function output_html($data, $query='') {
2211 $default = $this->get_defaultsetting();
2213 $defaultinfo = $default;
2214 if (!is_null($default) and $default !== '') {
2215 $defaultinfo = "\n".$default;
2218 return format_admin_setting($this, $this->visiblename,
2219 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2220 $this->description, true, '', $defaultinfo, $query);
2226 * General text area with html editor.
2228 class admin_setting_confightmleditor extends admin_setting_configtext {
2229 private $rows;
2230 private $cols;
2233 * @param string $name
2234 * @param string $visiblename
2235 * @param string $description
2236 * @param mixed $defaultsetting string or array
2237 * @param mixed $paramtype
2239 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2240 $this->rows = $rows;
2241 $this->cols = $cols;
2242 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2243 editors_head_setup();
2247 * Returns an XHTML string for the editor
2249 * @param string $data
2250 * @param string $query
2251 * @return string XHTML string for the editor
2253 public function output_html($data, $query='') {
2254 $default = $this->get_defaultsetting();
2256 $defaultinfo = $default;
2257 if (!is_null($default) and $default !== '') {
2258 $defaultinfo = "\n".$default;
2261 $editor = editors_get_preferred_editor(FORMAT_HTML);
2262 $editor->use_editor($this->get_id(), array('noclean'=>true));
2264 return format_admin_setting($this, $this->visiblename,
2265 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2266 $this->description, true, '', $defaultinfo, $query);
2272 * Password field, allows unmasking of password
2274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2276 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2278 * Constructor
2279 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2280 * @param string $visiblename localised
2281 * @param string $description long localised info
2282 * @param string $defaultsetting default password
2284 public function __construct($name, $visiblename, $description, $defaultsetting) {
2285 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2289 * Log config changes if necessary.
2290 * @param string $name
2291 * @param string $oldvalue
2292 * @param string $value
2294 protected function add_to_config_log($name, $oldvalue, $value) {
2295 if ($value !== '') {
2296 $value = '********';
2298 if ($oldvalue !== '' and $oldvalue !== null) {
2299 $oldvalue = '********';
2301 parent::add_to_config_log($name, $oldvalue, $value);
2305 * Returns XHTML for the field
2306 * Writes Javascript into the HTML below right before the last div
2308 * @todo Make javascript available through newer methods if possible
2309 * @param string $data Value for the field
2310 * @param string $query Passed as final argument for format_admin_setting
2311 * @return string XHTML field
2313 public function output_html($data, $query='') {
2314 $id = $this->get_id();
2315 $unmask = get_string('unmaskpassword', 'form');
2316 $unmaskjs = '<script type="text/javascript">
2317 //<![CDATA[
2318 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2320 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2322 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2324 var unmaskchb = document.createElement("input");
2325 unmaskchb.setAttribute("type", "checkbox");
2326 unmaskchb.setAttribute("id", "'.$id.'unmask");
2327 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2328 unmaskdiv.appendChild(unmaskchb);
2330 var unmasklbl = document.createElement("label");
2331 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2332 if (is_ie) {
2333 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2334 } else {
2335 unmasklbl.setAttribute("for", "'.$id.'unmask");
2337 unmaskdiv.appendChild(unmasklbl);
2339 if (is_ie) {
2340 // ugly hack to work around the famous onchange IE bug
2341 unmaskchb.onclick = function() {this.blur();};
2342 unmaskdiv.onclick = function() {this.blur();};
2344 //]]>
2345 </script>';
2346 return format_admin_setting($this, $this->visiblename,
2347 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
2348 $this->description, true, '', NULL, $query);
2353 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2354 * Note: Only advanced makes sense right now - locked does not.
2356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2358 class admin_setting_configempty extends admin_setting_configtext {
2361 * @param string $name
2362 * @param string $visiblename
2363 * @param string $description
2365 public function __construct($name, $visiblename, $description) {
2366 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2370 * Returns an XHTML string for the hidden field
2372 * @param string $data
2373 * @param string $query
2374 * @return string XHTML string for the editor
2376 public function output_html($data, $query='') {
2377 return format_admin_setting($this,
2378 $this->visiblename,
2379 '<div class="form-empty" >' .
2380 '<input type="hidden"' .
2381 ' id="'. $this->get_id() .'"' .
2382 ' name="'. $this->get_full_name() .'"' .
2383 ' value=""/></div>',
2384 $this->description,
2385 true,
2387 get_string('none'),
2388 $query);
2394 * Path to directory
2396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2398 class admin_setting_configfile extends admin_setting_configtext {
2400 * Constructor
2401 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2402 * @param string $visiblename localised
2403 * @param string $description long localised info
2404 * @param string $defaultdirectory default directory location
2406 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2407 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2411 * Returns XHTML for the field
2413 * Returns XHTML for the field and also checks whether the file
2414 * specified in $data exists using file_exists()
2416 * @param string $data File name and path to use in value attr
2417 * @param string $query
2418 * @return string XHTML field
2420 public function output_html($data, $query='') {
2421 global $CFG;
2422 $default = $this->get_defaultsetting();
2424 if ($data) {
2425 if (file_exists($data)) {
2426 $executable = '<span class="pathok">&#x2714;</span>';
2427 } else {
2428 $executable = '<span class="patherror">&#x2718;</span>';
2430 } else {
2431 $executable = '';
2433 $readonly = '';
2434 if (!empty($CFG->preventexecpath)) {
2435 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2436 $readonly = 'readonly="readonly"';
2439 return format_admin_setting($this, $this->visiblename,
2440 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2441 $this->description, true, '', $default, $query);
2445 * Checks if execpatch has been disabled in config.php
2447 public function write_setting($data) {
2448 global $CFG;
2449 if (!empty($CFG->preventexecpath)) {
2450 if ($this->get_setting() === null) {
2451 // Use default during installation.
2452 $data = $this->get_defaultsetting();
2453 if ($data === null) {
2454 $data = '';
2456 } else {
2457 return '';
2460 return parent::write_setting($data);
2466 * Path to executable file
2468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2470 class admin_setting_configexecutable extends admin_setting_configfile {
2473 * Returns an XHTML field
2475 * @param string $data This is the value for the field
2476 * @param string $query
2477 * @return string XHTML field
2479 public function output_html($data, $query='') {
2480 global $CFG;
2481 $default = $this->get_defaultsetting();
2483 if ($data) {
2484 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2485 $executable = '<span class="pathok">&#x2714;</span>';
2486 } else {
2487 $executable = '<span class="patherror">&#x2718;</span>';
2489 } else {
2490 $executable = '';
2492 $readonly = '';
2493 if (!empty($CFG->preventexecpath)) {
2494 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2495 $readonly = 'readonly="readonly"';
2498 return format_admin_setting($this, $this->visiblename,
2499 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2500 $this->description, true, '', $default, $query);
2506 * Path to directory
2508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2510 class admin_setting_configdirectory extends admin_setting_configfile {
2513 * Returns an XHTML field
2515 * @param string $data This is the value for the field
2516 * @param string $query
2517 * @return string XHTML
2519 public function output_html($data, $query='') {
2520 global $CFG;
2521 $default = $this->get_defaultsetting();
2523 if ($data) {
2524 if (file_exists($data) and is_dir($data)) {
2525 $executable = '<span class="pathok">&#x2714;</span>';
2526 } else {
2527 $executable = '<span class="patherror">&#x2718;</span>';
2529 } else {
2530 $executable = '';
2532 $readonly = '';
2533 if (!empty($CFG->preventexecpath)) {
2534 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2535 $readonly = 'readonly="readonly"';
2538 return format_admin_setting($this, $this->visiblename,
2539 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2540 $this->description, true, '', $default, $query);
2546 * Checkbox
2548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2550 class admin_setting_configcheckbox extends admin_setting {
2551 /** @var string Value used when checked */
2552 public $yes;
2553 /** @var string Value used when not checked */
2554 public $no;
2557 * Constructor
2558 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2559 * @param string $visiblename localised
2560 * @param string $description long localised info
2561 * @param string $defaultsetting
2562 * @param string $yes value used when checked
2563 * @param string $no value used when not checked
2565 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2566 parent::__construct($name, $visiblename, $description, $defaultsetting);
2567 $this->yes = (string)$yes;
2568 $this->no = (string)$no;
2572 * Retrieves the current setting using the objects name
2574 * @return string
2576 public function get_setting() {
2577 return $this->config_read($this->name);
2581 * Sets the value for the setting
2583 * Sets the value for the setting to either the yes or no values
2584 * of the object by comparing $data to yes
2586 * @param mixed $data Gets converted to str for comparison against yes value
2587 * @return string empty string or error
2589 public function write_setting($data) {
2590 if ((string)$data === $this->yes) { // convert to strings before comparison
2591 $data = $this->yes;
2592 } else {
2593 $data = $this->no;
2595 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2599 * Returns an XHTML checkbox field
2601 * @param string $data If $data matches yes then checkbox is checked
2602 * @param string $query
2603 * @return string XHTML field
2605 public function output_html($data, $query='') {
2606 $default = $this->get_defaultsetting();
2608 if (!is_null($default)) {
2609 if ((string)$default === $this->yes) {
2610 $defaultinfo = get_string('checkboxyes', 'admin');
2611 } else {
2612 $defaultinfo = get_string('checkboxno', 'admin');
2614 } else {
2615 $defaultinfo = NULL;
2618 if ((string)$data === $this->yes) { // convert to strings before comparison
2619 $checked = 'checked="checked"';
2620 } else {
2621 $checked = '';
2624 return format_admin_setting($this, $this->visiblename,
2625 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2626 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2627 $this->description, true, '', $defaultinfo, $query);
2633 * Multiple checkboxes, each represents different value, stored in csv format
2635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2637 class admin_setting_configmulticheckbox extends admin_setting {
2638 /** @var array Array of choices value=>label */
2639 public $choices;
2642 * Constructor: uses parent::__construct
2644 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2645 * @param string $visiblename localised
2646 * @param string $description long localised info
2647 * @param array $defaultsetting array of selected
2648 * @param array $choices array of $value=>$label for each checkbox
2650 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2651 $this->choices = $choices;
2652 parent::__construct($name, $visiblename, $description, $defaultsetting);
2656 * This public function may be used in ancestors for lazy loading of choices
2658 * @todo Check if this function is still required content commented out only returns true
2659 * @return bool true if loaded, false if error
2661 public function load_choices() {
2663 if (is_array($this->choices)) {
2664 return true;
2666 .... load choices here
2668 return true;
2672 * Is setting related to query text - used when searching
2674 * @param string $query
2675 * @return bool true on related, false on not or failure
2677 public function is_related($query) {
2678 if (!$this->load_choices() or empty($this->choices)) {
2679 return false;
2681 if (parent::is_related($query)) {
2682 return true;
2685 foreach ($this->choices as $desc) {
2686 if (strpos(core_text::strtolower($desc), $query) !== false) {
2687 return true;
2690 return false;
2694 * Returns the current setting if it is set
2696 * @return mixed null if null, else an array
2698 public function get_setting() {
2699 $result = $this->config_read($this->name);
2701 if (is_null($result)) {
2702 return NULL;
2704 if ($result === '') {
2705 return array();
2707 $enabled = explode(',', $result);
2708 $setting = array();
2709 foreach ($enabled as $option) {
2710 $setting[$option] = 1;
2712 return $setting;
2716 * Saves the setting(s) provided in $data
2718 * @param array $data An array of data, if not array returns empty str
2719 * @return mixed empty string on useless data or bool true=success, false=failed
2721 public function write_setting($data) {
2722 if (!is_array($data)) {
2723 return ''; // ignore it
2725 if (!$this->load_choices() or empty($this->choices)) {
2726 return '';
2728 unset($data['xxxxx']);
2729 $result = array();
2730 foreach ($data as $key => $value) {
2731 if ($value and array_key_exists($key, $this->choices)) {
2732 $result[] = $key;
2735 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2739 * Returns XHTML field(s) as required by choices
2741 * Relies on data being an array should data ever be another valid vartype with
2742 * acceptable value this may cause a warning/error
2743 * if (!is_array($data)) would fix the problem
2745 * @todo Add vartype handling to ensure $data is an array
2747 * @param array $data An array of checked values
2748 * @param string $query
2749 * @return string XHTML field
2751 public function output_html($data, $query='') {
2752 if (!$this->load_choices() or empty($this->choices)) {
2753 return '';
2755 $default = $this->get_defaultsetting();
2756 if (is_null($default)) {
2757 $default = array();
2759 if (is_null($data)) {
2760 $data = array();
2762 $options = array();
2763 $defaults = array();
2764 foreach ($this->choices as $key=>$description) {
2765 if (!empty($data[$key])) {
2766 $checked = 'checked="checked"';
2767 } else {
2768 $checked = '';
2770 if (!empty($default[$key])) {
2771 $defaults[] = $description;
2774 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2775 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2778 if (is_null($default)) {
2779 $defaultinfo = NULL;
2780 } else if (!empty($defaults)) {
2781 $defaultinfo = implode(', ', $defaults);
2782 } else {
2783 $defaultinfo = get_string('none');
2786 $return = '<div class="form-multicheckbox">';
2787 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2788 if ($options) {
2789 $return .= '<ul>';
2790 foreach ($options as $option) {
2791 $return .= '<li>'.$option.'</li>';
2793 $return .= '</ul>';
2795 $return .= '</div>';
2797 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2804 * Multiple checkboxes 2, value stored as string 00101011
2806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2808 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2811 * Returns the setting if set
2813 * @return mixed null if not set, else an array of set settings
2815 public function get_setting() {
2816 $result = $this->config_read($this->name);
2817 if (is_null($result)) {
2818 return NULL;
2820 if (!$this->load_choices()) {
2821 return NULL;
2823 $result = str_pad($result, count($this->choices), '0');
2824 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2825 $setting = array();
2826 foreach ($this->choices as $key=>$unused) {
2827 $value = array_shift($result);
2828 if ($value) {
2829 $setting[$key] = 1;
2832 return $setting;
2836 * Save setting(s) provided in $data param
2838 * @param array $data An array of settings to save
2839 * @return mixed empty string for bad data or bool true=>success, false=>error
2841 public function write_setting($data) {
2842 if (!is_array($data)) {
2843 return ''; // ignore it
2845 if (!$this->load_choices() or empty($this->choices)) {
2846 return '';
2848 $result = '';
2849 foreach ($this->choices as $key=>$unused) {
2850 if (!empty($data[$key])) {
2851 $result .= '1';
2852 } else {
2853 $result .= '0';
2856 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2862 * Select one value from list
2864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2866 class admin_setting_configselect extends admin_setting {
2867 /** @var array Array of choices value=>label */
2868 public $choices;
2871 * Constructor
2872 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2873 * @param string $visiblename localised
2874 * @param string $description long localised info
2875 * @param string|int $defaultsetting
2876 * @param array $choices array of $value=>$label for each selection
2878 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2879 $this->choices = $choices;
2880 parent::__construct($name, $visiblename, $description, $defaultsetting);
2884 * This function may be used in ancestors for lazy loading of choices
2886 * Override this method if loading of choices is expensive, such
2887 * as when it requires multiple db requests.
2889 * @return bool true if loaded, false if error
2891 public function load_choices() {
2893 if (is_array($this->choices)) {
2894 return true;
2896 .... load choices here
2898 return true;
2902 * Check if this is $query is related to a choice
2904 * @param string $query
2905 * @return bool true if related, false if not
2907 public function is_related($query) {
2908 if (parent::is_related($query)) {
2909 return true;
2911 if (!$this->load_choices()) {
2912 return false;
2914 foreach ($this->choices as $key=>$value) {
2915 if (strpos(core_text::strtolower($key), $query) !== false) {
2916 return true;
2918 if (strpos(core_text::strtolower($value), $query) !== false) {
2919 return true;
2922 return false;
2926 * Return the setting
2928 * @return mixed returns config if successful else null
2930 public function get_setting() {
2931 return $this->config_read($this->name);
2935 * Save a setting
2937 * @param string $data
2938 * @return string empty of error string
2940 public function write_setting($data) {
2941 if (!$this->load_choices() or empty($this->choices)) {
2942 return '';
2944 if (!array_key_exists($data, $this->choices)) {
2945 return ''; // ignore it
2948 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2952 * Returns XHTML select field
2954 * Ensure the options are loaded, and generate the XHTML for the select
2955 * element and any warning message. Separating this out from output_html
2956 * makes it easier to subclass this class.
2958 * @param string $data the option to show as selected.
2959 * @param string $current the currently selected option in the database, null if none.
2960 * @param string $default the default selected option.
2961 * @return array the HTML for the select element, and a warning message.
2963 public function output_select_html($data, $current, $default, $extraname = '') {
2964 if (!$this->load_choices() or empty($this->choices)) {
2965 return array('', '');
2968 $warning = '';
2969 if (is_null($current)) {
2970 // first run
2971 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2972 // no warning
2973 } else if (!array_key_exists($current, $this->choices)) {
2974 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2975 if (!is_null($default) and $data == $current) {
2976 $data = $default; // use default instead of first value when showing the form
2980 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2981 foreach ($this->choices as $key => $value) {
2982 // the string cast is needed because key may be integer - 0 is equal to most strings!
2983 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2985 $selecthtml .= '</select>';
2986 return array($selecthtml, $warning);
2990 * Returns XHTML select field and wrapping div(s)
2992 * @see output_select_html()
2994 * @param string $data the option to show as selected
2995 * @param string $query
2996 * @return string XHTML field and wrapping div
2998 public function output_html($data, $query='') {
2999 $default = $this->get_defaultsetting();
3000 $current = $this->get_setting();
3002 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3003 if (!$selecthtml) {
3004 return '';
3007 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3008 $defaultinfo = $this->choices[$default];
3009 } else {
3010 $defaultinfo = NULL;
3013 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3015 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3021 * Select multiple items from list
3023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3025 class admin_setting_configmultiselect extends admin_setting_configselect {
3027 * Constructor
3028 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3029 * @param string $visiblename localised
3030 * @param string $description long localised info
3031 * @param array $defaultsetting array of selected items
3032 * @param array $choices array of $value=>$label for each list item
3034 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3035 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3039 * Returns the select setting(s)
3041 * @return mixed null or array. Null if no settings else array of setting(s)
3043 public function get_setting() {
3044 $result = $this->config_read($this->name);
3045 if (is_null($result)) {
3046 return NULL;
3048 if ($result === '') {
3049 return array();
3051 return explode(',', $result);
3055 * Saves setting(s) provided through $data
3057 * Potential bug in the works should anyone call with this function
3058 * using a vartype that is not an array
3060 * @param array $data
3062 public function write_setting($data) {
3063 if (!is_array($data)) {
3064 return ''; //ignore it
3066 if (!$this->load_choices() or empty($this->choices)) {
3067 return '';
3070 unset($data['xxxxx']);
3072 $save = array();
3073 foreach ($data as $value) {
3074 if (!array_key_exists($value, $this->choices)) {
3075 continue; // ignore it
3077 $save[] = $value;
3080 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3084 * Is setting related to query text - used when searching
3086 * @param string $query
3087 * @return bool true if related, false if not
3089 public function is_related($query) {
3090 if (!$this->load_choices() or empty($this->choices)) {
3091 return false;
3093 if (parent::is_related($query)) {
3094 return true;
3097 foreach ($this->choices as $desc) {
3098 if (strpos(core_text::strtolower($desc), $query) !== false) {
3099 return true;
3102 return false;
3106 * Returns XHTML multi-select field
3108 * @todo Add vartype handling to ensure $data is an array
3109 * @param array $data Array of values to select by default
3110 * @param string $query
3111 * @return string XHTML multi-select field
3113 public function output_html($data, $query='') {
3114 if (!$this->load_choices() or empty($this->choices)) {
3115 return '';
3117 $choices = $this->choices;
3118 $default = $this->get_defaultsetting();
3119 if (is_null($default)) {
3120 $default = array();
3122 if (is_null($data)) {
3123 $data = array();
3126 $defaults = array();
3127 $size = min(10, count($this->choices));
3128 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3129 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3130 foreach ($this->choices as $key => $description) {
3131 if (in_array($key, $data)) {
3132 $selected = 'selected="selected"';
3133 } else {
3134 $selected = '';
3136 if (in_array($key, $default)) {
3137 $defaults[] = $description;
3140 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3143 if (is_null($default)) {
3144 $defaultinfo = NULL;
3145 } if (!empty($defaults)) {
3146 $defaultinfo = implode(', ', $defaults);
3147 } else {
3148 $defaultinfo = get_string('none');
3151 $return .= '</select></div>';
3152 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3157 * Time selector
3159 * This is a liiitle bit messy. we're using two selects, but we're returning
3160 * them as an array named after $name (so we only use $name2 internally for the setting)
3162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3164 class admin_setting_configtime extends admin_setting {
3165 /** @var string Used for setting second select (minutes) */
3166 public $name2;
3169 * Constructor
3170 * @param string $hoursname setting for hours
3171 * @param string $minutesname setting for hours
3172 * @param string $visiblename localised
3173 * @param string $description long localised info
3174 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3176 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3177 $this->name2 = $minutesname;
3178 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3182 * Get the selected time
3184 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3186 public function get_setting() {
3187 $result1 = $this->config_read($this->name);
3188 $result2 = $this->config_read($this->name2);
3189 if (is_null($result1) or is_null($result2)) {
3190 return NULL;
3193 return array('h' => $result1, 'm' => $result2);
3197 * Store the time (hours and minutes)
3199 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3200 * @return bool true if success, false if not
3202 public function write_setting($data) {
3203 if (!is_array($data)) {
3204 return '';
3207 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3208 return ($result ? '' : get_string('errorsetting', 'admin'));
3212 * Returns XHTML time select fields
3214 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3215 * @param string $query
3216 * @return string XHTML time select fields and wrapping div(s)
3218 public function output_html($data, $query='') {
3219 $default = $this->get_defaultsetting();
3221 if (is_array($default)) {
3222 $defaultinfo = $default['h'].':'.$default['m'];
3223 } else {
3224 $defaultinfo = NULL;
3227 $return = '<div class="form-time defaultsnext">';
3228 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3229 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3230 for ($i = 0; $i < 24; $i++) {
3231 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3233 $return .= '</select>:';
3234 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3235 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3236 for ($i = 0; $i < 60; $i += 5) {
3237 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3239 $return .= '</select>';
3240 $return .= '</div>';
3241 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3248 * Seconds duration setting.
3250 * @copyright 2012 Petr Skoda (http://skodak.org)
3251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3253 class admin_setting_configduration extends admin_setting {
3255 /** @var int default duration unit */
3256 protected $defaultunit;
3259 * Constructor
3260 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3261 * or 'myplugin/mysetting' for ones in config_plugins.
3262 * @param string $visiblename localised name
3263 * @param string $description localised long description
3264 * @param mixed $defaultsetting string or array depending on implementation
3265 * @param int $defaultunit - day, week, etc. (in seconds)
3267 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3268 if (is_number($defaultsetting)) {
3269 $defaultsetting = self::parse_seconds($defaultsetting);
3271 $units = self::get_units();
3272 if (isset($units[$defaultunit])) {
3273 $this->defaultunit = $defaultunit;
3274 } else {
3275 $this->defaultunit = 86400;
3277 parent::__construct($name, $visiblename, $description, $defaultsetting);
3281 * Returns selectable units.
3282 * @static
3283 * @return array
3285 protected static function get_units() {
3286 return array(
3287 604800 => get_string('weeks'),
3288 86400 => get_string('days'),
3289 3600 => get_string('hours'),
3290 60 => get_string('minutes'),
3291 1 => get_string('seconds'),
3296 * Converts seconds to some more user friendly string.
3297 * @static
3298 * @param int $seconds
3299 * @return string
3301 protected static function get_duration_text($seconds) {
3302 if (empty($seconds)) {
3303 return get_string('none');
3305 $data = self::parse_seconds($seconds);
3306 switch ($data['u']) {
3307 case (60*60*24*7):
3308 return get_string('numweeks', '', $data['v']);
3309 case (60*60*24):
3310 return get_string('numdays', '', $data['v']);
3311 case (60*60):
3312 return get_string('numhours', '', $data['v']);
3313 case (60):
3314 return get_string('numminutes', '', $data['v']);
3315 default:
3316 return get_string('numseconds', '', $data['v']*$data['u']);
3321 * Finds suitable units for given duration.
3322 * @static
3323 * @param int $seconds
3324 * @return array
3326 protected static function parse_seconds($seconds) {
3327 foreach (self::get_units() as $unit => $unused) {
3328 if ($seconds % $unit === 0) {
3329 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3332 return array('v'=>(int)$seconds, 'u'=>1);
3336 * Get the selected duration as array.
3338 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3340 public function get_setting() {
3341 $seconds = $this->config_read($this->name);
3342 if (is_null($seconds)) {
3343 return null;
3346 return self::parse_seconds($seconds);
3350 * Store the duration as seconds.
3352 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3353 * @return bool true if success, false if not
3355 public function write_setting($data) {
3356 if (!is_array($data)) {
3357 return '';
3360 $seconds = (int)($data['v']*$data['u']);
3361 if ($seconds < 0) {
3362 return get_string('errorsetting', 'admin');
3365 $result = $this->config_write($this->name, $seconds);
3366 return ($result ? '' : get_string('errorsetting', 'admin'));
3370 * Returns duration text+select fields.
3372 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3373 * @param string $query
3374 * @return string duration text+select fields and wrapping div(s)
3376 public function output_html($data, $query='') {
3377 $default = $this->get_defaultsetting();
3379 if (is_number($default)) {
3380 $defaultinfo = self::get_duration_text($default);
3381 } else if (is_array($default)) {
3382 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3383 } else {
3384 $defaultinfo = null;
3387 $units = self::get_units();
3389 $return = '<div class="form-duration defaultsnext">';
3390 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3391 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3392 foreach ($units as $val => $text) {
3393 $selected = '';
3394 if ($data['v'] == 0) {
3395 if ($val == $this->defaultunit) {
3396 $selected = ' selected="selected"';
3398 } else if ($val == $data['u']) {
3399 $selected = ' selected="selected"';
3401 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3403 $return .= '</select></div>';
3404 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3410 * Used to validate a textarea used for ip addresses
3412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3414 class admin_setting_configiplist extends admin_setting_configtextarea {
3417 * Validate the contents of the textarea as IP addresses
3419 * Used to validate a new line separated list of IP addresses collected from
3420 * a textarea control
3422 * @param string $data A list of IP Addresses separated by new lines
3423 * @return mixed bool true for success or string:error on failure
3425 public function validate($data) {
3426 if(!empty($data)) {
3427 $ips = explode("\n", $data);
3428 } else {
3429 return true;
3431 $result = true;
3432 foreach($ips as $ip) {
3433 $ip = trim($ip);
3434 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3435 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3436 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3437 $result = true;
3438 } else {
3439 $result = false;
3440 break;
3443 if($result) {
3444 return true;
3445 } else {
3446 return get_string('validateerror', 'admin');
3453 * An admin setting for selecting one or more users who have a capability
3454 * in the system context
3456 * An admin setting for selecting one or more users, who have a particular capability
3457 * in the system context. Warning, make sure the list will never be too long. There is
3458 * no paging or searching of this list.
3460 * To correctly get a list of users from this config setting, you need to call the
3461 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3465 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3466 /** @var string The capabilities name */
3467 protected $capability;
3468 /** @var int include admin users too */
3469 protected $includeadmins;
3472 * Constructor.
3474 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3475 * @param string $visiblename localised name
3476 * @param string $description localised long description
3477 * @param array $defaultsetting array of usernames
3478 * @param string $capability string capability name.
3479 * @param bool $includeadmins include administrators
3481 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3482 $this->capability = $capability;
3483 $this->includeadmins = $includeadmins;
3484 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3488 * Load all of the uses who have the capability into choice array
3490 * @return bool Always returns true
3492 function load_choices() {
3493 if (is_array($this->choices)) {
3494 return true;
3496 list($sort, $sortparams) = users_order_by_sql('u');
3497 if (!empty($sortparams)) {
3498 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3499 'This is unexpected, and a problem because there is no way to pass these ' .
3500 'parameters to get_users_by_capability. See MDL-34657.');
3502 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3503 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3504 $this->choices = array(
3505 '$@NONE@$' => get_string('nobody'),
3506 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3508 if ($this->includeadmins) {
3509 $admins = get_admins();
3510 foreach ($admins as $user) {
3511 $this->choices[$user->id] = fullname($user);
3514 if (is_array($users)) {
3515 foreach ($users as $user) {
3516 $this->choices[$user->id] = fullname($user);
3519 return true;
3523 * Returns the default setting for class
3525 * @return mixed Array, or string. Empty string if no default
3527 public function get_defaultsetting() {
3528 $this->load_choices();
3529 $defaultsetting = parent::get_defaultsetting();
3530 if (empty($defaultsetting)) {
3531 return array('$@NONE@$');
3532 } else if (array_key_exists($defaultsetting, $this->choices)) {
3533 return $defaultsetting;
3534 } else {
3535 return '';
3540 * Returns the current setting
3542 * @return mixed array or string
3544 public function get_setting() {
3545 $result = parent::get_setting();
3546 if ($result === null) {
3547 // this is necessary for settings upgrade
3548 return null;
3550 if (empty($result)) {
3551 $result = array('$@NONE@$');
3553 return $result;
3557 * Save the chosen setting provided as $data
3559 * @param array $data
3560 * @return mixed string or array
3562 public function write_setting($data) {
3563 // If all is selected, remove any explicit options.
3564 if (in_array('$@ALL@$', $data)) {
3565 $data = array('$@ALL@$');
3567 // None never needs to be written to the DB.
3568 if (in_array('$@NONE@$', $data)) {
3569 unset($data[array_search('$@NONE@$', $data)]);
3571 return parent::write_setting($data);
3577 * Special checkbox for calendar - resets SESSION vars.
3579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3581 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3583 * Calls the parent::__construct with default values
3585 * name => calendar_adminseesall
3586 * visiblename => get_string('adminseesall', 'admin')
3587 * description => get_string('helpadminseesall', 'admin')
3588 * defaultsetting => 0
3590 public function __construct() {
3591 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3592 get_string('helpadminseesall', 'admin'), '0');
3596 * Stores the setting passed in $data
3598 * @param mixed gets converted to string for comparison
3599 * @return string empty string or error message
3601 public function write_setting($data) {
3602 global $SESSION;
3603 return parent::write_setting($data);
3608 * Special select for settings that are altered in setup.php and can not be altered on the fly
3610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3612 class admin_setting_special_selectsetup extends admin_setting_configselect {
3614 * Reads the setting directly from the database
3616 * @return mixed
3618 public function get_setting() {
3619 // read directly from db!
3620 return get_config(NULL, $this->name);
3624 * Save the setting passed in $data
3626 * @param string $data The setting to save
3627 * @return string empty or error message
3629 public function write_setting($data) {
3630 global $CFG;
3631 // do not change active CFG setting!
3632 $current = $CFG->{$this->name};
3633 $result = parent::write_setting($data);
3634 $CFG->{$this->name} = $current;
3635 return $result;
3641 * Special select for frontpage - stores data in course table
3643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3645 class admin_setting_sitesetselect extends admin_setting_configselect {
3647 * Returns the site name for the selected site
3649 * @see get_site()
3650 * @return string The site name of the selected site
3652 public function get_setting() {
3653 $site = course_get_format(get_site())->get_course();
3654 return $site->{$this->name};
3658 * Updates the database and save the setting
3660 * @param string data
3661 * @return string empty or error message
3663 public function write_setting($data) {
3664 global $DB, $SITE, $COURSE;
3665 if (!in_array($data, array_keys($this->choices))) {
3666 return get_string('errorsetting', 'admin');
3668 $record = new stdClass();
3669 $record->id = SITEID;
3670 $temp = $this->name;
3671 $record->$temp = $data;
3672 $record->timemodified = time();
3674 course_get_format($SITE)->update_course_format_options($record);
3675 $DB->update_record('course', $record);
3677 // Reset caches.
3678 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3679 if ($SITE->id == $COURSE->id) {
3680 $COURSE = $SITE;
3682 format_base::reset_course_cache($SITE->id);
3684 return '';
3691 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3692 * block to hidden.
3694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3696 class admin_setting_bloglevel extends admin_setting_configselect {
3698 * Updates the database and save the setting
3700 * @param string data
3701 * @return string empty or error message
3703 public function write_setting($data) {
3704 global $DB, $CFG;
3705 if ($data == 0) {
3706 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3707 foreach ($blogblocks as $block) {
3708 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3710 } else {
3711 // reenable all blocks only when switching from disabled blogs
3712 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3713 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3714 foreach ($blogblocks as $block) {
3715 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3719 return parent::write_setting($data);
3725 * Special select - lists on the frontpage - hacky
3727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3729 class admin_setting_courselist_frontpage extends admin_setting {
3730 /** @var array Array of choices value=>label */
3731 public $choices;
3734 * Construct override, requires one param
3736 * @param bool $loggedin Is the user logged in
3738 public function __construct($loggedin) {
3739 global $CFG;
3740 require_once($CFG->dirroot.'/course/lib.php');
3741 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3742 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3743 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3744 $defaults = array(FRONTPAGEALLCOURSELIST);
3745 parent::__construct($name, $visiblename, $description, $defaults);
3749 * Loads the choices available
3751 * @return bool always returns true
3753 public function load_choices() {
3754 if (is_array($this->choices)) {
3755 return true;
3757 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3758 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3759 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3760 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3761 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3762 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3763 'none' => get_string('none'));
3764 if ($this->name === 'frontpage') {
3765 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3767 return true;
3771 * Returns the selected settings
3773 * @param mixed array or setting or null
3775 public function get_setting() {
3776 $result = $this->config_read($this->name);
3777 if (is_null($result)) {
3778 return NULL;
3780 if ($result === '') {
3781 return array();
3783 return explode(',', $result);
3787 * Save the selected options
3789 * @param array $data
3790 * @return mixed empty string (data is not an array) or bool true=success false=failure
3792 public function write_setting($data) {
3793 if (!is_array($data)) {
3794 return '';
3796 $this->load_choices();
3797 $save = array();
3798 foreach($data as $datum) {
3799 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3800 continue;
3802 $save[$datum] = $datum; // no duplicates
3804 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3808 * Return XHTML select field and wrapping div
3810 * @todo Add vartype handling to make sure $data is an array
3811 * @param array $data Array of elements to select by default
3812 * @return string XHTML select field and wrapping div
3814 public function output_html($data, $query='') {
3815 $this->load_choices();
3816 $currentsetting = array();
3817 foreach ($data as $key) {
3818 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3819 $currentsetting[] = $key; // already selected first
3823 $return = '<div class="form-group">';
3824 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3825 if (!array_key_exists($i, $currentsetting)) {
3826 $currentsetting[$i] = 'none'; //none
3828 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3829 foreach ($this->choices as $key => $value) {
3830 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3832 $return .= '</select>';
3833 if ($i !== count($this->choices) - 2) {
3834 $return .= '<br />';
3837 $return .= '</div>';
3839 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3845 * Special checkbox for frontpage - stores data in course table
3847 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3849 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3851 * Returns the current sites name
3853 * @return string
3855 public function get_setting() {
3856 $site = course_get_format(get_site())->get_course();
3857 return $site->{$this->name};
3861 * Save the selected setting
3863 * @param string $data The selected site
3864 * @return string empty string or error message
3866 public function write_setting($data) {
3867 global $DB, $SITE, $COURSE;
3868 $record = new stdClass();
3869 $record->id = $SITE->id;
3870 $record->{$this->name} = ($data == '1' ? 1 : 0);
3871 $record->timemodified = time();
3873 course_get_format($SITE)->update_course_format_options($record);
3874 $DB->update_record('course', $record);
3876 // Reset caches.
3877 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3878 if ($SITE->id == $COURSE->id) {
3879 $COURSE = $SITE;
3881 format_base::reset_course_cache($SITE->id);
3883 return '';
3888 * Special text for frontpage - stores data in course table.
3889 * Empty string means not set here. Manual setting is required.
3891 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3893 class admin_setting_sitesettext extends admin_setting_configtext {
3895 * Return the current setting
3897 * @return mixed string or null
3899 public function get_setting() {
3900 $site = course_get_format(get_site())->get_course();
3901 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3905 * Validate the selected data
3907 * @param string $data The selected value to validate
3908 * @return mixed true or message string
3910 public function validate($data) {
3911 $cleaned = clean_param($data, PARAM_TEXT);
3912 if ($cleaned === '') {
3913 return get_string('required');
3915 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3916 return true;
3917 } else {
3918 return get_string('validateerror', 'admin');
3923 * Save the selected setting
3925 * @param string $data The selected value
3926 * @return string empty or error message
3928 public function write_setting($data) {
3929 global $DB, $SITE, $COURSE;
3930 $data = trim($data);
3931 $validated = $this->validate($data);
3932 if ($validated !== true) {
3933 return $validated;
3936 $record = new stdClass();
3937 $record->id = $SITE->id;
3938 $record->{$this->name} = $data;
3939 $record->timemodified = time();
3941 course_get_format($SITE)->update_course_format_options($record);
3942 $DB->update_record('course', $record);
3944 // Reset caches.
3945 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3946 if ($SITE->id == $COURSE->id) {
3947 $COURSE = $SITE;
3949 format_base::reset_course_cache($SITE->id);
3951 return '';
3957 * Special text editor for site description.
3959 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3961 class admin_setting_special_frontpagedesc extends admin_setting {
3963 * Calls parent::__construct with specific arguments
3965 public function __construct() {
3966 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3967 editors_head_setup();
3971 * Return the current setting
3972 * @return string The current setting
3974 public function get_setting() {
3975 $site = course_get_format(get_site())->get_course();
3976 return $site->{$this->name};
3980 * Save the new setting
3982 * @param string $data The new value to save
3983 * @return string empty or error message
3985 public function write_setting($data) {
3986 global $DB, $SITE, $COURSE;
3987 $record = new stdClass();
3988 $record->id = $SITE->id;
3989 $record->{$this->name} = $data;
3990 $record->timemodified = time();
3992 course_get_format($SITE)->update_course_format_options($record);
3993 $DB->update_record('course', $record);
3995 // Reset caches.
3996 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3997 if ($SITE->id == $COURSE->id) {
3998 $COURSE = $SITE;
4000 format_base::reset_course_cache($SITE->id);
4002 return '';
4006 * Returns XHTML for the field plus wrapping div
4008 * @param string $data The current value
4009 * @param string $query
4010 * @return string The XHTML output
4012 public function output_html($data, $query='') {
4013 global $CFG;
4015 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4017 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4023 * Administration interface for emoticon_manager settings.
4025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4027 class admin_setting_emoticons extends admin_setting {
4030 * Calls parent::__construct with specific args
4032 public function __construct() {
4033 global $CFG;
4035 $manager = get_emoticon_manager();
4036 $defaults = $this->prepare_form_data($manager->default_emoticons());
4037 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4041 * Return the current setting(s)
4043 * @return array Current settings array
4045 public function get_setting() {
4046 global $CFG;
4048 $manager = get_emoticon_manager();
4050 $config = $this->config_read($this->name);
4051 if (is_null($config)) {
4052 return null;
4055 $config = $manager->decode_stored_config($config);
4056 if (is_null($config)) {
4057 return null;
4060 return $this->prepare_form_data($config);
4064 * Save selected settings
4066 * @param array $data Array of settings to save
4067 * @return bool
4069 public function write_setting($data) {
4071 $manager = get_emoticon_manager();
4072 $emoticons = $this->process_form_data($data);
4074 if ($emoticons === false) {
4075 return false;
4078 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4079 return ''; // success
4080 } else {
4081 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4086 * Return XHTML field(s) for options
4088 * @param array $data Array of options to set in HTML
4089 * @return string XHTML string for the fields and wrapping div(s)
4091 public function output_html($data, $query='') {
4092 global $OUTPUT;
4094 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4095 $out .= html_writer::start_tag('thead');
4096 $out .= html_writer::start_tag('tr');
4097 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4098 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4099 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4100 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4101 $out .= html_writer::tag('th', '');
4102 $out .= html_writer::end_tag('tr');
4103 $out .= html_writer::end_tag('thead');
4104 $out .= html_writer::start_tag('tbody');
4105 $i = 0;
4106 foreach($data as $field => $value) {
4107 switch ($i) {
4108 case 0:
4109 $out .= html_writer::start_tag('tr');
4110 $current_text = $value;
4111 $current_filename = '';
4112 $current_imagecomponent = '';
4113 $current_altidentifier = '';
4114 $current_altcomponent = '';
4115 case 1:
4116 $current_filename = $value;
4117 case 2:
4118 $current_imagecomponent = $value;
4119 case 3:
4120 $current_altidentifier = $value;
4121 case 4:
4122 $current_altcomponent = $value;
4125 $out .= html_writer::tag('td',
4126 html_writer::empty_tag('input',
4127 array(
4128 'type' => 'text',
4129 'class' => 'form-text',
4130 'name' => $this->get_full_name().'['.$field.']',
4131 'value' => $value,
4133 ), array('class' => 'c'.$i)
4136 if ($i == 4) {
4137 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4138 $alt = get_string($current_altidentifier, $current_altcomponent);
4139 } else {
4140 $alt = $current_text;
4142 if ($current_filename) {
4143 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4144 } else {
4145 $out .= html_writer::tag('td', '');
4147 $out .= html_writer::end_tag('tr');
4148 $i = 0;
4149 } else {
4150 $i++;
4154 $out .= html_writer::end_tag('tbody');
4155 $out .= html_writer::end_tag('table');
4156 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4157 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4159 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4163 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4165 * @see self::process_form_data()
4166 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4167 * @return array of form fields and their values
4169 protected function prepare_form_data(array $emoticons) {
4171 $form = array();
4172 $i = 0;
4173 foreach ($emoticons as $emoticon) {
4174 $form['text'.$i] = $emoticon->text;
4175 $form['imagename'.$i] = $emoticon->imagename;
4176 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4177 $form['altidentifier'.$i] = $emoticon->altidentifier;
4178 $form['altcomponent'.$i] = $emoticon->altcomponent;
4179 $i++;
4181 // add one more blank field set for new object
4182 $form['text'.$i] = '';
4183 $form['imagename'.$i] = '';
4184 $form['imagecomponent'.$i] = '';
4185 $form['altidentifier'.$i] = '';
4186 $form['altcomponent'.$i] = '';
4188 return $form;
4192 * Converts the data from admin settings form into an array of emoticon objects
4194 * @see self::prepare_form_data()
4195 * @param array $data array of admin form fields and values
4196 * @return false|array of emoticon objects
4198 protected function process_form_data(array $form) {
4200 $count = count($form); // number of form field values
4202 if ($count % 5) {
4203 // we must get five fields per emoticon object
4204 return false;
4207 $emoticons = array();
4208 for ($i = 0; $i < $count / 5; $i++) {
4209 $emoticon = new stdClass();
4210 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4211 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4212 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4213 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4214 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4216 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4217 // prevent from breaking http://url.addresses by accident
4218 $emoticon->text = '';
4221 if (strlen($emoticon->text) < 2) {
4222 // do not allow single character emoticons
4223 $emoticon->text = '';
4226 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4227 // emoticon text must contain some non-alphanumeric character to prevent
4228 // breaking HTML tags
4229 $emoticon->text = '';
4232 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4233 $emoticons[] = $emoticon;
4236 return $emoticons;
4242 * Special setting for limiting of the list of available languages.
4244 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4246 class admin_setting_langlist extends admin_setting_configtext {
4248 * Calls parent::__construct with specific arguments
4250 public function __construct() {
4251 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4255 * Save the new setting
4257 * @param string $data The new setting
4258 * @return bool
4260 public function write_setting($data) {
4261 $return = parent::write_setting($data);
4262 get_string_manager()->reset_caches();
4263 return $return;
4269 * Selection of one of the recognised countries using the list
4270 * returned by {@link get_list_of_countries()}.
4272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4274 class admin_settings_country_select extends admin_setting_configselect {
4275 protected $includeall;
4276 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4277 $this->includeall = $includeall;
4278 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4282 * Lazy-load the available choices for the select box
4284 public function load_choices() {
4285 global $CFG;
4286 if (is_array($this->choices)) {
4287 return true;
4289 $this->choices = array_merge(
4290 array('0' => get_string('choosedots')),
4291 get_string_manager()->get_list_of_countries($this->includeall));
4292 return true;
4298 * admin_setting_configselect for the default number of sections in a course,
4299 * simply so we can lazy-load the choices.
4301 * @copyright 2011 The Open University
4302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4304 class admin_settings_num_course_sections extends admin_setting_configselect {
4305 public function __construct($name, $visiblename, $description, $defaultsetting) {
4306 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4309 /** Lazy-load the available choices for the select box */
4310 public function load_choices() {
4311 $max = get_config('moodlecourse', 'maxsections');
4312 if (!isset($max) || !is_numeric($max)) {
4313 $max = 52;
4315 for ($i = 0; $i <= $max; $i++) {
4316 $this->choices[$i] = "$i";
4318 return true;
4324 * Course category selection
4326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4328 class admin_settings_coursecat_select extends admin_setting_configselect {
4330 * Calls parent::__construct with specific arguments
4332 public function __construct($name, $visiblename, $description, $defaultsetting) {
4333 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4337 * Load the available choices for the select box
4339 * @return bool
4341 public function load_choices() {
4342 global $CFG;
4343 require_once($CFG->dirroot.'/course/lib.php');
4344 if (is_array($this->choices)) {
4345 return true;
4347 $this->choices = make_categories_options();
4348 return true;
4354 * Special control for selecting days to backup
4356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4358 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4360 * Calls parent::__construct with specific arguments
4362 public function __construct() {
4363 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4364 $this->plugin = 'backup';
4368 * Load the available choices for the select box
4370 * @return bool Always returns true
4372 public function load_choices() {
4373 if (is_array($this->choices)) {
4374 return true;
4376 $this->choices = array();
4377 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4378 foreach ($days as $day) {
4379 $this->choices[$day] = get_string($day, 'calendar');
4381 return true;
4387 * Special debug setting
4389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4391 class admin_setting_special_debug extends admin_setting_configselect {
4393 * Calls parent::__construct with specific arguments
4395 public function __construct() {
4396 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4400 * Load the available choices for the select box
4402 * @return bool
4404 public function load_choices() {
4405 if (is_array($this->choices)) {
4406 return true;
4408 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4409 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4410 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4411 DEBUG_ALL => get_string('debugall', 'admin'),
4412 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4413 return true;
4419 * Special admin control
4421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4423 class admin_setting_special_calendar_weekend extends admin_setting {
4425 * Calls parent::__construct with specific arguments
4427 public function __construct() {
4428 $name = 'calendar_weekend';
4429 $visiblename = get_string('calendar_weekend', 'admin');
4430 $description = get_string('helpweekenddays', 'admin');
4431 $default = array ('0', '6'); // Saturdays and Sundays
4432 parent::__construct($name, $visiblename, $description, $default);
4436 * Gets the current settings as an array
4438 * @return mixed Null if none, else array of settings
4440 public function get_setting() {
4441 $result = $this->config_read($this->name);
4442 if (is_null($result)) {
4443 return NULL;
4445 if ($result === '') {
4446 return array();
4448 $settings = array();
4449 for ($i=0; $i<7; $i++) {
4450 if ($result & (1 << $i)) {
4451 $settings[] = $i;
4454 return $settings;
4458 * Save the new settings
4460 * @param array $data Array of new settings
4461 * @return bool
4463 public function write_setting($data) {
4464 if (!is_array($data)) {
4465 return '';
4467 unset($data['xxxxx']);
4468 $result = 0;
4469 foreach($data as $index) {
4470 $result |= 1 << $index;
4472 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4476 * Return XHTML to display the control
4478 * @param array $data array of selected days
4479 * @param string $query
4480 * @return string XHTML for display (field + wrapping div(s)
4482 public function output_html($data, $query='') {
4483 // The order matters very much because of the implied numeric keys
4484 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4485 $return = '<table><thead><tr>';
4486 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4487 foreach($days as $index => $day) {
4488 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4490 $return .= '</tr></thead><tbody><tr>';
4491 foreach($days as $index => $day) {
4492 $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>';
4494 $return .= '</tr></tbody></table>';
4496 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4503 * Admin setting that allows a user to pick a behaviour.
4505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4507 class admin_setting_question_behaviour extends admin_setting_configselect {
4509 * @param string $name name of config variable
4510 * @param string $visiblename display name
4511 * @param string $description description
4512 * @param string $default default.
4514 public function __construct($name, $visiblename, $description, $default) {
4515 parent::__construct($name, $visiblename, $description, $default, NULL);
4519 * Load list of behaviours as choices
4520 * @return bool true => success, false => error.
4522 public function load_choices() {
4523 global $CFG;
4524 require_once($CFG->dirroot . '/question/engine/lib.php');
4525 $this->choices = question_engine::get_behaviour_options('');
4526 return true;
4532 * Admin setting that allows a user to pick appropriate roles for something.
4534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4536 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4537 /** @var array Array of capabilities which identify roles */
4538 private $types;
4541 * @param string $name Name of config variable
4542 * @param string $visiblename Display name
4543 * @param string $description Description
4544 * @param array $types Array of archetypes which identify
4545 * roles that will be enabled by default.
4547 public function __construct($name, $visiblename, $description, $types) {
4548 parent::__construct($name, $visiblename, $description, NULL, NULL);
4549 $this->types = $types;
4553 * Load roles as choices
4555 * @return bool true=>success, false=>error
4557 public function load_choices() {
4558 global $CFG, $DB;
4559 if (during_initial_install()) {
4560 return false;
4562 if (is_array($this->choices)) {
4563 return true;
4565 if ($roles = get_all_roles()) {
4566 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4567 return true;
4568 } else {
4569 return false;
4574 * Return the default setting for this control
4576 * @return array Array of default settings
4578 public function get_defaultsetting() {
4579 global $CFG;
4581 if (during_initial_install()) {
4582 return null;
4584 $result = array();
4585 foreach($this->types as $archetype) {
4586 if ($caproles = get_archetype_roles($archetype)) {
4587 foreach ($caproles as $caprole) {
4588 $result[$caprole->id] = 1;
4592 return $result;
4598 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4602 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4604 * Constructor
4605 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4606 * @param string $visiblename localised
4607 * @param string $description long localised info
4608 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4609 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4610 * @param int $size default field size
4612 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4613 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4614 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4620 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4622 * @copyright 2009 Petr Skoda (http://skodak.org)
4623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4625 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4628 * Constructor
4629 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4630 * @param string $visiblename localised
4631 * @param string $description long localised info
4632 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4633 * @param string $yes value used when checked
4634 * @param string $no value used when not checked
4636 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4637 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4638 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4645 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4647 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4649 * @copyright 2010 Sam Hemelryk
4650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4652 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4654 * Constructor
4655 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4656 * @param string $visiblename localised
4657 * @param string $description long localised info
4658 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4659 * @param string $yes value used when checked
4660 * @param string $no value used when not checked
4662 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4663 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4664 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4671 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4675 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4677 * Calls parent::__construct with specific arguments
4679 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4680 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4681 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4688 * Graded roles in gradebook
4690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4692 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4694 * Calls parent::__construct with specific arguments
4696 public function __construct() {
4697 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4698 get_string('configgradebookroles', 'admin'),
4699 array('student'));
4706 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4708 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4710 * Saves the new settings passed in $data
4712 * @param string $data
4713 * @return mixed string or Array
4715 public function write_setting($data) {
4716 global $CFG, $DB;
4718 $oldvalue = $this->config_read($this->name);
4719 $return = parent::write_setting($data);
4720 $newvalue = $this->config_read($this->name);
4722 if ($oldvalue !== $newvalue) {
4723 // force full regrading
4724 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4727 return $return;
4733 * Which roles to show on course description page
4735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4737 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4739 * Calls parent::__construct with specific arguments
4741 public function __construct() {
4742 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4743 get_string('coursecontact_desc', 'admin'),
4744 array('editingteacher'));
4751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4753 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4755 * Calls parent::__construct with specific arguments
4757 function admin_setting_special_gradelimiting() {
4758 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4759 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4763 * Force site regrading
4765 function regrade_all() {
4766 global $CFG;
4767 require_once("$CFG->libdir/gradelib.php");
4768 grade_force_site_regrading();
4772 * Saves the new settings
4774 * @param mixed $data
4775 * @return string empty string or error message
4777 function write_setting($data) {
4778 $previous = $this->get_setting();
4780 if ($previous === null) {
4781 if ($data) {
4782 $this->regrade_all();
4784 } else {
4785 if ($data != $previous) {
4786 $this->regrade_all();
4789 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4796 * Primary grade export plugin - has state tracking.
4798 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4800 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4802 * Calls parent::__construct with specific arguments
4804 public function __construct() {
4805 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4806 get_string('configgradeexport', 'admin'), array(), NULL);
4810 * Load the available choices for the multicheckbox
4812 * @return bool always returns true
4814 public function load_choices() {
4815 if (is_array($this->choices)) {
4816 return true;
4818 $this->choices = array();
4820 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4821 foreach($plugins as $plugin => $unused) {
4822 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4825 return true;
4831 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4835 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4837 * Config gradepointmax constructor
4839 * @param string $name Overidden by "gradepointmax"
4840 * @param string $visiblename Overridden by "gradepointmax" language string.
4841 * @param string $description Overridden by "gradepointmax_help" language string.
4842 * @param string $defaultsetting Not used, overridden by 100.
4843 * @param mixed $paramtype Overridden by PARAM_INT.
4844 * @param int $size Overridden by 5.
4846 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4847 $name = 'gradepointdefault';
4848 $visiblename = get_string('gradepointdefault', 'grades');
4849 $description = get_string('gradepointdefault_help', 'grades');
4850 $defaultsetting = 100;
4851 $paramtype = PARAM_INT;
4852 $size = 5;
4853 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4857 * Validate data before storage
4858 * @param string $data The submitted data
4859 * @return bool|string true if ok, string if error found
4861 public function validate($data) {
4862 global $CFG;
4863 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4864 return true;
4865 } else {
4866 return get_string('gradepointdefault_validateerror', 'grades');
4873 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4877 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4880 * Config gradepointmax constructor
4882 * @param string $name Overidden by "gradepointmax"
4883 * @param string $visiblename Overridden by "gradepointmax" language string.
4884 * @param string $description Overridden by "gradepointmax_help" language string.
4885 * @param string $defaultsetting Not used, overridden by 100.
4886 * @param mixed $paramtype Overridden by PARAM_INT.
4887 * @param int $size Overridden by 5.
4889 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4890 $name = 'gradepointmax';
4891 $visiblename = get_string('gradepointmax', 'grades');
4892 $description = get_string('gradepointmax_help', 'grades');
4893 $defaultsetting = 100;
4894 $paramtype = PARAM_INT;
4895 $size = 5;
4896 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4900 * Save the selected setting
4902 * @param string $data The selected site
4903 * @return string empty string or error message
4905 public function write_setting($data) {
4906 if ($data === '') {
4907 $data = (int)$this->defaultsetting;
4908 } else {
4909 $data = $data;
4911 return parent::write_setting($data);
4915 * Validate data before storage
4916 * @param string $data The submitted data
4917 * @return bool|string true if ok, string if error found
4919 public function validate($data) {
4920 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4921 return true;
4922 } else {
4923 return get_string('gradepointmax_validateerror', 'grades');
4928 * Return an XHTML string for the setting
4929 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4930 * @param string $query search query to be highlighted
4931 * @return string XHTML to display control
4933 public function output_html($data, $query = '') {
4934 $default = $this->get_defaultsetting();
4936 $attr = array(
4937 'type' => 'text',
4938 'size' => $this->size,
4939 'id' => $this->get_id(),
4940 'name' => $this->get_full_name(),
4941 'value' => s($data),
4942 'maxlength' => '5'
4944 $input = html_writer::empty_tag('input', $attr);
4946 $attr = array('class' => 'form-text defaultsnext');
4947 $div = html_writer::tag('div', $input, $attr);
4948 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
4954 * Grade category settings
4956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4958 class admin_setting_gradecat_combo extends admin_setting {
4959 /** @var array Array of choices */
4960 public $choices;
4963 * Sets choices and calls parent::__construct with passed arguments
4964 * @param string $name
4965 * @param string $visiblename
4966 * @param string $description
4967 * @param mixed $defaultsetting string or array depending on implementation
4968 * @param array $choices An array of choices for the control
4970 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4971 $this->choices = $choices;
4972 parent::__construct($name, $visiblename, $description, $defaultsetting);
4976 * Return the current setting(s) array
4978 * @return array Array of value=>xx, forced=>xx, adv=>xx
4980 public function get_setting() {
4981 global $CFG;
4983 $value = $this->config_read($this->name);
4984 $flag = $this->config_read($this->name.'_flag');
4986 if (is_null($value) or is_null($flag)) {
4987 return NULL;
4990 $flag = (int)$flag;
4991 $forced = (boolean)(1 & $flag); // first bit
4992 $adv = (boolean)(2 & $flag); // second bit
4994 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4998 * Save the new settings passed in $data
5000 * @todo Add vartype handling to ensure $data is array
5001 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5002 * @return string empty or error message
5004 public function write_setting($data) {
5005 global $CFG;
5007 $value = $data['value'];
5008 $forced = empty($data['forced']) ? 0 : 1;
5009 $adv = empty($data['adv']) ? 0 : 2;
5010 $flag = ($forced | $adv); //bitwise or
5012 if (!in_array($value, array_keys($this->choices))) {
5013 return 'Error setting ';
5016 $oldvalue = $this->config_read($this->name);
5017 $oldflag = (int)$this->config_read($this->name.'_flag');
5018 $oldforced = (1 & $oldflag); // first bit
5020 $result1 = $this->config_write($this->name, $value);
5021 $result2 = $this->config_write($this->name.'_flag', $flag);
5023 // force regrade if needed
5024 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5025 require_once($CFG->libdir.'/gradelib.php');
5026 grade_category::updated_forced_settings();
5029 if ($result1 and $result2) {
5030 return '';
5031 } else {
5032 return get_string('errorsetting', 'admin');
5037 * Return XHTML to display the field and wrapping div
5039 * @todo Add vartype handling to ensure $data is array
5040 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5041 * @param string $query
5042 * @return string XHTML to display control
5044 public function output_html($data, $query='') {
5045 $value = $data['value'];
5046 $forced = !empty($data['forced']);
5047 $adv = !empty($data['adv']);
5049 $default = $this->get_defaultsetting();
5050 if (!is_null($default)) {
5051 $defaultinfo = array();
5052 if (isset($this->choices[$default['value']])) {
5053 $defaultinfo[] = $this->choices[$default['value']];
5055 if (!empty($default['forced'])) {
5056 $defaultinfo[] = get_string('force');
5058 if (!empty($default['adv'])) {
5059 $defaultinfo[] = get_string('advanced');
5061 $defaultinfo = implode(', ', $defaultinfo);
5063 } else {
5064 $defaultinfo = NULL;
5068 $return = '<div class="form-group">';
5069 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5070 foreach ($this->choices as $key => $val) {
5071 // the string cast is needed because key may be integer - 0 is equal to most strings!
5072 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5074 $return .= '</select>';
5075 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5076 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5077 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5078 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5079 $return .= '</div>';
5081 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5087 * Selection of grade report in user profiles
5089 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5091 class admin_setting_grade_profilereport extends admin_setting_configselect {
5093 * Calls parent::__construct with specific arguments
5095 public function __construct() {
5096 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5100 * Loads an array of choices for the configselect control
5102 * @return bool always return true
5104 public function load_choices() {
5105 if (is_array($this->choices)) {
5106 return true;
5108 $this->choices = array();
5110 global $CFG;
5111 require_once($CFG->libdir.'/gradelib.php');
5113 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5114 if (file_exists($plugindir.'/lib.php')) {
5115 require_once($plugindir.'/lib.php');
5116 $functionname = 'grade_report_'.$plugin.'_profilereport';
5117 if (function_exists($functionname)) {
5118 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5122 return true;
5128 * Special class for register auth selection
5130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5132 class admin_setting_special_registerauth extends admin_setting_configselect {
5134 * Calls parent::__construct with specific arguments
5136 public function __construct() {
5137 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5141 * Returns the default option
5143 * @return string empty or default option
5145 public function get_defaultsetting() {
5146 $this->load_choices();
5147 $defaultsetting = parent::get_defaultsetting();
5148 if (array_key_exists($defaultsetting, $this->choices)) {
5149 return $defaultsetting;
5150 } else {
5151 return '';
5156 * Loads the possible choices for the array
5158 * @return bool always returns true
5160 public function load_choices() {
5161 global $CFG;
5163 if (is_array($this->choices)) {
5164 return true;
5166 $this->choices = array();
5167 $this->choices[''] = get_string('disable');
5169 $authsenabled = get_enabled_auth_plugins(true);
5171 foreach ($authsenabled as $auth) {
5172 $authplugin = get_auth_plugin($auth);
5173 if (!$authplugin->can_signup()) {
5174 continue;
5176 // Get the auth title (from core or own auth lang files)
5177 $authtitle = $authplugin->get_title();
5178 $this->choices[$auth] = $authtitle;
5180 return true;
5186 * General plugins manager
5188 class admin_page_pluginsoverview extends admin_externalpage {
5191 * Sets basic information about the external page
5193 public function __construct() {
5194 global $CFG;
5195 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5196 "$CFG->wwwroot/$CFG->admin/plugins.php");
5201 * Module manage page
5203 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5205 class admin_page_managemods extends admin_externalpage {
5207 * Calls parent::__construct with specific arguments
5209 public function __construct() {
5210 global $CFG;
5211 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5215 * Try to find the specified module
5217 * @param string $query The module to search for
5218 * @return array
5220 public function search($query) {
5221 global $CFG, $DB;
5222 if ($result = parent::search($query)) {
5223 return $result;
5226 $found = false;
5227 if ($modules = $DB->get_records('modules')) {
5228 foreach ($modules as $module) {
5229 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5230 continue;
5232 if (strpos($module->name, $query) !== false) {
5233 $found = true;
5234 break;
5236 $strmodulename = get_string('modulename', $module->name);
5237 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5238 $found = true;
5239 break;
5243 if ($found) {
5244 $result = new stdClass();
5245 $result->page = $this;
5246 $result->settings = array();
5247 return array($this->name => $result);
5248 } else {
5249 return array();
5256 * Special class for enrol plugins management.
5258 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5261 class admin_setting_manageenrols extends admin_setting {
5263 * Calls parent::__construct with specific arguments
5265 public function __construct() {
5266 $this->nosave = true;
5267 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5271 * Always returns true, does nothing
5273 * @return true
5275 public function get_setting() {
5276 return true;
5280 * Always returns true, does nothing
5282 * @return true
5284 public function get_defaultsetting() {
5285 return true;
5289 * Always returns '', does not write anything
5291 * @return string Always returns ''
5293 public function write_setting($data) {
5294 // do not write any setting
5295 return '';
5299 * Checks if $query is one of the available enrol plugins
5301 * @param string $query The string to search for
5302 * @return bool Returns true if found, false if not
5304 public function is_related($query) {
5305 if (parent::is_related($query)) {
5306 return true;
5309 $query = core_text::strtolower($query);
5310 $enrols = enrol_get_plugins(false);
5311 foreach ($enrols as $name=>$enrol) {
5312 $localised = get_string('pluginname', 'enrol_'.$name);
5313 if (strpos(core_text::strtolower($name), $query) !== false) {
5314 return true;
5316 if (strpos(core_text::strtolower($localised), $query) !== false) {
5317 return true;
5320 return false;
5324 * Builds the XHTML to display the control
5326 * @param string $data Unused
5327 * @param string $query
5328 * @return string
5330 public function output_html($data, $query='') {
5331 global $CFG, $OUTPUT, $DB, $PAGE;
5333 // Display strings.
5334 $strup = get_string('up');
5335 $strdown = get_string('down');
5336 $strsettings = get_string('settings');
5337 $strenable = get_string('enable');
5338 $strdisable = get_string('disable');
5339 $struninstall = get_string('uninstallplugin', 'core_admin');
5340 $strusage = get_string('enrolusage', 'enrol');
5341 $strversion = get_string('version');
5342 $strtest = get_string('testsettings', 'core_enrol');
5344 $pluginmanager = core_plugin_manager::instance();
5346 $enrols_available = enrol_get_plugins(false);
5347 $active_enrols = enrol_get_plugins(true);
5349 $allenrols = array();
5350 foreach ($active_enrols as $key=>$enrol) {
5351 $allenrols[$key] = true;
5353 foreach ($enrols_available as $key=>$enrol) {
5354 $allenrols[$key] = true;
5356 // Now find all borked plugins and at least allow then to uninstall.
5357 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5358 foreach ($condidates as $candidate) {
5359 if (empty($allenrols[$candidate])) {
5360 $allenrols[$candidate] = true;
5364 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5365 $return .= $OUTPUT->box_start('generalbox enrolsui');
5367 $table = new html_table();
5368 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5369 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5370 $table->id = 'courseenrolmentplugins';
5371 $table->attributes['class'] = 'admintable generaltable';
5372 $table->data = array();
5374 // Iterate through enrol plugins and add to the display table.
5375 $updowncount = 1;
5376 $enrolcount = count($active_enrols);
5377 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5378 $printed = array();
5379 foreach($allenrols as $enrol => $unused) {
5380 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5381 $version = get_config('enrol_'.$enrol, 'version');
5382 if ($version === false) {
5383 $version = '';
5386 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5387 $name = get_string('pluginname', 'enrol_'.$enrol);
5388 } else {
5389 $name = $enrol;
5391 // Usage.
5392 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5393 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5394 $usage = "$ci / $cp";
5396 // Hide/show links.
5397 $class = '';
5398 if (isset($active_enrols[$enrol])) {
5399 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5400 $hideshow = "<a href=\"$aurl\">";
5401 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5402 $enabled = true;
5403 $displayname = $name;
5404 } else if (isset($enrols_available[$enrol])) {
5405 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5406 $hideshow = "<a href=\"$aurl\">";
5407 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5408 $enabled = false;
5409 $displayname = $name;
5410 $class = 'dimmed_text';
5411 } else {
5412 $hideshow = '';
5413 $enabled = false;
5414 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5416 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5417 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5418 } else {
5419 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5422 // Up/down link (only if enrol is enabled).
5423 $updown = '';
5424 if ($enabled) {
5425 if ($updowncount > 1) {
5426 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5427 $updown .= "<a href=\"$aurl\">";
5428 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5429 } else {
5430 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5432 if ($updowncount < $enrolcount) {
5433 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5434 $updown .= "<a href=\"$aurl\">";
5435 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5436 } else {
5437 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5439 ++$updowncount;
5442 // Add settings link.
5443 if (!$version) {
5444 $settings = '';
5445 } else if ($surl = $plugininfo->get_settings_url()) {
5446 $settings = html_writer::link($surl, $strsettings);
5447 } else {
5448 $settings = '';
5451 // Add uninstall info.
5452 $uninstall = '';
5453 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5454 $uninstall = html_writer::link($uninstallurl, $struninstall);
5457 $test = '';
5458 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5459 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5460 $test = html_writer::link($testsettingsurl, $strtest);
5463 // Add a row to the table.
5464 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5465 if ($class) {
5466 $row->attributes['class'] = $class;
5468 $table->data[] = $row;
5470 $printed[$enrol] = true;
5473 $return .= html_writer::table($table);
5474 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5475 $return .= $OUTPUT->box_end();
5476 return highlight($query, $return);
5482 * Blocks manage page
5484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5486 class admin_page_manageblocks extends admin_externalpage {
5488 * Calls parent::__construct with specific arguments
5490 public function __construct() {
5491 global $CFG;
5492 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5496 * Search for a specific block
5498 * @param string $query The string to search for
5499 * @return array
5501 public function search($query) {
5502 global $CFG, $DB;
5503 if ($result = parent::search($query)) {
5504 return $result;
5507 $found = false;
5508 if ($blocks = $DB->get_records('block')) {
5509 foreach ($blocks as $block) {
5510 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5511 continue;
5513 if (strpos($block->name, $query) !== false) {
5514 $found = true;
5515 break;
5517 $strblockname = get_string('pluginname', 'block_'.$block->name);
5518 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5519 $found = true;
5520 break;
5524 if ($found) {
5525 $result = new stdClass();
5526 $result->page = $this;
5527 $result->settings = array();
5528 return array($this->name => $result);
5529 } else {
5530 return array();
5536 * Message outputs configuration
5538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5540 class admin_page_managemessageoutputs extends admin_externalpage {
5542 * Calls parent::__construct with specific arguments
5544 public function __construct() {
5545 global $CFG;
5546 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5550 * Search for a specific message processor
5552 * @param string $query The string to search for
5553 * @return array
5555 public function search($query) {
5556 global $CFG, $DB;
5557 if ($result = parent::search($query)) {
5558 return $result;
5561 $found = false;
5562 if ($processors = get_message_processors()) {
5563 foreach ($processors as $processor) {
5564 if (!$processor->available) {
5565 continue;
5567 if (strpos($processor->name, $query) !== false) {
5568 $found = true;
5569 break;
5571 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5572 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5573 $found = true;
5574 break;
5578 if ($found) {
5579 $result = new stdClass();
5580 $result->page = $this;
5581 $result->settings = array();
5582 return array($this->name => $result);
5583 } else {
5584 return array();
5590 * Default message outputs configuration
5592 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5594 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5596 * Calls parent::__construct with specific arguments
5598 public function __construct() {
5599 global $CFG;
5600 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5606 * Manage question behaviours page
5608 * @copyright 2011 The Open University
5609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5611 class admin_page_manageqbehaviours extends admin_externalpage {
5613 * Constructor
5615 public function __construct() {
5616 global $CFG;
5617 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5618 new moodle_url('/admin/qbehaviours.php'));
5622 * Search question behaviours for the specified string
5624 * @param string $query The string to search for in question behaviours
5625 * @return array
5627 public function search($query) {
5628 global $CFG;
5629 if ($result = parent::search($query)) {
5630 return $result;
5633 $found = false;
5634 require_once($CFG->dirroot . '/question/engine/lib.php');
5635 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5636 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5637 $query) !== false) {
5638 $found = true;
5639 break;
5642 if ($found) {
5643 $result = new stdClass();
5644 $result->page = $this;
5645 $result->settings = array();
5646 return array($this->name => $result);
5647 } else {
5648 return array();
5655 * Question type manage page
5657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5659 class admin_page_manageqtypes extends admin_externalpage {
5661 * Calls parent::__construct with specific arguments
5663 public function __construct() {
5664 global $CFG;
5665 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5666 new moodle_url('/admin/qtypes.php'));
5670 * Search question types for the specified string
5672 * @param string $query The string to search for in question types
5673 * @return array
5675 public function search($query) {
5676 global $CFG;
5677 if ($result = parent::search($query)) {
5678 return $result;
5681 $found = false;
5682 require_once($CFG->dirroot . '/question/engine/bank.php');
5683 foreach (question_bank::get_all_qtypes() as $qtype) {
5684 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5685 $found = true;
5686 break;
5689 if ($found) {
5690 $result = new stdClass();
5691 $result->page = $this;
5692 $result->settings = array();
5693 return array($this->name => $result);
5694 } else {
5695 return array();
5701 class admin_page_manageportfolios extends admin_externalpage {
5703 * Calls parent::__construct with specific arguments
5705 public function __construct() {
5706 global $CFG;
5707 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5708 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5712 * Searches page for the specified string.
5713 * @param string $query The string to search for
5714 * @return bool True if it is found on this page
5716 public function search($query) {
5717 global $CFG;
5718 if ($result = parent::search($query)) {
5719 return $result;
5722 $found = false;
5723 $portfolios = core_component::get_plugin_list('portfolio');
5724 foreach ($portfolios as $p => $dir) {
5725 if (strpos($p, $query) !== false) {
5726 $found = true;
5727 break;
5730 if (!$found) {
5731 foreach (portfolio_instances(false, false) as $instance) {
5732 $title = $instance->get('name');
5733 if (strpos(core_text::strtolower($title), $query) !== false) {
5734 $found = true;
5735 break;
5740 if ($found) {
5741 $result = new stdClass();
5742 $result->page = $this;
5743 $result->settings = array();
5744 return array($this->name => $result);
5745 } else {
5746 return array();
5752 class admin_page_managerepositories extends admin_externalpage {
5754 * Calls parent::__construct with specific arguments
5756 public function __construct() {
5757 global $CFG;
5758 parent::__construct('managerepositories', get_string('manage',
5759 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5763 * Searches page for the specified string.
5764 * @param string $query The string to search for
5765 * @return bool True if it is found on this page
5767 public function search($query) {
5768 global $CFG;
5769 if ($result = parent::search($query)) {
5770 return $result;
5773 $found = false;
5774 $repositories= core_component::get_plugin_list('repository');
5775 foreach ($repositories as $p => $dir) {
5776 if (strpos($p, $query) !== false) {
5777 $found = true;
5778 break;
5781 if (!$found) {
5782 foreach (repository::get_types() as $instance) {
5783 $title = $instance->get_typename();
5784 if (strpos(core_text::strtolower($title), $query) !== false) {
5785 $found = true;
5786 break;
5791 if ($found) {
5792 $result = new stdClass();
5793 $result->page = $this;
5794 $result->settings = array();
5795 return array($this->name => $result);
5796 } else {
5797 return array();
5804 * Special class for authentication administration.
5806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5808 class admin_setting_manageauths extends admin_setting {
5810 * Calls parent::__construct with specific arguments
5812 public function __construct() {
5813 $this->nosave = true;
5814 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5818 * Always returns true
5820 * @return true
5822 public function get_setting() {
5823 return true;
5827 * Always returns true
5829 * @return true
5831 public function get_defaultsetting() {
5832 return true;
5836 * Always returns '' and doesn't write anything
5838 * @return string Always returns ''
5840 public function write_setting($data) {
5841 // do not write any setting
5842 return '';
5846 * Search to find if Query is related to auth plugin
5848 * @param string $query The string to search for
5849 * @return bool true for related false for not
5851 public function is_related($query) {
5852 if (parent::is_related($query)) {
5853 return true;
5856 $authsavailable = core_component::get_plugin_list('auth');
5857 foreach ($authsavailable as $auth => $dir) {
5858 if (strpos($auth, $query) !== false) {
5859 return true;
5861 $authplugin = get_auth_plugin($auth);
5862 $authtitle = $authplugin->get_title();
5863 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5864 return true;
5867 return false;
5871 * Return XHTML to display control
5873 * @param mixed $data Unused
5874 * @param string $query
5875 * @return string highlight
5877 public function output_html($data, $query='') {
5878 global $CFG, $OUTPUT, $DB;
5880 // display strings
5881 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5882 'settings', 'edit', 'name', 'enable', 'disable',
5883 'up', 'down', 'none', 'users'));
5884 $txt->updown = "$txt->up/$txt->down";
5885 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5886 $txt->testsettings = get_string('testsettings', 'core_auth');
5888 $authsavailable = core_component::get_plugin_list('auth');
5889 get_enabled_auth_plugins(true); // fix the list of enabled auths
5890 if (empty($CFG->auth)) {
5891 $authsenabled = array();
5892 } else {
5893 $authsenabled = explode(',', $CFG->auth);
5896 // construct the display array, with enabled auth plugins at the top, in order
5897 $displayauths = array();
5898 $registrationauths = array();
5899 $registrationauths[''] = $txt->disable;
5900 $authplugins = array();
5901 foreach ($authsenabled as $auth) {
5902 $authplugin = get_auth_plugin($auth);
5903 $authplugins[$auth] = $authplugin;
5904 /// Get the auth title (from core or own auth lang files)
5905 $authtitle = $authplugin->get_title();
5906 /// Apply titles
5907 $displayauths[$auth] = $authtitle;
5908 if ($authplugin->can_signup()) {
5909 $registrationauths[$auth] = $authtitle;
5913 foreach ($authsavailable as $auth => $dir) {
5914 if (array_key_exists($auth, $displayauths)) {
5915 continue; //already in the list
5917 $authplugin = get_auth_plugin($auth);
5918 $authplugins[$auth] = $authplugin;
5919 /// Get the auth title (from core or own auth lang files)
5920 $authtitle = $authplugin->get_title();
5921 /// Apply titles
5922 $displayauths[$auth] = $authtitle;
5923 if ($authplugin->can_signup()) {
5924 $registrationauths[$auth] = $authtitle;
5928 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5929 $return .= $OUTPUT->box_start('generalbox authsui');
5931 $table = new html_table();
5932 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
5933 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5934 $table->data = array();
5935 $table->attributes['class'] = 'admintable generaltable';
5936 $table->id = 'manageauthtable';
5938 //add always enabled plugins first
5939 $displayname = $displayauths['manual'];
5940 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5941 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5942 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
5943 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5944 $displayname = $displayauths['nologin'];
5945 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5946 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
5947 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
5950 // iterate through auth plugins and add to the display table
5951 $updowncount = 1;
5952 $authcount = count($authsenabled);
5953 $url = "auth.php?sesskey=" . sesskey();
5954 foreach ($displayauths as $auth => $name) {
5955 if ($auth == 'manual' or $auth == 'nologin') {
5956 continue;
5958 $class = '';
5959 // hide/show link
5960 if (in_array($auth, $authsenabled)) {
5961 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5962 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5963 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5964 $enabled = true;
5965 $displayname = $name;
5967 else {
5968 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5969 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5970 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5971 $enabled = false;
5972 $displayname = $name;
5973 $class = 'dimmed_text';
5976 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
5978 // up/down link (only if auth is enabled)
5979 $updown = '';
5980 if ($enabled) {
5981 if ($updowncount > 1) {
5982 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5983 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5985 else {
5986 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5988 if ($updowncount < $authcount) {
5989 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5990 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5992 else {
5993 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5995 ++ $updowncount;
5998 // settings link
5999 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6000 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6001 } else {
6002 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6005 // Uninstall link.
6006 $uninstall = '';
6007 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6008 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6011 $test = '';
6012 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6013 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6014 $test = html_writer::link($testurl, $txt->testsettings);
6017 // Add a row to the table.
6018 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6019 if ($class) {
6020 $row->attributes['class'] = $class;
6022 $table->data[] = $row;
6024 $return .= html_writer::table($table);
6025 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6026 $return .= $OUTPUT->box_end();
6027 return highlight($query, $return);
6033 * Special class for authentication administration.
6035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6037 class admin_setting_manageeditors extends admin_setting {
6039 * Calls parent::__construct with specific arguments
6041 public function __construct() {
6042 $this->nosave = true;
6043 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6047 * Always returns true, does nothing
6049 * @return true
6051 public function get_setting() {
6052 return true;
6056 * Always returns true, does nothing
6058 * @return true
6060 public function get_defaultsetting() {
6061 return true;
6065 * Always returns '', does not write anything
6067 * @return string Always returns ''
6069 public function write_setting($data) {
6070 // do not write any setting
6071 return '';
6075 * Checks if $query is one of the available editors
6077 * @param string $query The string to search for
6078 * @return bool Returns true if found, false if not
6080 public function is_related($query) {
6081 if (parent::is_related($query)) {
6082 return true;
6085 $editors_available = editors_get_available();
6086 foreach ($editors_available as $editor=>$editorstr) {
6087 if (strpos($editor, $query) !== false) {
6088 return true;
6090 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6091 return true;
6094 return false;
6098 * Builds the XHTML to display the control
6100 * @param string $data Unused
6101 * @param string $query
6102 * @return string
6104 public function output_html($data, $query='') {
6105 global $CFG, $OUTPUT;
6107 // display strings
6108 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6109 'up', 'down', 'none'));
6110 $struninstall = get_string('uninstallplugin', 'core_admin');
6112 $txt->updown = "$txt->up/$txt->down";
6114 $editors_available = editors_get_available();
6115 $active_editors = explode(',', $CFG->texteditors);
6117 $active_editors = array_reverse($active_editors);
6118 foreach ($active_editors as $key=>$editor) {
6119 if (empty($editors_available[$editor])) {
6120 unset($active_editors[$key]);
6121 } else {
6122 $name = $editors_available[$editor];
6123 unset($editors_available[$editor]);
6124 $editors_available[$editor] = $name;
6127 if (empty($active_editors)) {
6128 //$active_editors = array('textarea');
6130 $editors_available = array_reverse($editors_available, true);
6131 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6132 $return .= $OUTPUT->box_start('generalbox editorsui');
6134 $table = new html_table();
6135 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6136 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6137 $table->id = 'editormanagement';
6138 $table->attributes['class'] = 'admintable generaltable';
6139 $table->data = array();
6141 // iterate through auth plugins and add to the display table
6142 $updowncount = 1;
6143 $editorcount = count($active_editors);
6144 $url = "editors.php?sesskey=" . sesskey();
6145 foreach ($editors_available as $editor => $name) {
6146 // hide/show link
6147 $class = '';
6148 if (in_array($editor, $active_editors)) {
6149 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6150 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6151 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6152 $enabled = true;
6153 $displayname = $name;
6155 else {
6156 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6157 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6158 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6159 $enabled = false;
6160 $displayname = $name;
6161 $class = 'dimmed_text';
6164 // up/down link (only if auth is enabled)
6165 $updown = '';
6166 if ($enabled) {
6167 if ($updowncount > 1) {
6168 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6169 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6171 else {
6172 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6174 if ($updowncount < $editorcount) {
6175 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6176 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6178 else {
6179 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6181 ++ $updowncount;
6184 // settings link
6185 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6186 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6187 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6188 } else {
6189 $settings = '';
6192 $uninstall = '';
6193 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6194 $uninstall = html_writer::link($uninstallurl, $struninstall);
6197 // Add a row to the table.
6198 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6199 if ($class) {
6200 $row->attributes['class'] = $class;
6202 $table->data[] = $row;
6204 $return .= html_writer::table($table);
6205 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6206 $return .= $OUTPUT->box_end();
6207 return highlight($query, $return);
6213 * Special class for license administration.
6215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6217 class admin_setting_managelicenses extends admin_setting {
6219 * Calls parent::__construct with specific arguments
6221 public function __construct() {
6222 $this->nosave = true;
6223 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6227 * Always returns true, does nothing
6229 * @return true
6231 public function get_setting() {
6232 return true;
6236 * Always returns true, does nothing
6238 * @return true
6240 public function get_defaultsetting() {
6241 return true;
6245 * Always returns '', does not write anything
6247 * @return string Always returns ''
6249 public function write_setting($data) {
6250 // do not write any setting
6251 return '';
6255 * Builds the XHTML to display the control
6257 * @param string $data Unused
6258 * @param string $query
6259 * @return string
6261 public function output_html($data, $query='') {
6262 global $CFG, $OUTPUT;
6263 require_once($CFG->libdir . '/licenselib.php');
6264 $url = "licenses.php?sesskey=" . sesskey();
6266 // display strings
6267 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6268 $licenses = license_manager::get_licenses();
6270 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6272 $return .= $OUTPUT->box_start('generalbox editorsui');
6274 $table = new html_table();
6275 $table->head = array($txt->name, $txt->enable);
6276 $table->colclasses = array('leftalign', 'centeralign');
6277 $table->id = 'availablelicenses';
6278 $table->attributes['class'] = 'admintable generaltable';
6279 $table->data = array();
6281 foreach ($licenses as $value) {
6282 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6284 if ($value->enabled == 1) {
6285 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6286 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6287 } else {
6288 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6289 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6292 if ($value->shortname == $CFG->sitedefaultlicense) {
6293 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6294 $hideshow = '';
6297 $enabled = true;
6299 $table->data[] =array($displayname, $hideshow);
6301 $return .= html_writer::table($table);
6302 $return .= $OUTPUT->box_end();
6303 return highlight($query, $return);
6308 * Course formats manager. Allows to enable/disable formats and jump to settings
6310 class admin_setting_manageformats extends admin_setting {
6313 * Calls parent::__construct with specific arguments
6315 public function __construct() {
6316 $this->nosave = true;
6317 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6321 * Always returns true
6323 * @return true
6325 public function get_setting() {
6326 return true;
6330 * Always returns true
6332 * @return true
6334 public function get_defaultsetting() {
6335 return true;
6339 * Always returns '' and doesn't write anything
6341 * @param mixed $data string or array, must not be NULL
6342 * @return string Always returns ''
6344 public function write_setting($data) {
6345 // do not write any setting
6346 return '';
6350 * Search to find if Query is related to format plugin
6352 * @param string $query The string to search for
6353 * @return bool true for related false for not
6355 public function is_related($query) {
6356 if (parent::is_related($query)) {
6357 return true;
6359 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6360 foreach ($formats as $format) {
6361 if (strpos($format->component, $query) !== false ||
6362 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6363 return true;
6366 return false;
6370 * Return XHTML to display control
6372 * @param mixed $data Unused
6373 * @param string $query
6374 * @return string highlight
6376 public function output_html($data, $query='') {
6377 global $CFG, $OUTPUT;
6378 $return = '';
6379 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6380 $return .= $OUTPUT->box_start('generalbox formatsui');
6382 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6384 // display strings
6385 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6386 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6387 $txt->updown = "$txt->up/$txt->down";
6389 $table = new html_table();
6390 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6391 $table->align = array('left', 'center', 'center', 'center', 'center');
6392 $table->attributes['class'] = 'manageformattable generaltable admintable';
6393 $table->data = array();
6395 $cnt = 0;
6396 $defaultformat = get_config('moodlecourse', 'format');
6397 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6398 foreach ($formats as $format) {
6399 $url = new moodle_url('/admin/courseformats.php',
6400 array('sesskey' => sesskey(), 'format' => $format->name));
6401 $isdefault = '';
6402 $class = '';
6403 if ($format->is_enabled()) {
6404 $strformatname = $format->displayname;
6405 if ($defaultformat === $format->name) {
6406 $hideshow = $txt->default;
6407 } else {
6408 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6409 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6411 } else {
6412 $strformatname = $format->displayname;
6413 $class = 'dimmed_text';
6414 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6415 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6417 $updown = '';
6418 if ($cnt) {
6419 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6420 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6421 } else {
6422 $updown .= $spacer;
6424 if ($cnt < count($formats) - 1) {
6425 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6426 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6427 } else {
6428 $updown .= $spacer;
6430 $cnt++;
6431 $settings = '';
6432 if ($format->get_settings_url()) {
6433 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6435 $uninstall = '';
6436 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6437 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6439 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6440 if ($class) {
6441 $row->attributes['class'] = $class;
6443 $table->data[] = $row;
6445 $return .= html_writer::table($table);
6446 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6447 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6448 $return .= $OUTPUT->box_end();
6449 return highlight($query, $return);
6454 * Special class for filter administration.
6456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6458 class admin_page_managefilters extends admin_externalpage {
6460 * Calls parent::__construct with specific arguments
6462 public function __construct() {
6463 global $CFG;
6464 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6468 * Searches all installed filters for specified filter
6470 * @param string $query The filter(string) to search for
6471 * @param string $query
6473 public function search($query) {
6474 global $CFG;
6475 if ($result = parent::search($query)) {
6476 return $result;
6479 $found = false;
6480 $filternames = filter_get_all_installed();
6481 foreach ($filternames as $path => $strfiltername) {
6482 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6483 $found = true;
6484 break;
6486 if (strpos($path, $query) !== false) {
6487 $found = true;
6488 break;
6492 if ($found) {
6493 $result = new stdClass;
6494 $result->page = $this;
6495 $result->settings = array();
6496 return array($this->name => $result);
6497 } else {
6498 return array();
6505 * Initialise admin page - this function does require login and permission
6506 * checks specified in page definition.
6508 * This function must be called on each admin page before other code.
6510 * @global moodle_page $PAGE
6512 * @param string $section name of page
6513 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6514 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6515 * added to the turn blocks editing on/off form, so this page reloads correctly.
6516 * @param string $actualurl if the actual page being viewed is not the normal one for this
6517 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6518 * @param array $options Additional options that can be specified for page setup.
6519 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6521 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6522 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6524 $PAGE->set_context(null); // hack - set context to something, by default to system context
6526 $site = get_site();
6527 require_login();
6529 if (!empty($options['pagelayout'])) {
6530 // A specific page layout has been requested.
6531 $PAGE->set_pagelayout($options['pagelayout']);
6532 } else if ($section === 'upgradesettings') {
6533 $PAGE->set_pagelayout('maintenance');
6534 } else {
6535 $PAGE->set_pagelayout('admin');
6538 $adminroot = admin_get_root(false, false); // settings not required for external pages
6539 $extpage = $adminroot->locate($section, true);
6541 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6542 // The requested section isn't in the admin tree
6543 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6544 if (!has_capability('moodle/site:config', context_system::instance())) {
6545 // The requested section could depend on a different capability
6546 // but most likely the user has inadequate capabilities
6547 print_error('accessdenied', 'admin');
6548 } else {
6549 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6553 // this eliminates our need to authenticate on the actual pages
6554 if (!$extpage->check_access()) {
6555 print_error('accessdenied', 'admin');
6556 die;
6559 navigation_node::require_admin_tree();
6561 // $PAGE->set_extra_button($extrabutton); TODO
6563 if (!$actualurl) {
6564 $actualurl = $extpage->url;
6567 $PAGE->set_url($actualurl, $extraurlparams);
6568 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6569 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6572 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6573 // During initial install.
6574 $strinstallation = get_string('installation', 'install');
6575 $strsettings = get_string('settings');
6576 $PAGE->navbar->add($strsettings);
6577 $PAGE->set_title($strinstallation);
6578 $PAGE->set_heading($strinstallation);
6579 $PAGE->set_cacheable(false);
6580 return;
6583 // Locate the current item on the navigation and make it active when found.
6584 $path = $extpage->path;
6585 $node = $PAGE->settingsnav;
6586 while ($node && count($path) > 0) {
6587 $node = $node->get(array_pop($path));
6589 if ($node) {
6590 $node->make_active();
6593 // Normal case.
6594 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6595 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6596 $USER->editing = $adminediting;
6599 $visiblepathtosection = array_reverse($extpage->visiblepath);
6601 if ($PAGE->user_allowed_editing()) {
6602 if ($PAGE->user_is_editing()) {
6603 $caption = get_string('blockseditoff');
6604 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6605 } else {
6606 $caption = get_string('blocksediton');
6607 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6609 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6612 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6613 $PAGE->set_heading($SITE->fullname);
6615 // prevent caching in nav block
6616 $PAGE->navigation->clear_cache();
6620 * Returns the reference to admin tree root
6622 * @return object admin_root object
6624 function admin_get_root($reload=false, $requirefulltree=true) {
6625 global $CFG, $DB, $OUTPUT;
6627 static $ADMIN = NULL;
6629 if (is_null($ADMIN)) {
6630 // create the admin tree!
6631 $ADMIN = new admin_root($requirefulltree);
6634 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6635 $ADMIN->purge_children($requirefulltree);
6638 if (!$ADMIN->loaded) {
6639 // we process this file first to create categories first and in correct order
6640 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6642 // now we process all other files in admin/settings to build the admin tree
6643 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6644 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6645 continue;
6647 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6648 // plugins are loaded last - they may insert pages anywhere
6649 continue;
6651 require($file);
6653 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6655 $ADMIN->loaded = true;
6658 return $ADMIN;
6661 /// settings utility functions
6664 * This function applies default settings.
6666 * @param object $node, NULL means complete tree, null by default
6667 * @param bool $unconditional if true overrides all values with defaults, null buy default
6669 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6670 global $CFG;
6672 if (is_null($node)) {
6673 core_plugin_manager::reset_caches();
6674 $node = admin_get_root(true, true);
6677 if ($node instanceof admin_category) {
6678 $entries = array_keys($node->children);
6679 foreach ($entries as $entry) {
6680 admin_apply_default_settings($node->children[$entry], $unconditional);
6683 } else if ($node instanceof admin_settingpage) {
6684 foreach ($node->settings as $setting) {
6685 if (!$unconditional and !is_null($setting->get_setting())) {
6686 //do not override existing defaults
6687 continue;
6689 $defaultsetting = $setting->get_defaultsetting();
6690 if (is_null($defaultsetting)) {
6691 // no value yet - default maybe applied after admin user creation or in upgradesettings
6692 continue;
6694 $setting->write_setting($defaultsetting);
6695 $setting->write_setting_flags(null);
6698 // Just in case somebody modifies the list of active plugins directly.
6699 core_plugin_manager::reset_caches();
6703 * Store changed settings, this function updates the errors variable in $ADMIN
6705 * @param object $formdata from form
6706 * @return int number of changed settings
6708 function admin_write_settings($formdata) {
6709 global $CFG, $SITE, $DB;
6711 $olddbsessions = !empty($CFG->dbsessions);
6712 $formdata = (array)$formdata;
6714 $data = array();
6715 foreach ($formdata as $fullname=>$value) {
6716 if (strpos($fullname, 's_') !== 0) {
6717 continue; // not a config value
6719 $data[$fullname] = $value;
6722 $adminroot = admin_get_root();
6723 $settings = admin_find_write_settings($adminroot, $data);
6725 $count = 0;
6726 foreach ($settings as $fullname=>$setting) {
6727 /** @var $setting admin_setting */
6728 $original = $setting->get_setting();
6729 $error = $setting->write_setting($data[$fullname]);
6730 if ($error !== '') {
6731 $adminroot->errors[$fullname] = new stdClass();
6732 $adminroot->errors[$fullname]->data = $data[$fullname];
6733 $adminroot->errors[$fullname]->id = $setting->get_id();
6734 $adminroot->errors[$fullname]->error = $error;
6735 } else {
6736 $setting->write_setting_flags($data);
6738 if ($setting->post_write_settings($original)) {
6739 $count++;
6743 if ($olddbsessions != !empty($CFG->dbsessions)) {
6744 require_logout();
6747 // Now update $SITE - just update the fields, in case other people have a
6748 // a reference to it (e.g. $PAGE, $COURSE).
6749 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6750 foreach (get_object_vars($newsite) as $field => $value) {
6751 $SITE->$field = $value;
6754 // now reload all settings - some of them might depend on the changed
6755 admin_get_root(true);
6756 return $count;
6760 * Internal recursive function - finds all settings from submitted form
6762 * @param object $node Instance of admin_category, or admin_settingpage
6763 * @param array $data
6764 * @return array
6766 function admin_find_write_settings($node, $data) {
6767 $return = array();
6769 if (empty($data)) {
6770 return $return;
6773 if ($node instanceof admin_category) {
6774 $entries = array_keys($node->children);
6775 foreach ($entries as $entry) {
6776 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6779 } else if ($node instanceof admin_settingpage) {
6780 foreach ($node->settings as $setting) {
6781 $fullname = $setting->get_full_name();
6782 if (array_key_exists($fullname, $data)) {
6783 $return[$fullname] = $setting;
6789 return $return;
6793 * Internal function - prints the search results
6795 * @param string $query String to search for
6796 * @return string empty or XHTML
6798 function admin_search_settings_html($query) {
6799 global $CFG, $OUTPUT;
6801 if (core_text::strlen($query) < 2) {
6802 return '';
6804 $query = core_text::strtolower($query);
6806 $adminroot = admin_get_root();
6807 $findings = $adminroot->search($query);
6808 $return = '';
6809 $savebutton = false;
6811 foreach ($findings as $found) {
6812 $page = $found->page;
6813 $settings = $found->settings;
6814 if ($page->is_hidden()) {
6815 // hidden pages are not displayed in search results
6816 continue;
6818 if ($page instanceof admin_externalpage) {
6819 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6820 } else if ($page instanceof admin_settingpage) {
6821 $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');
6822 } else {
6823 continue;
6825 if (!empty($settings)) {
6826 $return .= '<fieldset class="adminsettings">'."\n";
6827 foreach ($settings as $setting) {
6828 if (empty($setting->nosave)) {
6829 $savebutton = true;
6831 $return .= '<div class="clearer"><!-- --></div>'."\n";
6832 $fullname = $setting->get_full_name();
6833 if (array_key_exists($fullname, $adminroot->errors)) {
6834 $data = $adminroot->errors[$fullname]->data;
6835 } else {
6836 $data = $setting->get_setting();
6837 // do not use defaults if settings not available - upgradesettings handles the defaults!
6839 $return .= $setting->output_html($data, $query);
6841 $return .= '</fieldset>';
6845 if ($savebutton) {
6846 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6849 return $return;
6853 * Internal function - returns arrays of html pages with uninitialised settings
6855 * @param object $node Instance of admin_category or admin_settingpage
6856 * @return array
6858 function admin_output_new_settings_by_page($node) {
6859 global $OUTPUT;
6860 $return = array();
6862 if ($node instanceof admin_category) {
6863 $entries = array_keys($node->children);
6864 foreach ($entries as $entry) {
6865 $return += admin_output_new_settings_by_page($node->children[$entry]);
6868 } else if ($node instanceof admin_settingpage) {
6869 $newsettings = array();
6870 foreach ($node->settings as $setting) {
6871 if (is_null($setting->get_setting())) {
6872 $newsettings[] = $setting;
6875 if (count($newsettings) > 0) {
6876 $adminroot = admin_get_root();
6877 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6878 $page .= '<fieldset class="adminsettings">'."\n";
6879 foreach ($newsettings as $setting) {
6880 $fullname = $setting->get_full_name();
6881 if (array_key_exists($fullname, $adminroot->errors)) {
6882 $data = $adminroot->errors[$fullname]->data;
6883 } else {
6884 $data = $setting->get_setting();
6885 if (is_null($data)) {
6886 $data = $setting->get_defaultsetting();
6889 $page .= '<div class="clearer"><!-- --></div>'."\n";
6890 $page .= $setting->output_html($data);
6892 $page .= '</fieldset>';
6893 $return[$node->name] = $page;
6897 return $return;
6901 * Format admin settings
6903 * @param object $setting
6904 * @param string $title label element
6905 * @param string $form form fragment, html code - not highlighted automatically
6906 * @param string $description
6907 * @param bool $label link label to id, true by default
6908 * @param string $warning warning text
6909 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6910 * @param string $query search query to be highlighted
6911 * @return string XHTML
6913 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6914 global $CFG;
6916 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6917 $fullname = $setting->get_full_name();
6919 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6920 if ($label) {
6921 $labelfor = 'for = "'.$setting->get_id().'"';
6922 } else {
6923 $labelfor = '';
6925 $form .= $setting->output_setting_flags();
6927 $override = '';
6928 if (empty($setting->plugin)) {
6929 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6930 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6932 } else {
6933 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6934 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6938 if ($warning !== '') {
6939 $warning = '<div class="form-warning">'.$warning.'</div>';
6942 $defaults = array();
6943 if (!is_null($defaultinfo)) {
6944 if ($defaultinfo === '') {
6945 $defaultinfo = get_string('emptysettingvalue', 'admin');
6947 $defaults[] = $defaultinfo;
6950 $setting->get_setting_flag_defaults($defaults);
6952 if (!empty($defaults)) {
6953 $defaultinfo = implode(', ', $defaults);
6954 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6955 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6959 $adminroot = admin_get_root();
6960 $error = '';
6961 if (array_key_exists($fullname, $adminroot->errors)) {
6962 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
6965 $str = '
6966 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6967 <div class="form-label">
6968 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6969 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6970 </div>
6971 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
6972 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6973 </div>';
6975 return $str;
6979 * Based on find_new_settings{@link ()} in upgradesettings.php
6980 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6982 * @param object $node Instance of admin_category, or admin_settingpage
6983 * @return boolean true if any settings haven't been initialised, false if they all have
6985 function any_new_admin_settings($node) {
6987 if ($node instanceof admin_category) {
6988 $entries = array_keys($node->children);
6989 foreach ($entries as $entry) {
6990 if (any_new_admin_settings($node->children[$entry])) {
6991 return true;
6995 } else if ($node instanceof admin_settingpage) {
6996 foreach ($node->settings as $setting) {
6997 if ($setting->get_setting() === NULL) {
6998 return true;
7003 return false;
7007 * Moved from admin/replace.php so that we can use this in cron
7009 * @param string $search string to look for
7010 * @param string $replace string to replace
7011 * @return bool success or fail
7013 function db_replace($search, $replace) {
7014 global $DB, $CFG, $OUTPUT;
7016 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7017 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7018 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7019 'block_instances', '');
7021 // Turn off time limits, sometimes upgrades can be slow.
7022 core_php_time_limit::raise();
7024 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7025 return false;
7027 foreach ($tables as $table) {
7029 if (in_array($table, $skiptables)) { // Don't process these
7030 continue;
7033 if ($columns = $DB->get_columns($table)) {
7034 $DB->set_debug(true);
7035 foreach ($columns as $column) {
7036 $DB->replace_all_text($table, $column, $search, $replace);
7038 $DB->set_debug(false);
7042 // delete modinfo caches
7043 rebuild_course_cache(0, true);
7045 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7046 $blocks = core_component::get_plugin_list('block');
7047 foreach ($blocks as $blockname=>$fullblock) {
7048 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7049 continue;
7052 if (!is_readable($fullblock.'/lib.php')) {
7053 continue;
7056 $function = 'block_'.$blockname.'_global_db_replace';
7057 include_once($fullblock.'/lib.php');
7058 if (!function_exists($function)) {
7059 continue;
7062 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7063 $function($search, $replace);
7064 echo $OUTPUT->notification("...finished", 'notifysuccess');
7067 purge_all_caches();
7069 return true;
7073 * Manage repository settings
7075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7077 class admin_setting_managerepository extends admin_setting {
7078 /** @var string */
7079 private $baseurl;
7082 * calls parent::__construct with specific arguments
7084 public function __construct() {
7085 global $CFG;
7086 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7087 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7091 * Always returns true, does nothing
7093 * @return true
7095 public function get_setting() {
7096 return true;
7100 * Always returns true does nothing
7102 * @return true
7104 public function get_defaultsetting() {
7105 return true;
7109 * Always returns s_managerepository
7111 * @return string Always return 's_managerepository'
7113 public function get_full_name() {
7114 return 's_managerepository';
7118 * Always returns '' doesn't do anything
7120 public function write_setting($data) {
7121 $url = $this->baseurl . '&amp;new=' . $data;
7122 return '';
7123 // TODO
7124 // Should not use redirect and exit here
7125 // Find a better way to do this.
7126 // redirect($url);
7127 // exit;
7131 * Searches repository plugins for one that matches $query
7133 * @param string $query The string to search for
7134 * @return bool true if found, false if not
7136 public function is_related($query) {
7137 if (parent::is_related($query)) {
7138 return true;
7141 $repositories= core_component::get_plugin_list('repository');
7142 foreach ($repositories as $p => $dir) {
7143 if (strpos($p, $query) !== false) {
7144 return true;
7147 foreach (repository::get_types() as $instance) {
7148 $title = $instance->get_typename();
7149 if (strpos(core_text::strtolower($title), $query) !== false) {
7150 return true;
7153 return false;
7157 * Helper function that generates a moodle_url object
7158 * relevant to the repository
7161 function repository_action_url($repository) {
7162 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7166 * Builds XHTML to display the control
7168 * @param string $data Unused
7169 * @param string $query
7170 * @return string XHTML
7172 public function output_html($data, $query='') {
7173 global $CFG, $USER, $OUTPUT;
7175 // Get strings that are used
7176 $strshow = get_string('on', 'repository');
7177 $strhide = get_string('off', 'repository');
7178 $strdelete = get_string('disabled', 'repository');
7180 $actionchoicesforexisting = array(
7181 'show' => $strshow,
7182 'hide' => $strhide,
7183 'delete' => $strdelete
7186 $actionchoicesfornew = array(
7187 'newon' => $strshow,
7188 'newoff' => $strhide,
7189 'delete' => $strdelete
7192 $return = '';
7193 $return .= $OUTPUT->box_start('generalbox');
7195 // Set strings that are used multiple times
7196 $settingsstr = get_string('settings');
7197 $disablestr = get_string('disable');
7199 // Table to list plug-ins
7200 $table = new html_table();
7201 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7202 $table->align = array('left', 'center', 'center', 'center', 'center');
7203 $table->data = array();
7205 // Get list of used plug-ins
7206 $repositorytypes = repository::get_types();
7207 if (!empty($repositorytypes)) {
7208 // Array to store plugins being used
7209 $alreadyplugins = array();
7210 $totalrepositorytypes = count($repositorytypes);
7211 $updowncount = 1;
7212 foreach ($repositorytypes as $i) {
7213 $settings = '';
7214 $typename = $i->get_typename();
7215 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7216 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7217 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7219 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7220 // Calculate number of instances in order to display them for the Moodle administrator
7221 if (!empty($instanceoptionnames)) {
7222 $params = array();
7223 $params['context'] = array(context_system::instance());
7224 $params['onlyvisible'] = false;
7225 $params['type'] = $typename;
7226 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7227 // site instances
7228 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7229 $params['context'] = array();
7230 $instances = repository::static_function($typename, 'get_instances', $params);
7231 $courseinstances = array();
7232 $userinstances = array();
7234 foreach ($instances as $instance) {
7235 $repocontext = context::instance_by_id($instance->instance->contextid);
7236 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7237 $courseinstances[] = $instance;
7238 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7239 $userinstances[] = $instance;
7242 // course instances
7243 $instancenumber = count($courseinstances);
7244 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7246 // user private instances
7247 $instancenumber = count($userinstances);
7248 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7249 } else {
7250 $admininstancenumbertext = "";
7251 $courseinstancenumbertext = "";
7252 $userinstancenumbertext = "";
7255 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7257 $settings .= $OUTPUT->container_start('mdl-left');
7258 $settings .= '<br/>';
7259 $settings .= $admininstancenumbertext;
7260 $settings .= '<br/>';
7261 $settings .= $courseinstancenumbertext;
7262 $settings .= '<br/>';
7263 $settings .= $userinstancenumbertext;
7264 $settings .= $OUTPUT->container_end();
7266 // Get the current visibility
7267 if ($i->get_visible()) {
7268 $currentaction = 'show';
7269 } else {
7270 $currentaction = 'hide';
7273 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7275 // Display up/down link
7276 $updown = '';
7277 // Should be done with CSS instead.
7278 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7280 if ($updowncount > 1) {
7281 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7282 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7284 else {
7285 $updown .= $spacer;
7287 if ($updowncount < $totalrepositorytypes) {
7288 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7289 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7291 else {
7292 $updown .= $spacer;
7295 $updowncount++;
7297 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7299 if (!in_array($typename, $alreadyplugins)) {
7300 $alreadyplugins[] = $typename;
7305 // Get all the plugins that exist on disk
7306 $plugins = core_component::get_plugin_list('repository');
7307 if (!empty($plugins)) {
7308 foreach ($plugins as $plugin => $dir) {
7309 // Check that it has not already been listed
7310 if (!in_array($plugin, $alreadyplugins)) {
7311 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7312 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7317 $return .= html_writer::table($table);
7318 $return .= $OUTPUT->box_end();
7319 return highlight($query, $return);
7324 * Special checkbox for enable mobile web service
7325 * If enable then we store the service id of the mobile service into config table
7326 * If disable then we unstore the service id from the config table
7328 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7330 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7331 private $xmlrpcuse;
7332 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7333 private $restuse;
7336 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7338 * @return boolean
7340 private function is_protocol_cap_allowed() {
7341 global $DB, $CFG;
7343 // We keep xmlrpc enabled for backward compatibility.
7344 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7345 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7346 $params = array();
7347 $params['permission'] = CAP_ALLOW;
7348 $params['roleid'] = $CFG->defaultuserroleid;
7349 $params['capability'] = 'webservice/xmlrpc:use';
7350 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7353 // If the $this->restuse variable is not set, it needs to be set.
7354 if (empty($this->restuse) and $this->restuse!==false) {
7355 $params = array();
7356 $params['permission'] = CAP_ALLOW;
7357 $params['roleid'] = $CFG->defaultuserroleid;
7358 $params['capability'] = 'webservice/rest:use';
7359 $this->restuse = $DB->record_exists('role_capabilities', $params);
7362 return ($this->xmlrpcuse && $this->restuse);
7366 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7367 * @param type $status true to allow, false to not set
7369 private function set_protocol_cap($status) {
7370 global $CFG;
7371 if ($status and !$this->is_protocol_cap_allowed()) {
7372 //need to allow the cap
7373 $permission = CAP_ALLOW;
7374 $assign = true;
7375 } else if (!$status and $this->is_protocol_cap_allowed()){
7376 //need to disallow the cap
7377 $permission = CAP_INHERIT;
7378 $assign = true;
7380 if (!empty($assign)) {
7381 $systemcontext = context_system::instance();
7382 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7383 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7388 * Builds XHTML to display the control.
7389 * The main purpose of this overloading is to display a warning when https
7390 * is not supported by the server
7391 * @param string $data Unused
7392 * @param string $query
7393 * @return string XHTML
7395 public function output_html($data, $query='') {
7396 global $CFG, $OUTPUT;
7397 $html = parent::output_html($data, $query);
7399 if ((string)$data === $this->yes) {
7400 require_once($CFG->dirroot . "/lib/filelib.php");
7401 $curl = new curl();
7402 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7403 $curl->head($httpswwwroot . "/login/index.php");
7404 $info = $curl->get_info();
7405 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7406 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7410 return $html;
7414 * Retrieves the current setting using the objects name
7416 * @return string
7418 public function get_setting() {
7419 global $CFG;
7421 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7422 // Or if web services aren't enabled this can't be,
7423 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7424 return 0;
7427 require_once($CFG->dirroot . '/webservice/lib.php');
7428 $webservicemanager = new webservice();
7429 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7430 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7431 return $this->config_read($this->name); //same as returning 1
7432 } else {
7433 return 0;
7438 * Save the selected setting
7440 * @param string $data The selected site
7441 * @return string empty string or error message
7443 public function write_setting($data) {
7444 global $DB, $CFG;
7446 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7447 if (empty($CFG->defaultuserroleid)) {
7448 return '';
7451 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7453 require_once($CFG->dirroot . '/webservice/lib.php');
7454 $webservicemanager = new webservice();
7456 $updateprotocol = false;
7457 if ((string)$data === $this->yes) {
7458 //code run when enable mobile web service
7459 //enable web service systeme if necessary
7460 set_config('enablewebservices', true);
7462 //enable mobile service
7463 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7464 $mobileservice->enabled = 1;
7465 $webservicemanager->update_external_service($mobileservice);
7467 //enable xml-rpc server
7468 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7470 if (!in_array('xmlrpc', $activeprotocols)) {
7471 $activeprotocols[] = 'xmlrpc';
7472 $updateprotocol = true;
7475 if (!in_array('rest', $activeprotocols)) {
7476 $activeprotocols[] = 'rest';
7477 $updateprotocol = true;
7480 if ($updateprotocol) {
7481 set_config('webserviceprotocols', implode(',', $activeprotocols));
7484 //allow xml-rpc:use capability for authenticated user
7485 $this->set_protocol_cap(true);
7487 } else {
7488 //disable web service system if no other services are enabled
7489 $otherenabledservices = $DB->get_records_select('external_services',
7490 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7491 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7492 if (empty($otherenabledservices)) {
7493 set_config('enablewebservices', false);
7495 //also disable xml-rpc server
7496 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7497 $protocolkey = array_search('xmlrpc', $activeprotocols);
7498 if ($protocolkey !== false) {
7499 unset($activeprotocols[$protocolkey]);
7500 $updateprotocol = true;
7503 $protocolkey = array_search('rest', $activeprotocols);
7504 if ($protocolkey !== false) {
7505 unset($activeprotocols[$protocolkey]);
7506 $updateprotocol = true;
7509 if ($updateprotocol) {
7510 set_config('webserviceprotocols', implode(',', $activeprotocols));
7513 //disallow xml-rpc:use capability for authenticated user
7514 $this->set_protocol_cap(false);
7517 //disable the mobile service
7518 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7519 $mobileservice->enabled = 0;
7520 $webservicemanager->update_external_service($mobileservice);
7523 return (parent::write_setting($data));
7528 * Special class for management of external services
7530 * @author Petr Skoda (skodak)
7532 class admin_setting_manageexternalservices extends admin_setting {
7534 * Calls parent::__construct with specific arguments
7536 public function __construct() {
7537 $this->nosave = true;
7538 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7542 * Always returns true, does nothing
7544 * @return true
7546 public function get_setting() {
7547 return true;
7551 * Always returns true, does nothing
7553 * @return true
7555 public function get_defaultsetting() {
7556 return true;
7560 * Always returns '', does not write anything
7562 * @return string Always returns ''
7564 public function write_setting($data) {
7565 // do not write any setting
7566 return '';
7570 * Checks if $query is one of the available external services
7572 * @param string $query The string to search for
7573 * @return bool Returns true if found, false if not
7575 public function is_related($query) {
7576 global $DB;
7578 if (parent::is_related($query)) {
7579 return true;
7582 $services = $DB->get_records('external_services', array(), 'id, name');
7583 foreach ($services as $service) {
7584 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7585 return true;
7588 return false;
7592 * Builds the XHTML to display the control
7594 * @param string $data Unused
7595 * @param string $query
7596 * @return string
7598 public function output_html($data, $query='') {
7599 global $CFG, $OUTPUT, $DB;
7601 // display strings
7602 $stradministration = get_string('administration');
7603 $stredit = get_string('edit');
7604 $strservice = get_string('externalservice', 'webservice');
7605 $strdelete = get_string('delete');
7606 $strplugin = get_string('plugin', 'admin');
7607 $stradd = get_string('add');
7608 $strfunctions = get_string('functions', 'webservice');
7609 $strusers = get_string('users');
7610 $strserviceusers = get_string('serviceusers', 'webservice');
7612 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7613 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7614 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7616 // built in services
7617 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7618 $return = "";
7619 if (!empty($services)) {
7620 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7624 $table = new html_table();
7625 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7626 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7627 $table->id = 'builtinservices';
7628 $table->attributes['class'] = 'admintable externalservices generaltable';
7629 $table->data = array();
7631 // iterate through auth plugins and add to the display table
7632 foreach ($services as $service) {
7633 $name = $service->name;
7635 // hide/show link
7636 if ($service->enabled) {
7637 $displayname = "<span>$name</span>";
7638 } else {
7639 $displayname = "<span class=\"dimmed_text\">$name</span>";
7642 $plugin = $service->component;
7644 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7646 if ($service->restrictedusers) {
7647 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7648 } else {
7649 $users = get_string('allusers', 'webservice');
7652 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7654 // add a row to the table
7655 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7657 $return .= html_writer::table($table);
7660 // Custom services
7661 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7662 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7664 $table = new html_table();
7665 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7666 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7667 $table->id = 'customservices';
7668 $table->attributes['class'] = 'admintable externalservices generaltable';
7669 $table->data = array();
7671 // iterate through auth plugins and add to the display table
7672 foreach ($services as $service) {
7673 $name = $service->name;
7675 // hide/show link
7676 if ($service->enabled) {
7677 $displayname = "<span>$name</span>";
7678 } else {
7679 $displayname = "<span class=\"dimmed_text\">$name</span>";
7682 // delete link
7683 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7685 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7687 if ($service->restrictedusers) {
7688 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7689 } else {
7690 $users = get_string('allusers', 'webservice');
7693 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7695 // add a row to the table
7696 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7698 // add new custom service option
7699 $return .= html_writer::table($table);
7701 $return .= '<br />';
7702 // add a token to the table
7703 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7705 return highlight($query, $return);
7710 * Special class for overview of external services
7712 * @author Jerome Mouneyrac
7714 class admin_setting_webservicesoverview extends admin_setting {
7717 * Calls parent::__construct with specific arguments
7719 public function __construct() {
7720 $this->nosave = true;
7721 parent::__construct('webservicesoverviewui',
7722 get_string('webservicesoverview', 'webservice'), '', '');
7726 * Always returns true, does nothing
7728 * @return true
7730 public function get_setting() {
7731 return true;
7735 * Always returns true, does nothing
7737 * @return true
7739 public function get_defaultsetting() {
7740 return true;
7744 * Always returns '', does not write anything
7746 * @return string Always returns ''
7748 public function write_setting($data) {
7749 // do not write any setting
7750 return '';
7754 * Builds the XHTML to display the control
7756 * @param string $data Unused
7757 * @param string $query
7758 * @return string
7760 public function output_html($data, $query='') {
7761 global $CFG, $OUTPUT;
7763 $return = "";
7764 $brtag = html_writer::empty_tag('br');
7766 // Enable mobile web service
7767 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7768 get_string('enablemobilewebservice', 'admin'),
7769 get_string('configenablemobilewebservice',
7770 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7771 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
7772 $wsmobileparam = new stdClass();
7773 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7774 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7775 get_string('mobile', 'admin'));
7776 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7777 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7778 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7779 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7780 . $brtag . $brtag;
7782 /// One system controlling Moodle with Token
7783 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7784 $table = new html_table();
7785 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7786 get_string('description'));
7787 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7788 $table->id = 'onesystemcontrol';
7789 $table->attributes['class'] = 'admintable wsoverview generaltable';
7790 $table->data = array();
7792 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7793 . $brtag . $brtag;
7795 /// 1. Enable Web Services
7796 $row = array();
7797 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7798 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7799 array('href' => $url));
7800 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7801 if ($CFG->enablewebservices) {
7802 $status = get_string('yes');
7804 $row[1] = $status;
7805 $row[2] = get_string('enablewsdescription', 'webservice');
7806 $table->data[] = $row;
7808 /// 2. Enable protocols
7809 $row = array();
7810 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7811 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7812 array('href' => $url));
7813 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7814 //retrieve activated protocol
7815 $active_protocols = empty($CFG->webserviceprotocols) ?
7816 array() : explode(',', $CFG->webserviceprotocols);
7817 if (!empty($active_protocols)) {
7818 $status = "";
7819 foreach ($active_protocols as $protocol) {
7820 $status .= $protocol . $brtag;
7823 $row[1] = $status;
7824 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7825 $table->data[] = $row;
7827 /// 3. Create user account
7828 $row = array();
7829 $url = new moodle_url("/user/editadvanced.php?id=-1");
7830 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7831 array('href' => $url));
7832 $row[1] = "";
7833 $row[2] = get_string('createuserdescription', 'webservice');
7834 $table->data[] = $row;
7836 /// 4. Add capability to users
7837 $row = array();
7838 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7839 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7840 array('href' => $url));
7841 $row[1] = "";
7842 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7843 $table->data[] = $row;
7845 /// 5. Select a web service
7846 $row = array();
7847 $url = new moodle_url("/admin/settings.php?section=externalservices");
7848 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7849 array('href' => $url));
7850 $row[1] = "";
7851 $row[2] = get_string('createservicedescription', 'webservice');
7852 $table->data[] = $row;
7854 /// 6. Add functions
7855 $row = array();
7856 $url = new moodle_url("/admin/settings.php?section=externalservices");
7857 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7858 array('href' => $url));
7859 $row[1] = "";
7860 $row[2] = get_string('addfunctionsdescription', 'webservice');
7861 $table->data[] = $row;
7863 /// 7. Add the specific user
7864 $row = array();
7865 $url = new moodle_url("/admin/settings.php?section=externalservices");
7866 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7867 array('href' => $url));
7868 $row[1] = "";
7869 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7870 $table->data[] = $row;
7872 /// 8. Create token for the specific user
7873 $row = array();
7874 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7875 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7876 array('href' => $url));
7877 $row[1] = "";
7878 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7879 $table->data[] = $row;
7881 /// 9. Enable the documentation
7882 $row = array();
7883 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7884 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7885 array('href' => $url));
7886 $status = '<span class="warning">' . get_string('no') . '</span>';
7887 if ($CFG->enablewsdocumentation) {
7888 $status = get_string('yes');
7890 $row[1] = $status;
7891 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7892 $table->data[] = $row;
7894 /// 10. Test the service
7895 $row = array();
7896 $url = new moodle_url("/admin/webservice/testclient.php");
7897 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7898 array('href' => $url));
7899 $row[1] = "";
7900 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7901 $table->data[] = $row;
7903 $return .= html_writer::table($table);
7905 /// Users as clients with token
7906 $return .= $brtag . $brtag . $brtag;
7907 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7908 $table = new html_table();
7909 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7910 get_string('description'));
7911 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7912 $table->id = 'userasclients';
7913 $table->attributes['class'] = 'admintable wsoverview generaltable';
7914 $table->data = array();
7916 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7917 $brtag . $brtag;
7919 /// 1. Enable Web Services
7920 $row = array();
7921 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7922 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7923 array('href' => $url));
7924 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7925 if ($CFG->enablewebservices) {
7926 $status = get_string('yes');
7928 $row[1] = $status;
7929 $row[2] = get_string('enablewsdescription', 'webservice');
7930 $table->data[] = $row;
7932 /// 2. Enable protocols
7933 $row = array();
7934 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7935 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7936 array('href' => $url));
7937 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7938 //retrieve activated protocol
7939 $active_protocols = empty($CFG->webserviceprotocols) ?
7940 array() : explode(',', $CFG->webserviceprotocols);
7941 if (!empty($active_protocols)) {
7942 $status = "";
7943 foreach ($active_protocols as $protocol) {
7944 $status .= $protocol . $brtag;
7947 $row[1] = $status;
7948 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7949 $table->data[] = $row;
7952 /// 3. Select a web service
7953 $row = array();
7954 $url = new moodle_url("/admin/settings.php?section=externalservices");
7955 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7956 array('href' => $url));
7957 $row[1] = "";
7958 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7959 $table->data[] = $row;
7961 /// 4. Add functions
7962 $row = array();
7963 $url = new moodle_url("/admin/settings.php?section=externalservices");
7964 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7965 array('href' => $url));
7966 $row[1] = "";
7967 $row[2] = get_string('addfunctionsdescription', 'webservice');
7968 $table->data[] = $row;
7970 /// 5. Add capability to users
7971 $row = array();
7972 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7973 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7974 array('href' => $url));
7975 $row[1] = "";
7976 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7977 $table->data[] = $row;
7979 /// 6. Test the service
7980 $row = array();
7981 $url = new moodle_url("/admin/webservice/testclient.php");
7982 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7983 array('href' => $url));
7984 $row[1] = "";
7985 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7986 $table->data[] = $row;
7988 $return .= html_writer::table($table);
7990 return highlight($query, $return);
7997 * Special class for web service protocol administration.
7999 * @author Petr Skoda (skodak)
8001 class admin_setting_managewebserviceprotocols extends admin_setting {
8004 * Calls parent::__construct with specific arguments
8006 public function __construct() {
8007 $this->nosave = true;
8008 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8012 * Always returns true, does nothing
8014 * @return true
8016 public function get_setting() {
8017 return true;
8021 * Always returns true, does nothing
8023 * @return true
8025 public function get_defaultsetting() {
8026 return true;
8030 * Always returns '', does not write anything
8032 * @return string Always returns ''
8034 public function write_setting($data) {
8035 // do not write any setting
8036 return '';
8040 * Checks if $query is one of the available webservices
8042 * @param string $query The string to search for
8043 * @return bool Returns true if found, false if not
8045 public function is_related($query) {
8046 if (parent::is_related($query)) {
8047 return true;
8050 $protocols = core_component::get_plugin_list('webservice');
8051 foreach ($protocols as $protocol=>$location) {
8052 if (strpos($protocol, $query) !== false) {
8053 return true;
8055 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8056 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8057 return true;
8060 return false;
8064 * Builds the XHTML to display the control
8066 * @param string $data Unused
8067 * @param string $query
8068 * @return string
8070 public function output_html($data, $query='') {
8071 global $CFG, $OUTPUT;
8073 // display strings
8074 $stradministration = get_string('administration');
8075 $strsettings = get_string('settings');
8076 $stredit = get_string('edit');
8077 $strprotocol = get_string('protocol', 'webservice');
8078 $strenable = get_string('enable');
8079 $strdisable = get_string('disable');
8080 $strversion = get_string('version');
8082 $protocols_available = core_component::get_plugin_list('webservice');
8083 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8084 ksort($protocols_available);
8086 foreach ($active_protocols as $key=>$protocol) {
8087 if (empty($protocols_available[$protocol])) {
8088 unset($active_protocols[$key]);
8092 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8093 $return .= $OUTPUT->box_start('generalbox webservicesui');
8095 $table = new html_table();
8096 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8097 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8098 $table->id = 'webserviceprotocols';
8099 $table->attributes['class'] = 'admintable generaltable';
8100 $table->data = array();
8102 // iterate through auth plugins and add to the display table
8103 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8104 foreach ($protocols_available as $protocol => $location) {
8105 $name = get_string('pluginname', 'webservice_'.$protocol);
8107 $plugin = new stdClass();
8108 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8109 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8111 $version = isset($plugin->version) ? $plugin->version : '';
8113 // hide/show link
8114 if (in_array($protocol, $active_protocols)) {
8115 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8116 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8117 $displayname = "<span>$name</span>";
8118 } else {
8119 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8120 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8121 $displayname = "<span class=\"dimmed_text\">$name</span>";
8124 // settings link
8125 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8126 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8127 } else {
8128 $settings = '';
8131 // add a row to the table
8132 $table->data[] = array($displayname, $version, $hideshow, $settings);
8134 $return .= html_writer::table($table);
8135 $return .= get_string('configwebserviceplugins', 'webservice');
8136 $return .= $OUTPUT->box_end();
8138 return highlight($query, $return);
8144 * Special class for web service token administration.
8146 * @author Jerome Mouneyrac
8148 class admin_setting_managewebservicetokens extends admin_setting {
8151 * Calls parent::__construct with specific arguments
8153 public function __construct() {
8154 $this->nosave = true;
8155 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8159 * Always returns true, does nothing
8161 * @return true
8163 public function get_setting() {
8164 return true;
8168 * Always returns true, does nothing
8170 * @return true
8172 public function get_defaultsetting() {
8173 return true;
8177 * Always returns '', does not write anything
8179 * @return string Always returns ''
8181 public function write_setting($data) {
8182 // do not write any setting
8183 return '';
8187 * Builds the XHTML to display the control
8189 * @param string $data Unused
8190 * @param string $query
8191 * @return string
8193 public function output_html($data, $query='') {
8194 global $CFG, $OUTPUT, $DB, $USER;
8196 // display strings
8197 $stroperation = get_string('operation', 'webservice');
8198 $strtoken = get_string('token', 'webservice');
8199 $strservice = get_string('service', 'webservice');
8200 $struser = get_string('user');
8201 $strcontext = get_string('context', 'webservice');
8202 $strvaliduntil = get_string('validuntil', 'webservice');
8203 $striprestriction = get_string('iprestriction', 'webservice');
8205 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8207 $table = new html_table();
8208 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8209 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8210 $table->id = 'webservicetokens';
8211 $table->attributes['class'] = 'admintable generaltable';
8212 $table->data = array();
8214 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8216 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8218 //here retrieve token list (including linked users firstname/lastname and linked services name)
8219 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8220 FROM {external_tokens} t, {user} u, {external_services} s
8221 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8222 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8223 if (!empty($tokens)) {
8224 foreach ($tokens as $token) {
8225 //TODO: retrieve context
8227 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8228 $delete .= get_string('delete')."</a>";
8230 $validuntil = '';
8231 if (!empty($token->validuntil)) {
8232 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8235 $iprestriction = '';
8236 if (!empty($token->iprestriction)) {
8237 $iprestriction = $token->iprestriction;
8240 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8241 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8242 $useratag .= $token->firstname." ".$token->lastname;
8243 $useratag .= html_writer::end_tag('a');
8245 //check user missing capabilities
8246 require_once($CFG->dirroot . '/webservice/lib.php');
8247 $webservicemanager = new webservice();
8248 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8249 array(array('id' => $token->userid)), $token->serviceid);
8251 if (!is_siteadmin($token->userid) and
8252 array_key_exists($token->userid, $usermissingcaps)) {
8253 $missingcapabilities = implode(', ',
8254 $usermissingcaps[$token->userid]);
8255 if (!empty($missingcapabilities)) {
8256 $useratag .= html_writer::tag('div',
8257 get_string('usermissingcaps', 'webservice',
8258 $missingcapabilities)
8259 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8260 array('class' => 'missingcaps'));
8264 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8267 $return .= html_writer::table($table);
8268 } else {
8269 $return .= get_string('notoken', 'webservice');
8272 $return .= $OUTPUT->box_end();
8273 // add a token to the table
8274 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8275 $return .= get_string('add')."</a>";
8277 return highlight($query, $return);
8283 * Colour picker
8285 * @copyright 2010 Sam Hemelryk
8286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8288 class admin_setting_configcolourpicker extends admin_setting {
8291 * Information for previewing the colour
8293 * @var array|null
8295 protected $previewconfig = null;
8298 * Use default when empty.
8300 protected $usedefaultwhenempty = true;
8304 * @param string $name
8305 * @param string $visiblename
8306 * @param string $description
8307 * @param string $defaultsetting
8308 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8310 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8311 $usedefaultwhenempty = true) {
8312 $this->previewconfig = $previewconfig;
8313 $this->usedefaultwhenempty = $usedefaultwhenempty;
8314 parent::__construct($name, $visiblename, $description, $defaultsetting);
8318 * Return the setting
8320 * @return mixed returns config if successful else null
8322 public function get_setting() {
8323 return $this->config_read($this->name);
8327 * Saves the setting
8329 * @param string $data
8330 * @return bool
8332 public function write_setting($data) {
8333 $data = $this->validate($data);
8334 if ($data === false) {
8335 return get_string('validateerror', 'admin');
8337 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8341 * Validates the colour that was entered by the user
8343 * @param string $data
8344 * @return string|false
8346 protected function validate($data) {
8348 * List of valid HTML colour names
8350 * @var array
8352 $colornames = array(
8353 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8354 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8355 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8356 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8357 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8358 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8359 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8360 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8361 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8362 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8363 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8364 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8365 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8366 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8367 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8368 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8369 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8370 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8371 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8372 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8373 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8374 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8375 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8376 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8377 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8378 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8379 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8380 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8381 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8382 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8383 'whitesmoke', 'yellow', 'yellowgreen'
8386 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8387 if (strpos($data, '#')!==0) {
8388 $data = '#'.$data;
8390 return $data;
8391 } else if (in_array(strtolower($data), $colornames)) {
8392 return $data;
8393 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8394 return $data;
8395 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8396 return $data;
8397 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8398 return $data;
8399 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8400 return $data;
8401 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8402 return $data;
8403 } else if (empty($data)) {
8404 if ($this->usedefaultwhenempty){
8405 return $this->defaultsetting;
8406 } else {
8407 return '';
8409 } else {
8410 return false;
8415 * Generates the HTML for the setting
8417 * @global moodle_page $PAGE
8418 * @global core_renderer $OUTPUT
8419 * @param string $data
8420 * @param string $query
8422 public function output_html($data, $query = '') {
8423 global $PAGE, $OUTPUT;
8424 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8425 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8426 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8427 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8428 if (!empty($this->previewconfig)) {
8429 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8431 $content .= html_writer::end_tag('div');
8432 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8438 * Class used for uploading of one file into file storage,
8439 * the file name is stored in config table.
8441 * Please note you need to implement your own '_pluginfile' callback function,
8442 * this setting only stores the file, it does not deal with file serving.
8444 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8447 class admin_setting_configstoredfile extends admin_setting {
8448 /** @var array file area options - should be one file only */
8449 protected $options;
8450 /** @var string name of the file area */
8451 protected $filearea;
8452 /** @var int intemid */
8453 protected $itemid;
8454 /** @var string used for detection of changes */
8455 protected $oldhashes;
8458 * Create new stored file setting.
8460 * @param string $name low level setting name
8461 * @param string $visiblename human readable setting name
8462 * @param string $description description of setting
8463 * @param mixed $filearea file area for file storage
8464 * @param int $itemid itemid for file storage
8465 * @param array $options file area options
8467 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8468 parent::__construct($name, $visiblename, $description, '');
8469 $this->filearea = $filearea;
8470 $this->itemid = $itemid;
8471 $this->options = (array)$options;
8475 * Applies defaults and returns all options.
8476 * @return array
8478 protected function get_options() {
8479 global $CFG;
8481 require_once("$CFG->libdir/filelib.php");
8482 require_once("$CFG->dirroot/repository/lib.php");
8483 $defaults = array(
8484 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8485 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8486 'context' => context_system::instance());
8487 foreach($this->options as $k => $v) {
8488 $defaults[$k] = $v;
8491 return $defaults;
8494 public function get_setting() {
8495 return $this->config_read($this->name);
8498 public function write_setting($data) {
8499 global $USER;
8501 // Let's not deal with validation here, this is for admins only.
8502 $current = $this->get_setting();
8503 if (empty($data) && $current === null) {
8504 // This will be the case when applying default settings (installation).
8505 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8506 } else if (!is_number($data)) {
8507 // Draft item id is expected here!
8508 return get_string('errorsetting', 'admin');
8511 $options = $this->get_options();
8512 $fs = get_file_storage();
8513 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8515 $this->oldhashes = null;
8516 if ($current) {
8517 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8518 if ($file = $fs->get_file_by_hash($hash)) {
8519 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8521 unset($file);
8524 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8525 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8526 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8527 // with an error because the draft area does not exist, as he did not use it.
8528 $usercontext = context_user::instance($USER->id);
8529 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8530 return get_string('errorsetting', 'admin');
8534 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8535 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8537 $filepath = '';
8538 if ($files) {
8539 /** @var stored_file $file */
8540 $file = reset($files);
8541 $filepath = $file->get_filepath().$file->get_filename();
8544 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8547 public function post_write_settings($original) {
8548 $options = $this->get_options();
8549 $fs = get_file_storage();
8550 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8552 $current = $this->get_setting();
8553 $newhashes = null;
8554 if ($current) {
8555 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8556 if ($file = $fs->get_file_by_hash($hash)) {
8557 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8559 unset($file);
8562 if ($this->oldhashes === $newhashes) {
8563 $this->oldhashes = null;
8564 return false;
8566 $this->oldhashes = null;
8568 $callbackfunction = $this->updatedcallback;
8569 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8570 $callbackfunction($this->get_full_name());
8572 return true;
8575 public function output_html($data, $query = '') {
8576 global $PAGE, $CFG;
8578 $options = $this->get_options();
8579 $id = $this->get_id();
8580 $elname = $this->get_full_name();
8581 $draftitemid = file_get_submitted_draft_itemid($elname);
8582 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8583 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8585 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8586 require_once("$CFG->dirroot/lib/form/filemanager.php");
8588 $fmoptions = new stdClass();
8589 $fmoptions->mainfile = $options['mainfile'];
8590 $fmoptions->maxbytes = $options['maxbytes'];
8591 $fmoptions->maxfiles = $options['maxfiles'];
8592 $fmoptions->client_id = uniqid();
8593 $fmoptions->itemid = $draftitemid;
8594 $fmoptions->subdirs = $options['subdirs'];
8595 $fmoptions->target = $id;
8596 $fmoptions->accepted_types = $options['accepted_types'];
8597 $fmoptions->return_types = $options['return_types'];
8598 $fmoptions->context = $options['context'];
8599 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8601 $fm = new form_filemanager($fmoptions);
8602 $output = $PAGE->get_renderer('core', 'files');
8603 $html = $output->render($fm);
8605 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8606 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8608 return format_admin_setting($this, $this->visiblename,
8609 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8615 * Administration interface for user specified regular expressions for device detection.
8617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8619 class admin_setting_devicedetectregex extends admin_setting {
8622 * Calls parent::__construct with specific args
8624 * @param string $name
8625 * @param string $visiblename
8626 * @param string $description
8627 * @param mixed $defaultsetting
8629 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8630 global $CFG;
8631 parent::__construct($name, $visiblename, $description, $defaultsetting);
8635 * Return the current setting(s)
8637 * @return array Current settings array
8639 public function get_setting() {
8640 global $CFG;
8642 $config = $this->config_read($this->name);
8643 if (is_null($config)) {
8644 return null;
8647 return $this->prepare_form_data($config);
8651 * Save selected settings
8653 * @param array $data Array of settings to save
8654 * @return bool
8656 public function write_setting($data) {
8657 if (empty($data)) {
8658 $data = array();
8661 if ($this->config_write($this->name, $this->process_form_data($data))) {
8662 return ''; // success
8663 } else {
8664 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8669 * Return XHTML field(s) for regexes
8671 * @param array $data Array of options to set in HTML
8672 * @return string XHTML string for the fields and wrapping div(s)
8674 public function output_html($data, $query='') {
8675 global $OUTPUT;
8677 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8678 $out .= html_writer::start_tag('thead');
8679 $out .= html_writer::start_tag('tr');
8680 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8681 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8682 $out .= html_writer::end_tag('tr');
8683 $out .= html_writer::end_tag('thead');
8684 $out .= html_writer::start_tag('tbody');
8686 if (empty($data)) {
8687 $looplimit = 1;
8688 } else {
8689 $looplimit = (count($data)/2)+1;
8692 for ($i=0; $i<$looplimit; $i++) {
8693 $out .= html_writer::start_tag('tr');
8695 $expressionname = 'expression'.$i;
8697 if (!empty($data[$expressionname])){
8698 $expression = $data[$expressionname];
8699 } else {
8700 $expression = '';
8703 $out .= html_writer::tag('td',
8704 html_writer::empty_tag('input',
8705 array(
8706 'type' => 'text',
8707 'class' => 'form-text',
8708 'name' => $this->get_full_name().'[expression'.$i.']',
8709 'value' => $expression,
8711 ), array('class' => 'c'.$i)
8714 $valuename = 'value'.$i;
8716 if (!empty($data[$valuename])){
8717 $value = $data[$valuename];
8718 } else {
8719 $value= '';
8722 $out .= html_writer::tag('td',
8723 html_writer::empty_tag('input',
8724 array(
8725 'type' => 'text',
8726 'class' => 'form-text',
8727 'name' => $this->get_full_name().'[value'.$i.']',
8728 'value' => $value,
8730 ), array('class' => 'c'.$i)
8733 $out .= html_writer::end_tag('tr');
8736 $out .= html_writer::end_tag('tbody');
8737 $out .= html_writer::end_tag('table');
8739 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8743 * Converts the string of regexes
8745 * @see self::process_form_data()
8746 * @param $regexes string of regexes
8747 * @return array of form fields and their values
8749 protected function prepare_form_data($regexes) {
8751 $regexes = json_decode($regexes);
8753 $form = array();
8755 $i = 0;
8757 foreach ($regexes as $value => $regex) {
8758 $expressionname = 'expression'.$i;
8759 $valuename = 'value'.$i;
8761 $form[$expressionname] = $regex;
8762 $form[$valuename] = $value;
8763 $i++;
8766 return $form;
8770 * Converts the data from admin settings form into a string of regexes
8772 * @see self::prepare_form_data()
8773 * @param array $data array of admin form fields and values
8774 * @return false|string of regexes
8776 protected function process_form_data(array $form) {
8778 $count = count($form); // number of form field values
8780 if ($count % 2) {
8781 // we must get five fields per expression
8782 return false;
8785 $regexes = array();
8786 for ($i = 0; $i < $count / 2; $i++) {
8787 $expressionname = "expression".$i;
8788 $valuename = "value".$i;
8790 $expression = trim($form['expression'.$i]);
8791 $value = trim($form['value'.$i]);
8793 if (empty($expression)){
8794 continue;
8797 $regexes[$value] = $expression;
8800 $regexes = json_encode($regexes);
8802 return $regexes;
8807 * Multiselect for current modules
8809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8811 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8812 private $excludesystem;
8815 * Calls parent::__construct - note array $choices is not required
8817 * @param string $name setting name
8818 * @param string $visiblename localised setting name
8819 * @param string $description setting description
8820 * @param array $defaultsetting a plain array of default module ids
8821 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8823 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8824 $excludesystem = true) {
8825 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8826 $this->excludesystem = $excludesystem;
8830 * Loads an array of current module choices
8832 * @return bool always return true
8834 public function load_choices() {
8835 if (is_array($this->choices)) {
8836 return true;
8838 $this->choices = array();
8840 global $CFG, $DB;
8841 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8842 foreach ($records as $record) {
8843 // Exclude modules if the code doesn't exist
8844 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8845 // Also exclude system modules (if specified)
8846 if (!($this->excludesystem &&
8847 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8848 MOD_ARCHETYPE_SYSTEM)) {
8849 $this->choices[$record->id] = $record->name;
8853 return true;
8858 * Admin setting to show if a php extension is enabled or not.
8860 * @copyright 2013 Damyon Wiese
8861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8863 class admin_setting_php_extension_enabled extends admin_setting {
8865 /** @var string The name of the extension to check for */
8866 private $extension;
8869 * Calls parent::__construct with specific arguments
8871 public function __construct($name, $visiblename, $description, $extension) {
8872 $this->extension = $extension;
8873 $this->nosave = true;
8874 parent::__construct($name, $visiblename, $description, '');
8878 * Always returns true, does nothing
8880 * @return true
8882 public function get_setting() {
8883 return true;
8887 * Always returns true, does nothing
8889 * @return true
8891 public function get_defaultsetting() {
8892 return true;
8896 * Always returns '', does not write anything
8898 * @return string Always returns ''
8900 public function write_setting($data) {
8901 // Do not write any setting.
8902 return '';
8906 * Outputs the html for this setting.
8907 * @return string Returns an XHTML string
8909 public function output_html($data, $query='') {
8910 global $OUTPUT;
8912 $o = '';
8913 if (!extension_loaded($this->extension)) {
8914 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
8916 $o .= format_admin_setting($this, $this->visiblename, $warning);
8918 return $o;