Merge branch 'MDL-56673-fix' of git://github.com/danpoltawski/moodle
[moodle.git] / lib / adminlib.php
blob515a6c2511eb04c06390432847752bf952506123
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(__DIR__.'/../../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 areas, collections and instances associated with this plugin.
170 core_tag_area::uninstall($component);
172 // Custom plugin uninstall.
173 $plugindirectory = core_component::get_plugin_directory($type, $name);
174 $uninstalllib = $plugindirectory . '/db/uninstall.php';
175 if (file_exists($uninstalllib)) {
176 require_once($uninstalllib);
177 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
178 if (function_exists($uninstallfunction)) {
179 // Do not verify result, let plugin complain if necessary.
180 $uninstallfunction();
184 // Specific plugin type cleanup.
185 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
186 if ($plugininfo) {
187 $plugininfo->uninstall_cleanup();
188 core_plugin_manager::reset_caches();
190 $plugininfo = null;
192 // perform clean-up task common for all the plugin/subplugin types
194 //delete the web service functions and pre-built services
195 require_once($CFG->dirroot.'/lib/externallib.php');
196 external_delete_descriptions($component);
198 // delete calendar events
199 $DB->delete_records('event', array('modulename' => $pluginname));
201 // Delete scheduled tasks.
202 $DB->delete_records('task_scheduled', array('component' => $component));
204 // Delete Inbound Message datakeys.
205 $DB->delete_records_select('messageinbound_datakeys',
206 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
208 // Delete Inbound Message handlers.
209 $DB->delete_records('messageinbound_handlers', array('component' => $component));
211 // delete all the logs
212 $DB->delete_records('log', array('module' => $pluginname));
214 // delete log_display information
215 $DB->delete_records('log_display', array('component' => $component));
217 // delete the module configuration records
218 unset_all_config_for_plugin($component);
219 if ($type === 'mod') {
220 unset_all_config_for_plugin($pluginname);
223 // delete message provider
224 message_provider_uninstall($component);
226 // delete the plugin tables
227 $xmldbfilepath = $plugindirectory . '/db/install.xml';
228 drop_plugin_tables($component, $xmldbfilepath, false);
229 if ($type === 'mod' or $type === 'block') {
230 // non-frankenstyle table prefixes
231 drop_plugin_tables($name, $xmldbfilepath, false);
234 // delete the capabilities that were defined by this module
235 capabilities_cleanup($component);
237 // remove event handlers and dequeue pending events
238 events_uninstall($component);
240 // Delete all remaining files in the filepool owned by the component.
241 $fs = get_file_storage();
242 $fs->delete_component_files($component);
244 // Finally purge all caches.
245 purge_all_caches();
247 // Invalidate the hash used for upgrade detections.
248 set_config('allversionshash', '');
250 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
254 * Returns the version of installed component
256 * @param string $component component name
257 * @param string $source either 'disk' or 'installed' - where to get the version information from
258 * @return string|bool version number or false if the component is not found
260 function get_component_version($component, $source='installed') {
261 global $CFG, $DB;
263 list($type, $name) = core_component::normalize_component($component);
265 // moodle core or a core subsystem
266 if ($type === 'core') {
267 if ($source === 'installed') {
268 if (empty($CFG->version)) {
269 return false;
270 } else {
271 return $CFG->version;
273 } else {
274 if (!is_readable($CFG->dirroot.'/version.php')) {
275 return false;
276 } else {
277 $version = null; //initialize variable for IDEs
278 include($CFG->dirroot.'/version.php');
279 return $version;
284 // activity module
285 if ($type === 'mod') {
286 if ($source === 'installed') {
287 if ($CFG->version < 2013092001.02) {
288 return $DB->get_field('modules', 'version', array('name'=>$name));
289 } else {
290 return get_config('mod_'.$name, 'version');
293 } else {
294 $mods = core_component::get_plugin_list('mod');
295 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
296 return false;
297 } else {
298 $plugin = new stdClass();
299 $plugin->version = null;
300 $module = $plugin;
301 include($mods[$name].'/version.php');
302 return $plugin->version;
307 // block
308 if ($type === 'block') {
309 if ($source === 'installed') {
310 if ($CFG->version < 2013092001.02) {
311 return $DB->get_field('block', 'version', array('name'=>$name));
312 } else {
313 return get_config('block_'.$name, 'version');
315 } else {
316 $blocks = core_component::get_plugin_list('block');
317 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
318 return false;
319 } else {
320 $plugin = new stdclass();
321 include($blocks[$name].'/version.php');
322 return $plugin->version;
327 // all other plugin types
328 if ($source === 'installed') {
329 return get_config($type.'_'.$name, 'version');
330 } else {
331 $plugins = core_component::get_plugin_list($type);
332 if (empty($plugins[$name])) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($plugins[$name].'/version.php');
337 return $plugin->version;
343 * Delete all plugin tables
345 * @param string $name Name of plugin, used as table prefix
346 * @param string $file Path to install.xml file
347 * @param bool $feedback defaults to true
348 * @return bool Always returns true
350 function drop_plugin_tables($name, $file, $feedback=true) {
351 global $CFG, $DB;
353 // first try normal delete
354 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
355 return true;
358 // then try to find all tables that start with name and are not in any xml file
359 $used_tables = get_used_table_names();
361 $tables = $DB->get_tables();
363 /// Iterate over, fixing id fields as necessary
364 foreach ($tables as $table) {
365 if (in_array($table, $used_tables)) {
366 continue;
369 if (strpos($table, $name) !== 0) {
370 continue;
373 // found orphan table --> delete it
374 if ($DB->get_manager()->table_exists($table)) {
375 $xmldb_table = new xmldb_table($table);
376 $DB->get_manager()->drop_table($xmldb_table);
380 return true;
384 * Returns names of all known tables == tables that moodle knows about.
386 * @return array Array of lowercase table names
388 function get_used_table_names() {
389 $table_names = array();
390 $dbdirs = get_db_directories();
392 foreach ($dbdirs as $dbdir) {
393 $file = $dbdir.'/install.xml';
395 $xmldb_file = new xmldb_file($file);
397 if (!$xmldb_file->fileExists()) {
398 continue;
401 $loaded = $xmldb_file->loadXMLStructure();
402 $structure = $xmldb_file->getStructure();
404 if ($loaded and $tables = $structure->getTables()) {
405 foreach($tables as $table) {
406 $table_names[] = strtolower($table->getName());
411 return $table_names;
415 * Returns list of all directories where we expect install.xml files
416 * @return array Array of paths
418 function get_db_directories() {
419 global $CFG;
421 $dbdirs = array();
423 /// First, the main one (lib/db)
424 $dbdirs[] = $CFG->libdir.'/db';
426 /// Then, all the ones defined by core_component::get_plugin_types()
427 $plugintypes = core_component::get_plugin_types();
428 foreach ($plugintypes as $plugintype => $pluginbasedir) {
429 if ($plugins = core_component::get_plugin_list($plugintype)) {
430 foreach ($plugins as $plugin => $plugindir) {
431 $dbdirs[] = $plugindir.'/db';
436 return $dbdirs;
440 * Try to obtain or release the cron lock.
441 * @param string $name name of lock
442 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
443 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
444 * @return bool true if lock obtained
446 function set_cron_lock($name, $until, $ignorecurrent=false) {
447 global $DB;
448 if (empty($name)) {
449 debugging("Tried to get a cron lock for a null fieldname");
450 return false;
453 // remove lock by force == remove from config table
454 if (is_null($until)) {
455 set_config($name, null);
456 return true;
459 if (!$ignorecurrent) {
460 // read value from db - other processes might have changed it
461 $value = $DB->get_field('config', 'value', array('name'=>$name));
463 if ($value and $value > time()) {
464 //lock active
465 return false;
469 set_config($name, $until);
470 return true;
474 * Test if and critical warnings are present
475 * @return bool
477 function admin_critical_warnings_present() {
478 global $SESSION;
480 if (!has_capability('moodle/site:config', context_system::instance())) {
481 return 0;
484 if (!isset($SESSION->admin_critical_warning)) {
485 $SESSION->admin_critical_warning = 0;
486 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
487 $SESSION->admin_critical_warning = 1;
491 return $SESSION->admin_critical_warning;
495 * Detects if float supports at least 10 decimal digits
497 * Detects if float supports at least 10 decimal digits
498 * and also if float-->string conversion works as expected.
500 * @return bool true if problem found
502 function is_float_problem() {
503 $num1 = 2009010200.01;
504 $num2 = 2009010200.02;
506 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
510 * Try to verify that dataroot is not accessible from web.
512 * Try to verify that dataroot is not accessible from web.
513 * It is not 100% correct but might help to reduce number of vulnerable sites.
514 * Protection from httpd.conf and .htaccess is not detected properly.
516 * @uses INSECURE_DATAROOT_WARNING
517 * @uses INSECURE_DATAROOT_ERROR
518 * @param bool $fetchtest try to test public access by fetching file, default false
519 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
521 function is_dataroot_insecure($fetchtest=false) {
522 global $CFG;
524 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
526 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
527 $rp = strrev(trim($rp, '/'));
528 $rp = explode('/', $rp);
529 foreach($rp as $r) {
530 if (strpos($siteroot, '/'.$r.'/') === 0) {
531 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
532 } else {
533 break; // probably alias root
537 $siteroot = strrev($siteroot);
538 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
540 if (strpos($dataroot, $siteroot) !== 0) {
541 return false;
544 if (!$fetchtest) {
545 return INSECURE_DATAROOT_WARNING;
548 // now try all methods to fetch a test file using http protocol
550 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
551 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
552 $httpdocroot = $matches[1];
553 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
554 make_upload_directory('diag');
555 $testfile = $CFG->dataroot.'/diag/public.txt';
556 if (!file_exists($testfile)) {
557 file_put_contents($testfile, 'test file, do not delete');
558 @chmod($testfile, $CFG->filepermissions);
560 $teststr = trim(file_get_contents($testfile));
561 if (empty($teststr)) {
562 // hmm, strange
563 return INSECURE_DATAROOT_WARNING;
566 $testurl = $datarooturl.'/diag/public.txt';
567 if (extension_loaded('curl') and
568 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
569 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
570 ($ch = @curl_init($testurl)) !== false) {
571 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
572 curl_setopt($ch, CURLOPT_HEADER, false);
573 $data = curl_exec($ch);
574 if (!curl_errno($ch)) {
575 $data = trim($data);
576 if ($data === $teststr) {
577 curl_close($ch);
578 return INSECURE_DATAROOT_ERROR;
581 curl_close($ch);
584 if ($data = @file_get_contents($testurl)) {
585 $data = trim($data);
586 if ($data === $teststr) {
587 return INSECURE_DATAROOT_ERROR;
591 preg_match('|https?://([^/]+)|i', $testurl, $matches);
592 $sitename = $matches[1];
593 $error = 0;
594 if ($fp = @fsockopen($sitename, 80, $error)) {
595 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
596 $localurl = $matches[1];
597 $out = "GET $localurl HTTP/1.1\r\n";
598 $out .= "Host: $sitename\r\n";
599 $out .= "Connection: Close\r\n\r\n";
600 fwrite($fp, $out);
601 $data = '';
602 $incoming = false;
603 while (!feof($fp)) {
604 if ($incoming) {
605 $data .= fgets($fp, 1024);
606 } else if (@fgets($fp, 1024) === "\r\n") {
607 $incoming = true;
610 fclose($fp);
611 $data = trim($data);
612 if ($data === $teststr) {
613 return INSECURE_DATAROOT_ERROR;
617 return INSECURE_DATAROOT_WARNING;
621 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
623 function enable_cli_maintenance_mode() {
624 global $CFG;
626 if (file_exists("$CFG->dataroot/climaintenance.html")) {
627 unlink("$CFG->dataroot/climaintenance.html");
630 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
631 $data = $CFG->maintenance_message;
632 $data = bootstrap_renderer::early_error_content($data, null, null, null);
633 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
635 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
636 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
638 } else {
639 $data = get_string('sitemaintenance', 'admin');
640 $data = bootstrap_renderer::early_error_content($data, null, null, null);
641 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
644 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
645 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
648 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
652 * Interface for anything appearing in the admin tree
654 * The interface that is implemented by anything that appears in the admin tree
655 * block. It forces inheriting classes to define a method for checking user permissions
656 * and methods for finding something in the admin tree.
658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
660 interface part_of_admin_tree {
663 * Finds a named part_of_admin_tree.
665 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
666 * and not parentable_part_of_admin_tree, then this function should only check if
667 * $this->name matches $name. If it does, it should return a reference to $this,
668 * otherwise, it should return a reference to NULL.
670 * If a class inherits parentable_part_of_admin_tree, this method should be called
671 * recursively on all child objects (assuming, of course, the parent object's name
672 * doesn't match the search criterion).
674 * @param string $name The internal name of the part_of_admin_tree we're searching for.
675 * @return mixed An object reference or a NULL reference.
677 public function locate($name);
680 * Removes named part_of_admin_tree.
682 * @param string $name The internal name of the part_of_admin_tree we want to remove.
683 * @return bool success.
685 public function prune($name);
688 * Search using query
689 * @param string $query
690 * @return mixed array-object structure of found settings and pages
692 public function search($query);
695 * Verifies current user's access to this part_of_admin_tree.
697 * Used to check if the current user has access to this part of the admin tree or
698 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
699 * then this method is usually just a call to has_capability() in the site context.
701 * If a class inherits parentable_part_of_admin_tree, this method should return the
702 * logical OR of the return of check_access() on all child objects.
704 * @return bool True if the user has access, false if she doesn't.
706 public function check_access();
709 * Mostly useful for removing of some parts of the tree in admin tree block.
711 * @return True is hidden from normal list view
713 public function is_hidden();
716 * Show we display Save button at the page bottom?
717 * @return bool
719 public function show_save();
724 * Interface implemented by any part_of_admin_tree that has children.
726 * The interface implemented by any part_of_admin_tree that can be a parent
727 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
728 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
729 * include an add method for adding other part_of_admin_tree objects as children.
731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 interface parentable_part_of_admin_tree extends part_of_admin_tree {
736 * Adds a part_of_admin_tree object to the admin tree.
738 * Used to add a part_of_admin_tree object to this object or a child of this
739 * object. $something should only be added if $destinationname matches
740 * $this->name. If it doesn't, add should be called on child objects that are
741 * also parentable_part_of_admin_tree's.
743 * $something should be appended as the last child in the $destinationname. If the
744 * $beforesibling is specified, $something should be prepended to it. If the given
745 * sibling is not found, $something should be appended to the end of $destinationname
746 * and a developer debugging message should be displayed.
748 * @param string $destinationname The internal name of the new parent for $something.
749 * @param part_of_admin_tree $something The object to be added.
750 * @return bool True on success, false on failure.
752 public function add($destinationname, $something, $beforesibling = null);
758 * The object used to represent folders (a.k.a. categories) in the admin tree block.
760 * Each admin_category object contains a number of part_of_admin_tree objects.
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class admin_category implements parentable_part_of_admin_tree {
766 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
767 protected $children;
768 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
769 public $name;
770 /** @var string The displayed name for this category. Usually obtained through get_string() */
771 public $visiblename;
772 /** @var bool Should this category be hidden in admin tree block? */
773 public $hidden;
774 /** @var mixed Either a string or an array or strings */
775 public $path;
776 /** @var mixed Either a string or an array or strings */
777 public $visiblepath;
779 /** @var array fast lookup category cache, all categories of one tree point to one cache */
780 protected $category_cache;
782 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
783 protected $sort = false;
784 /** @var bool If set to true children will be sorted in ascending order. */
785 protected $sortasc = true;
786 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
787 protected $sortsplit = true;
788 /** @var bool $sorted True if the children have been sorted and don't need resorting */
789 protected $sorted = false;
792 * Constructor for an empty admin category
794 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
795 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
796 * @param bool $hidden hide category in admin tree block, defaults to false
798 public function __construct($name, $visiblename, $hidden=false) {
799 $this->children = array();
800 $this->name = $name;
801 $this->visiblename = $visiblename;
802 $this->hidden = $hidden;
806 * Returns a reference to the part_of_admin_tree object with internal name $name.
808 * @param string $name The internal name of the object we want.
809 * @param bool $findpath initialize path and visiblepath arrays
810 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
811 * defaults to false
813 public function locate($name, $findpath=false) {
814 if (!isset($this->category_cache[$this->name])) {
815 // somebody much have purged the cache
816 $this->category_cache[$this->name] = $this;
819 if ($this->name == $name) {
820 if ($findpath) {
821 $this->visiblepath[] = $this->visiblename;
822 $this->path[] = $this->name;
824 return $this;
827 // quick category lookup
828 if (!$findpath and isset($this->category_cache[$name])) {
829 return $this->category_cache[$name];
832 $return = NULL;
833 foreach($this->children as $childid=>$unused) {
834 if ($return = $this->children[$childid]->locate($name, $findpath)) {
835 break;
839 if (!is_null($return) and $findpath) {
840 $return->visiblepath[] = $this->visiblename;
841 $return->path[] = $this->name;
844 return $return;
848 * Search using query
850 * @param string query
851 * @return mixed array-object structure of found settings and pages
853 public function search($query) {
854 $result = array();
855 foreach ($this->get_children() as $child) {
856 $subsearch = $child->search($query);
857 if (!is_array($subsearch)) {
858 debugging('Incorrect search result from '.$child->name);
859 continue;
861 $result = array_merge($result, $subsearch);
863 return $result;
867 * Removes part_of_admin_tree object with internal name $name.
869 * @param string $name The internal name of the object we want to remove.
870 * @return bool success
872 public function prune($name) {
874 if ($this->name == $name) {
875 return false; //can not remove itself
878 foreach($this->children as $precedence => $child) {
879 if ($child->name == $name) {
880 // clear cache and delete self
881 while($this->category_cache) {
882 // delete the cache, but keep the original array address
883 array_pop($this->category_cache);
885 unset($this->children[$precedence]);
886 return true;
887 } else if ($this->children[$precedence]->prune($name)) {
888 return true;
891 return false;
895 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
897 * By default the new part of the tree is appended as the last child of the parent. You
898 * can specify a sibling node that the new part should be prepended to. If the given
899 * sibling is not found, the part is appended to the end (as it would be by default) and
900 * a developer debugging message is displayed.
902 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
903 * @param string $destinationame The internal name of the immediate parent that we want for $something.
904 * @param mixed $something A part_of_admin_tree or setting instance to be added.
905 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
906 * @return bool True if successfully added, false if $something can not be added.
908 public function add($parentname, $something, $beforesibling = null) {
909 global $CFG;
911 $parent = $this->locate($parentname);
912 if (is_null($parent)) {
913 debugging('parent does not exist!');
914 return false;
917 if ($something instanceof part_of_admin_tree) {
918 if (!($parent instanceof parentable_part_of_admin_tree)) {
919 debugging('error - parts of tree can be inserted only into parentable parts');
920 return false;
922 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
923 // The name of the node is already used, simply warn the developer that this should not happen.
924 // It is intentional to check for the debug level before performing the check.
925 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
927 if (is_null($beforesibling)) {
928 // Append $something as the parent's last child.
929 $parent->children[] = $something;
930 } else {
931 if (!is_string($beforesibling) or trim($beforesibling) === '') {
932 throw new coding_exception('Unexpected value of the beforesibling parameter');
934 // Try to find the position of the sibling.
935 $siblingposition = null;
936 foreach ($parent->children as $childposition => $child) {
937 if ($child->name === $beforesibling) {
938 $siblingposition = $childposition;
939 break;
942 if (is_null($siblingposition)) {
943 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
944 $parent->children[] = $something;
945 } else {
946 $parent->children = array_merge(
947 array_slice($parent->children, 0, $siblingposition),
948 array($something),
949 array_slice($parent->children, $siblingposition)
953 if ($something instanceof admin_category) {
954 if (isset($this->category_cache[$something->name])) {
955 debugging('Duplicate admin category name: '.$something->name);
956 } else {
957 $this->category_cache[$something->name] = $something;
958 $something->category_cache =& $this->category_cache;
959 foreach ($something->children as $child) {
960 // just in case somebody already added subcategories
961 if ($child instanceof admin_category) {
962 if (isset($this->category_cache[$child->name])) {
963 debugging('Duplicate admin category name: '.$child->name);
964 } else {
965 $this->category_cache[$child->name] = $child;
966 $child->category_cache =& $this->category_cache;
972 return true;
974 } else {
975 debugging('error - can not add this element');
976 return false;
982 * Checks if the user has access to anything in this category.
984 * @return bool True if the user has access to at least one child in this category, false otherwise.
986 public function check_access() {
987 foreach ($this->children as $child) {
988 if ($child->check_access()) {
989 return true;
992 return false;
996 * Is this category hidden in admin tree block?
998 * @return bool True if hidden
1000 public function is_hidden() {
1001 return $this->hidden;
1005 * Show we display Save button at the page bottom?
1006 * @return bool
1008 public function show_save() {
1009 foreach ($this->children as $child) {
1010 if ($child->show_save()) {
1011 return true;
1014 return false;
1018 * Sets sorting on this category.
1020 * Please note this function doesn't actually do the sorting.
1021 * It can be called anytime.
1022 * Sorting occurs when the user calls get_children.
1023 * Code using the children array directly won't see the sorted results.
1025 * @param bool $sort If set to true children will be sorted, if false they won't be.
1026 * @param bool $asc If true sorting will be ascending, otherwise descending.
1027 * @param bool $split If true we sort pages and sub categories separately.
1029 public function set_sorting($sort, $asc = true, $split = true) {
1030 $this->sort = (bool)$sort;
1031 $this->sortasc = (bool)$asc;
1032 $this->sortsplit = (bool)$split;
1036 * Returns the children associated with this category.
1038 * @return part_of_admin_tree[]
1040 public function get_children() {
1041 // If we should sort and it hasn't already been sorted.
1042 if ($this->sort && !$this->sorted) {
1043 if ($this->sortsplit) {
1044 $categories = array();
1045 $pages = array();
1046 foreach ($this->children as $child) {
1047 if ($child instanceof admin_category) {
1048 $categories[] = $child;
1049 } else {
1050 $pages[] = $child;
1053 core_collator::asort_objects_by_property($categories, 'visiblename');
1054 core_collator::asort_objects_by_property($pages, 'visiblename');
1055 if (!$this->sortasc) {
1056 $categories = array_reverse($categories);
1057 $pages = array_reverse($pages);
1059 $this->children = array_merge($pages, $categories);
1060 } else {
1061 core_collator::asort_objects_by_property($this->children, 'visiblename');
1062 if (!$this->sortasc) {
1063 $this->children = array_reverse($this->children);
1066 $this->sorted = true;
1068 return $this->children;
1072 * Magically gets a property from this object.
1074 * @param $property
1075 * @return part_of_admin_tree[]
1076 * @throws coding_exception
1078 public function __get($property) {
1079 if ($property === 'children') {
1080 return $this->get_children();
1082 throw new coding_exception('Invalid property requested.');
1086 * Magically sets a property against this object.
1088 * @param string $property
1089 * @param mixed $value
1090 * @throws coding_exception
1092 public function __set($property, $value) {
1093 if ($property === 'children') {
1094 $this->sorted = false;
1095 $this->children = $value;
1096 } else {
1097 throw new coding_exception('Invalid property requested.');
1102 * Checks if an inaccessible property is set.
1104 * @param string $property
1105 * @return bool
1106 * @throws coding_exception
1108 public function __isset($property) {
1109 if ($property === 'children') {
1110 return isset($this->children);
1112 throw new coding_exception('Invalid property requested.');
1118 * Root of admin settings tree, does not have any parent.
1120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1122 class admin_root extends admin_category {
1123 /** @var array List of errors */
1124 public $errors;
1125 /** @var string search query */
1126 public $search;
1127 /** @var bool full tree flag - true means all settings required, false only pages required */
1128 public $fulltree;
1129 /** @var bool flag indicating loaded tree */
1130 public $loaded;
1131 /** @var mixed site custom defaults overriding defaults in settings files*/
1132 public $custom_defaults;
1135 * @param bool $fulltree true means all settings required,
1136 * false only pages required
1138 public function __construct($fulltree) {
1139 global $CFG;
1141 parent::__construct('root', get_string('administration'), false);
1142 $this->errors = array();
1143 $this->search = '';
1144 $this->fulltree = $fulltree;
1145 $this->loaded = false;
1147 $this->category_cache = array();
1149 // load custom defaults if found
1150 $this->custom_defaults = null;
1151 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1152 if (is_readable($defaultsfile)) {
1153 $defaults = array();
1154 include($defaultsfile);
1155 if (is_array($defaults) and count($defaults)) {
1156 $this->custom_defaults = $defaults;
1162 * Empties children array, and sets loaded to false
1164 * @param bool $requirefulltree
1166 public function purge_children($requirefulltree) {
1167 $this->children = array();
1168 $this->fulltree = ($requirefulltree || $this->fulltree);
1169 $this->loaded = false;
1170 //break circular dependencies - this helps PHP 5.2
1171 while($this->category_cache) {
1172 array_pop($this->category_cache);
1174 $this->category_cache = array();
1180 * Links external PHP pages into the admin tree.
1182 * See detailed usage example at the top of this document (adminlib.php)
1184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1186 class admin_externalpage implements part_of_admin_tree {
1188 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1189 public $name;
1191 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1192 public $visiblename;
1194 /** @var string The external URL that we should link to when someone requests this external page. */
1195 public $url;
1197 /** @var string The role capability/permission a user must have to access this external page. */
1198 public $req_capability;
1200 /** @var object The context in which capability/permission should be checked, default is site context. */
1201 public $context;
1203 /** @var bool hidden in admin tree block. */
1204 public $hidden;
1206 /** @var mixed either string or array of string */
1207 public $path;
1209 /** @var array list of visible names of page parents */
1210 public $visiblepath;
1213 * Constructor for adding an external page into the admin tree.
1215 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1216 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1217 * @param string $url The external URL that we should link to when someone requests this external page.
1218 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1219 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1220 * @param stdClass $context The context the page relates to. Not sure what happens
1221 * if you specify something other than system or front page. Defaults to system.
1223 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1224 $this->name = $name;
1225 $this->visiblename = $visiblename;
1226 $this->url = $url;
1227 if (is_array($req_capability)) {
1228 $this->req_capability = $req_capability;
1229 } else {
1230 $this->req_capability = array($req_capability);
1232 $this->hidden = $hidden;
1233 $this->context = $context;
1237 * Returns a reference to the part_of_admin_tree object with internal name $name.
1239 * @param string $name The internal name of the object we want.
1240 * @param bool $findpath defaults to false
1241 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1243 public function locate($name, $findpath=false) {
1244 if ($this->name == $name) {
1245 if ($findpath) {
1246 $this->visiblepath = array($this->visiblename);
1247 $this->path = array($this->name);
1249 return $this;
1250 } else {
1251 $return = NULL;
1252 return $return;
1257 * This function always returns false, required function by interface
1259 * @param string $name
1260 * @return false
1262 public function prune($name) {
1263 return false;
1267 * Search using query
1269 * @param string $query
1270 * @return mixed array-object structure of found settings and pages
1272 public function search($query) {
1273 $found = false;
1274 if (strpos(strtolower($this->name), $query) !== false) {
1275 $found = true;
1276 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1277 $found = true;
1279 if ($found) {
1280 $result = new stdClass();
1281 $result->page = $this;
1282 $result->settings = array();
1283 return array($this->name => $result);
1284 } else {
1285 return array();
1290 * Determines if the current user has access to this external page based on $this->req_capability.
1292 * @return bool True if user has access, false otherwise.
1294 public function check_access() {
1295 global $CFG;
1296 $context = empty($this->context) ? context_system::instance() : $this->context;
1297 foreach($this->req_capability as $cap) {
1298 if (has_capability($cap, $context)) {
1299 return true;
1302 return false;
1306 * Is this external page hidden in admin tree block?
1308 * @return bool True if hidden
1310 public function is_hidden() {
1311 return $this->hidden;
1315 * Show we display Save button at the page bottom?
1316 * @return bool
1318 public function show_save() {
1319 return false;
1325 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1329 class admin_settingpage implements part_of_admin_tree {
1331 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1332 public $name;
1334 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1335 public $visiblename;
1337 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1338 public $settings;
1340 /** @var string The role capability/permission a user must have to access this external page. */
1341 public $req_capability;
1343 /** @var object The context in which capability/permission should be checked, default is site context. */
1344 public $context;
1346 /** @var bool hidden in admin tree block. */
1347 public $hidden;
1349 /** @var mixed string of paths or array of strings of paths */
1350 public $path;
1352 /** @var array list of visible names of page parents */
1353 public $visiblepath;
1356 * see admin_settingpage for details of this function
1358 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1359 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1360 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1361 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1362 * @param stdClass $context The context the page relates to. Not sure what happens
1363 * if you specify something other than system or front page. Defaults to system.
1365 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1366 $this->settings = new stdClass();
1367 $this->name = $name;
1368 $this->visiblename = $visiblename;
1369 if (is_array($req_capability)) {
1370 $this->req_capability = $req_capability;
1371 } else {
1372 $this->req_capability = array($req_capability);
1374 $this->hidden = $hidden;
1375 $this->context = $context;
1379 * see admin_category
1381 * @param string $name
1382 * @param bool $findpath
1383 * @return mixed Object (this) if name == this->name, else returns null
1385 public function locate($name, $findpath=false) {
1386 if ($this->name == $name) {
1387 if ($findpath) {
1388 $this->visiblepath = array($this->visiblename);
1389 $this->path = array($this->name);
1391 return $this;
1392 } else {
1393 $return = NULL;
1394 return $return;
1399 * Search string in settings page.
1401 * @param string $query
1402 * @return array
1404 public function search($query) {
1405 $found = array();
1407 foreach ($this->settings as $setting) {
1408 if ($setting->is_related($query)) {
1409 $found[] = $setting;
1413 if ($found) {
1414 $result = new stdClass();
1415 $result->page = $this;
1416 $result->settings = $found;
1417 return array($this->name => $result);
1420 $found = false;
1421 if (strpos(strtolower($this->name), $query) !== false) {
1422 $found = true;
1423 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1424 $found = true;
1426 if ($found) {
1427 $result = new stdClass();
1428 $result->page = $this;
1429 $result->settings = array();
1430 return array($this->name => $result);
1431 } else {
1432 return array();
1437 * This function always returns false, required by interface
1439 * @param string $name
1440 * @return bool Always false
1442 public function prune($name) {
1443 return false;
1447 * adds an admin_setting to this admin_settingpage
1449 * 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
1450 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1452 * @param object $setting is the admin_setting object you want to add
1453 * @return bool true if successful, false if not
1455 public function add($setting) {
1456 if (!($setting instanceof admin_setting)) {
1457 debugging('error - not a setting instance');
1458 return false;
1461 $name = $setting->name;
1462 if ($setting->plugin) {
1463 $name = $setting->plugin . $name;
1465 $this->settings->{$name} = $setting;
1466 return true;
1470 * see admin_externalpage
1472 * @return bool Returns true for yes false for no
1474 public function check_access() {
1475 global $CFG;
1476 $context = empty($this->context) ? context_system::instance() : $this->context;
1477 foreach($this->req_capability as $cap) {
1478 if (has_capability($cap, $context)) {
1479 return true;
1482 return false;
1486 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1487 * @return string Returns an XHTML string
1489 public function output_html() {
1490 $adminroot = admin_get_root();
1491 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1492 foreach($this->settings as $setting) {
1493 $fullname = $setting->get_full_name();
1494 if (array_key_exists($fullname, $adminroot->errors)) {
1495 $data = $adminroot->errors[$fullname]->data;
1496 } else {
1497 $data = $setting->get_setting();
1498 // do not use defaults if settings not available - upgrade settings handles the defaults!
1500 $return .= $setting->output_html($data);
1502 $return .= '</fieldset>';
1503 return $return;
1507 * Is this settings page hidden in admin tree block?
1509 * @return bool True if hidden
1511 public function is_hidden() {
1512 return $this->hidden;
1516 * Show we display Save button at the page bottom?
1517 * @return bool
1519 public function show_save() {
1520 foreach($this->settings as $setting) {
1521 if (empty($setting->nosave)) {
1522 return true;
1525 return false;
1531 * Admin settings class. Only exists on setting pages.
1532 * Read & write happens at this level; no authentication.
1534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1536 abstract class admin_setting {
1537 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1538 public $name;
1539 /** @var string localised name */
1540 public $visiblename;
1541 /** @var string localised long description in Markdown format */
1542 public $description;
1543 /** @var mixed Can be string or array of string */
1544 public $defaultsetting;
1545 /** @var string */
1546 public $updatedcallback;
1547 /** @var mixed can be String or Null. Null means main config table */
1548 public $plugin; // null means main config table
1549 /** @var bool true indicates this setting does not actually save anything, just information */
1550 public $nosave = false;
1551 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1552 public $affectsmodinfo = false;
1553 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1554 private $flags = array();
1555 /** @var bool Whether this field must be forced LTR. */
1556 private $forceltr = null;
1559 * Constructor
1560 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1561 * or 'myplugin/mysetting' for ones in config_plugins.
1562 * @param string $visiblename localised name
1563 * @param string $description localised long description
1564 * @param mixed $defaultsetting string or array depending on implementation
1566 public function __construct($name, $visiblename, $description, $defaultsetting) {
1567 $this->parse_setting_name($name);
1568 $this->visiblename = $visiblename;
1569 $this->description = $description;
1570 $this->defaultsetting = $defaultsetting;
1574 * Generic function to add a flag to this admin setting.
1576 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1577 * @param bool $default - The default for the flag
1578 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1579 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1581 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1582 if (empty($this->flags[$shortname])) {
1583 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1584 } else {
1585 $this->flags[$shortname]->set_options($enabled, $default);
1590 * Set the enabled options flag on this admin setting.
1592 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1593 * @param bool $default - The default for the flag
1595 public function set_enabled_flag_options($enabled, $default) {
1596 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1600 * Set the advanced options flag on this admin setting.
1602 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1603 * @param bool $default - The default for the flag
1605 public function set_advanced_flag_options($enabled, $default) {
1606 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1611 * Set the locked options flag on this admin setting.
1613 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1614 * @param bool $default - The default for the flag
1616 public function set_locked_flag_options($enabled, $default) {
1617 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1621 * Get the currently saved value for a setting flag
1623 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1624 * @return bool
1626 public function get_setting_flag_value(admin_setting_flag $flag) {
1627 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1628 if (!isset($value)) {
1629 $value = $flag->get_default();
1632 return !empty($value);
1636 * Get the list of defaults for the flags on this setting.
1638 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1640 public function get_setting_flag_defaults(& $defaults) {
1641 foreach ($this->flags as $flag) {
1642 if ($flag->is_enabled() && $flag->get_default()) {
1643 $defaults[] = $flag->get_displayname();
1649 * Output the input fields for the advanced and locked flags on this setting.
1651 * @param bool $adv - The current value of the advanced flag.
1652 * @param bool $locked - The current value of the locked flag.
1653 * @return string $output - The html for the flags.
1655 public function output_setting_flags() {
1656 $output = '';
1658 foreach ($this->flags as $flag) {
1659 if ($flag->is_enabled()) {
1660 $output .= $flag->output_setting_flag($this);
1664 if (!empty($output)) {
1665 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1667 return $output;
1671 * Write the values of the flags for this admin setting.
1673 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1674 * @return bool - true if successful.
1676 public function write_setting_flags($data) {
1677 $result = true;
1678 foreach ($this->flags as $flag) {
1679 $result = $result && $flag->write_setting_flag($this, $data);
1681 return $result;
1685 * Set up $this->name and potentially $this->plugin
1687 * Set up $this->name and possibly $this->plugin based on whether $name looks
1688 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1689 * on the names, that is, output a developer debug warning if the name
1690 * contains anything other than [a-zA-Z0-9_]+.
1692 * @param string $name the setting name passed in to the constructor.
1694 private function parse_setting_name($name) {
1695 $bits = explode('/', $name);
1696 if (count($bits) > 2) {
1697 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1699 $this->name = array_pop($bits);
1700 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1701 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1703 if (!empty($bits)) {
1704 $this->plugin = array_pop($bits);
1705 if ($this->plugin === 'moodle') {
1706 $this->plugin = null;
1707 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1708 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1714 * Returns the fullname prefixed by the plugin
1715 * @return string
1717 public function get_full_name() {
1718 return 's_'.$this->plugin.'_'.$this->name;
1722 * Returns the ID string based on plugin and name
1723 * @return string
1725 public function get_id() {
1726 return 'id_s_'.$this->plugin.'_'.$this->name;
1730 * @param bool $affectsmodinfo If true, changes to this setting will
1731 * cause the course cache to be rebuilt
1733 public function set_affects_modinfo($affectsmodinfo) {
1734 $this->affectsmodinfo = $affectsmodinfo;
1738 * Returns the config if possible
1740 * @return mixed returns config if successful else null
1742 public function config_read($name) {
1743 global $CFG;
1744 if (!empty($this->plugin)) {
1745 $value = get_config($this->plugin, $name);
1746 return $value === false ? NULL : $value;
1748 } else {
1749 if (isset($CFG->$name)) {
1750 return $CFG->$name;
1751 } else {
1752 return NULL;
1758 * Used to set a config pair and log change
1760 * @param string $name
1761 * @param mixed $value Gets converted to string if not null
1762 * @return bool Write setting to config table
1764 public function config_write($name, $value) {
1765 global $DB, $USER, $CFG;
1767 if ($this->nosave) {
1768 return true;
1771 // make sure it is a real change
1772 $oldvalue = get_config($this->plugin, $name);
1773 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1774 $value = is_null($value) ? null : (string)$value;
1776 if ($oldvalue === $value) {
1777 return true;
1780 // store change
1781 set_config($name, $value, $this->plugin);
1783 // Some admin settings affect course modinfo
1784 if ($this->affectsmodinfo) {
1785 // Clear course cache for all courses
1786 rebuild_course_cache(0, true);
1789 $this->add_to_config_log($name, $oldvalue, $value);
1791 return true; // BC only
1795 * Log config changes if necessary.
1796 * @param string $name
1797 * @param string $oldvalue
1798 * @param string $value
1800 protected function add_to_config_log($name, $oldvalue, $value) {
1801 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1805 * Returns current value of this setting
1806 * @return mixed array or string depending on instance, NULL means not set yet
1808 public abstract function get_setting();
1811 * Returns default setting if exists
1812 * @return mixed array or string depending on instance; NULL means no default, user must supply
1814 public function get_defaultsetting() {
1815 $adminroot = admin_get_root(false, false);
1816 if (!empty($adminroot->custom_defaults)) {
1817 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1818 if (isset($adminroot->custom_defaults[$plugin])) {
1819 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1820 return $adminroot->custom_defaults[$plugin][$this->name];
1824 return $this->defaultsetting;
1828 * Store new setting
1830 * @param mixed $data string or array, must not be NULL
1831 * @return string empty string if ok, string error message otherwise
1833 public abstract function write_setting($data);
1836 * Return part of form with setting
1837 * This function should always be overwritten
1839 * @param mixed $data array or string depending on setting
1840 * @param string $query
1841 * @return string
1843 public function output_html($data, $query='') {
1844 // should be overridden
1845 return;
1849 * Function called if setting updated - cleanup, cache reset, etc.
1850 * @param string $functionname Sets the function name
1851 * @return void
1853 public function set_updatedcallback($functionname) {
1854 $this->updatedcallback = $functionname;
1858 * Execute postupdatecallback if necessary.
1859 * @param mixed $original original value before write_setting()
1860 * @return bool true if changed, false if not.
1862 public function post_write_settings($original) {
1863 // Comparison must work for arrays too.
1864 if (serialize($original) === serialize($this->get_setting())) {
1865 return false;
1868 $callbackfunction = $this->updatedcallback;
1869 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1870 $callbackfunction($this->get_full_name());
1872 return true;
1876 * Is setting related to query text - used when searching
1877 * @param string $query
1878 * @return bool
1880 public function is_related($query) {
1881 if (strpos(strtolower($this->name), $query) !== false) {
1882 return true;
1884 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1885 return true;
1887 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1888 return true;
1890 $current = $this->get_setting();
1891 if (!is_null($current)) {
1892 if (is_string($current)) {
1893 if (strpos(core_text::strtolower($current), $query) !== false) {
1894 return true;
1898 $default = $this->get_defaultsetting();
1899 if (!is_null($default)) {
1900 if (is_string($default)) {
1901 if (strpos(core_text::strtolower($default), $query) !== false) {
1902 return true;
1906 return false;
1910 * Get whether this should be displayed in LTR mode.
1912 * @return bool|null
1914 public function get_force_ltr() {
1915 return $this->forceltr;
1919 * Set whether to force LTR or not.
1921 * @param bool $value True when forced, false when not force, null when unknown.
1923 public function set_force_ltr($value) {
1924 $this->forceltr = $value;
1929 * An additional option that can be applied to an admin setting.
1930 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1934 class admin_setting_flag {
1935 /** @var bool Flag to indicate if this option can be toggled for this setting */
1936 private $enabled = false;
1937 /** @var bool Flag to indicate if this option defaults to true or false */
1938 private $default = false;
1939 /** @var string Short string used to create setting name - e.g. 'adv' */
1940 private $shortname = '';
1941 /** @var string String used as the label for this flag */
1942 private $displayname = '';
1943 /** @const Checkbox for this flag is displayed in admin page */
1944 const ENABLED = true;
1945 /** @const Checkbox for this flag is not displayed in admin page */
1946 const DISABLED = false;
1949 * Constructor
1951 * @param bool $enabled Can this option can be toggled.
1952 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1953 * @param bool $default The default checked state for this setting option.
1954 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1955 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1957 public function __construct($enabled, $default, $shortname, $displayname) {
1958 $this->shortname = $shortname;
1959 $this->displayname = $displayname;
1960 $this->set_options($enabled, $default);
1964 * Update the values of this setting options class
1966 * @param bool $enabled Can this option can be toggled.
1967 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1968 * @param bool $default The default checked state for this setting option.
1970 public function set_options($enabled, $default) {
1971 $this->enabled = $enabled;
1972 $this->default = $default;
1976 * Should this option appear in the interface and be toggleable?
1978 * @return bool Is it enabled?
1980 public function is_enabled() {
1981 return $this->enabled;
1985 * Should this option be checked by default?
1987 * @return bool Is it on by default?
1989 public function get_default() {
1990 return $this->default;
1994 * Return the short name for this flag. e.g. 'adv' or 'locked'
1996 * @return string
1998 public function get_shortname() {
1999 return $this->shortname;
2003 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2005 * @return string
2007 public function get_displayname() {
2008 return $this->displayname;
2012 * Save the submitted data for this flag - or set it to the default if $data is null.
2014 * @param admin_setting $setting - The admin setting for this flag
2015 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2016 * @return bool
2018 public function write_setting_flag(admin_setting $setting, $data) {
2019 $result = true;
2020 if ($this->is_enabled()) {
2021 if (!isset($data)) {
2022 $value = $this->get_default();
2023 } else {
2024 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2026 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2029 return $result;
2034 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2036 * @param admin_setting $setting - The admin setting for this flag
2037 * @return string - The html for the checkbox.
2039 public function output_setting_flag(admin_setting $setting) {
2040 global $OUTPUT;
2042 $value = $setting->get_setting_flag_value($this);
2044 $context = new stdClass();
2045 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2046 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2047 $context->value = 1;
2048 $context->checked = $value ? true : false;
2049 $context->label = $this->get_displayname();
2051 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2057 * No setting - just heading and text.
2059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2061 class admin_setting_heading extends admin_setting {
2064 * not a setting, just text
2065 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2066 * @param string $heading heading
2067 * @param string $information text in box
2069 public function __construct($name, $heading, $information) {
2070 $this->nosave = true;
2071 parent::__construct($name, $heading, $information, '');
2075 * Always returns true
2076 * @return bool Always returns true
2078 public function get_setting() {
2079 return true;
2083 * Always returns true
2084 * @return bool Always returns true
2086 public function get_defaultsetting() {
2087 return true;
2091 * Never write settings
2092 * @return string Always returns an empty string
2094 public function write_setting($data) {
2095 // do not write any setting
2096 return '';
2100 * Returns an HTML string
2101 * @return string Returns an HTML string
2103 public function output_html($data, $query='') {
2104 global $OUTPUT;
2105 $context = new stdClass();
2106 $context->title = $this->visiblename;
2107 $context->description = $this->description;
2108 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2109 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2115 * The most flexible setting, the user enters text.
2117 * This type of field should be used for config settings which are using
2118 * English words and are not localised (passwords, database name, list of values, ...).
2120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2122 class admin_setting_configtext extends admin_setting {
2124 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2125 public $paramtype;
2126 /** @var int default field size */
2127 public $size;
2130 * Config text constructor
2132 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2133 * @param string $visiblename localised
2134 * @param string $description long localised info
2135 * @param string $defaultsetting
2136 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2137 * @param int $size default field size
2139 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2140 $this->paramtype = $paramtype;
2141 if (!is_null($size)) {
2142 $this->size = $size;
2143 } else {
2144 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2146 parent::__construct($name, $visiblename, $description, $defaultsetting);
2150 * Get whether this should be displayed in LTR mode.
2152 * Try to guess from the PARAM type unless specifically set.
2154 public function get_force_ltr() {
2155 $forceltr = parent::get_force_ltr();
2156 if ($forceltr === null) {
2157 return !is_rtl_compatible($this->paramtype);
2159 return $forceltr;
2163 * Return the setting
2165 * @return mixed returns config if successful else null
2167 public function get_setting() {
2168 return $this->config_read($this->name);
2171 public function write_setting($data) {
2172 if ($this->paramtype === PARAM_INT and $data === '') {
2173 // do not complain if '' used instead of 0
2174 $data = 0;
2176 // $data is a string
2177 $validated = $this->validate($data);
2178 if ($validated !== true) {
2179 return $validated;
2181 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2185 * Validate data before storage
2186 * @param string data
2187 * @return mixed true if ok string if error found
2189 public function validate($data) {
2190 // allow paramtype to be a custom regex if it is the form of /pattern/
2191 if (preg_match('#^/.*/$#', $this->paramtype)) {
2192 if (preg_match($this->paramtype, $data)) {
2193 return true;
2194 } else {
2195 return get_string('validateerror', 'admin');
2198 } else if ($this->paramtype === PARAM_RAW) {
2199 return true;
2201 } else {
2202 $cleaned = clean_param($data, $this->paramtype);
2203 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2204 return true;
2205 } else {
2206 return get_string('validateerror', 'admin');
2212 * Return an XHTML string for the setting
2213 * @return string Returns an XHTML string
2215 public function output_html($data, $query='') {
2216 global $OUTPUT;
2218 $default = $this->get_defaultsetting();
2219 $context = (object) [
2220 'size' => $this->size,
2221 'id' => $this->get_id(),
2222 'name' => $this->get_full_name(),
2223 'value' => $data,
2224 'forceltr' => $this->get_force_ltr(),
2226 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2228 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2233 * Text input with a maximum length constraint.
2235 * @copyright 2015 onwards Ankit Agarwal
2236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2238 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2240 /** @var int maximum number of chars allowed. */
2241 protected $maxlength;
2244 * Config text constructor
2246 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2247 * or 'myplugin/mysetting' for ones in config_plugins.
2248 * @param string $visiblename localised
2249 * @param string $description long localised info
2250 * @param string $defaultsetting
2251 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2252 * @param int $size default field size
2253 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2255 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2256 $size=null, $maxlength = 0) {
2257 $this->maxlength = $maxlength;
2258 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2262 * Validate data before storage
2264 * @param string $data data
2265 * @return mixed true if ok string if error found
2267 public function validate($data) {
2268 $parentvalidation = parent::validate($data);
2269 if ($parentvalidation === true) {
2270 if ($this->maxlength > 0) {
2271 // Max length check.
2272 $length = core_text::strlen($data);
2273 if ($length > $this->maxlength) {
2274 return get_string('maximumchars', 'moodle', $this->maxlength);
2276 return true;
2277 } else {
2278 return true; // No max length check needed.
2280 } else {
2281 return $parentvalidation;
2287 * General text area without html editor.
2289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2291 class admin_setting_configtextarea extends admin_setting_configtext {
2292 private $rows;
2293 private $cols;
2296 * @param string $name
2297 * @param string $visiblename
2298 * @param string $description
2299 * @param mixed $defaultsetting string or array
2300 * @param mixed $paramtype
2301 * @param string $cols The number of columns to make the editor
2302 * @param string $rows The number of rows to make the editor
2304 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2305 $this->rows = $rows;
2306 $this->cols = $cols;
2307 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2311 * Returns an XHTML string for the editor
2313 * @param string $data
2314 * @param string $query
2315 * @return string XHTML string for the editor
2317 public function output_html($data, $query='') {
2318 global $OUTPUT;
2320 $default = $this->get_defaultsetting();
2321 $defaultinfo = $default;
2322 if (!is_null($default) and $default !== '') {
2323 $defaultinfo = "\n".$default;
2326 $context = (object) [
2327 'cols' => $this->cols,
2328 'rows' => $this->rows,
2329 'id' => $this->get_id(),
2330 'name' => $this->get_full_name(),
2331 'value' => $data,
2332 'forceltr' => $this->get_force_ltr(),
2334 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2336 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2341 * General text area with html editor.
2343 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2346 * @param string $name
2347 * @param string $visiblename
2348 * @param string $description
2349 * @param mixed $defaultsetting string or array
2350 * @param mixed $paramtype
2352 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2353 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2354 $this->set_force_ltr(false);
2355 editors_head_setup();
2359 * Returns an XHTML string for the editor
2361 * @param string $data
2362 * @param string $query
2363 * @return string XHTML string for the editor
2365 public function output_html($data, $query='') {
2366 $editor = editors_get_preferred_editor(FORMAT_HTML);
2367 $editor->set_text($data);
2368 $editor->use_editor($this->get_id(), array('noclean'=>true));
2369 return parent::output_html($data, $query);
2375 * Password field, allows unmasking of password
2377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2379 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2382 * Constructor
2383 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2384 * @param string $visiblename localised
2385 * @param string $description long localised info
2386 * @param string $defaultsetting default password
2388 public function __construct($name, $visiblename, $description, $defaultsetting) {
2389 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2393 * Log config changes if necessary.
2394 * @param string $name
2395 * @param string $oldvalue
2396 * @param string $value
2398 protected function add_to_config_log($name, $oldvalue, $value) {
2399 if ($value !== '') {
2400 $value = '********';
2402 if ($oldvalue !== '' and $oldvalue !== null) {
2403 $oldvalue = '********';
2405 parent::add_to_config_log($name, $oldvalue, $value);
2409 * Returns HTML for the field.
2411 * @param string $data Value for the field
2412 * @param string $query Passed as final argument for format_admin_setting
2413 * @return string Rendered HTML
2415 public function output_html($data, $query='') {
2416 global $OUTPUT;
2417 $context = (object) [
2418 'id' => $this->get_id(),
2419 'name' => $this->get_full_name(),
2420 'size' => $this->size,
2421 'value' => $data,
2422 'forceltr' => $this->get_force_ltr(),
2424 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2425 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2431 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2432 * Note: Only advanced makes sense right now - locked does not.
2434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2436 class admin_setting_configempty extends admin_setting_configtext {
2439 * @param string $name
2440 * @param string $visiblename
2441 * @param string $description
2443 public function __construct($name, $visiblename, $description) {
2444 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2448 * Returns an XHTML string for the hidden field
2450 * @param string $data
2451 * @param string $query
2452 * @return string XHTML string for the editor
2454 public function output_html($data, $query='') {
2455 global $OUTPUT;
2457 $context = (object) [
2458 'id' => $this->get_id(),
2459 'name' => $this->get_full_name()
2461 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2463 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2469 * Path to directory
2471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2473 class admin_setting_configfile extends admin_setting_configtext {
2475 * Constructor
2476 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2477 * @param string $visiblename localised
2478 * @param string $description long localised info
2479 * @param string $defaultdirectory default directory location
2481 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2482 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2486 * Returns XHTML for the field
2488 * Returns XHTML for the field and also checks whether the file
2489 * specified in $data exists using file_exists()
2491 * @param string $data File name and path to use in value attr
2492 * @param string $query
2493 * @return string XHTML field
2495 public function output_html($data, $query='') {
2496 global $CFG, $OUTPUT;
2498 $default = $this->get_defaultsetting();
2499 $context = (object) [
2500 'id' => $this->get_id(),
2501 'name' => $this->get_full_name(),
2502 'size' => $this->size,
2503 'value' => $data,
2504 'showvalidity' => !empty($data),
2505 'valid' => $data && file_exists($data),
2506 'readonly' => !empty($CFG->preventexecpath),
2507 'forceltr' => $this->get_force_ltr(),
2510 if ($context->readonly) {
2511 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2514 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2516 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2520 * Checks if execpatch has been disabled in config.php
2522 public function write_setting($data) {
2523 global $CFG;
2524 if (!empty($CFG->preventexecpath)) {
2525 if ($this->get_setting() === null) {
2526 // Use default during installation.
2527 $data = $this->get_defaultsetting();
2528 if ($data === null) {
2529 $data = '';
2531 } else {
2532 return '';
2535 return parent::write_setting($data);
2542 * Path to executable file
2544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2546 class admin_setting_configexecutable extends admin_setting_configfile {
2549 * Returns an XHTML field
2551 * @param string $data This is the value for the field
2552 * @param string $query
2553 * @return string XHTML field
2555 public function output_html($data, $query='') {
2556 global $CFG, $OUTPUT;
2557 $default = $this->get_defaultsetting();
2558 require_once("$CFG->libdir/filelib.php");
2560 $context = (object) [
2561 'id' => $this->get_id(),
2562 'name' => $this->get_full_name(),
2563 'size' => $this->size,
2564 'value' => $data,
2565 'showvalidity' => !empty($data),
2566 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2567 'readonly' => !empty($CFG->preventexecpath),
2568 'forceltr' => $this->get_force_ltr()
2571 if (!empty($CFG->preventexecpath)) {
2572 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2575 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2577 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2583 * Path to directory
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2587 class admin_setting_configdirectory extends admin_setting_configfile {
2590 * Returns an XHTML field
2592 * @param string $data This is the value for the field
2593 * @param string $query
2594 * @return string XHTML
2596 public function output_html($data, $query='') {
2597 global $CFG, $OUTPUT;
2598 $default = $this->get_defaultsetting();
2600 $context = (object) [
2601 'id' => $this->get_id(),
2602 'name' => $this->get_full_name(),
2603 'size' => $this->size,
2604 'value' => $data,
2605 'showvalidity' => !empty($data),
2606 'valid' => $data && file_exists($data) && is_dir($data),
2607 'readonly' => !empty($CFG->preventexecpath),
2608 'forceltr' => $this->get_force_ltr()
2611 if (!empty($CFG->preventexecpath)) {
2612 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2615 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2617 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2623 * Checkbox
2625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2627 class admin_setting_configcheckbox extends admin_setting {
2628 /** @var string Value used when checked */
2629 public $yes;
2630 /** @var string Value used when not checked */
2631 public $no;
2634 * Constructor
2635 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2636 * @param string $visiblename localised
2637 * @param string $description long localised info
2638 * @param string $defaultsetting
2639 * @param string $yes value used when checked
2640 * @param string $no value used when not checked
2642 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2643 parent::__construct($name, $visiblename, $description, $defaultsetting);
2644 $this->yes = (string)$yes;
2645 $this->no = (string)$no;
2649 * Retrieves the current setting using the objects name
2651 * @return string
2653 public function get_setting() {
2654 return $this->config_read($this->name);
2658 * Sets the value for the setting
2660 * Sets the value for the setting to either the yes or no values
2661 * of the object by comparing $data to yes
2663 * @param mixed $data Gets converted to str for comparison against yes value
2664 * @return string empty string or error
2666 public function write_setting($data) {
2667 if ((string)$data === $this->yes) { // convert to strings before comparison
2668 $data = $this->yes;
2669 } else {
2670 $data = $this->no;
2672 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2676 * Returns an XHTML checkbox field
2678 * @param string $data If $data matches yes then checkbox is checked
2679 * @param string $query
2680 * @return string XHTML field
2682 public function output_html($data, $query='') {
2683 global $OUTPUT;
2685 $context = (object) [
2686 'id' => $this->get_id(),
2687 'name' => $this->get_full_name(),
2688 'no' => $this->no,
2689 'value' => $this->yes,
2690 'checked' => (string) $data === $this->yes,
2693 $default = $this->get_defaultsetting();
2694 if (!is_null($default)) {
2695 if ((string)$default === $this->yes) {
2696 $defaultinfo = get_string('checkboxyes', 'admin');
2697 } else {
2698 $defaultinfo = get_string('checkboxno', 'admin');
2700 } else {
2701 $defaultinfo = NULL;
2704 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2706 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2712 * Multiple checkboxes, each represents different value, stored in csv format
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2716 class admin_setting_configmulticheckbox extends admin_setting {
2717 /** @var array Array of choices value=>label */
2718 public $choices;
2721 * Constructor: uses parent::__construct
2723 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2724 * @param string $visiblename localised
2725 * @param string $description long localised info
2726 * @param array $defaultsetting array of selected
2727 * @param array $choices array of $value=>$label for each checkbox
2729 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2730 $this->choices = $choices;
2731 parent::__construct($name, $visiblename, $description, $defaultsetting);
2735 * This public function may be used in ancestors for lazy loading of choices
2737 * @todo Check if this function is still required content commented out only returns true
2738 * @return bool true if loaded, false if error
2740 public function load_choices() {
2742 if (is_array($this->choices)) {
2743 return true;
2745 .... load choices here
2747 return true;
2751 * Is setting related to query text - used when searching
2753 * @param string $query
2754 * @return bool true on related, false on not or failure
2756 public function is_related($query) {
2757 if (!$this->load_choices() or empty($this->choices)) {
2758 return false;
2760 if (parent::is_related($query)) {
2761 return true;
2764 foreach ($this->choices as $desc) {
2765 if (strpos(core_text::strtolower($desc), $query) !== false) {
2766 return true;
2769 return false;
2773 * Returns the current setting if it is set
2775 * @return mixed null if null, else an array
2777 public function get_setting() {
2778 $result = $this->config_read($this->name);
2780 if (is_null($result)) {
2781 return NULL;
2783 if ($result === '') {
2784 return array();
2786 $enabled = explode(',', $result);
2787 $setting = array();
2788 foreach ($enabled as $option) {
2789 $setting[$option] = 1;
2791 return $setting;
2795 * Saves the setting(s) provided in $data
2797 * @param array $data An array of data, if not array returns empty str
2798 * @return mixed empty string on useless data or bool true=success, false=failed
2800 public function write_setting($data) {
2801 if (!is_array($data)) {
2802 return ''; // ignore it
2804 if (!$this->load_choices() or empty($this->choices)) {
2805 return '';
2807 unset($data['xxxxx']);
2808 $result = array();
2809 foreach ($data as $key => $value) {
2810 if ($value and array_key_exists($key, $this->choices)) {
2811 $result[] = $key;
2814 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2818 * Returns XHTML field(s) as required by choices
2820 * Relies on data being an array should data ever be another valid vartype with
2821 * acceptable value this may cause a warning/error
2822 * if (!is_array($data)) would fix the problem
2824 * @todo Add vartype handling to ensure $data is an array
2826 * @param array $data An array of checked values
2827 * @param string $query
2828 * @return string XHTML field
2830 public function output_html($data, $query='') {
2831 global $OUTPUT;
2833 if (!$this->load_choices() or empty($this->choices)) {
2834 return '';
2837 $default = $this->get_defaultsetting();
2838 if (is_null($default)) {
2839 $default = array();
2841 if (is_null($data)) {
2842 $data = array();
2845 $context = (object) [
2846 'id' => $this->get_id(),
2847 'name' => $this->get_full_name(),
2850 $options = array();
2851 $defaults = array();
2852 foreach ($this->choices as $key => $description) {
2853 if (!empty($default[$key])) {
2854 $defaults[] = $description;
2857 $options[] = [
2858 'key' => $key,
2859 'checked' => !empty($data[$key]),
2860 'label' => highlightfast($query, $description)
2864 if (is_null($default)) {
2865 $defaultinfo = null;
2866 } else if (!empty($defaults)) {
2867 $defaultinfo = implode(', ', $defaults);
2868 } else {
2869 $defaultinfo = get_string('none');
2872 $context->options = $options;
2873 $context->hasoptions = !empty($options);
2875 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
2877 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
2884 * Multiple checkboxes 2, value stored as string 00101011
2886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2888 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2891 * Returns the setting if set
2893 * @return mixed null if not set, else an array of set settings
2895 public function get_setting() {
2896 $result = $this->config_read($this->name);
2897 if (is_null($result)) {
2898 return NULL;
2900 if (!$this->load_choices()) {
2901 return NULL;
2903 $result = str_pad($result, count($this->choices), '0');
2904 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2905 $setting = array();
2906 foreach ($this->choices as $key=>$unused) {
2907 $value = array_shift($result);
2908 if ($value) {
2909 $setting[$key] = 1;
2912 return $setting;
2916 * Save setting(s) provided in $data param
2918 * @param array $data An array of settings to save
2919 * @return mixed empty string for bad data or bool true=>success, false=>error
2921 public function write_setting($data) {
2922 if (!is_array($data)) {
2923 return ''; // ignore it
2925 if (!$this->load_choices() or empty($this->choices)) {
2926 return '';
2928 $result = '';
2929 foreach ($this->choices as $key=>$unused) {
2930 if (!empty($data[$key])) {
2931 $result .= '1';
2932 } else {
2933 $result .= '0';
2936 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2942 * Select one value from list
2944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 class admin_setting_configselect extends admin_setting {
2947 /** @var array Array of choices value=>label */
2948 public $choices;
2951 * Constructor
2952 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2953 * @param string $visiblename localised
2954 * @param string $description long localised info
2955 * @param string|int $defaultsetting
2956 * @param array $choices array of $value=>$label for each selection
2958 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2959 $this->choices = $choices;
2960 parent::__construct($name, $visiblename, $description, $defaultsetting);
2964 * This function may be used in ancestors for lazy loading of choices
2966 * Override this method if loading of choices is expensive, such
2967 * as when it requires multiple db requests.
2969 * @return bool true if loaded, false if error
2971 public function load_choices() {
2973 if (is_array($this->choices)) {
2974 return true;
2976 .... load choices here
2978 return true;
2982 * Check if this is $query is related to a choice
2984 * @param string $query
2985 * @return bool true if related, false if not
2987 public function is_related($query) {
2988 if (parent::is_related($query)) {
2989 return true;
2991 if (!$this->load_choices()) {
2992 return false;
2994 foreach ($this->choices as $key=>$value) {
2995 if (strpos(core_text::strtolower($key), $query) !== false) {
2996 return true;
2998 if (strpos(core_text::strtolower($value), $query) !== false) {
2999 return true;
3002 return false;
3006 * Return the setting
3008 * @return mixed returns config if successful else null
3010 public function get_setting() {
3011 return $this->config_read($this->name);
3015 * Save a setting
3017 * @param string $data
3018 * @return string empty of error string
3020 public function write_setting($data) {
3021 if (!$this->load_choices() or empty($this->choices)) {
3022 return '';
3024 if (!array_key_exists($data, $this->choices)) {
3025 return ''; // ignore it
3028 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3032 * Returns XHTML select field
3034 * Ensure the options are loaded, and generate the XHTML for the select
3035 * element and any warning message. Separating this out from output_html
3036 * makes it easier to subclass this class.
3038 * @param string $data the option to show as selected.
3039 * @param string $current the currently selected option in the database, null if none.
3040 * @param string $default the default selected option.
3041 * @return array the HTML for the select element, and a warning message.
3042 * @deprecated since Moodle 3.2
3044 public function output_select_html($data, $current, $default, $extraname = '') {
3045 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3049 * Returns XHTML select field and wrapping div(s)
3051 * @see output_select_html()
3053 * @param string $data the option to show as selected
3054 * @param string $query
3055 * @return string XHTML field and wrapping div
3057 public function output_html($data, $query='') {
3058 global $OUTPUT;
3060 $default = $this->get_defaultsetting();
3061 $current = $this->get_setting();
3063 if (!$this->load_choices() || empty($this->choices)) {
3064 return '';
3067 $context = (object) [
3068 'id' => $this->get_id(),
3069 'name' => $this->get_full_name(),
3072 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3073 $defaultinfo = $this->choices[$default];
3074 } else {
3075 $defaultinfo = NULL;
3078 // Warnings.
3079 $warning = '';
3080 if ($current === null) {
3081 // First run.
3082 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3083 // No warning.
3084 } else if (!array_key_exists($current, $this->choices)) {
3085 $warning = get_string('warningcurrentsetting', 'admin', $current);
3086 if (!is_null($default) && $data == $current) {
3087 $data = $default; // Use default instead of first value when showing the form.
3091 $options = [];
3092 foreach ($this->choices as $value => $name) {
3093 $options[] = [
3094 'value' => $value,
3095 'name' => $name,
3096 'selected' => (string) $value == $data
3099 $context->options = $options;
3101 $element = $OUTPUT->render_from_template('core_admin/setting_configselect', $context);
3103 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3109 * Select multiple items from list
3111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3113 class admin_setting_configmultiselect extends admin_setting_configselect {
3115 * Constructor
3116 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3117 * @param string $visiblename localised
3118 * @param string $description long localised info
3119 * @param array $defaultsetting array of selected items
3120 * @param array $choices array of $value=>$label for each list item
3122 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3123 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3127 * Returns the select setting(s)
3129 * @return mixed null or array. Null if no settings else array of setting(s)
3131 public function get_setting() {
3132 $result = $this->config_read($this->name);
3133 if (is_null($result)) {
3134 return NULL;
3136 if ($result === '') {
3137 return array();
3139 return explode(',', $result);
3143 * Saves setting(s) provided through $data
3145 * Potential bug in the works should anyone call with this function
3146 * using a vartype that is not an array
3148 * @param array $data
3150 public function write_setting($data) {
3151 if (!is_array($data)) {
3152 return ''; //ignore it
3154 if (!$this->load_choices() or empty($this->choices)) {
3155 return '';
3158 unset($data['xxxxx']);
3160 $save = array();
3161 foreach ($data as $value) {
3162 if (!array_key_exists($value, $this->choices)) {
3163 continue; // ignore it
3165 $save[] = $value;
3168 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3172 * Is setting related to query text - used when searching
3174 * @param string $query
3175 * @return bool true if related, false if not
3177 public function is_related($query) {
3178 if (!$this->load_choices() or empty($this->choices)) {
3179 return false;
3181 if (parent::is_related($query)) {
3182 return true;
3185 foreach ($this->choices as $desc) {
3186 if (strpos(core_text::strtolower($desc), $query) !== false) {
3187 return true;
3190 return false;
3194 * Returns XHTML multi-select field
3196 * @todo Add vartype handling to ensure $data is an array
3197 * @param array $data Array of values to select by default
3198 * @param string $query
3199 * @return string XHTML multi-select field
3201 public function output_html($data, $query='') {
3202 global $OUTPUT;
3204 if (!$this->load_choices() or empty($this->choices)) {
3205 return '';
3208 $default = $this->get_defaultsetting();
3209 if (is_null($default)) {
3210 $default = array();
3212 if (is_null($data)) {
3213 $data = array();
3216 $context = (object) [
3217 'id' => $this->get_id(),
3218 'name' => $this->get_full_name(),
3219 'size' => min(10, count($this->choices))
3222 $defaults = [];
3223 $options = [];
3224 foreach ($this->choices as $value => $name) {
3225 if (in_array($value, $default)) {
3226 $defaults[] = $name;
3228 $options[] = [
3229 'value' => $value,
3230 'name' => $name,
3231 'selected' => in_array($value, $data)
3234 $context->options = $options;
3236 if (is_null($default)) {
3237 $defaultinfo = NULL;
3238 } if (!empty($defaults)) {
3239 $defaultinfo = implode(', ', $defaults);
3240 } else {
3241 $defaultinfo = get_string('none');
3244 $element = $OUTPUT->render_from_template('core_admin/setting_configmultiselect', $context);
3246 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3251 * Time selector
3253 * This is a liiitle bit messy. we're using two selects, but we're returning
3254 * them as an array named after $name (so we only use $name2 internally for the setting)
3256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3258 class admin_setting_configtime extends admin_setting {
3259 /** @var string Used for setting second select (minutes) */
3260 public $name2;
3263 * Constructor
3264 * @param string $hoursname setting for hours
3265 * @param string $minutesname setting for hours
3266 * @param string $visiblename localised
3267 * @param string $description long localised info
3268 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3270 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3271 $this->name2 = $minutesname;
3272 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3276 * Get the selected time
3278 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3280 public function get_setting() {
3281 $result1 = $this->config_read($this->name);
3282 $result2 = $this->config_read($this->name2);
3283 if (is_null($result1) or is_null($result2)) {
3284 return NULL;
3287 return array('h' => $result1, 'm' => $result2);
3291 * Store the time (hours and minutes)
3293 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3294 * @return bool true if success, false if not
3296 public function write_setting($data) {
3297 if (!is_array($data)) {
3298 return '';
3301 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3302 return ($result ? '' : get_string('errorsetting', 'admin'));
3306 * Returns XHTML time select fields
3308 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3309 * @param string $query
3310 * @return string XHTML time select fields and wrapping div(s)
3312 public function output_html($data, $query='') {
3313 global $OUTPUT;
3315 $default = $this->get_defaultsetting();
3316 if (is_array($default)) {
3317 $defaultinfo = $default['h'].':'.$default['m'];
3318 } else {
3319 $defaultinfo = NULL;
3322 $context = (object) [
3323 'id' => $this->get_id(),
3324 'name' => $this->get_full_name(),
3325 'hours' => array_map(function($i) use ($data) {
3326 return [
3327 'value' => $i,
3328 'name' => $i,
3329 'selected' => $i == $data['h']
3331 }, range(0, 23)),
3332 'minutes' => array_map(function($i) use ($data) {
3333 return [
3334 'value' => $i,
3335 'name' => $i,
3336 'selected' => $i == $data['m']
3338 }, range(0, 59, 5))
3341 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3343 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3344 $this->get_id() . 'h', '', $defaultinfo, $query);
3351 * Seconds duration setting.
3353 * @copyright 2012 Petr Skoda (http://skodak.org)
3354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3356 class admin_setting_configduration extends admin_setting {
3358 /** @var int default duration unit */
3359 protected $defaultunit;
3362 * Constructor
3363 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3364 * or 'myplugin/mysetting' for ones in config_plugins.
3365 * @param string $visiblename localised name
3366 * @param string $description localised long description
3367 * @param mixed $defaultsetting string or array depending on implementation
3368 * @param int $defaultunit - day, week, etc. (in seconds)
3370 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3371 if (is_number($defaultsetting)) {
3372 $defaultsetting = self::parse_seconds($defaultsetting);
3374 $units = self::get_units();
3375 if (isset($units[$defaultunit])) {
3376 $this->defaultunit = $defaultunit;
3377 } else {
3378 $this->defaultunit = 86400;
3380 parent::__construct($name, $visiblename, $description, $defaultsetting);
3384 * Returns selectable units.
3385 * @static
3386 * @return array
3388 protected static function get_units() {
3389 return array(
3390 604800 => get_string('weeks'),
3391 86400 => get_string('days'),
3392 3600 => get_string('hours'),
3393 60 => get_string('minutes'),
3394 1 => get_string('seconds'),
3399 * Converts seconds to some more user friendly string.
3400 * @static
3401 * @param int $seconds
3402 * @return string
3404 protected static function get_duration_text($seconds) {
3405 if (empty($seconds)) {
3406 return get_string('none');
3408 $data = self::parse_seconds($seconds);
3409 switch ($data['u']) {
3410 case (60*60*24*7):
3411 return get_string('numweeks', '', $data['v']);
3412 case (60*60*24):
3413 return get_string('numdays', '', $data['v']);
3414 case (60*60):
3415 return get_string('numhours', '', $data['v']);
3416 case (60):
3417 return get_string('numminutes', '', $data['v']);
3418 default:
3419 return get_string('numseconds', '', $data['v']*$data['u']);
3424 * Finds suitable units for given duration.
3425 * @static
3426 * @param int $seconds
3427 * @return array
3429 protected static function parse_seconds($seconds) {
3430 foreach (self::get_units() as $unit => $unused) {
3431 if ($seconds % $unit === 0) {
3432 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3435 return array('v'=>(int)$seconds, 'u'=>1);
3439 * Get the selected duration as array.
3441 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3443 public function get_setting() {
3444 $seconds = $this->config_read($this->name);
3445 if (is_null($seconds)) {
3446 return null;
3449 return self::parse_seconds($seconds);
3453 * Store the duration as seconds.
3455 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3456 * @return bool true if success, false if not
3458 public function write_setting($data) {
3459 if (!is_array($data)) {
3460 return '';
3463 $seconds = (int)($data['v']*$data['u']);
3464 if ($seconds < 0) {
3465 return get_string('errorsetting', 'admin');
3468 $result = $this->config_write($this->name, $seconds);
3469 return ($result ? '' : get_string('errorsetting', 'admin'));
3473 * Returns duration text+select fields.
3475 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3476 * @param string $query
3477 * @return string duration text+select fields and wrapping div(s)
3479 public function output_html($data, $query='') {
3480 global $OUTPUT;
3482 $default = $this->get_defaultsetting();
3483 if (is_number($default)) {
3484 $defaultinfo = self::get_duration_text($default);
3485 } else if (is_array($default)) {
3486 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3487 } else {
3488 $defaultinfo = null;
3491 $inputid = $this->get_id() . 'v';
3492 $units = self::get_units();
3493 $defaultunit = $this->defaultunit;
3495 $context = (object) [
3496 'id' => $this->get_id(),
3497 'name' => $this->get_full_name(),
3498 'value' => $data['v'],
3499 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3500 return [
3501 'value' => $unit,
3502 'name' => $units[$unit],
3503 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3505 }, array_keys($units))
3508 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3510 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3516 * Seconds duration setting with an advanced checkbox, that controls a additional
3517 * $name.'_adv' setting.
3519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3520 * @copyright 2014 The Open University
3522 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3524 * Constructor
3525 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3526 * or 'myplugin/mysetting' for ones in config_plugins.
3527 * @param string $visiblename localised name
3528 * @param string $description localised long description
3529 * @param array $defaultsetting array of int value, and bool whether it is
3530 * is advanced by default.
3531 * @param int $defaultunit - day, week, etc. (in seconds)
3533 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3534 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3535 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3541 * Used to validate a textarea used for ip addresses
3543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3544 * @copyright 2011 Petr Skoda (http://skodak.org)
3546 class admin_setting_configiplist extends admin_setting_configtextarea {
3549 * Validate the contents of the textarea as IP addresses
3551 * Used to validate a new line separated list of IP addresses collected from
3552 * a textarea control
3554 * @param string $data A list of IP Addresses separated by new lines
3555 * @return mixed bool true for success or string:error on failure
3557 public function validate($data) {
3558 if(!empty($data)) {
3559 $ips = explode("\n", $data);
3560 } else {
3561 return true;
3563 $result = true;
3564 $badips = array();
3565 foreach($ips as $ip) {
3566 $ip = trim($ip);
3567 if (empty($ip)) {
3568 continue;
3570 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3571 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3572 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3573 } else {
3574 $result = false;
3575 $badips[] = $ip;
3578 if($result) {
3579 return true;
3580 } else {
3581 return get_string('validateiperror', 'admin', join(', ', $badips));
3588 * An admin setting for selecting one or more users who have a capability
3589 * in the system context
3591 * An admin setting for selecting one or more users, who have a particular capability
3592 * in the system context. Warning, make sure the list will never be too long. There is
3593 * no paging or searching of this list.
3595 * To correctly get a list of users from this config setting, you need to call the
3596 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3601 /** @var string The capabilities name */
3602 protected $capability;
3603 /** @var int include admin users too */
3604 protected $includeadmins;
3607 * Constructor.
3609 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3610 * @param string $visiblename localised name
3611 * @param string $description localised long description
3612 * @param array $defaultsetting array of usernames
3613 * @param string $capability string capability name.
3614 * @param bool $includeadmins include administrators
3616 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3617 $this->capability = $capability;
3618 $this->includeadmins = $includeadmins;
3619 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3623 * Load all of the uses who have the capability into choice array
3625 * @return bool Always returns true
3627 function load_choices() {
3628 if (is_array($this->choices)) {
3629 return true;
3631 list($sort, $sortparams) = users_order_by_sql('u');
3632 if (!empty($sortparams)) {
3633 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3634 'This is unexpected, and a problem because there is no way to pass these ' .
3635 'parameters to get_users_by_capability. See MDL-34657.');
3637 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3638 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3639 $this->choices = array(
3640 '$@NONE@$' => get_string('nobody'),
3641 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3643 if ($this->includeadmins) {
3644 $admins = get_admins();
3645 foreach ($admins as $user) {
3646 $this->choices[$user->id] = fullname($user);
3649 if (is_array($users)) {
3650 foreach ($users as $user) {
3651 $this->choices[$user->id] = fullname($user);
3654 return true;
3658 * Returns the default setting for class
3660 * @return mixed Array, or string. Empty string if no default
3662 public function get_defaultsetting() {
3663 $this->load_choices();
3664 $defaultsetting = parent::get_defaultsetting();
3665 if (empty($defaultsetting)) {
3666 return array('$@NONE@$');
3667 } else if (array_key_exists($defaultsetting, $this->choices)) {
3668 return $defaultsetting;
3669 } else {
3670 return '';
3675 * Returns the current setting
3677 * @return mixed array or string
3679 public function get_setting() {
3680 $result = parent::get_setting();
3681 if ($result === null) {
3682 // this is necessary for settings upgrade
3683 return null;
3685 if (empty($result)) {
3686 $result = array('$@NONE@$');
3688 return $result;
3692 * Save the chosen setting provided as $data
3694 * @param array $data
3695 * @return mixed string or array
3697 public function write_setting($data) {
3698 // If all is selected, remove any explicit options.
3699 if (in_array('$@ALL@$', $data)) {
3700 $data = array('$@ALL@$');
3702 // None never needs to be written to the DB.
3703 if (in_array('$@NONE@$', $data)) {
3704 unset($data[array_search('$@NONE@$', $data)]);
3706 return parent::write_setting($data);
3712 * Special checkbox for calendar - resets SESSION vars.
3714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3716 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3718 * Calls the parent::__construct with default values
3720 * name => calendar_adminseesall
3721 * visiblename => get_string('adminseesall', 'admin')
3722 * description => get_string('helpadminseesall', 'admin')
3723 * defaultsetting => 0
3725 public function __construct() {
3726 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3727 get_string('helpadminseesall', 'admin'), '0');
3731 * Stores the setting passed in $data
3733 * @param mixed gets converted to string for comparison
3734 * @return string empty string or error message
3736 public function write_setting($data) {
3737 global $SESSION;
3738 return parent::write_setting($data);
3743 * Special select for settings that are altered in setup.php and can not be altered on the fly
3745 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3747 class admin_setting_special_selectsetup extends admin_setting_configselect {
3749 * Reads the setting directly from the database
3751 * @return mixed
3753 public function get_setting() {
3754 // read directly from db!
3755 return get_config(NULL, $this->name);
3759 * Save the setting passed in $data
3761 * @param string $data The setting to save
3762 * @return string empty or error message
3764 public function write_setting($data) {
3765 global $CFG;
3766 // do not change active CFG setting!
3767 $current = $CFG->{$this->name};
3768 $result = parent::write_setting($data);
3769 $CFG->{$this->name} = $current;
3770 return $result;
3776 * Special select for frontpage - stores data in course table
3778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3780 class admin_setting_sitesetselect extends admin_setting_configselect {
3782 * Returns the site name for the selected site
3784 * @see get_site()
3785 * @return string The site name of the selected site
3787 public function get_setting() {
3788 $site = course_get_format(get_site())->get_course();
3789 return $site->{$this->name};
3793 * Updates the database and save the setting
3795 * @param string data
3796 * @return string empty or error message
3798 public function write_setting($data) {
3799 global $DB, $SITE, $COURSE;
3800 if (!in_array($data, array_keys($this->choices))) {
3801 return get_string('errorsetting', 'admin');
3803 $record = new stdClass();
3804 $record->id = SITEID;
3805 $temp = $this->name;
3806 $record->$temp = $data;
3807 $record->timemodified = time();
3809 course_get_format($SITE)->update_course_format_options($record);
3810 $DB->update_record('course', $record);
3812 // Reset caches.
3813 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3814 if ($SITE->id == $COURSE->id) {
3815 $COURSE = $SITE;
3817 format_base::reset_course_cache($SITE->id);
3819 return '';
3826 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3827 * block to hidden.
3829 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3831 class admin_setting_bloglevel extends admin_setting_configselect {
3833 * Updates the database and save the setting
3835 * @param string data
3836 * @return string empty or error message
3838 public function write_setting($data) {
3839 global $DB, $CFG;
3840 if ($data == 0) {
3841 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3842 foreach ($blogblocks as $block) {
3843 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3845 } else {
3846 // reenable all blocks only when switching from disabled blogs
3847 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3848 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3849 foreach ($blogblocks as $block) {
3850 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3854 return parent::write_setting($data);
3860 * Special select - lists on the frontpage - hacky
3862 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3864 class admin_setting_courselist_frontpage extends admin_setting {
3865 /** @var array Array of choices value=>label */
3866 public $choices;
3869 * Construct override, requires one param
3871 * @param bool $loggedin Is the user logged in
3873 public function __construct($loggedin) {
3874 global $CFG;
3875 require_once($CFG->dirroot.'/course/lib.php');
3876 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3877 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3878 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3879 $defaults = array(FRONTPAGEALLCOURSELIST);
3880 parent::__construct($name, $visiblename, $description, $defaults);
3884 * Loads the choices available
3886 * @return bool always returns true
3888 public function load_choices() {
3889 if (is_array($this->choices)) {
3890 return true;
3892 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3893 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3894 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3895 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3896 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3897 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3898 'none' => get_string('none'));
3899 if ($this->name === 'frontpage') {
3900 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3902 return true;
3906 * Returns the selected settings
3908 * @param mixed array or setting or null
3910 public function get_setting() {
3911 $result = $this->config_read($this->name);
3912 if (is_null($result)) {
3913 return NULL;
3915 if ($result === '') {
3916 return array();
3918 return explode(',', $result);
3922 * Save the selected options
3924 * @param array $data
3925 * @return mixed empty string (data is not an array) or bool true=success false=failure
3927 public function write_setting($data) {
3928 if (!is_array($data)) {
3929 return '';
3931 $this->load_choices();
3932 $save = array();
3933 foreach($data as $datum) {
3934 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3935 continue;
3937 $save[$datum] = $datum; // no duplicates
3939 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3943 * Return XHTML select field and wrapping div
3945 * @todo Add vartype handling to make sure $data is an array
3946 * @param array $data Array of elements to select by default
3947 * @return string XHTML select field and wrapping div
3949 public function output_html($data, $query='') {
3950 global $OUTPUT;
3952 $this->load_choices();
3953 $currentsetting = array();
3954 foreach ($data as $key) {
3955 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3956 $currentsetting[] = $key; // already selected first
3960 $context = (object) [
3961 'id' => $this->get_id(),
3962 'name' => $this->get_full_name(),
3965 $options = $this->choices;
3966 $selects = [];
3967 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3968 if (!array_key_exists($i, $currentsetting)) {
3969 $currentsetting[$i] = 'none';
3971 $selects[] = [
3972 'key' => $i,
3973 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
3974 return [
3975 'name' => $options[$option],
3976 'value' => $option,
3977 'selected' => $currentsetting[$i] == $option
3979 }, array_keys($options))
3982 $context->selects = $selects;
3984 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
3986 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
3992 * Special checkbox for frontpage - stores data in course table
3994 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3996 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3998 * Returns the current sites name
4000 * @return string
4002 public function get_setting() {
4003 $site = course_get_format(get_site())->get_course();
4004 return $site->{$this->name};
4008 * Save the selected setting
4010 * @param string $data The selected site
4011 * @return string empty string or error message
4013 public function write_setting($data) {
4014 global $DB, $SITE, $COURSE;
4015 $record = new stdClass();
4016 $record->id = $SITE->id;
4017 $record->{$this->name} = ($data == '1' ? 1 : 0);
4018 $record->timemodified = time();
4020 course_get_format($SITE)->update_course_format_options($record);
4021 $DB->update_record('course', $record);
4023 // Reset caches.
4024 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4025 if ($SITE->id == $COURSE->id) {
4026 $COURSE = $SITE;
4028 format_base::reset_course_cache($SITE->id);
4030 return '';
4035 * Special text for frontpage - stores data in course table.
4036 * Empty string means not set here. Manual setting is required.
4038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4040 class admin_setting_sitesettext extends admin_setting_configtext {
4043 * Constructor.
4045 public function __construct() {
4046 call_user_func_array(['parent', '__construct'], func_get_args());
4047 $this->set_force_ltr(false);
4051 * Return the current setting
4053 * @return mixed string or null
4055 public function get_setting() {
4056 $site = course_get_format(get_site())->get_course();
4057 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4061 * Validate the selected data
4063 * @param string $data The selected value to validate
4064 * @return mixed true or message string
4066 public function validate($data) {
4067 global $DB, $SITE;
4068 $cleaned = clean_param($data, PARAM_TEXT);
4069 if ($cleaned === '') {
4070 return get_string('required');
4072 if ($this->name ==='shortname' &&
4073 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4074 return get_string('shortnametaken', 'error', $data);
4076 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4077 return true;
4078 } else {
4079 return get_string('validateerror', 'admin');
4084 * Save the selected setting
4086 * @param string $data The selected value
4087 * @return string empty or error message
4089 public function write_setting($data) {
4090 global $DB, $SITE, $COURSE;
4091 $data = trim($data);
4092 $validated = $this->validate($data);
4093 if ($validated !== true) {
4094 return $validated;
4097 $record = new stdClass();
4098 $record->id = $SITE->id;
4099 $record->{$this->name} = $data;
4100 $record->timemodified = time();
4102 course_get_format($SITE)->update_course_format_options($record);
4103 $DB->update_record('course', $record);
4105 // Reset caches.
4106 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4107 if ($SITE->id == $COURSE->id) {
4108 $COURSE = $SITE;
4110 format_base::reset_course_cache($SITE->id);
4112 return '';
4118 * Special text editor for site description.
4120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4122 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4125 * Calls parent::__construct with specific arguments
4127 public function __construct() {
4128 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4129 PARAM_RAW, 60, 15);
4133 * Return the current setting
4134 * @return string The current setting
4136 public function get_setting() {
4137 $site = course_get_format(get_site())->get_course();
4138 return $site->{$this->name};
4142 * Save the new setting
4144 * @param string $data The new value to save
4145 * @return string empty or error message
4147 public function write_setting($data) {
4148 global $DB, $SITE, $COURSE;
4149 $record = new stdClass();
4150 $record->id = $SITE->id;
4151 $record->{$this->name} = $data;
4152 $record->timemodified = time();
4154 course_get_format($SITE)->update_course_format_options($record);
4155 $DB->update_record('course', $record);
4157 // Reset caches.
4158 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4159 if ($SITE->id == $COURSE->id) {
4160 $COURSE = $SITE;
4162 format_base::reset_course_cache($SITE->id);
4164 return '';
4170 * Administration interface for emoticon_manager settings.
4172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4174 class admin_setting_emoticons extends admin_setting {
4177 * Calls parent::__construct with specific args
4179 public function __construct() {
4180 global $CFG;
4182 $manager = get_emoticon_manager();
4183 $defaults = $this->prepare_form_data($manager->default_emoticons());
4184 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4188 * Return the current setting(s)
4190 * @return array Current settings array
4192 public function get_setting() {
4193 global $CFG;
4195 $manager = get_emoticon_manager();
4197 $config = $this->config_read($this->name);
4198 if (is_null($config)) {
4199 return null;
4202 $config = $manager->decode_stored_config($config);
4203 if (is_null($config)) {
4204 return null;
4207 return $this->prepare_form_data($config);
4211 * Save selected settings
4213 * @param array $data Array of settings to save
4214 * @return bool
4216 public function write_setting($data) {
4218 $manager = get_emoticon_manager();
4219 $emoticons = $this->process_form_data($data);
4221 if ($emoticons === false) {
4222 return false;
4225 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4226 return ''; // success
4227 } else {
4228 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4233 * Return XHTML field(s) for options
4235 * @param array $data Array of options to set in HTML
4236 * @return string XHTML string for the fields and wrapping div(s)
4238 public function output_html($data, $query='') {
4239 global $OUTPUT;
4241 $context = (object) [
4242 'name' => $this->get_full_name(),
4243 'emoticons' => [],
4244 'forceltr' => true,
4247 $i = 0;
4248 foreach ($data as $field => $value) {
4250 // When $i == 0: text.
4251 // When $i == 1: imagename.
4252 // When $i == 2: imagecomponent.
4253 // When $i == 3: altidentifier.
4254 // When $i == 4: altcomponent.
4255 $fields[$i] = (object) [
4256 'field' => $field,
4257 'value' => $value,
4258 'index' => $i
4260 $i++;
4262 if ($i > 4) {
4263 $icon = null;
4264 if (!empty($fields[1]->value)) {
4265 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4266 $alt = get_string($fields[3]->value, $fields[4]->value);
4267 } else {
4268 $alt = $fields[0]->value;
4270 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4272 $context->emoticons[] = [
4273 'fields' => $fields,
4274 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4276 $fields = [];
4277 $i = 0;
4281 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4282 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4283 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4287 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4289 * @see self::process_form_data()
4290 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4291 * @return array of form fields and their values
4293 protected function prepare_form_data(array $emoticons) {
4295 $form = array();
4296 $i = 0;
4297 foreach ($emoticons as $emoticon) {
4298 $form['text'.$i] = $emoticon->text;
4299 $form['imagename'.$i] = $emoticon->imagename;
4300 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4301 $form['altidentifier'.$i] = $emoticon->altidentifier;
4302 $form['altcomponent'.$i] = $emoticon->altcomponent;
4303 $i++;
4305 // add one more blank field set for new object
4306 $form['text'.$i] = '';
4307 $form['imagename'.$i] = '';
4308 $form['imagecomponent'.$i] = '';
4309 $form['altidentifier'.$i] = '';
4310 $form['altcomponent'.$i] = '';
4312 return $form;
4316 * Converts the data from admin settings form into an array of emoticon objects
4318 * @see self::prepare_form_data()
4319 * @param array $data array of admin form fields and values
4320 * @return false|array of emoticon objects
4322 protected function process_form_data(array $form) {
4324 $count = count($form); // number of form field values
4326 if ($count % 5) {
4327 // we must get five fields per emoticon object
4328 return false;
4331 $emoticons = array();
4332 for ($i = 0; $i < $count / 5; $i++) {
4333 $emoticon = new stdClass();
4334 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4335 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4336 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4337 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4338 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4340 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4341 // prevent from breaking http://url.addresses by accident
4342 $emoticon->text = '';
4345 if (strlen($emoticon->text) < 2) {
4346 // do not allow single character emoticons
4347 $emoticon->text = '';
4350 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4351 // emoticon text must contain some non-alphanumeric character to prevent
4352 // breaking HTML tags
4353 $emoticon->text = '';
4356 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4357 $emoticons[] = $emoticon;
4360 return $emoticons;
4367 * Special setting for limiting of the list of available languages.
4369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4371 class admin_setting_langlist extends admin_setting_configtext {
4373 * Calls parent::__construct with specific arguments
4375 public function __construct() {
4376 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4380 * Save the new setting
4382 * @param string $data The new setting
4383 * @return bool
4385 public function write_setting($data) {
4386 $return = parent::write_setting($data);
4387 get_string_manager()->reset_caches();
4388 return $return;
4394 * Selection of one of the recognised countries using the list
4395 * returned by {@link get_list_of_countries()}.
4397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4399 class admin_settings_country_select extends admin_setting_configselect {
4400 protected $includeall;
4401 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4402 $this->includeall = $includeall;
4403 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4407 * Lazy-load the available choices for the select box
4409 public function load_choices() {
4410 global $CFG;
4411 if (is_array($this->choices)) {
4412 return true;
4414 $this->choices = array_merge(
4415 array('0' => get_string('choosedots')),
4416 get_string_manager()->get_list_of_countries($this->includeall));
4417 return true;
4423 * admin_setting_configselect for the default number of sections in a course,
4424 * simply so we can lazy-load the choices.
4426 * @copyright 2011 The Open University
4427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4429 class admin_settings_num_course_sections extends admin_setting_configselect {
4430 public function __construct($name, $visiblename, $description, $defaultsetting) {
4431 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4434 /** Lazy-load the available choices for the select box */
4435 public function load_choices() {
4436 $max = get_config('moodlecourse', 'maxsections');
4437 if (!isset($max) || !is_numeric($max)) {
4438 $max = 52;
4440 for ($i = 0; $i <= $max; $i++) {
4441 $this->choices[$i] = "$i";
4443 return true;
4449 * Course category selection
4451 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4453 class admin_settings_coursecat_select extends admin_setting_configselect {
4455 * Calls parent::__construct with specific arguments
4457 public function __construct($name, $visiblename, $description, $defaultsetting) {
4458 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4462 * Load the available choices for the select box
4464 * @return bool
4466 public function load_choices() {
4467 global $CFG;
4468 require_once($CFG->dirroot.'/course/lib.php');
4469 if (is_array($this->choices)) {
4470 return true;
4472 $this->choices = make_categories_options();
4473 return true;
4479 * Special control for selecting days to backup
4481 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4483 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4485 * Calls parent::__construct with specific arguments
4487 public function __construct() {
4488 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4489 $this->plugin = 'backup';
4493 * Load the available choices for the select box
4495 * @return bool Always returns true
4497 public function load_choices() {
4498 if (is_array($this->choices)) {
4499 return true;
4501 $this->choices = array();
4502 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4503 foreach ($days as $day) {
4504 $this->choices[$day] = get_string($day, 'calendar');
4506 return true;
4511 * Special setting for backup auto destination.
4513 * @package core
4514 * @subpackage admin
4515 * @copyright 2014 Frédéric Massart - FMCorz.net
4516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4518 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4521 * Calls parent::__construct with specific arguments.
4523 public function __construct() {
4524 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4528 * Check if the directory must be set, depending on backup/backup_auto_storage.
4530 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4531 * there will be conflicts if this validation happens before the other one.
4533 * @param string $data Form data.
4534 * @return string Empty when no errors.
4536 public function write_setting($data) {
4537 $storage = (int) get_config('backup', 'backup_auto_storage');
4538 if ($storage !== 0) {
4539 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4540 // The directory must exist and be writable.
4541 return get_string('backuperrorinvaliddestination');
4544 return parent::write_setting($data);
4550 * Special debug setting
4552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4554 class admin_setting_special_debug extends admin_setting_configselect {
4556 * Calls parent::__construct with specific arguments
4558 public function __construct() {
4559 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4563 * Load the available choices for the select box
4565 * @return bool
4567 public function load_choices() {
4568 if (is_array($this->choices)) {
4569 return true;
4571 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4572 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4573 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4574 DEBUG_ALL => get_string('debugall', 'admin'),
4575 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4576 return true;
4582 * Special admin control
4584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4586 class admin_setting_special_calendar_weekend extends admin_setting {
4588 * Calls parent::__construct with specific arguments
4590 public function __construct() {
4591 $name = 'calendar_weekend';
4592 $visiblename = get_string('calendar_weekend', 'admin');
4593 $description = get_string('helpweekenddays', 'admin');
4594 $default = array ('0', '6'); // Saturdays and Sundays
4595 parent::__construct($name, $visiblename, $description, $default);
4599 * Gets the current settings as an array
4601 * @return mixed Null if none, else array of settings
4603 public function get_setting() {
4604 $result = $this->config_read($this->name);
4605 if (is_null($result)) {
4606 return NULL;
4608 if ($result === '') {
4609 return array();
4611 $settings = array();
4612 for ($i=0; $i<7; $i++) {
4613 if ($result & (1 << $i)) {
4614 $settings[] = $i;
4617 return $settings;
4621 * Save the new settings
4623 * @param array $data Array of new settings
4624 * @return bool
4626 public function write_setting($data) {
4627 if (!is_array($data)) {
4628 return '';
4630 unset($data['xxxxx']);
4631 $result = 0;
4632 foreach($data as $index) {
4633 $result |= 1 << $index;
4635 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4639 * Return XHTML to display the control
4641 * @param array $data array of selected days
4642 * @param string $query
4643 * @return string XHTML for display (field + wrapping div(s)
4645 public function output_html($data, $query='') {
4646 global $OUTPUT;
4648 // The order matters very much because of the implied numeric keys.
4649 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4650 $context = (object) [
4651 'name' => $this->get_full_name(),
4652 'id' => $this->get_id(),
4653 'days' => array_map(function($index) use ($days, $data) {
4654 return [
4655 'index' => $index,
4656 'label' => get_string($days[$index], 'calendar'),
4657 'checked' => in_array($index, $data)
4659 }, array_keys($days))
4662 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
4664 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4671 * Admin setting that allows a user to pick a behaviour.
4673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4675 class admin_setting_question_behaviour extends admin_setting_configselect {
4677 * @param string $name name of config variable
4678 * @param string $visiblename display name
4679 * @param string $description description
4680 * @param string $default default.
4682 public function __construct($name, $visiblename, $description, $default) {
4683 parent::__construct($name, $visiblename, $description, $default, null);
4687 * Load list of behaviours as choices
4688 * @return bool true => success, false => error.
4690 public function load_choices() {
4691 global $CFG;
4692 require_once($CFG->dirroot . '/question/engine/lib.php');
4693 $this->choices = question_engine::get_behaviour_options('');
4694 return true;
4700 * Admin setting that allows a user to pick appropriate roles for something.
4702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4704 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4705 /** @var array Array of capabilities which identify roles */
4706 private $types;
4709 * @param string $name Name of config variable
4710 * @param string $visiblename Display name
4711 * @param string $description Description
4712 * @param array $types Array of archetypes which identify
4713 * roles that will be enabled by default.
4715 public function __construct($name, $visiblename, $description, $types) {
4716 parent::__construct($name, $visiblename, $description, NULL, NULL);
4717 $this->types = $types;
4721 * Load roles as choices
4723 * @return bool true=>success, false=>error
4725 public function load_choices() {
4726 global $CFG, $DB;
4727 if (during_initial_install()) {
4728 return false;
4730 if (is_array($this->choices)) {
4731 return true;
4733 if ($roles = get_all_roles()) {
4734 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4735 return true;
4736 } else {
4737 return false;
4742 * Return the default setting for this control
4744 * @return array Array of default settings
4746 public function get_defaultsetting() {
4747 global $CFG;
4749 if (during_initial_install()) {
4750 return null;
4752 $result = array();
4753 foreach($this->types as $archetype) {
4754 if ($caproles = get_archetype_roles($archetype)) {
4755 foreach ($caproles as $caprole) {
4756 $result[$caprole->id] = 1;
4760 return $result;
4766 * Admin setting that is a list of installed filter plugins.
4768 * @copyright 2015 The Open University
4769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4771 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
4774 * Constructor
4776 * @param string $name unique ascii name, either 'mysetting' for settings
4777 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
4778 * @param string $visiblename localised name
4779 * @param string $description localised long description
4780 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
4782 public function __construct($name, $visiblename, $description, $default) {
4783 if (empty($default)) {
4784 $default = array();
4786 $this->load_choices();
4787 foreach ($default as $plugin) {
4788 if (!isset($this->choices[$plugin])) {
4789 unset($default[$plugin]);
4792 parent::__construct($name, $visiblename, $description, $default, null);
4795 public function load_choices() {
4796 if (is_array($this->choices)) {
4797 return true;
4799 $this->choices = array();
4801 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
4802 $this->choices[$plugin] = filter_get_name($plugin);
4804 return true;
4810 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4812 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4814 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4816 * Constructor
4817 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4818 * @param string $visiblename localised
4819 * @param string $description long localised info
4820 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4821 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4822 * @param int $size default field size
4824 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4825 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4826 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4832 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4834 * @copyright 2009 Petr Skoda (http://skodak.org)
4835 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4837 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4840 * Constructor
4841 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4842 * @param string $visiblename localised
4843 * @param string $description long localised info
4844 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4845 * @param string $yes value used when checked
4846 * @param string $no value used when not checked
4848 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4849 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4850 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4857 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4859 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4861 * @copyright 2010 Sam Hemelryk
4862 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4864 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4866 * Constructor
4867 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4868 * @param string $visiblename localised
4869 * @param string $description long localised info
4870 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4871 * @param string $yes value used when checked
4872 * @param string $no value used when not checked
4874 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4875 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4876 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4883 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4887 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4889 * Calls parent::__construct with specific arguments
4891 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4892 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4893 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4900 * Graded roles in gradebook
4902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4904 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4906 * Calls parent::__construct with specific arguments
4908 public function __construct() {
4909 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4910 get_string('configgradebookroles', 'admin'),
4911 array('student'));
4918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4920 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4922 * Saves the new settings passed in $data
4924 * @param string $data
4925 * @return mixed string or Array
4927 public function write_setting($data) {
4928 global $CFG, $DB;
4930 $oldvalue = $this->config_read($this->name);
4931 $return = parent::write_setting($data);
4932 $newvalue = $this->config_read($this->name);
4934 if ($oldvalue !== $newvalue) {
4935 // force full regrading
4936 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4939 return $return;
4945 * Which roles to show on course description page
4947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4949 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4951 * Calls parent::__construct with specific arguments
4953 public function __construct() {
4954 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4955 get_string('coursecontact_desc', 'admin'),
4956 array('editingteacher'));
4957 $this->set_updatedcallback(create_function('',
4958 "cache::make('core', 'coursecontacts')->purge();"));
4965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4967 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4969 * Calls parent::__construct with specific arguments
4971 public function __construct() {
4972 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4973 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4977 * Old syntax of class constructor. Deprecated in PHP7.
4979 * @deprecated since Moodle 3.1
4981 public function admin_setting_special_gradelimiting() {
4982 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
4983 self::__construct();
4987 * Force site regrading
4989 function regrade_all() {
4990 global $CFG;
4991 require_once("$CFG->libdir/gradelib.php");
4992 grade_force_site_regrading();
4996 * Saves the new settings
4998 * @param mixed $data
4999 * @return string empty string or error message
5001 function write_setting($data) {
5002 $previous = $this->get_setting();
5004 if ($previous === null) {
5005 if ($data) {
5006 $this->regrade_all();
5008 } else {
5009 if ($data != $previous) {
5010 $this->regrade_all();
5013 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5019 * Special setting for $CFG->grade_minmaxtouse.
5021 * @package core
5022 * @copyright 2015 Frédéric Massart - FMCorz.net
5023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5025 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5028 * Constructor.
5030 public function __construct() {
5031 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5032 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5033 array(
5034 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5035 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5041 * Saves the new setting.
5043 * @param mixed $data
5044 * @return string empty string or error message
5046 function write_setting($data) {
5047 global $CFG;
5049 $previous = $this->get_setting();
5050 $result = parent::write_setting($data);
5052 // If saved and the value has changed.
5053 if (empty($result) && $previous != $data) {
5054 require_once($CFG->libdir . '/gradelib.php');
5055 grade_force_site_regrading();
5058 return $result;
5065 * Primary grade export plugin - has state tracking.
5067 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5069 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5071 * Calls parent::__construct with specific arguments
5073 public function __construct() {
5074 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5075 get_string('configgradeexport', 'admin'), array(), NULL);
5079 * Load the available choices for the multicheckbox
5081 * @return bool always returns true
5083 public function load_choices() {
5084 if (is_array($this->choices)) {
5085 return true;
5087 $this->choices = array();
5089 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5090 foreach($plugins as $plugin => $unused) {
5091 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5094 return true;
5100 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5104 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5106 * Config gradepointmax constructor
5108 * @param string $name Overidden by "gradepointmax"
5109 * @param string $visiblename Overridden by "gradepointmax" language string.
5110 * @param string $description Overridden by "gradepointmax_help" language string.
5111 * @param string $defaultsetting Not used, overridden by 100.
5112 * @param mixed $paramtype Overridden by PARAM_INT.
5113 * @param int $size Overridden by 5.
5115 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5116 $name = 'gradepointdefault';
5117 $visiblename = get_string('gradepointdefault', 'grades');
5118 $description = get_string('gradepointdefault_help', 'grades');
5119 $defaultsetting = 100;
5120 $paramtype = PARAM_INT;
5121 $size = 5;
5122 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5126 * Validate data before storage
5127 * @param string $data The submitted data
5128 * @return bool|string true if ok, string if error found
5130 public function validate($data) {
5131 global $CFG;
5132 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5133 return true;
5134 } else {
5135 return get_string('gradepointdefault_validateerror', 'grades');
5142 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5144 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5146 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5149 * Config gradepointmax constructor
5151 * @param string $name Overidden by "gradepointmax"
5152 * @param string $visiblename Overridden by "gradepointmax" language string.
5153 * @param string $description Overridden by "gradepointmax_help" language string.
5154 * @param string $defaultsetting Not used, overridden by 100.
5155 * @param mixed $paramtype Overridden by PARAM_INT.
5156 * @param int $size Overridden by 5.
5158 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5159 $name = 'gradepointmax';
5160 $visiblename = get_string('gradepointmax', 'grades');
5161 $description = get_string('gradepointmax_help', 'grades');
5162 $defaultsetting = 100;
5163 $paramtype = PARAM_INT;
5164 $size = 5;
5165 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5169 * Save the selected setting
5171 * @param string $data The selected site
5172 * @return string empty string or error message
5174 public function write_setting($data) {
5175 if ($data === '') {
5176 $data = (int)$this->defaultsetting;
5177 } else {
5178 $data = $data;
5180 return parent::write_setting($data);
5184 * Validate data before storage
5185 * @param string $data The submitted data
5186 * @return bool|string true if ok, string if error found
5188 public function validate($data) {
5189 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5190 return true;
5191 } else {
5192 return get_string('gradepointmax_validateerror', 'grades');
5197 * Return an XHTML string for the setting
5198 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5199 * @param string $query search query to be highlighted
5200 * @return string XHTML to display control
5202 public function output_html($data, $query = '') {
5203 global $OUTPUT;
5205 $default = $this->get_defaultsetting();
5206 $context = (object) [
5207 'size' => $this->size,
5208 'id' => $this->get_id(),
5209 'name' => $this->get_full_name(),
5210 'value' => $data,
5211 'attributes' => [
5212 'maxlength' => 5
5214 'forceltr' => $this->get_force_ltr()
5216 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5218 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5224 * Grade category settings
5226 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5228 class admin_setting_gradecat_combo extends admin_setting {
5229 /** @var array Array of choices */
5230 public $choices;
5233 * Sets choices and calls parent::__construct with passed arguments
5234 * @param string $name
5235 * @param string $visiblename
5236 * @param string $description
5237 * @param mixed $defaultsetting string or array depending on implementation
5238 * @param array $choices An array of choices for the control
5240 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5241 $this->choices = $choices;
5242 parent::__construct($name, $visiblename, $description, $defaultsetting);
5246 * Return the current setting(s) array
5248 * @return array Array of value=>xx, forced=>xx, adv=>xx
5250 public function get_setting() {
5251 global $CFG;
5253 $value = $this->config_read($this->name);
5254 $flag = $this->config_read($this->name.'_flag');
5256 if (is_null($value) or is_null($flag)) {
5257 return NULL;
5260 $flag = (int)$flag;
5261 $forced = (boolean)(1 & $flag); // first bit
5262 $adv = (boolean)(2 & $flag); // second bit
5264 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5268 * Save the new settings passed in $data
5270 * @todo Add vartype handling to ensure $data is array
5271 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5272 * @return string empty or error message
5274 public function write_setting($data) {
5275 global $CFG;
5277 $value = $data['value'];
5278 $forced = empty($data['forced']) ? 0 : 1;
5279 $adv = empty($data['adv']) ? 0 : 2;
5280 $flag = ($forced | $adv); //bitwise or
5282 if (!in_array($value, array_keys($this->choices))) {
5283 return 'Error setting ';
5286 $oldvalue = $this->config_read($this->name);
5287 $oldflag = (int)$this->config_read($this->name.'_flag');
5288 $oldforced = (1 & $oldflag); // first bit
5290 $result1 = $this->config_write($this->name, $value);
5291 $result2 = $this->config_write($this->name.'_flag', $flag);
5293 // force regrade if needed
5294 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5295 require_once($CFG->libdir.'/gradelib.php');
5296 grade_category::updated_forced_settings();
5299 if ($result1 and $result2) {
5300 return '';
5301 } else {
5302 return get_string('errorsetting', 'admin');
5307 * Return XHTML to display the field and wrapping div
5309 * @todo Add vartype handling to ensure $data is array
5310 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5311 * @param string $query
5312 * @return string XHTML to display control
5314 public function output_html($data, $query='') {
5315 global $OUTPUT;
5317 $value = $data['value'];
5319 $default = $this->get_defaultsetting();
5320 if (!is_null($default)) {
5321 $defaultinfo = array();
5322 if (isset($this->choices[$default['value']])) {
5323 $defaultinfo[] = $this->choices[$default['value']];
5325 if (!empty($default['forced'])) {
5326 $defaultinfo[] = get_string('force');
5328 if (!empty($default['adv'])) {
5329 $defaultinfo[] = get_string('advanced');
5331 $defaultinfo = implode(', ', $defaultinfo);
5333 } else {
5334 $defaultinfo = NULL;
5337 $options = $this->choices;
5338 $context = (object) [
5339 'id' => $this->get_id(),
5340 'name' => $this->get_full_name(),
5341 'forced' => !empty($data['forced']),
5342 'advanced' => !empty($data['adv']),
5343 'options' => array_map(function($option) use ($options, $value) {
5344 return [
5345 'value' => $option,
5346 'name' => $options[$option],
5347 'selected' => $option == $value
5349 }, array_keys($options)),
5352 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5354 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5360 * Selection of grade report in user profiles
5362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5364 class admin_setting_grade_profilereport extends admin_setting_configselect {
5366 * Calls parent::__construct with specific arguments
5368 public function __construct() {
5369 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5373 * Loads an array of choices for the configselect control
5375 * @return bool always return true
5377 public function load_choices() {
5378 if (is_array($this->choices)) {
5379 return true;
5381 $this->choices = array();
5383 global $CFG;
5384 require_once($CFG->libdir.'/gradelib.php');
5386 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5387 if (file_exists($plugindir.'/lib.php')) {
5388 require_once($plugindir.'/lib.php');
5389 $functionname = 'grade_report_'.$plugin.'_profilereport';
5390 if (function_exists($functionname)) {
5391 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5395 return true;
5400 * Provides a selection of grade reports to be used for "grades".
5402 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5405 class admin_setting_my_grades_report extends admin_setting_configselect {
5408 * Calls parent::__construct with specific arguments.
5410 public function __construct() {
5411 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5412 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5416 * Loads an array of choices for the configselect control.
5418 * @return bool always returns true.
5420 public function load_choices() {
5421 global $CFG; // Remove this line and behold the horror of behat test failures!
5422 $this->choices = array();
5423 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5424 if (file_exists($plugindir . '/lib.php')) {
5425 require_once($plugindir . '/lib.php');
5426 // Check to see if the class exists. Check the correct plugin convention first.
5427 if (class_exists('gradereport_' . $plugin)) {
5428 $classname = 'gradereport_' . $plugin;
5429 } else if (class_exists('grade_report_' . $plugin)) {
5430 // We are using the old plugin naming convention.
5431 $classname = 'grade_report_' . $plugin;
5432 } else {
5433 continue;
5435 if ($classname::supports_mygrades()) {
5436 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5440 // Add an option to specify an external url.
5441 $this->choices['external'] = get_string('externalurl', 'grades');
5442 return true;
5447 * Special class for register auth selection
5449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5451 class admin_setting_special_registerauth extends admin_setting_configselect {
5453 * Calls parent::__construct with specific arguments
5455 public function __construct() {
5456 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5460 * Returns the default option
5462 * @return string empty or default option
5464 public function get_defaultsetting() {
5465 $this->load_choices();
5466 $defaultsetting = parent::get_defaultsetting();
5467 if (array_key_exists($defaultsetting, $this->choices)) {
5468 return $defaultsetting;
5469 } else {
5470 return '';
5475 * Loads the possible choices for the array
5477 * @return bool always returns true
5479 public function load_choices() {
5480 global $CFG;
5482 if (is_array($this->choices)) {
5483 return true;
5485 $this->choices = array();
5486 $this->choices[''] = get_string('disable');
5488 $authsenabled = get_enabled_auth_plugins(true);
5490 foreach ($authsenabled as $auth) {
5491 $authplugin = get_auth_plugin($auth);
5492 if (!$authplugin->can_signup()) {
5493 continue;
5495 // Get the auth title (from core or own auth lang files)
5496 $authtitle = $authplugin->get_title();
5497 $this->choices[$auth] = $authtitle;
5499 return true;
5505 * General plugins manager
5507 class admin_page_pluginsoverview extends admin_externalpage {
5510 * Sets basic information about the external page
5512 public function __construct() {
5513 global $CFG;
5514 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5515 "$CFG->wwwroot/$CFG->admin/plugins.php");
5520 * Module manage page
5522 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5524 class admin_page_managemods extends admin_externalpage {
5526 * Calls parent::__construct with specific arguments
5528 public function __construct() {
5529 global $CFG;
5530 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5534 * Try to find the specified module
5536 * @param string $query The module to search for
5537 * @return array
5539 public function search($query) {
5540 global $CFG, $DB;
5541 if ($result = parent::search($query)) {
5542 return $result;
5545 $found = false;
5546 if ($modules = $DB->get_records('modules')) {
5547 foreach ($modules as $module) {
5548 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5549 continue;
5551 if (strpos($module->name, $query) !== false) {
5552 $found = true;
5553 break;
5555 $strmodulename = get_string('modulename', $module->name);
5556 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5557 $found = true;
5558 break;
5562 if ($found) {
5563 $result = new stdClass();
5564 $result->page = $this;
5565 $result->settings = array();
5566 return array($this->name => $result);
5567 } else {
5568 return array();
5575 * Special class for enrol plugins management.
5577 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5578 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5580 class admin_setting_manageenrols extends admin_setting {
5582 * Calls parent::__construct with specific arguments
5584 public function __construct() {
5585 $this->nosave = true;
5586 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5590 * Always returns true, does nothing
5592 * @return true
5594 public function get_setting() {
5595 return true;
5599 * Always returns true, does nothing
5601 * @return true
5603 public function get_defaultsetting() {
5604 return true;
5608 * Always returns '', does not write anything
5610 * @return string Always returns ''
5612 public function write_setting($data) {
5613 // do not write any setting
5614 return '';
5618 * Checks if $query is one of the available enrol plugins
5620 * @param string $query The string to search for
5621 * @return bool Returns true if found, false if not
5623 public function is_related($query) {
5624 if (parent::is_related($query)) {
5625 return true;
5628 $query = core_text::strtolower($query);
5629 $enrols = enrol_get_plugins(false);
5630 foreach ($enrols as $name=>$enrol) {
5631 $localised = get_string('pluginname', 'enrol_'.$name);
5632 if (strpos(core_text::strtolower($name), $query) !== false) {
5633 return true;
5635 if (strpos(core_text::strtolower($localised), $query) !== false) {
5636 return true;
5639 return false;
5643 * Builds the XHTML to display the control
5645 * @param string $data Unused
5646 * @param string $query
5647 * @return string
5649 public function output_html($data, $query='') {
5650 global $CFG, $OUTPUT, $DB, $PAGE;
5652 // Display strings.
5653 $strup = get_string('up');
5654 $strdown = get_string('down');
5655 $strsettings = get_string('settings');
5656 $strenable = get_string('enable');
5657 $strdisable = get_string('disable');
5658 $struninstall = get_string('uninstallplugin', 'core_admin');
5659 $strusage = get_string('enrolusage', 'enrol');
5660 $strversion = get_string('version');
5661 $strtest = get_string('testsettings', 'core_enrol');
5663 $pluginmanager = core_plugin_manager::instance();
5665 $enrols_available = enrol_get_plugins(false);
5666 $active_enrols = enrol_get_plugins(true);
5668 $allenrols = array();
5669 foreach ($active_enrols as $key=>$enrol) {
5670 $allenrols[$key] = true;
5672 foreach ($enrols_available as $key=>$enrol) {
5673 $allenrols[$key] = true;
5675 // Now find all borked plugins and at least allow then to uninstall.
5676 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5677 foreach ($condidates as $candidate) {
5678 if (empty($allenrols[$candidate])) {
5679 $allenrols[$candidate] = true;
5683 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5684 $return .= $OUTPUT->box_start('generalbox enrolsui');
5686 $table = new html_table();
5687 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5688 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5689 $table->id = 'courseenrolmentplugins';
5690 $table->attributes['class'] = 'admintable generaltable';
5691 $table->data = array();
5693 // Iterate through enrol plugins and add to the display table.
5694 $updowncount = 1;
5695 $enrolcount = count($active_enrols);
5696 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5697 $printed = array();
5698 foreach($allenrols as $enrol => $unused) {
5699 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5700 $version = get_config('enrol_'.$enrol, 'version');
5701 if ($version === false) {
5702 $version = '';
5705 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5706 $name = get_string('pluginname', 'enrol_'.$enrol);
5707 } else {
5708 $name = $enrol;
5710 // Usage.
5711 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5712 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5713 $usage = "$ci / $cp";
5715 // Hide/show links.
5716 $class = '';
5717 if (isset($active_enrols[$enrol])) {
5718 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5719 $hideshow = "<a href=\"$aurl\">";
5720 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5721 $enabled = true;
5722 $displayname = $name;
5723 } else if (isset($enrols_available[$enrol])) {
5724 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5725 $hideshow = "<a href=\"$aurl\">";
5726 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5727 $enabled = false;
5728 $displayname = $name;
5729 $class = 'dimmed_text';
5730 } else {
5731 $hideshow = '';
5732 $enabled = false;
5733 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5735 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5736 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5737 } else {
5738 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5741 // Up/down link (only if enrol is enabled).
5742 $updown = '';
5743 if ($enabled) {
5744 if ($updowncount > 1) {
5745 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5746 $updown .= "<a href=\"$aurl\">";
5747 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5748 } else {
5749 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5751 if ($updowncount < $enrolcount) {
5752 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5753 $updown .= "<a href=\"$aurl\">";
5754 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5755 } else {
5756 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5758 ++$updowncount;
5761 // Add settings link.
5762 if (!$version) {
5763 $settings = '';
5764 } else if ($surl = $plugininfo->get_settings_url()) {
5765 $settings = html_writer::link($surl, $strsettings);
5766 } else {
5767 $settings = '';
5770 // Add uninstall info.
5771 $uninstall = '';
5772 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5773 $uninstall = html_writer::link($uninstallurl, $struninstall);
5776 $test = '';
5777 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5778 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5779 $test = html_writer::link($testsettingsurl, $strtest);
5782 // Add a row to the table.
5783 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5784 if ($class) {
5785 $row->attributes['class'] = $class;
5787 $table->data[] = $row;
5789 $printed[$enrol] = true;
5792 $return .= html_writer::table($table);
5793 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5794 $return .= $OUTPUT->box_end();
5795 return highlight($query, $return);
5801 * Blocks manage page
5803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5805 class admin_page_manageblocks extends admin_externalpage {
5807 * Calls parent::__construct with specific arguments
5809 public function __construct() {
5810 global $CFG;
5811 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5815 * Search for a specific block
5817 * @param string $query The string to search for
5818 * @return array
5820 public function search($query) {
5821 global $CFG, $DB;
5822 if ($result = parent::search($query)) {
5823 return $result;
5826 $found = false;
5827 if ($blocks = $DB->get_records('block')) {
5828 foreach ($blocks as $block) {
5829 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5830 continue;
5832 if (strpos($block->name, $query) !== false) {
5833 $found = true;
5834 break;
5836 $strblockname = get_string('pluginname', 'block_'.$block->name);
5837 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5838 $found = true;
5839 break;
5843 if ($found) {
5844 $result = new stdClass();
5845 $result->page = $this;
5846 $result->settings = array();
5847 return array($this->name => $result);
5848 } else {
5849 return array();
5855 * Message outputs configuration
5857 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5859 class admin_page_managemessageoutputs extends admin_externalpage {
5861 * Calls parent::__construct with specific arguments
5863 public function __construct() {
5864 global $CFG;
5865 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5869 * Search for a specific message processor
5871 * @param string $query The string to search for
5872 * @return array
5874 public function search($query) {
5875 global $CFG, $DB;
5876 if ($result = parent::search($query)) {
5877 return $result;
5880 $found = false;
5881 if ($processors = get_message_processors()) {
5882 foreach ($processors as $processor) {
5883 if (!$processor->available) {
5884 continue;
5886 if (strpos($processor->name, $query) !== false) {
5887 $found = true;
5888 break;
5890 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5891 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5892 $found = true;
5893 break;
5897 if ($found) {
5898 $result = new stdClass();
5899 $result->page = $this;
5900 $result->settings = array();
5901 return array($this->name => $result);
5902 } else {
5903 return array();
5909 * Default message outputs configuration
5911 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5913 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5915 * Calls parent::__construct with specific arguments
5917 public function __construct() {
5918 global $CFG;
5919 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5925 * Manage question behaviours page
5927 * @copyright 2011 The Open University
5928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5930 class admin_page_manageqbehaviours extends admin_externalpage {
5932 * Constructor
5934 public function __construct() {
5935 global $CFG;
5936 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5937 new moodle_url('/admin/qbehaviours.php'));
5941 * Search question behaviours for the specified string
5943 * @param string $query The string to search for in question behaviours
5944 * @return array
5946 public function search($query) {
5947 global $CFG;
5948 if ($result = parent::search($query)) {
5949 return $result;
5952 $found = false;
5953 require_once($CFG->dirroot . '/question/engine/lib.php');
5954 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5955 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5956 $query) !== false) {
5957 $found = true;
5958 break;
5961 if ($found) {
5962 $result = new stdClass();
5963 $result->page = $this;
5964 $result->settings = array();
5965 return array($this->name => $result);
5966 } else {
5967 return array();
5974 * Question type manage page
5976 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5978 class admin_page_manageqtypes extends admin_externalpage {
5980 * Calls parent::__construct with specific arguments
5982 public function __construct() {
5983 global $CFG;
5984 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5985 new moodle_url('/admin/qtypes.php'));
5989 * Search question types for the specified string
5991 * @param string $query The string to search for in question types
5992 * @return array
5994 public function search($query) {
5995 global $CFG;
5996 if ($result = parent::search($query)) {
5997 return $result;
6000 $found = false;
6001 require_once($CFG->dirroot . '/question/engine/bank.php');
6002 foreach (question_bank::get_all_qtypes() as $qtype) {
6003 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6004 $found = true;
6005 break;
6008 if ($found) {
6009 $result = new stdClass();
6010 $result->page = $this;
6011 $result->settings = array();
6012 return array($this->name => $result);
6013 } else {
6014 return array();
6020 class admin_page_manageportfolios extends admin_externalpage {
6022 * Calls parent::__construct with specific arguments
6024 public function __construct() {
6025 global $CFG;
6026 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6027 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6031 * Searches page for the specified string.
6032 * @param string $query The string to search for
6033 * @return bool True if it is found on this page
6035 public function search($query) {
6036 global $CFG;
6037 if ($result = parent::search($query)) {
6038 return $result;
6041 $found = false;
6042 $portfolios = core_component::get_plugin_list('portfolio');
6043 foreach ($portfolios as $p => $dir) {
6044 if (strpos($p, $query) !== false) {
6045 $found = true;
6046 break;
6049 if (!$found) {
6050 foreach (portfolio_instances(false, false) as $instance) {
6051 $title = $instance->get('name');
6052 if (strpos(core_text::strtolower($title), $query) !== false) {
6053 $found = true;
6054 break;
6059 if ($found) {
6060 $result = new stdClass();
6061 $result->page = $this;
6062 $result->settings = array();
6063 return array($this->name => $result);
6064 } else {
6065 return array();
6071 class admin_page_managerepositories extends admin_externalpage {
6073 * Calls parent::__construct with specific arguments
6075 public function __construct() {
6076 global $CFG;
6077 parent::__construct('managerepositories', get_string('manage',
6078 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6082 * Searches page for the specified string.
6083 * @param string $query The string to search for
6084 * @return bool True if it is found on this page
6086 public function search($query) {
6087 global $CFG;
6088 if ($result = parent::search($query)) {
6089 return $result;
6092 $found = false;
6093 $repositories= core_component::get_plugin_list('repository');
6094 foreach ($repositories as $p => $dir) {
6095 if (strpos($p, $query) !== false) {
6096 $found = true;
6097 break;
6100 if (!$found) {
6101 foreach (repository::get_types() as $instance) {
6102 $title = $instance->get_typename();
6103 if (strpos(core_text::strtolower($title), $query) !== false) {
6104 $found = true;
6105 break;
6110 if ($found) {
6111 $result = new stdClass();
6112 $result->page = $this;
6113 $result->settings = array();
6114 return array($this->name => $result);
6115 } else {
6116 return array();
6123 * Special class for authentication administration.
6125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6127 class admin_setting_manageauths extends admin_setting {
6129 * Calls parent::__construct with specific arguments
6131 public function __construct() {
6132 $this->nosave = true;
6133 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6137 * Always returns true
6139 * @return true
6141 public function get_setting() {
6142 return true;
6146 * Always returns true
6148 * @return true
6150 public function get_defaultsetting() {
6151 return true;
6155 * Always returns '' and doesn't write anything
6157 * @return string Always returns ''
6159 public function write_setting($data) {
6160 // do not write any setting
6161 return '';
6165 * Search to find if Query is related to auth plugin
6167 * @param string $query The string to search for
6168 * @return bool true for related false for not
6170 public function is_related($query) {
6171 if (parent::is_related($query)) {
6172 return true;
6175 $authsavailable = core_component::get_plugin_list('auth');
6176 foreach ($authsavailable as $auth => $dir) {
6177 if (strpos($auth, $query) !== false) {
6178 return true;
6180 $authplugin = get_auth_plugin($auth);
6181 $authtitle = $authplugin->get_title();
6182 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6183 return true;
6186 return false;
6190 * Return XHTML to display control
6192 * @param mixed $data Unused
6193 * @param string $query
6194 * @return string highlight
6196 public function output_html($data, $query='') {
6197 global $CFG, $OUTPUT, $DB;
6199 // display strings
6200 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6201 'settings', 'edit', 'name', 'enable', 'disable',
6202 'up', 'down', 'none', 'users'));
6203 $txt->updown = "$txt->up/$txt->down";
6204 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6205 $txt->testsettings = get_string('testsettings', 'core_auth');
6207 $authsavailable = core_component::get_plugin_list('auth');
6208 get_enabled_auth_plugins(true); // fix the list of enabled auths
6209 if (empty($CFG->auth)) {
6210 $authsenabled = array();
6211 } else {
6212 $authsenabled = explode(',', $CFG->auth);
6215 // construct the display array, with enabled auth plugins at the top, in order
6216 $displayauths = array();
6217 $registrationauths = array();
6218 $registrationauths[''] = $txt->disable;
6219 $authplugins = array();
6220 foreach ($authsenabled as $auth) {
6221 $authplugin = get_auth_plugin($auth);
6222 $authplugins[$auth] = $authplugin;
6223 /// Get the auth title (from core or own auth lang files)
6224 $authtitle = $authplugin->get_title();
6225 /// Apply titles
6226 $displayauths[$auth] = $authtitle;
6227 if ($authplugin->can_signup()) {
6228 $registrationauths[$auth] = $authtitle;
6232 foreach ($authsavailable as $auth => $dir) {
6233 if (array_key_exists($auth, $displayauths)) {
6234 continue; //already in the list
6236 $authplugin = get_auth_plugin($auth);
6237 $authplugins[$auth] = $authplugin;
6238 /// Get the auth title (from core or own auth lang files)
6239 $authtitle = $authplugin->get_title();
6240 /// Apply titles
6241 $displayauths[$auth] = $authtitle;
6242 if ($authplugin->can_signup()) {
6243 $registrationauths[$auth] = $authtitle;
6247 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6248 $return .= $OUTPUT->box_start('generalbox authsui');
6250 $table = new html_table();
6251 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6252 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6253 $table->data = array();
6254 $table->attributes['class'] = 'admintable generaltable';
6255 $table->id = 'manageauthtable';
6257 //add always enabled plugins first
6258 $displayname = $displayauths['manual'];
6259 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6260 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6261 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6262 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6263 $displayname = $displayauths['nologin'];
6264 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6265 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6266 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6269 // iterate through auth plugins and add to the display table
6270 $updowncount = 1;
6271 $authcount = count($authsenabled);
6272 $url = "auth.php?sesskey=" . sesskey();
6273 foreach ($displayauths as $auth => $name) {
6274 if ($auth == 'manual' or $auth == 'nologin') {
6275 continue;
6277 $class = '';
6278 // hide/show link
6279 if (in_array($auth, $authsenabled)) {
6280 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6281 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6282 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6283 $enabled = true;
6284 $displayname = $name;
6286 else {
6287 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6288 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6289 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6290 $enabled = false;
6291 $displayname = $name;
6292 $class = 'dimmed_text';
6295 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6297 // up/down link (only if auth is enabled)
6298 $updown = '';
6299 if ($enabled) {
6300 if ($updowncount > 1) {
6301 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6302 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6304 else {
6305 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6307 if ($updowncount < $authcount) {
6308 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6309 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6311 else {
6312 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6314 ++ $updowncount;
6317 // settings link
6318 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6319 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6320 } else {
6321 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6324 // Uninstall link.
6325 $uninstall = '';
6326 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6327 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6330 $test = '';
6331 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6332 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6333 $test = html_writer::link($testurl, $txt->testsettings);
6336 // Add a row to the table.
6337 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6338 if ($class) {
6339 $row->attributes['class'] = $class;
6341 $table->data[] = $row;
6343 $return .= html_writer::table($table);
6344 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6345 $return .= $OUTPUT->box_end();
6346 return highlight($query, $return);
6352 * Special class for authentication administration.
6354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6356 class admin_setting_manageeditors extends admin_setting {
6358 * Calls parent::__construct with specific arguments
6360 public function __construct() {
6361 $this->nosave = true;
6362 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6366 * Always returns true, does nothing
6368 * @return true
6370 public function get_setting() {
6371 return true;
6375 * Always returns true, does nothing
6377 * @return true
6379 public function get_defaultsetting() {
6380 return true;
6384 * Always returns '', does not write anything
6386 * @return string Always returns ''
6388 public function write_setting($data) {
6389 // do not write any setting
6390 return '';
6394 * Checks if $query is one of the available editors
6396 * @param string $query The string to search for
6397 * @return bool Returns true if found, false if not
6399 public function is_related($query) {
6400 if (parent::is_related($query)) {
6401 return true;
6404 $editors_available = editors_get_available();
6405 foreach ($editors_available as $editor=>$editorstr) {
6406 if (strpos($editor, $query) !== false) {
6407 return true;
6409 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6410 return true;
6413 return false;
6417 * Builds the XHTML to display the control
6419 * @param string $data Unused
6420 * @param string $query
6421 * @return string
6423 public function output_html($data, $query='') {
6424 global $CFG, $OUTPUT;
6426 // display strings
6427 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6428 'up', 'down', 'none'));
6429 $struninstall = get_string('uninstallplugin', 'core_admin');
6431 $txt->updown = "$txt->up/$txt->down";
6433 $editors_available = editors_get_available();
6434 $active_editors = explode(',', $CFG->texteditors);
6436 $active_editors = array_reverse($active_editors);
6437 foreach ($active_editors as $key=>$editor) {
6438 if (empty($editors_available[$editor])) {
6439 unset($active_editors[$key]);
6440 } else {
6441 $name = $editors_available[$editor];
6442 unset($editors_available[$editor]);
6443 $editors_available[$editor] = $name;
6446 if (empty($active_editors)) {
6447 //$active_editors = array('textarea');
6449 $editors_available = array_reverse($editors_available, true);
6450 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6451 $return .= $OUTPUT->box_start('generalbox editorsui');
6453 $table = new html_table();
6454 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6455 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6456 $table->id = 'editormanagement';
6457 $table->attributes['class'] = 'admintable generaltable';
6458 $table->data = array();
6460 // iterate through auth plugins and add to the display table
6461 $updowncount = 1;
6462 $editorcount = count($active_editors);
6463 $url = "editors.php?sesskey=" . sesskey();
6464 foreach ($editors_available as $editor => $name) {
6465 // hide/show link
6466 $class = '';
6467 if (in_array($editor, $active_editors)) {
6468 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6469 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6470 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6471 $enabled = true;
6472 $displayname = $name;
6474 else {
6475 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6476 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6477 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6478 $enabled = false;
6479 $displayname = $name;
6480 $class = 'dimmed_text';
6483 // up/down link (only if auth is enabled)
6484 $updown = '';
6485 if ($enabled) {
6486 if ($updowncount > 1) {
6487 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6488 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6490 else {
6491 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6493 if ($updowncount < $editorcount) {
6494 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6495 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6497 else {
6498 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6500 ++ $updowncount;
6503 // settings link
6504 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6505 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6506 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6507 } else {
6508 $settings = '';
6511 $uninstall = '';
6512 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6513 $uninstall = html_writer::link($uninstallurl, $struninstall);
6516 // Add a row to the table.
6517 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6518 if ($class) {
6519 $row->attributes['class'] = $class;
6521 $table->data[] = $row;
6523 $return .= html_writer::table($table);
6524 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6525 $return .= $OUTPUT->box_end();
6526 return highlight($query, $return);
6531 * Special class for antiviruses administration.
6533 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6536 class admin_setting_manageantiviruses extends admin_setting {
6538 * Calls parent::__construct with specific arguments
6540 public function __construct() {
6541 $this->nosave = true;
6542 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6546 * Always returns true, does nothing
6548 * @return true
6550 public function get_setting() {
6551 return true;
6555 * Always returns true, does nothing
6557 * @return true
6559 public function get_defaultsetting() {
6560 return true;
6564 * Always returns '', does not write anything
6566 * @param string $data Unused
6567 * @return string Always returns ''
6569 public function write_setting($data) {
6570 // Do not write any setting.
6571 return '';
6575 * Checks if $query is one of the available editors
6577 * @param string $query The string to search for
6578 * @return bool Returns true if found, false if not
6580 public function is_related($query) {
6581 if (parent::is_related($query)) {
6582 return true;
6585 $antivirusesavailable = \core\antivirus\manager::get_available();
6586 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6587 if (strpos($antivirus, $query) !== false) {
6588 return true;
6590 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6591 return true;
6594 return false;
6598 * Builds the XHTML to display the control
6600 * @param string $data Unused
6601 * @param string $query
6602 * @return string
6604 public function output_html($data, $query='') {
6605 global $CFG, $OUTPUT;
6607 // Display strings.
6608 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6609 'up', 'down', 'none'));
6610 $struninstall = get_string('uninstallplugin', 'core_admin');
6612 $txt->updown = "$txt->up/$txt->down";
6614 $antivirusesavailable = \core\antivirus\manager::get_available();
6615 $activeantiviruses = explode(',', $CFG->antiviruses);
6617 $activeantiviruses = array_reverse($activeantiviruses);
6618 foreach ($activeantiviruses as $key => $antivirus) {
6619 if (empty($antivirusesavailable[$antivirus])) {
6620 unset($activeantiviruses[$key]);
6621 } else {
6622 $name = $antivirusesavailable[$antivirus];
6623 unset($antivirusesavailable[$antivirus]);
6624 $antivirusesavailable[$antivirus] = $name;
6627 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6628 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6629 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6631 $table = new html_table();
6632 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6633 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6634 $table->id = 'antivirusmanagement';
6635 $table->attributes['class'] = 'admintable generaltable';
6636 $table->data = array();
6638 // Iterate through auth plugins and add to the display table.
6639 $updowncount = 1;
6640 $antiviruscount = count($activeantiviruses);
6641 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6642 foreach ($antivirusesavailable as $antivirus => $name) {
6643 // Hide/show link.
6644 $class = '';
6645 if (in_array($antivirus, $activeantiviruses)) {
6646 $hideshowurl = $baseurl;
6647 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6648 $hideshowimg = html_writer::img($OUTPUT->pix_url('t/hide'), 'disable', array('class' => 'iconsmall'));
6649 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6650 $enabled = true;
6651 $displayname = $name;
6652 } else {
6653 $hideshowurl = $baseurl;
6654 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6655 $hideshowimg = html_writer::img($OUTPUT->pix_url('t/show'), 'enable', array('class' => 'iconsmall'));
6656 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6657 $enabled = false;
6658 $displayname = $name;
6659 $class = 'dimmed_text';
6662 // Up/down link.
6663 $updown = '';
6664 if ($enabled) {
6665 if ($updowncount > 1) {
6666 $updownurl = $baseurl;
6667 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6668 $updownimg = html_writer::img($OUTPUT->pix_url('t/up'), 'up', array('class' => 'iconsmall'));
6669 $updown = html_writer::link($updownurl, $updownimg);
6670 } else {
6671 $updown .= html_writer::img($OUTPUT->pix_url('spacer'), '', array('class' => 'iconsmall'));
6673 if ($updowncount < $antiviruscount) {
6674 $updownurl = $baseurl;
6675 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6676 $updownimg = html_writer::img($OUTPUT->pix_url('t/down'), 'down', array('class' => 'iconsmall'));
6677 $updown = html_writer::link($updownurl, $updownimg);
6678 } else {
6679 $updown .= html_writer::img($OUTPUT->pix_url('spacer'), '', array('class' => 'iconsmall'));
6681 ++ $updowncount;
6684 // Settings link.
6685 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6686 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6687 $settings = html_writer::link($eurl, $txt->settings);
6688 } else {
6689 $settings = '';
6692 $uninstall = '';
6693 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6694 $uninstall = html_writer::link($uninstallurl, $struninstall);
6697 // Add a row to the table.
6698 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6699 if ($class) {
6700 $row->attributes['class'] = $class;
6702 $table->data[] = $row;
6704 $return .= html_writer::table($table);
6705 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6706 $return .= $OUTPUT->box_end();
6707 return highlight($query, $return);
6712 * Special class for license administration.
6714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6716 class admin_setting_managelicenses extends admin_setting {
6718 * Calls parent::__construct with specific arguments
6720 public function __construct() {
6721 $this->nosave = true;
6722 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6726 * Always returns true, does nothing
6728 * @return true
6730 public function get_setting() {
6731 return true;
6735 * Always returns true, does nothing
6737 * @return true
6739 public function get_defaultsetting() {
6740 return true;
6744 * Always returns '', does not write anything
6746 * @return string Always returns ''
6748 public function write_setting($data) {
6749 // do not write any setting
6750 return '';
6754 * Builds the XHTML to display the control
6756 * @param string $data Unused
6757 * @param string $query
6758 * @return string
6760 public function output_html($data, $query='') {
6761 global $CFG, $OUTPUT;
6762 require_once($CFG->libdir . '/licenselib.php');
6763 $url = "licenses.php?sesskey=" . sesskey();
6765 // display strings
6766 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6767 $licenses = license_manager::get_licenses();
6769 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6771 $return .= $OUTPUT->box_start('generalbox editorsui');
6773 $table = new html_table();
6774 $table->head = array($txt->name, $txt->enable);
6775 $table->colclasses = array('leftalign', 'centeralign');
6776 $table->id = 'availablelicenses';
6777 $table->attributes['class'] = 'admintable generaltable';
6778 $table->data = array();
6780 foreach ($licenses as $value) {
6781 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6783 if ($value->enabled == 1) {
6784 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6785 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6786 } else {
6787 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6788 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6791 if ($value->shortname == $CFG->sitedefaultlicense) {
6792 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6793 $hideshow = '';
6796 $enabled = true;
6798 $table->data[] =array($displayname, $hideshow);
6800 $return .= html_writer::table($table);
6801 $return .= $OUTPUT->box_end();
6802 return highlight($query, $return);
6807 * Course formats manager. Allows to enable/disable formats and jump to settings
6809 class admin_setting_manageformats extends admin_setting {
6812 * Calls parent::__construct with specific arguments
6814 public function __construct() {
6815 $this->nosave = true;
6816 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6820 * Always returns true
6822 * @return true
6824 public function get_setting() {
6825 return true;
6829 * Always returns true
6831 * @return true
6833 public function get_defaultsetting() {
6834 return true;
6838 * Always returns '' and doesn't write anything
6840 * @param mixed $data string or array, must not be NULL
6841 * @return string Always returns ''
6843 public function write_setting($data) {
6844 // do not write any setting
6845 return '';
6849 * Search to find if Query is related to format plugin
6851 * @param string $query The string to search for
6852 * @return bool true for related false for not
6854 public function is_related($query) {
6855 if (parent::is_related($query)) {
6856 return true;
6858 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6859 foreach ($formats as $format) {
6860 if (strpos($format->component, $query) !== false ||
6861 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6862 return true;
6865 return false;
6869 * Return XHTML to display control
6871 * @param mixed $data Unused
6872 * @param string $query
6873 * @return string highlight
6875 public function output_html($data, $query='') {
6876 global $CFG, $OUTPUT;
6877 $return = '';
6878 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6879 $return .= $OUTPUT->box_start('generalbox formatsui');
6881 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6883 // display strings
6884 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6885 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6886 $txt->updown = "$txt->up/$txt->down";
6888 $table = new html_table();
6889 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6890 $table->align = array('left', 'center', 'center', 'center', 'center');
6891 $table->attributes['class'] = 'manageformattable generaltable admintable';
6892 $table->data = array();
6894 $cnt = 0;
6895 $defaultformat = get_config('moodlecourse', 'format');
6896 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6897 foreach ($formats as $format) {
6898 $url = new moodle_url('/admin/courseformats.php',
6899 array('sesskey' => sesskey(), 'format' => $format->name));
6900 $isdefault = '';
6901 $class = '';
6902 if ($format->is_enabled()) {
6903 $strformatname = $format->displayname;
6904 if ($defaultformat === $format->name) {
6905 $hideshow = $txt->default;
6906 } else {
6907 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6908 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6910 } else {
6911 $strformatname = $format->displayname;
6912 $class = 'dimmed_text';
6913 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6914 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6916 $updown = '';
6917 if ($cnt) {
6918 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6919 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6920 } else {
6921 $updown .= $spacer;
6923 if ($cnt < count($formats) - 1) {
6924 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6925 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6926 } else {
6927 $updown .= $spacer;
6929 $cnt++;
6930 $settings = '';
6931 if ($format->get_settings_url()) {
6932 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6934 $uninstall = '';
6935 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6936 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6938 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6939 if ($class) {
6940 $row->attributes['class'] = $class;
6942 $table->data[] = $row;
6944 $return .= html_writer::table($table);
6945 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6946 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6947 $return .= $OUTPUT->box_end();
6948 return highlight($query, $return);
6953 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
6955 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
6956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6958 class admin_setting_managedataformats extends admin_setting {
6961 * Calls parent::__construct with specific arguments
6963 public function __construct() {
6964 $this->nosave = true;
6965 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
6969 * Always returns true
6971 * @return true
6973 public function get_setting() {
6974 return true;
6978 * Always returns true
6980 * @return true
6982 public function get_defaultsetting() {
6983 return true;
6987 * Always returns '' and doesn't write anything
6989 * @param mixed $data string or array, must not be NULL
6990 * @return string Always returns ''
6992 public function write_setting($data) {
6993 // Do not write any setting.
6994 return '';
6998 * Search to find if Query is related to format plugin
7000 * @param string $query The string to search for
7001 * @return bool true for related false for not
7003 public function is_related($query) {
7004 if (parent::is_related($query)) {
7005 return true;
7007 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7008 foreach ($formats as $format) {
7009 if (strpos($format->component, $query) !== false ||
7010 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7011 return true;
7014 return false;
7018 * Return XHTML to display control
7020 * @param mixed $data Unused
7021 * @param string $query
7022 * @return string highlight
7024 public function output_html($data, $query='') {
7025 global $CFG, $OUTPUT;
7026 $return = '';
7028 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7030 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7031 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7032 $txt->updown = "$txt->up/$txt->down";
7034 $table = new html_table();
7035 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7036 $table->align = array('left', 'center', 'center', 'center', 'center');
7037 $table->attributes['class'] = 'manageformattable generaltable admintable';
7038 $table->data = array();
7040 $cnt = 0;
7041 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7042 $totalenabled = 0;
7043 foreach ($formats as $format) {
7044 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7045 $totalenabled++;
7048 foreach ($formats as $format) {
7049 $status = $format->get_status();
7050 $url = new moodle_url('/admin/dataformats.php',
7051 array('sesskey' => sesskey(), 'name' => $format->name));
7053 $class = '';
7054 if ($format->is_enabled()) {
7055 $strformatname = $format->displayname;
7056 if ($totalenabled == 1&& $format->is_enabled()) {
7057 $hideshow = '';
7058 } else {
7059 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7060 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7062 } else {
7063 $class = 'dimmed_text';
7064 $strformatname = $format->displayname;
7065 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7066 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7069 $updown = '';
7070 if ($cnt) {
7071 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7072 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7073 } else {
7074 $updown .= $spacer;
7076 if ($cnt < count($formats) - 1) {
7077 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7078 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7079 } else {
7080 $updown .= $spacer;
7083 $uninstall = '';
7084 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7085 $uninstall = get_string('status_missing', 'core_plugin');
7086 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7087 $uninstall = get_string('status_new', 'core_plugin');
7088 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7089 if ($totalenabled != 1 || !$format->is_enabled()) {
7090 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7094 $settings = '';
7095 if ($format->get_settings_url()) {
7096 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7099 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7100 if ($class) {
7101 $row->attributes['class'] = $class;
7103 $table->data[] = $row;
7104 $cnt++;
7106 $return .= html_writer::table($table);
7107 return highlight($query, $return);
7112 * Special class for filter administration.
7114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7116 class admin_page_managefilters extends admin_externalpage {
7118 * Calls parent::__construct with specific arguments
7120 public function __construct() {
7121 global $CFG;
7122 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7126 * Searches all installed filters for specified filter
7128 * @param string $query The filter(string) to search for
7129 * @param string $query
7131 public function search($query) {
7132 global $CFG;
7133 if ($result = parent::search($query)) {
7134 return $result;
7137 $found = false;
7138 $filternames = filter_get_all_installed();
7139 foreach ($filternames as $path => $strfiltername) {
7140 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7141 $found = true;
7142 break;
7144 if (strpos($path, $query) !== false) {
7145 $found = true;
7146 break;
7150 if ($found) {
7151 $result = new stdClass;
7152 $result->page = $this;
7153 $result->settings = array();
7154 return array($this->name => $result);
7155 } else {
7156 return array();
7163 * Initialise admin page - this function does require login and permission
7164 * checks specified in page definition.
7166 * This function must be called on each admin page before other code.
7168 * @global moodle_page $PAGE
7170 * @param string $section name of page
7171 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7172 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7173 * added to the turn blocks editing on/off form, so this page reloads correctly.
7174 * @param string $actualurl if the actual page being viewed is not the normal one for this
7175 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7176 * @param array $options Additional options that can be specified for page setup.
7177 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7179 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7180 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7182 $PAGE->set_context(null); // hack - set context to something, by default to system context
7184 $site = get_site();
7185 require_login();
7187 if (!empty($options['pagelayout'])) {
7188 // A specific page layout has been requested.
7189 $PAGE->set_pagelayout($options['pagelayout']);
7190 } else if ($section === 'upgradesettings') {
7191 $PAGE->set_pagelayout('maintenance');
7192 } else {
7193 $PAGE->set_pagelayout('admin');
7196 $adminroot = admin_get_root(false, false); // settings not required for external pages
7197 $extpage = $adminroot->locate($section, true);
7199 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7200 // The requested section isn't in the admin tree
7201 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7202 if (!has_capability('moodle/site:config', context_system::instance())) {
7203 // The requested section could depend on a different capability
7204 // but most likely the user has inadequate capabilities
7205 print_error('accessdenied', 'admin');
7206 } else {
7207 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7211 // this eliminates our need to authenticate on the actual pages
7212 if (!$extpage->check_access()) {
7213 print_error('accessdenied', 'admin');
7214 die;
7217 navigation_node::require_admin_tree();
7219 // $PAGE->set_extra_button($extrabutton); TODO
7221 if (!$actualurl) {
7222 $actualurl = $extpage->url;
7225 $PAGE->set_url($actualurl, $extraurlparams);
7226 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7227 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7230 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7231 // During initial install.
7232 $strinstallation = get_string('installation', 'install');
7233 $strsettings = get_string('settings');
7234 $PAGE->navbar->add($strsettings);
7235 $PAGE->set_title($strinstallation);
7236 $PAGE->set_heading($strinstallation);
7237 $PAGE->set_cacheable(false);
7238 return;
7241 // Locate the current item on the navigation and make it active when found.
7242 $path = $extpage->path;
7243 $node = $PAGE->settingsnav;
7244 while ($node && count($path) > 0) {
7245 $node = $node->get(array_pop($path));
7247 if ($node) {
7248 $node->make_active();
7251 // Normal case.
7252 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7253 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7254 $USER->editing = $adminediting;
7257 $visiblepathtosection = array_reverse($extpage->visiblepath);
7259 if ($PAGE->user_allowed_editing()) {
7260 if ($PAGE->user_is_editing()) {
7261 $caption = get_string('blockseditoff');
7262 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7263 } else {
7264 $caption = get_string('blocksediton');
7265 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7267 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7270 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7271 $PAGE->set_heading($SITE->fullname);
7273 // prevent caching in nav block
7274 $PAGE->navigation->clear_cache();
7278 * Returns the reference to admin tree root
7280 * @return object admin_root object
7282 function admin_get_root($reload=false, $requirefulltree=true) {
7283 global $CFG, $DB, $OUTPUT;
7285 static $ADMIN = NULL;
7287 if (is_null($ADMIN)) {
7288 // create the admin tree!
7289 $ADMIN = new admin_root($requirefulltree);
7292 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7293 $ADMIN->purge_children($requirefulltree);
7296 if (!$ADMIN->loaded) {
7297 // we process this file first to create categories first and in correct order
7298 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7300 // now we process all other files in admin/settings to build the admin tree
7301 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7302 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7303 continue;
7305 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7306 // plugins are loaded last - they may insert pages anywhere
7307 continue;
7309 require($file);
7311 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
7313 $ADMIN->loaded = true;
7316 return $ADMIN;
7319 /// settings utility functions
7322 * This function applies default settings.
7324 * @param object $node, NULL means complete tree, null by default
7325 * @param bool $unconditional if true overrides all values with defaults, null buy default
7327 function admin_apply_default_settings($node=NULL, $unconditional=true) {
7328 global $CFG;
7330 if (is_null($node)) {
7331 core_plugin_manager::reset_caches();
7332 $node = admin_get_root(true, true);
7335 if ($node instanceof admin_category) {
7336 $entries = array_keys($node->children);
7337 foreach ($entries as $entry) {
7338 admin_apply_default_settings($node->children[$entry], $unconditional);
7341 } else if ($node instanceof admin_settingpage) {
7342 foreach ($node->settings as $setting) {
7343 if (!$unconditional and !is_null($setting->get_setting())) {
7344 //do not override existing defaults
7345 continue;
7347 $defaultsetting = $setting->get_defaultsetting();
7348 if (is_null($defaultsetting)) {
7349 // no value yet - default maybe applied after admin user creation or in upgradesettings
7350 continue;
7352 $setting->write_setting($defaultsetting);
7353 $setting->write_setting_flags(null);
7356 // Just in case somebody modifies the list of active plugins directly.
7357 core_plugin_manager::reset_caches();
7361 * Store changed settings, this function updates the errors variable in $ADMIN
7363 * @param object $formdata from form
7364 * @return int number of changed settings
7366 function admin_write_settings($formdata) {
7367 global $CFG, $SITE, $DB;
7369 $olddbsessions = !empty($CFG->dbsessions);
7370 $formdata = (array)$formdata;
7372 $data = array();
7373 foreach ($formdata as $fullname=>$value) {
7374 if (strpos($fullname, 's_') !== 0) {
7375 continue; // not a config value
7377 $data[$fullname] = $value;
7380 $adminroot = admin_get_root();
7381 $settings = admin_find_write_settings($adminroot, $data);
7383 $count = 0;
7384 foreach ($settings as $fullname=>$setting) {
7385 /** @var $setting admin_setting */
7386 $original = $setting->get_setting();
7387 $error = $setting->write_setting($data[$fullname]);
7388 if ($error !== '') {
7389 $adminroot->errors[$fullname] = new stdClass();
7390 $adminroot->errors[$fullname]->data = $data[$fullname];
7391 $adminroot->errors[$fullname]->id = $setting->get_id();
7392 $adminroot->errors[$fullname]->error = $error;
7393 } else {
7394 $setting->write_setting_flags($data);
7396 if ($setting->post_write_settings($original)) {
7397 $count++;
7401 if ($olddbsessions != !empty($CFG->dbsessions)) {
7402 require_logout();
7405 // Now update $SITE - just update the fields, in case other people have a
7406 // a reference to it (e.g. $PAGE, $COURSE).
7407 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
7408 foreach (get_object_vars($newsite) as $field => $value) {
7409 $SITE->$field = $value;
7412 // now reload all settings - some of them might depend on the changed
7413 admin_get_root(true);
7414 return $count;
7418 * Internal recursive function - finds all settings from submitted form
7420 * @param object $node Instance of admin_category, or admin_settingpage
7421 * @param array $data
7422 * @return array
7424 function admin_find_write_settings($node, $data) {
7425 $return = array();
7427 if (empty($data)) {
7428 return $return;
7431 if ($node instanceof admin_category) {
7432 $entries = array_keys($node->children);
7433 foreach ($entries as $entry) {
7434 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
7437 } else if ($node instanceof admin_settingpage) {
7438 foreach ($node->settings as $setting) {
7439 $fullname = $setting->get_full_name();
7440 if (array_key_exists($fullname, $data)) {
7441 $return[$fullname] = $setting;
7447 return $return;
7451 * Internal function - prints the search results
7453 * @param string $query String to search for
7454 * @return string empty or XHTML
7456 function admin_search_settings_html($query) {
7457 global $CFG, $OUTPUT, $PAGE;
7459 if (core_text::strlen($query) < 2) {
7460 return '';
7462 $query = core_text::strtolower($query);
7464 $adminroot = admin_get_root();
7465 $findings = $adminroot->search($query);
7466 $savebutton = false;
7468 $tpldata = (object) [
7469 'actionurl' => $PAGE->url->out(false),
7470 'results' => [],
7471 'sesskey' => sesskey(),
7474 foreach ($findings as $found) {
7475 $page = $found->page;
7476 $settings = $found->settings;
7477 if ($page->is_hidden()) {
7478 // hidden pages are not displayed in search results
7479 continue;
7482 $heading = highlight($query, $page->visiblename);
7483 $headingurl = null;
7484 if ($page instanceof admin_externalpage) {
7485 $headingurl = new moodle_url($page->url);
7486 } else if ($page instanceof admin_settingpage) {
7487 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
7488 } else {
7489 continue;
7492 $sectionsettings = [];
7493 if (!empty($settings)) {
7494 foreach ($settings as $setting) {
7495 if (empty($setting->nosave)) {
7496 $savebutton = true;
7498 $fullname = $setting->get_full_name();
7499 if (array_key_exists($fullname, $adminroot->errors)) {
7500 $data = $adminroot->errors[$fullname]->data;
7501 } else {
7502 $data = $setting->get_setting();
7503 // do not use defaults if settings not available - upgradesettings handles the defaults!
7505 $sectionsettings[] = $setting->output_html($data, $query);
7509 $tpldata->results[] = (object) [
7510 'title' => $heading,
7511 'url' => $headingurl->out(false),
7512 'settings' => $sectionsettings
7516 $tpldata->showsave = $savebutton;
7517 $tpldata->hasresults = !empty($tpldata->results);
7519 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
7523 * Internal function - returns arrays of html pages with uninitialised settings
7525 * @param object $node Instance of admin_category or admin_settingpage
7526 * @return array
7528 function admin_output_new_settings_by_page($node) {
7529 global $OUTPUT;
7530 $return = array();
7532 if ($node instanceof admin_category) {
7533 $entries = array_keys($node->children);
7534 foreach ($entries as $entry) {
7535 $return += admin_output_new_settings_by_page($node->children[$entry]);
7538 } else if ($node instanceof admin_settingpage) {
7539 $newsettings = array();
7540 foreach ($node->settings as $setting) {
7541 if (is_null($setting->get_setting())) {
7542 $newsettings[] = $setting;
7545 if (count($newsettings) > 0) {
7546 $adminroot = admin_get_root();
7547 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
7548 $page .= '<fieldset class="adminsettings">'."\n";
7549 foreach ($newsettings as $setting) {
7550 $fullname = $setting->get_full_name();
7551 if (array_key_exists($fullname, $adminroot->errors)) {
7552 $data = $adminroot->errors[$fullname]->data;
7553 } else {
7554 $data = $setting->get_setting();
7555 if (is_null($data)) {
7556 $data = $setting->get_defaultsetting();
7559 $page .= '<div class="clearer"><!-- --></div>'."\n";
7560 $page .= $setting->output_html($data);
7562 $page .= '</fieldset>';
7563 $return[$node->name] = $page;
7567 return $return;
7571 * Format admin settings
7573 * @param object $setting
7574 * @param string $title label element
7575 * @param string $form form fragment, html code - not highlighted automatically
7576 * @param string $description
7577 * @param mixed $label link label to id, true by default or string being the label to connect it to
7578 * @param string $warning warning text
7579 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
7580 * @param string $query search query to be highlighted
7581 * @return string XHTML
7583 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
7584 global $CFG, $OUTPUT;
7586 $context = (object) [
7587 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
7588 'fullname' => $setting->get_full_name(),
7591 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
7592 if ($label === true) {
7593 $context->labelfor = $setting->get_id();
7594 } else if ($label === false) {
7595 $context->labelfor = '';
7596 } else {
7597 $context->labelfor = $label;
7600 $form .= $setting->output_setting_flags();
7602 $context->warning = $warning;
7603 $context->override = '';
7604 if (empty($setting->plugin)) {
7605 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
7606 $context->override = get_string('configoverride', 'admin');
7608 } else {
7609 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
7610 $context->override = get_string('configoverride', 'admin');
7614 $defaults = array();
7615 if (!is_null($defaultinfo)) {
7616 if ($defaultinfo === '') {
7617 $defaultinfo = get_string('emptysettingvalue', 'admin');
7619 $defaults[] = $defaultinfo;
7622 $context->default = null;
7623 $setting->get_setting_flag_defaults($defaults);
7624 if (!empty($defaults)) {
7625 $defaultinfo = implode(', ', $defaults);
7626 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7627 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
7631 $context->error = '';
7632 $adminroot = admin_get_root();
7633 if (array_key_exists($context->fullname, $adminroot->errors)) {
7634 $context->error = $adminroot->errors[$context->fullname]->error;
7637 $context->id = 'admin-' . $setting->name;
7638 $context->title = highlightfast($query, $title);
7639 $context->name = highlightfast($query, $context->name);
7640 $context->description = highlight($query, markdown_to_html($description));
7641 $context->element = $form;
7642 $context->forceltr = $setting->get_force_ltr();
7644 return $OUTPUT->render_from_template('core_admin/setting', $context);
7648 * Based on find_new_settings{@link ()} in upgradesettings.php
7649 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7651 * @param object $node Instance of admin_category, or admin_settingpage
7652 * @return boolean true if any settings haven't been initialised, false if they all have
7654 function any_new_admin_settings($node) {
7656 if ($node instanceof admin_category) {
7657 $entries = array_keys($node->children);
7658 foreach ($entries as $entry) {
7659 if (any_new_admin_settings($node->children[$entry])) {
7660 return true;
7664 } else if ($node instanceof admin_settingpage) {
7665 foreach ($node->settings as $setting) {
7666 if ($setting->get_setting() === NULL) {
7667 return true;
7672 return false;
7676 * Moved from admin/replace.php so that we can use this in cron
7678 * @param string $search string to look for
7679 * @param string $replace string to replace
7680 * @return bool success or fail
7682 function db_replace($search, $replace) {
7683 global $DB, $CFG, $OUTPUT;
7685 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7686 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7687 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7688 'block_instances', '');
7690 // Turn off time limits, sometimes upgrades can be slow.
7691 core_php_time_limit::raise();
7693 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7694 return false;
7696 foreach ($tables as $table) {
7698 if (in_array($table, $skiptables)) { // Don't process these
7699 continue;
7702 if ($columns = $DB->get_columns($table)) {
7703 $DB->set_debug(true);
7704 foreach ($columns as $column) {
7705 $DB->replace_all_text($table, $column, $search, $replace);
7707 $DB->set_debug(false);
7711 // delete modinfo caches
7712 rebuild_course_cache(0, true);
7714 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7715 $blocks = core_component::get_plugin_list('block');
7716 foreach ($blocks as $blockname=>$fullblock) {
7717 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7718 continue;
7721 if (!is_readable($fullblock.'/lib.php')) {
7722 continue;
7725 $function = 'block_'.$blockname.'_global_db_replace';
7726 include_once($fullblock.'/lib.php');
7727 if (!function_exists($function)) {
7728 continue;
7731 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7732 $function($search, $replace);
7733 echo $OUTPUT->notification("...finished", 'notifysuccess');
7736 purge_all_caches();
7738 return true;
7742 * Manage repository settings
7744 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7746 class admin_setting_managerepository extends admin_setting {
7747 /** @var string */
7748 private $baseurl;
7751 * calls parent::__construct with specific arguments
7753 public function __construct() {
7754 global $CFG;
7755 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7756 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7760 * Always returns true, does nothing
7762 * @return true
7764 public function get_setting() {
7765 return true;
7769 * Always returns true does nothing
7771 * @return true
7773 public function get_defaultsetting() {
7774 return true;
7778 * Always returns s_managerepository
7780 * @return string Always return 's_managerepository'
7782 public function get_full_name() {
7783 return 's_managerepository';
7787 * Always returns '' doesn't do anything
7789 public function write_setting($data) {
7790 $url = $this->baseurl . '&amp;new=' . $data;
7791 return '';
7792 // TODO
7793 // Should not use redirect and exit here
7794 // Find a better way to do this.
7795 // redirect($url);
7796 // exit;
7800 * Searches repository plugins for one that matches $query
7802 * @param string $query The string to search for
7803 * @return bool true if found, false if not
7805 public function is_related($query) {
7806 if (parent::is_related($query)) {
7807 return true;
7810 $repositories= core_component::get_plugin_list('repository');
7811 foreach ($repositories as $p => $dir) {
7812 if (strpos($p, $query) !== false) {
7813 return true;
7816 foreach (repository::get_types() as $instance) {
7817 $title = $instance->get_typename();
7818 if (strpos(core_text::strtolower($title), $query) !== false) {
7819 return true;
7822 return false;
7826 * Helper function that generates a moodle_url object
7827 * relevant to the repository
7830 function repository_action_url($repository) {
7831 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7835 * Builds XHTML to display the control
7837 * @param string $data Unused
7838 * @param string $query
7839 * @return string XHTML
7841 public function output_html($data, $query='') {
7842 global $CFG, $USER, $OUTPUT;
7844 // Get strings that are used
7845 $strshow = get_string('on', 'repository');
7846 $strhide = get_string('off', 'repository');
7847 $strdelete = get_string('disabled', 'repository');
7849 $actionchoicesforexisting = array(
7850 'show' => $strshow,
7851 'hide' => $strhide,
7852 'delete' => $strdelete
7855 $actionchoicesfornew = array(
7856 'newon' => $strshow,
7857 'newoff' => $strhide,
7858 'delete' => $strdelete
7861 $return = '';
7862 $return .= $OUTPUT->box_start('generalbox');
7864 // Set strings that are used multiple times
7865 $settingsstr = get_string('settings');
7866 $disablestr = get_string('disable');
7868 // Table to list plug-ins
7869 $table = new html_table();
7870 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7871 $table->align = array('left', 'center', 'center', 'center', 'center');
7872 $table->data = array();
7874 // Get list of used plug-ins
7875 $repositorytypes = repository::get_types();
7876 if (!empty($repositorytypes)) {
7877 // Array to store plugins being used
7878 $alreadyplugins = array();
7879 $totalrepositorytypes = count($repositorytypes);
7880 $updowncount = 1;
7881 foreach ($repositorytypes as $i) {
7882 $settings = '';
7883 $typename = $i->get_typename();
7884 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7885 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7886 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7888 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7889 // Calculate number of instances in order to display them for the Moodle administrator
7890 if (!empty($instanceoptionnames)) {
7891 $params = array();
7892 $params['context'] = array(context_system::instance());
7893 $params['onlyvisible'] = false;
7894 $params['type'] = $typename;
7895 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7896 // site instances
7897 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7898 $params['context'] = array();
7899 $instances = repository::static_function($typename, 'get_instances', $params);
7900 $courseinstances = array();
7901 $userinstances = array();
7903 foreach ($instances as $instance) {
7904 $repocontext = context::instance_by_id($instance->instance->contextid);
7905 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7906 $courseinstances[] = $instance;
7907 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7908 $userinstances[] = $instance;
7911 // course instances
7912 $instancenumber = count($courseinstances);
7913 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7915 // user private instances
7916 $instancenumber = count($userinstances);
7917 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7918 } else {
7919 $admininstancenumbertext = "";
7920 $courseinstancenumbertext = "";
7921 $userinstancenumbertext = "";
7924 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7926 $settings .= $OUTPUT->container_start('mdl-left');
7927 $settings .= '<br/>';
7928 $settings .= $admininstancenumbertext;
7929 $settings .= '<br/>';
7930 $settings .= $courseinstancenumbertext;
7931 $settings .= '<br/>';
7932 $settings .= $userinstancenumbertext;
7933 $settings .= $OUTPUT->container_end();
7935 // Get the current visibility
7936 if ($i->get_visible()) {
7937 $currentaction = 'show';
7938 } else {
7939 $currentaction = 'hide';
7942 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7944 // Display up/down link
7945 $updown = '';
7946 // Should be done with CSS instead.
7947 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7949 if ($updowncount > 1) {
7950 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7951 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7953 else {
7954 $updown .= $spacer;
7956 if ($updowncount < $totalrepositorytypes) {
7957 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7958 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7960 else {
7961 $updown .= $spacer;
7964 $updowncount++;
7966 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7968 if (!in_array($typename, $alreadyplugins)) {
7969 $alreadyplugins[] = $typename;
7974 // Get all the plugins that exist on disk
7975 $plugins = core_component::get_plugin_list('repository');
7976 if (!empty($plugins)) {
7977 foreach ($plugins as $plugin => $dir) {
7978 // Check that it has not already been listed
7979 if (!in_array($plugin, $alreadyplugins)) {
7980 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7981 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7986 $return .= html_writer::table($table);
7987 $return .= $OUTPUT->box_end();
7988 return highlight($query, $return);
7993 * Special checkbox for enable mobile web service
7994 * If enable then we store the service id of the mobile service into config table
7995 * If disable then we unstore the service id from the config table
7997 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7999 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
8000 private $restuse;
8003 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
8005 * @return boolean
8007 private function is_protocol_cap_allowed() {
8008 global $DB, $CFG;
8010 // If the $this->restuse variable is not set, it needs to be set.
8011 if (empty($this->restuse) and $this->restuse!==false) {
8012 $params = array();
8013 $params['permission'] = CAP_ALLOW;
8014 $params['roleid'] = $CFG->defaultuserroleid;
8015 $params['capability'] = 'webservice/rest:use';
8016 $this->restuse = $DB->record_exists('role_capabilities', $params);
8019 return $this->restuse;
8023 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
8024 * @param type $status true to allow, false to not set
8026 private function set_protocol_cap($status) {
8027 global $CFG;
8028 if ($status and !$this->is_protocol_cap_allowed()) {
8029 //need to allow the cap
8030 $permission = CAP_ALLOW;
8031 $assign = true;
8032 } else if (!$status and $this->is_protocol_cap_allowed()){
8033 //need to disallow the cap
8034 $permission = CAP_INHERIT;
8035 $assign = true;
8037 if (!empty($assign)) {
8038 $systemcontext = context_system::instance();
8039 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8044 * Builds XHTML to display the control.
8045 * The main purpose of this overloading is to display a warning when https
8046 * is not supported by the server
8047 * @param string $data Unused
8048 * @param string $query
8049 * @return string XHTML
8051 public function output_html($data, $query='') {
8052 global $CFG, $OUTPUT;
8053 $html = parent::output_html($data, $query);
8055 if ((string)$data === $this->yes) {
8056 require_once($CFG->dirroot . "/lib/filelib.php");
8057 $curl = new curl();
8058 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
8059 $curl->head($httpswwwroot . "/login/index.php");
8060 $info = $curl->get_info();
8061 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
8062 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
8066 return $html;
8070 * Retrieves the current setting using the objects name
8072 * @return string
8074 public function get_setting() {
8075 global $CFG;
8077 // First check if is not set.
8078 $result = $this->config_read($this->name);
8079 if (is_null($result)) {
8080 return null;
8083 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8084 // Or if web services aren't enabled this can't be,
8085 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8086 return 0;
8089 require_once($CFG->dirroot . '/webservice/lib.php');
8090 $webservicemanager = new webservice();
8091 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8092 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8093 return $result;
8094 } else {
8095 return 0;
8100 * Save the selected setting
8102 * @param string $data The selected site
8103 * @return string empty string or error message
8105 public function write_setting($data) {
8106 global $DB, $CFG;
8108 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8109 if (empty($CFG->defaultuserroleid)) {
8110 return '';
8113 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8115 require_once($CFG->dirroot . '/webservice/lib.php');
8116 $webservicemanager = new webservice();
8118 $updateprotocol = false;
8119 if ((string)$data === $this->yes) {
8120 //code run when enable mobile web service
8121 //enable web service systeme if necessary
8122 set_config('enablewebservices', true);
8124 //enable mobile service
8125 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8126 $mobileservice->enabled = 1;
8127 $webservicemanager->update_external_service($mobileservice);
8129 // Enable REST server.
8130 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8132 if (!in_array('rest', $activeprotocols)) {
8133 $activeprotocols[] = 'rest';
8134 $updateprotocol = true;
8137 if ($updateprotocol) {
8138 set_config('webserviceprotocols', implode(',', $activeprotocols));
8141 // Allow rest:use capability for authenticated user.
8142 $this->set_protocol_cap(true);
8144 } else {
8145 //disable web service system if no other services are enabled
8146 $otherenabledservices = $DB->get_records_select('external_services',
8147 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8148 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8149 if (empty($otherenabledservices)) {
8150 set_config('enablewebservices', false);
8152 // Also disable REST server.
8153 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8155 $protocolkey = array_search('rest', $activeprotocols);
8156 if ($protocolkey !== false) {
8157 unset($activeprotocols[$protocolkey]);
8158 $updateprotocol = true;
8161 if ($updateprotocol) {
8162 set_config('webserviceprotocols', implode(',', $activeprotocols));
8165 // Disallow rest:use capability for authenticated user.
8166 $this->set_protocol_cap(false);
8169 //disable the mobile service
8170 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8171 $mobileservice->enabled = 0;
8172 $webservicemanager->update_external_service($mobileservice);
8175 return (parent::write_setting($data));
8180 * Special class for management of external services
8182 * @author Petr Skoda (skodak)
8184 class admin_setting_manageexternalservices extends admin_setting {
8186 * Calls parent::__construct with specific arguments
8188 public function __construct() {
8189 $this->nosave = true;
8190 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8194 * Always returns true, does nothing
8196 * @return true
8198 public function get_setting() {
8199 return true;
8203 * Always returns true, does nothing
8205 * @return true
8207 public function get_defaultsetting() {
8208 return true;
8212 * Always returns '', does not write anything
8214 * @return string Always returns ''
8216 public function write_setting($data) {
8217 // do not write any setting
8218 return '';
8222 * Checks if $query is one of the available external services
8224 * @param string $query The string to search for
8225 * @return bool Returns true if found, false if not
8227 public function is_related($query) {
8228 global $DB;
8230 if (parent::is_related($query)) {
8231 return true;
8234 $services = $DB->get_records('external_services', array(), 'id, name');
8235 foreach ($services as $service) {
8236 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8237 return true;
8240 return false;
8244 * Builds the XHTML to display the control
8246 * @param string $data Unused
8247 * @param string $query
8248 * @return string
8250 public function output_html($data, $query='') {
8251 global $CFG, $OUTPUT, $DB;
8253 // display strings
8254 $stradministration = get_string('administration');
8255 $stredit = get_string('edit');
8256 $strservice = get_string('externalservice', 'webservice');
8257 $strdelete = get_string('delete');
8258 $strplugin = get_string('plugin', 'admin');
8259 $stradd = get_string('add');
8260 $strfunctions = get_string('functions', 'webservice');
8261 $strusers = get_string('users');
8262 $strserviceusers = get_string('serviceusers', 'webservice');
8264 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8265 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8266 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8268 // built in services
8269 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8270 $return = "";
8271 if (!empty($services)) {
8272 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8276 $table = new html_table();
8277 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8278 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8279 $table->id = 'builtinservices';
8280 $table->attributes['class'] = 'admintable externalservices generaltable';
8281 $table->data = array();
8283 // iterate through auth plugins and add to the display table
8284 foreach ($services as $service) {
8285 $name = $service->name;
8287 // hide/show link
8288 if ($service->enabled) {
8289 $displayname = "<span>$name</span>";
8290 } else {
8291 $displayname = "<span class=\"dimmed_text\">$name</span>";
8294 $plugin = $service->component;
8296 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8298 if ($service->restrictedusers) {
8299 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8300 } else {
8301 $users = get_string('allusers', 'webservice');
8304 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8306 // add a row to the table
8307 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
8309 $return .= html_writer::table($table);
8312 // Custom services
8313 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
8314 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
8316 $table = new html_table();
8317 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
8318 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8319 $table->id = 'customservices';
8320 $table->attributes['class'] = 'admintable externalservices generaltable';
8321 $table->data = array();
8323 // iterate through auth plugins and add to the display table
8324 foreach ($services as $service) {
8325 $name = $service->name;
8327 // hide/show link
8328 if ($service->enabled) {
8329 $displayname = "<span>$name</span>";
8330 } else {
8331 $displayname = "<span class=\"dimmed_text\">$name</span>";
8334 // delete link
8335 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
8337 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8339 if ($service->restrictedusers) {
8340 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8341 } else {
8342 $users = get_string('allusers', 'webservice');
8345 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8347 // add a row to the table
8348 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
8350 // add new custom service option
8351 $return .= html_writer::table($table);
8353 $return .= '<br />';
8354 // add a token to the table
8355 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
8357 return highlight($query, $return);
8362 * Special class for overview of external services
8364 * @author Jerome Mouneyrac
8366 class admin_setting_webservicesoverview extends admin_setting {
8369 * Calls parent::__construct with specific arguments
8371 public function __construct() {
8372 $this->nosave = true;
8373 parent::__construct('webservicesoverviewui',
8374 get_string('webservicesoverview', 'webservice'), '', '');
8378 * Always returns true, does nothing
8380 * @return true
8382 public function get_setting() {
8383 return true;
8387 * Always returns true, does nothing
8389 * @return true
8391 public function get_defaultsetting() {
8392 return true;
8396 * Always returns '', does not write anything
8398 * @return string Always returns ''
8400 public function write_setting($data) {
8401 // do not write any setting
8402 return '';
8406 * Builds the XHTML to display the control
8408 * @param string $data Unused
8409 * @param string $query
8410 * @return string
8412 public function output_html($data, $query='') {
8413 global $CFG, $OUTPUT;
8415 $return = "";
8416 $brtag = html_writer::empty_tag('br');
8418 // Enable mobile web service
8419 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
8420 get_string('enablemobilewebservice', 'admin'),
8421 get_string('configenablemobilewebservice',
8422 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
8423 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
8424 $wsmobileparam = new stdClass();
8425 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
8426 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
8427 get_string('mobile', 'admin'));
8428 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
8429 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
8430 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
8431 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
8432 . $brtag . $brtag;
8434 /// One system controlling Moodle with Token
8435 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
8436 $table = new html_table();
8437 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8438 get_string('description'));
8439 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8440 $table->id = 'onesystemcontrol';
8441 $table->attributes['class'] = 'admintable wsoverview generaltable';
8442 $table->data = array();
8444 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
8445 . $brtag . $brtag;
8447 /// 1. Enable Web Services
8448 $row = array();
8449 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8450 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8451 array('href' => $url));
8452 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8453 if ($CFG->enablewebservices) {
8454 $status = get_string('yes');
8456 $row[1] = $status;
8457 $row[2] = get_string('enablewsdescription', 'webservice');
8458 $table->data[] = $row;
8460 /// 2. Enable protocols
8461 $row = array();
8462 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8463 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8464 array('href' => $url));
8465 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8466 //retrieve activated protocol
8467 $active_protocols = empty($CFG->webserviceprotocols) ?
8468 array() : explode(',', $CFG->webserviceprotocols);
8469 if (!empty($active_protocols)) {
8470 $status = "";
8471 foreach ($active_protocols as $protocol) {
8472 $status .= $protocol . $brtag;
8475 $row[1] = $status;
8476 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8477 $table->data[] = $row;
8479 /// 3. Create user account
8480 $row = array();
8481 $url = new moodle_url("/user/editadvanced.php?id=-1");
8482 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
8483 array('href' => $url));
8484 $row[1] = "";
8485 $row[2] = get_string('createuserdescription', 'webservice');
8486 $table->data[] = $row;
8488 /// 4. Add capability to users
8489 $row = array();
8490 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8491 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
8492 array('href' => $url));
8493 $row[1] = "";
8494 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
8495 $table->data[] = $row;
8497 /// 5. Select a web service
8498 $row = array();
8499 $url = new moodle_url("/admin/settings.php?section=externalservices");
8500 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8501 array('href' => $url));
8502 $row[1] = "";
8503 $row[2] = get_string('createservicedescription', 'webservice');
8504 $table->data[] = $row;
8506 /// 6. Add functions
8507 $row = array();
8508 $url = new moodle_url("/admin/settings.php?section=externalservices");
8509 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8510 array('href' => $url));
8511 $row[1] = "";
8512 $row[2] = get_string('addfunctionsdescription', 'webservice');
8513 $table->data[] = $row;
8515 /// 7. Add the specific user
8516 $row = array();
8517 $url = new moodle_url("/admin/settings.php?section=externalservices");
8518 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
8519 array('href' => $url));
8520 $row[1] = "";
8521 $row[2] = get_string('selectspecificuserdescription', 'webservice');
8522 $table->data[] = $row;
8524 /// 8. Create token for the specific user
8525 $row = array();
8526 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
8527 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
8528 array('href' => $url));
8529 $row[1] = "";
8530 $row[2] = get_string('createtokenforuserdescription', 'webservice');
8531 $table->data[] = $row;
8533 /// 9. Enable the documentation
8534 $row = array();
8535 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
8536 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
8537 array('href' => $url));
8538 $status = '<span class="warning">' . get_string('no') . '</span>';
8539 if ($CFG->enablewsdocumentation) {
8540 $status = get_string('yes');
8542 $row[1] = $status;
8543 $row[2] = get_string('enabledocumentationdescription', 'webservice');
8544 $table->data[] = $row;
8546 /// 10. Test the service
8547 $row = array();
8548 $url = new moodle_url("/admin/webservice/testclient.php");
8549 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8550 array('href' => $url));
8551 $row[1] = "";
8552 $row[2] = get_string('testwithtestclientdescription', 'webservice');
8553 $table->data[] = $row;
8555 $return .= html_writer::table($table);
8557 /// Users as clients with token
8558 $return .= $brtag . $brtag . $brtag;
8559 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
8560 $table = new html_table();
8561 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8562 get_string('description'));
8563 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8564 $table->id = 'userasclients';
8565 $table->attributes['class'] = 'admintable wsoverview generaltable';
8566 $table->data = array();
8568 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
8569 $brtag . $brtag;
8571 /// 1. Enable Web Services
8572 $row = array();
8573 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8574 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8575 array('href' => $url));
8576 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8577 if ($CFG->enablewebservices) {
8578 $status = get_string('yes');
8580 $row[1] = $status;
8581 $row[2] = get_string('enablewsdescription', 'webservice');
8582 $table->data[] = $row;
8584 /// 2. Enable protocols
8585 $row = array();
8586 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8587 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8588 array('href' => $url));
8589 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8590 //retrieve activated protocol
8591 $active_protocols = empty($CFG->webserviceprotocols) ?
8592 array() : explode(',', $CFG->webserviceprotocols);
8593 if (!empty($active_protocols)) {
8594 $status = "";
8595 foreach ($active_protocols as $protocol) {
8596 $status .= $protocol . $brtag;
8599 $row[1] = $status;
8600 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8601 $table->data[] = $row;
8604 /// 3. Select a web service
8605 $row = array();
8606 $url = new moodle_url("/admin/settings.php?section=externalservices");
8607 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8608 array('href' => $url));
8609 $row[1] = "";
8610 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8611 $table->data[] = $row;
8613 /// 4. Add functions
8614 $row = array();
8615 $url = new moodle_url("/admin/settings.php?section=externalservices");
8616 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8617 array('href' => $url));
8618 $row[1] = "";
8619 $row[2] = get_string('addfunctionsdescription', 'webservice');
8620 $table->data[] = $row;
8622 /// 5. Add capability to users
8623 $row = array();
8624 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8625 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8626 array('href' => $url));
8627 $row[1] = "";
8628 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8629 $table->data[] = $row;
8631 /// 6. Test the service
8632 $row = array();
8633 $url = new moodle_url("/admin/webservice/testclient.php");
8634 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8635 array('href' => $url));
8636 $row[1] = "";
8637 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8638 $table->data[] = $row;
8640 $return .= html_writer::table($table);
8642 return highlight($query, $return);
8649 * Special class for web service protocol administration.
8651 * @author Petr Skoda (skodak)
8653 class admin_setting_managewebserviceprotocols extends admin_setting {
8656 * Calls parent::__construct with specific arguments
8658 public function __construct() {
8659 $this->nosave = true;
8660 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8664 * Always returns true, does nothing
8666 * @return true
8668 public function get_setting() {
8669 return true;
8673 * Always returns true, does nothing
8675 * @return true
8677 public function get_defaultsetting() {
8678 return true;
8682 * Always returns '', does not write anything
8684 * @return string Always returns ''
8686 public function write_setting($data) {
8687 // do not write any setting
8688 return '';
8692 * Checks if $query is one of the available webservices
8694 * @param string $query The string to search for
8695 * @return bool Returns true if found, false if not
8697 public function is_related($query) {
8698 if (parent::is_related($query)) {
8699 return true;
8702 $protocols = core_component::get_plugin_list('webservice');
8703 foreach ($protocols as $protocol=>$location) {
8704 if (strpos($protocol, $query) !== false) {
8705 return true;
8707 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8708 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8709 return true;
8712 return false;
8716 * Builds the XHTML to display the control
8718 * @param string $data Unused
8719 * @param string $query
8720 * @return string
8722 public function output_html($data, $query='') {
8723 global $CFG, $OUTPUT;
8725 // display strings
8726 $stradministration = get_string('administration');
8727 $strsettings = get_string('settings');
8728 $stredit = get_string('edit');
8729 $strprotocol = get_string('protocol', 'webservice');
8730 $strenable = get_string('enable');
8731 $strdisable = get_string('disable');
8732 $strversion = get_string('version');
8734 $protocols_available = core_component::get_plugin_list('webservice');
8735 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8736 ksort($protocols_available);
8738 foreach ($active_protocols as $key=>$protocol) {
8739 if (empty($protocols_available[$protocol])) {
8740 unset($active_protocols[$key]);
8744 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8745 $return .= $OUTPUT->box_start('generalbox webservicesui');
8747 $table = new html_table();
8748 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8749 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8750 $table->id = 'webserviceprotocols';
8751 $table->attributes['class'] = 'admintable generaltable';
8752 $table->data = array();
8754 // iterate through auth plugins and add to the display table
8755 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8756 foreach ($protocols_available as $protocol => $location) {
8757 $name = get_string('pluginname', 'webservice_'.$protocol);
8759 $plugin = new stdClass();
8760 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8761 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8763 $version = isset($plugin->version) ? $plugin->version : '';
8765 // hide/show link
8766 if (in_array($protocol, $active_protocols)) {
8767 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8768 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8769 $displayname = "<span>$name</span>";
8770 } else {
8771 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8772 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8773 $displayname = "<span class=\"dimmed_text\">$name</span>";
8776 // settings link
8777 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8778 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8779 } else {
8780 $settings = '';
8783 // add a row to the table
8784 $table->data[] = array($displayname, $version, $hideshow, $settings);
8786 $return .= html_writer::table($table);
8787 $return .= get_string('configwebserviceplugins', 'webservice');
8788 $return .= $OUTPUT->box_end();
8790 return highlight($query, $return);
8796 * Special class for web service token administration.
8798 * @author Jerome Mouneyrac
8800 class admin_setting_managewebservicetokens extends admin_setting {
8803 * Calls parent::__construct with specific arguments
8805 public function __construct() {
8806 $this->nosave = true;
8807 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8811 * Always returns true, does nothing
8813 * @return true
8815 public function get_setting() {
8816 return true;
8820 * Always returns true, does nothing
8822 * @return true
8824 public function get_defaultsetting() {
8825 return true;
8829 * Always returns '', does not write anything
8831 * @return string Always returns ''
8833 public function write_setting($data) {
8834 // do not write any setting
8835 return '';
8839 * Builds the XHTML to display the control
8841 * @param string $data Unused
8842 * @param string $query
8843 * @return string
8845 public function output_html($data, $query='') {
8846 global $CFG, $OUTPUT, $DB, $USER;
8848 // display strings
8849 $stroperation = get_string('operation', 'webservice');
8850 $strtoken = get_string('token', 'webservice');
8851 $strservice = get_string('service', 'webservice');
8852 $struser = get_string('user');
8853 $strcontext = get_string('context', 'webservice');
8854 $strvaliduntil = get_string('validuntil', 'webservice');
8855 $striprestriction = get_string('iprestriction', 'webservice');
8857 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8859 $table = new html_table();
8860 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8861 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8862 $table->id = 'webservicetokens';
8863 $table->attributes['class'] = 'admintable generaltable';
8864 $table->data = array();
8866 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8868 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8870 //here retrieve token list (including linked users firstname/lastname and linked services name)
8871 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8872 FROM {external_tokens} t, {user} u, {external_services} s
8873 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8874 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8875 if (!empty($tokens)) {
8876 foreach ($tokens as $token) {
8877 //TODO: retrieve context
8879 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8880 $delete .= get_string('delete')."</a>";
8882 $validuntil = '';
8883 if (!empty($token->validuntil)) {
8884 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8887 $iprestriction = '';
8888 if (!empty($token->iprestriction)) {
8889 $iprestriction = $token->iprestriction;
8892 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8893 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8894 $useratag .= $token->firstname." ".$token->lastname;
8895 $useratag .= html_writer::end_tag('a');
8897 //check user missing capabilities
8898 require_once($CFG->dirroot . '/webservice/lib.php');
8899 $webservicemanager = new webservice();
8900 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8901 array(array('id' => $token->userid)), $token->serviceid);
8903 if (!is_siteadmin($token->userid) and
8904 array_key_exists($token->userid, $usermissingcaps)) {
8905 $missingcapabilities = implode(', ',
8906 $usermissingcaps[$token->userid]);
8907 if (!empty($missingcapabilities)) {
8908 $useratag .= html_writer::tag('div',
8909 get_string('usermissingcaps', 'webservice',
8910 $missingcapabilities)
8911 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8912 array('class' => 'missingcaps'));
8916 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8919 $return .= html_writer::table($table);
8920 } else {
8921 $return .= get_string('notoken', 'webservice');
8924 $return .= $OUTPUT->box_end();
8925 // add a token to the table
8926 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8927 $return .= get_string('add')."</a>";
8929 return highlight($query, $return);
8935 * Colour picker
8937 * @copyright 2010 Sam Hemelryk
8938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8940 class admin_setting_configcolourpicker extends admin_setting {
8943 * Information for previewing the colour
8945 * @var array|null
8947 protected $previewconfig = null;
8950 * Use default when empty.
8952 protected $usedefaultwhenempty = true;
8956 * @param string $name
8957 * @param string $visiblename
8958 * @param string $description
8959 * @param string $defaultsetting
8960 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8962 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8963 $usedefaultwhenempty = true) {
8964 $this->previewconfig = $previewconfig;
8965 $this->usedefaultwhenempty = $usedefaultwhenempty;
8966 parent::__construct($name, $visiblename, $description, $defaultsetting);
8967 $this->set_force_ltr(true);
8971 * Return the setting
8973 * @return mixed returns config if successful else null
8975 public function get_setting() {
8976 return $this->config_read($this->name);
8980 * Saves the setting
8982 * @param string $data
8983 * @return bool
8985 public function write_setting($data) {
8986 $data = $this->validate($data);
8987 if ($data === false) {
8988 return get_string('validateerror', 'admin');
8990 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8994 * Validates the colour that was entered by the user
8996 * @param string $data
8997 * @return string|false
8999 protected function validate($data) {
9001 * List of valid HTML colour names
9003 * @var array
9005 $colornames = array(
9006 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
9007 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
9008 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
9009 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
9010 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
9011 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
9012 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
9013 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
9014 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
9015 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
9016 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
9017 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
9018 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
9019 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
9020 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
9021 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
9022 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
9023 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
9024 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
9025 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
9026 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
9027 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
9028 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
9029 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
9030 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
9031 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
9032 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
9033 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
9034 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
9035 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
9036 'whitesmoke', 'yellow', 'yellowgreen'
9039 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
9040 if (strpos($data, '#')!==0) {
9041 $data = '#'.$data;
9043 return $data;
9044 } else if (in_array(strtolower($data), $colornames)) {
9045 return $data;
9046 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9047 return $data;
9048 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9049 return $data;
9050 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9051 return $data;
9052 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9053 return $data;
9054 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9055 return $data;
9056 } else if (empty($data)) {
9057 if ($this->usedefaultwhenempty){
9058 return $this->defaultsetting;
9059 } else {
9060 return '';
9062 } else {
9063 return false;
9068 * Generates the HTML for the setting
9070 * @global moodle_page $PAGE
9071 * @global core_renderer $OUTPUT
9072 * @param string $data
9073 * @param string $query
9075 public function output_html($data, $query = '') {
9076 global $PAGE, $OUTPUT;
9078 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
9079 $context = (object) [
9080 'id' => $this->get_id(),
9081 'name' => $this->get_full_name(),
9082 'value' => $data,
9083 'icon' => $icon->export_for_template($OUTPUT),
9084 'haspreviewconfig' => !empty($this->previewconfig),
9085 'forceltr' => $this->get_force_ltr()
9088 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
9089 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9091 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
9092 $this->get_defaultsetting(), $query);
9099 * Class used for uploading of one file into file storage,
9100 * the file name is stored in config table.
9102 * Please note you need to implement your own '_pluginfile' callback function,
9103 * this setting only stores the file, it does not deal with file serving.
9105 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9108 class admin_setting_configstoredfile extends admin_setting {
9109 /** @var array file area options - should be one file only */
9110 protected $options;
9111 /** @var string name of the file area */
9112 protected $filearea;
9113 /** @var int intemid */
9114 protected $itemid;
9115 /** @var string used for detection of changes */
9116 protected $oldhashes;
9119 * Create new stored file setting.
9121 * @param string $name low level setting name
9122 * @param string $visiblename human readable setting name
9123 * @param string $description description of setting
9124 * @param mixed $filearea file area for file storage
9125 * @param int $itemid itemid for file storage
9126 * @param array $options file area options
9128 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9129 parent::__construct($name, $visiblename, $description, '');
9130 $this->filearea = $filearea;
9131 $this->itemid = $itemid;
9132 $this->options = (array)$options;
9136 * Applies defaults and returns all options.
9137 * @return array
9139 protected function get_options() {
9140 global $CFG;
9142 require_once("$CFG->libdir/filelib.php");
9143 require_once("$CFG->dirroot/repository/lib.php");
9144 $defaults = array(
9145 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9146 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9147 'context' => context_system::instance());
9148 foreach($this->options as $k => $v) {
9149 $defaults[$k] = $v;
9152 return $defaults;
9155 public function get_setting() {
9156 return $this->config_read($this->name);
9159 public function write_setting($data) {
9160 global $USER;
9162 // Let's not deal with validation here, this is for admins only.
9163 $current = $this->get_setting();
9164 if (empty($data) && $current === null) {
9165 // This will be the case when applying default settings (installation).
9166 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9167 } else if (!is_number($data)) {
9168 // Draft item id is expected here!
9169 return get_string('errorsetting', 'admin');
9172 $options = $this->get_options();
9173 $fs = get_file_storage();
9174 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9176 $this->oldhashes = null;
9177 if ($current) {
9178 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9179 if ($file = $fs->get_file_by_hash($hash)) {
9180 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9182 unset($file);
9185 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9186 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9187 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9188 // with an error because the draft area does not exist, as he did not use it.
9189 $usercontext = context_user::instance($USER->id);
9190 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9191 return get_string('errorsetting', 'admin');
9195 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9196 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9198 $filepath = '';
9199 if ($files) {
9200 /** @var stored_file $file */
9201 $file = reset($files);
9202 $filepath = $file->get_filepath().$file->get_filename();
9205 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9208 public function post_write_settings($original) {
9209 $options = $this->get_options();
9210 $fs = get_file_storage();
9211 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9213 $current = $this->get_setting();
9214 $newhashes = null;
9215 if ($current) {
9216 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9217 if ($file = $fs->get_file_by_hash($hash)) {
9218 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9220 unset($file);
9223 if ($this->oldhashes === $newhashes) {
9224 $this->oldhashes = null;
9225 return false;
9227 $this->oldhashes = null;
9229 $callbackfunction = $this->updatedcallback;
9230 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9231 $callbackfunction($this->get_full_name());
9233 return true;
9236 public function output_html($data, $query = '') {
9237 global $PAGE, $CFG;
9239 $options = $this->get_options();
9240 $id = $this->get_id();
9241 $elname = $this->get_full_name();
9242 $draftitemid = file_get_submitted_draft_itemid($elname);
9243 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9244 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9246 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9247 require_once("$CFG->dirroot/lib/form/filemanager.php");
9249 $fmoptions = new stdClass();
9250 $fmoptions->mainfile = $options['mainfile'];
9251 $fmoptions->maxbytes = $options['maxbytes'];
9252 $fmoptions->maxfiles = $options['maxfiles'];
9253 $fmoptions->client_id = uniqid();
9254 $fmoptions->itemid = $draftitemid;
9255 $fmoptions->subdirs = $options['subdirs'];
9256 $fmoptions->target = $id;
9257 $fmoptions->accepted_types = $options['accepted_types'];
9258 $fmoptions->return_types = $options['return_types'];
9259 $fmoptions->context = $options['context'];
9260 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9262 $fm = new form_filemanager($fmoptions);
9263 $output = $PAGE->get_renderer('core', 'files');
9264 $html = $output->render($fm);
9266 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9267 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9269 return format_admin_setting($this, $this->visiblename,
9270 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
9271 $this->description, true, '', '', $query);
9277 * Administration interface for user specified regular expressions for device detection.
9279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9281 class admin_setting_devicedetectregex extends admin_setting {
9284 * Calls parent::__construct with specific args
9286 * @param string $name
9287 * @param string $visiblename
9288 * @param string $description
9289 * @param mixed $defaultsetting
9291 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9292 global $CFG;
9293 parent::__construct($name, $visiblename, $description, $defaultsetting);
9297 * Return the current setting(s)
9299 * @return array Current settings array
9301 public function get_setting() {
9302 global $CFG;
9304 $config = $this->config_read($this->name);
9305 if (is_null($config)) {
9306 return null;
9309 return $this->prepare_form_data($config);
9313 * Save selected settings
9315 * @param array $data Array of settings to save
9316 * @return bool
9318 public function write_setting($data) {
9319 if (empty($data)) {
9320 $data = array();
9323 if ($this->config_write($this->name, $this->process_form_data($data))) {
9324 return ''; // success
9325 } else {
9326 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9331 * Return XHTML field(s) for regexes
9333 * @param array $data Array of options to set in HTML
9334 * @return string XHTML string for the fields and wrapping div(s)
9336 public function output_html($data, $query='') {
9337 global $OUTPUT;
9339 $context = (object) [
9340 'expressions' => [],
9341 'name' => $this->get_full_name()
9344 if (empty($data)) {
9345 $looplimit = 1;
9346 } else {
9347 $looplimit = (count($data)/2)+1;
9350 for ($i=0; $i<$looplimit; $i++) {
9352 $expressionname = 'expression'.$i;
9354 if (!empty($data[$expressionname])){
9355 $expression = $data[$expressionname];
9356 } else {
9357 $expression = '';
9360 $valuename = 'value'.$i;
9362 if (!empty($data[$valuename])){
9363 $value = $data[$valuename];
9364 } else {
9365 $value= '';
9368 $context->expressions[] = [
9369 'index' => $i,
9370 'expression' => $expression,
9371 'value' => $value
9375 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
9377 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
9381 * Converts the string of regexes
9383 * @see self::process_form_data()
9384 * @param $regexes string of regexes
9385 * @return array of form fields and their values
9387 protected function prepare_form_data($regexes) {
9389 $regexes = json_decode($regexes);
9391 $form = array();
9393 $i = 0;
9395 foreach ($regexes as $value => $regex) {
9396 $expressionname = 'expression'.$i;
9397 $valuename = 'value'.$i;
9399 $form[$expressionname] = $regex;
9400 $form[$valuename] = $value;
9401 $i++;
9404 return $form;
9408 * Converts the data from admin settings form into a string of regexes
9410 * @see self::prepare_form_data()
9411 * @param array $data array of admin form fields and values
9412 * @return false|string of regexes
9414 protected function process_form_data(array $form) {
9416 $count = count($form); // number of form field values
9418 if ($count % 2) {
9419 // we must get five fields per expression
9420 return false;
9423 $regexes = array();
9424 for ($i = 0; $i < $count / 2; $i++) {
9425 $expressionname = "expression".$i;
9426 $valuename = "value".$i;
9428 $expression = trim($form['expression'.$i]);
9429 $value = trim($form['value'.$i]);
9431 if (empty($expression)){
9432 continue;
9435 $regexes[$value] = $expression;
9438 $regexes = json_encode($regexes);
9440 return $regexes;
9446 * Multiselect for current modules
9448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9450 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
9451 private $excludesystem;
9454 * Calls parent::__construct - note array $choices is not required
9456 * @param string $name setting name
9457 * @param string $visiblename localised setting name
9458 * @param string $description setting description
9459 * @param array $defaultsetting a plain array of default module ids
9460 * @param bool $excludesystem If true, excludes modules with 'system' archetype
9462 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
9463 $excludesystem = true) {
9464 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
9465 $this->excludesystem = $excludesystem;
9469 * Loads an array of current module choices
9471 * @return bool always return true
9473 public function load_choices() {
9474 if (is_array($this->choices)) {
9475 return true;
9477 $this->choices = array();
9479 global $CFG, $DB;
9480 $records = $DB->get_records('modules', array('visible'=>1), 'name');
9481 foreach ($records as $record) {
9482 // Exclude modules if the code doesn't exist
9483 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
9484 // Also exclude system modules (if specified)
9485 if (!($this->excludesystem &&
9486 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
9487 MOD_ARCHETYPE_SYSTEM)) {
9488 $this->choices[$record->id] = $record->name;
9492 return true;
9497 * Admin setting to show if a php extension is enabled or not.
9499 * @copyright 2013 Damyon Wiese
9500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9502 class admin_setting_php_extension_enabled extends admin_setting {
9504 /** @var string The name of the extension to check for */
9505 private $extension;
9508 * Calls parent::__construct with specific arguments
9510 public function __construct($name, $visiblename, $description, $extension) {
9511 $this->extension = $extension;
9512 $this->nosave = true;
9513 parent::__construct($name, $visiblename, $description, '');
9517 * Always returns true, does nothing
9519 * @return true
9521 public function get_setting() {
9522 return true;
9526 * Always returns true, does nothing
9528 * @return true
9530 public function get_defaultsetting() {
9531 return true;
9535 * Always returns '', does not write anything
9537 * @return string Always returns ''
9539 public function write_setting($data) {
9540 // Do not write any setting.
9541 return '';
9545 * Outputs the html for this setting.
9546 * @return string Returns an XHTML string
9548 public function output_html($data, $query='') {
9549 global $OUTPUT;
9551 $o = '';
9552 if (!extension_loaded($this->extension)) {
9553 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
9555 $o .= format_admin_setting($this, $this->visiblename, $warning);
9557 return $o;
9562 * Server timezone setting.
9564 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9566 * @author Petr Skoda <petr.skoda@totaralms.com>
9568 class admin_setting_servertimezone extends admin_setting_configselect {
9570 * Constructor.
9572 public function __construct() {
9573 $default = core_date::get_default_php_timezone();
9574 if ($default === 'UTC') {
9575 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
9576 $default = 'Europe/London';
9579 parent::__construct('timezone',
9580 new lang_string('timezone', 'core_admin'),
9581 new lang_string('configtimezone', 'core_admin'), $default, null);
9585 * Lazy load timezone options.
9586 * @return bool true if loaded, false if error
9588 public function load_choices() {
9589 global $CFG;
9590 if (is_array($this->choices)) {
9591 return true;
9594 $current = isset($CFG->timezone) ? $CFG->timezone : null;
9595 $this->choices = core_date::get_list_of_timezones($current, false);
9596 if ($current == 99) {
9597 // Do not show 99 unless it is current value, we want to get rid of it over time.
9598 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
9599 core_date::get_default_php_timezone());
9602 return true;
9607 * Forced user timezone setting.
9609 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9611 * @author Petr Skoda <petr.skoda@totaralms.com>
9613 class admin_setting_forcetimezone extends admin_setting_configselect {
9615 * Constructor.
9617 public function __construct() {
9618 parent::__construct('forcetimezone',
9619 new lang_string('forcetimezone', 'core_admin'),
9620 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
9624 * Lazy load timezone options.
9625 * @return bool true if loaded, false if error
9627 public function load_choices() {
9628 global $CFG;
9629 if (is_array($this->choices)) {
9630 return true;
9633 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
9634 $this->choices = core_date::get_list_of_timezones($current, true);
9635 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
9637 return true;
9643 * Search setup steps info.
9645 * @package core
9646 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
9647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9649 class admin_setting_searchsetupinfo extends admin_setting {
9652 * Calls parent::__construct with specific arguments
9654 public function __construct() {
9655 $this->nosave = true;
9656 parent::__construct('searchsetupinfo', '', '', '');
9660 * Always returns true, does nothing
9662 * @return true
9664 public function get_setting() {
9665 return true;
9669 * Always returns true, does nothing
9671 * @return true
9673 public function get_defaultsetting() {
9674 return true;
9678 * Always returns '', does not write anything
9680 * @param array $data
9681 * @return string Always returns ''
9683 public function write_setting($data) {
9684 // Do not write any setting.
9685 return '';
9689 * Builds the HTML to display the control
9691 * @param string $data Unused
9692 * @param string $query
9693 * @return string
9695 public function output_html($data, $query='') {
9696 global $CFG, $OUTPUT;
9698 $return = '';
9699 $brtag = html_writer::empty_tag('br');
9701 $searchareas = \core_search\manager::get_search_areas_list();
9702 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
9703 $anyindexed = false;
9704 foreach ($searchareas as $areaid => $searcharea) {
9705 list($componentname, $varname) = $searcharea->get_config_var_name();
9706 if (get_config($componentname, $varname . '_indexingstart')) {
9707 $anyindexed = true;
9708 break;
9712 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
9714 $table = new html_table();
9715 $table->head = array(get_string('step', 'search'), get_string('status'));
9716 $table->colclasses = array('leftalign step', 'leftalign status');
9717 $table->id = 'searchsetup';
9718 $table->attributes['class'] = 'admintable generaltable';
9719 $table->data = array();
9721 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
9723 // Select a search engine.
9724 $row = array();
9725 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
9726 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
9727 array('href' => $url));
9729 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9730 if (!empty($CFG->searchengine)) {
9731 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
9732 array('class' => 'statusok'));
9735 $row[1] = $status;
9736 $table->data[] = $row;
9738 // Available areas.
9739 $row = array();
9740 $url = new moodle_url('/admin/searchareas.php');
9741 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
9742 array('href' => $url));
9744 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9745 if ($anyenabled) {
9746 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9749 $row[1] = $status;
9750 $table->data[] = $row;
9752 // Setup search engine.
9753 $row = array();
9754 if (empty($CFG->searchengine)) {
9755 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
9756 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9757 } else {
9758 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
9759 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
9760 array('href' => $url));
9761 // Check the engine status.
9762 $searchengine = \core_search\manager::search_engine_instance();
9763 try {
9764 $serverstatus = $searchengine->is_server_ready();
9765 } catch (\moodle_exception $e) {
9766 $serverstatus = $e->getMessage();
9768 if ($serverstatus === true) {
9769 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9770 } else {
9771 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
9773 $row[1] = $status;
9775 $table->data[] = $row;
9777 // Indexed data.
9778 $row = array();
9779 $url = new moodle_url('/admin/searchareas.php');
9780 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
9781 if ($anyindexed) {
9782 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9783 } else {
9784 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9786 $row[1] = $status;
9787 $table->data[] = $row;
9789 // Enable global search.
9790 $row = array();
9791 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
9792 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
9793 array('href' => $url));
9794 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9795 if (\core_search\manager::is_global_search_enabled()) {
9796 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9798 $row[1] = $status;
9799 $table->data[] = $row;
9801 $return .= html_writer::table($table);
9803 return highlight($query, $return);