Merge branch 'MDL-67410-37' of https://github.com/felicemcc/moodle into MOODLE_37_STABLE
[moodle.git] / lib / adminlib.php
blob125cc64536db1a559086e0a9f45efe1183833cfc
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 // Delete all remaining files in the filepool owned by the component.
238 $fs = get_file_storage();
239 $fs->delete_component_files($component);
241 // Finally purge all caches.
242 purge_all_caches();
244 // Invalidate the hash used for upgrade detections.
245 set_config('allversionshash', '');
247 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
251 * Returns the version of installed component
253 * @param string $component component name
254 * @param string $source either 'disk' or 'installed' - where to get the version information from
255 * @return string|bool version number or false if the component is not found
257 function get_component_version($component, $source='installed') {
258 global $CFG, $DB;
260 list($type, $name) = core_component::normalize_component($component);
262 // moodle core or a core subsystem
263 if ($type === 'core') {
264 if ($source === 'installed') {
265 if (empty($CFG->version)) {
266 return false;
267 } else {
268 return $CFG->version;
270 } else {
271 if (!is_readable($CFG->dirroot.'/version.php')) {
272 return false;
273 } else {
274 $version = null; //initialize variable for IDEs
275 include($CFG->dirroot.'/version.php');
276 return $version;
281 // activity module
282 if ($type === 'mod') {
283 if ($source === 'installed') {
284 if ($CFG->version < 2013092001.02) {
285 return $DB->get_field('modules', 'version', array('name'=>$name));
286 } else {
287 return get_config('mod_'.$name, 'version');
290 } else {
291 $mods = core_component::get_plugin_list('mod');
292 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
293 return false;
294 } else {
295 $plugin = new stdClass();
296 $plugin->version = null;
297 $module = $plugin;
298 include($mods[$name].'/version.php');
299 return $plugin->version;
304 // block
305 if ($type === 'block') {
306 if ($source === 'installed') {
307 if ($CFG->version < 2013092001.02) {
308 return $DB->get_field('block', 'version', array('name'=>$name));
309 } else {
310 return get_config('block_'.$name, 'version');
312 } else {
313 $blocks = core_component::get_plugin_list('block');
314 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
315 return false;
316 } else {
317 $plugin = new stdclass();
318 include($blocks[$name].'/version.php');
319 return $plugin->version;
324 // all other plugin types
325 if ($source === 'installed') {
326 return get_config($type.'_'.$name, 'version');
327 } else {
328 $plugins = core_component::get_plugin_list($type);
329 if (empty($plugins[$name])) {
330 return false;
331 } else {
332 $plugin = new stdclass();
333 include($plugins[$name].'/version.php');
334 return $plugin->version;
340 * Delete all plugin tables
342 * @param string $name Name of plugin, used as table prefix
343 * @param string $file Path to install.xml file
344 * @param bool $feedback defaults to true
345 * @return bool Always returns true
347 function drop_plugin_tables($name, $file, $feedback=true) {
348 global $CFG, $DB;
350 // first try normal delete
351 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
352 return true;
355 // then try to find all tables that start with name and are not in any xml file
356 $used_tables = get_used_table_names();
358 $tables = $DB->get_tables();
360 /// Iterate over, fixing id fields as necessary
361 foreach ($tables as $table) {
362 if (in_array($table, $used_tables)) {
363 continue;
366 if (strpos($table, $name) !== 0) {
367 continue;
370 // found orphan table --> delete it
371 if ($DB->get_manager()->table_exists($table)) {
372 $xmldb_table = new xmldb_table($table);
373 $DB->get_manager()->drop_table($xmldb_table);
377 return true;
381 * Returns names of all known tables == tables that moodle knows about.
383 * @return array Array of lowercase table names
385 function get_used_table_names() {
386 $table_names = array();
387 $dbdirs = get_db_directories();
389 foreach ($dbdirs as $dbdir) {
390 $file = $dbdir.'/install.xml';
392 $xmldb_file = new xmldb_file($file);
394 if (!$xmldb_file->fileExists()) {
395 continue;
398 $loaded = $xmldb_file->loadXMLStructure();
399 $structure = $xmldb_file->getStructure();
401 if ($loaded and $tables = $structure->getTables()) {
402 foreach($tables as $table) {
403 $table_names[] = strtolower($table->getName());
408 return $table_names;
412 * Returns list of all directories where we expect install.xml files
413 * @return array Array of paths
415 function get_db_directories() {
416 global $CFG;
418 $dbdirs = array();
420 /// First, the main one (lib/db)
421 $dbdirs[] = $CFG->libdir.'/db';
423 /// Then, all the ones defined by core_component::get_plugin_types()
424 $plugintypes = core_component::get_plugin_types();
425 foreach ($plugintypes as $plugintype => $pluginbasedir) {
426 if ($plugins = core_component::get_plugin_list($plugintype)) {
427 foreach ($plugins as $plugin => $plugindir) {
428 $dbdirs[] = $plugindir.'/db';
433 return $dbdirs;
437 * Try to obtain or release the cron lock.
438 * @param string $name name of lock
439 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
440 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
441 * @return bool true if lock obtained
443 function set_cron_lock($name, $until, $ignorecurrent=false) {
444 global $DB;
445 if (empty($name)) {
446 debugging("Tried to get a cron lock for a null fieldname");
447 return false;
450 // remove lock by force == remove from config table
451 if (is_null($until)) {
452 set_config($name, null);
453 return true;
456 if (!$ignorecurrent) {
457 // read value from db - other processes might have changed it
458 $value = $DB->get_field('config', 'value', array('name'=>$name));
460 if ($value and $value > time()) {
461 //lock active
462 return false;
466 set_config($name, $until);
467 return true;
471 * Test if and critical warnings are present
472 * @return bool
474 function admin_critical_warnings_present() {
475 global $SESSION;
477 if (!has_capability('moodle/site:config', context_system::instance())) {
478 return 0;
481 if (!isset($SESSION->admin_critical_warning)) {
482 $SESSION->admin_critical_warning = 0;
483 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
484 $SESSION->admin_critical_warning = 1;
488 return $SESSION->admin_critical_warning;
492 * Detects if float supports at least 10 decimal digits
494 * Detects if float supports at least 10 decimal digits
495 * and also if float-->string conversion works as expected.
497 * @return bool true if problem found
499 function is_float_problem() {
500 $num1 = 2009010200.01;
501 $num2 = 2009010200.02;
503 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
507 * Try to verify that dataroot is not accessible from web.
509 * Try to verify that dataroot is not accessible from web.
510 * It is not 100% correct but might help to reduce number of vulnerable sites.
511 * Protection from httpd.conf and .htaccess is not detected properly.
513 * @uses INSECURE_DATAROOT_WARNING
514 * @uses INSECURE_DATAROOT_ERROR
515 * @param bool $fetchtest try to test public access by fetching file, default false
516 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
518 function is_dataroot_insecure($fetchtest=false) {
519 global $CFG;
521 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
523 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
524 $rp = strrev(trim($rp, '/'));
525 $rp = explode('/', $rp);
526 foreach($rp as $r) {
527 if (strpos($siteroot, '/'.$r.'/') === 0) {
528 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
529 } else {
530 break; // probably alias root
534 $siteroot = strrev($siteroot);
535 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
537 if (strpos($dataroot, $siteroot) !== 0) {
538 return false;
541 if (!$fetchtest) {
542 return INSECURE_DATAROOT_WARNING;
545 // now try all methods to fetch a test file using http protocol
547 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
548 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
549 $httpdocroot = $matches[1];
550 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
551 make_upload_directory('diag');
552 $testfile = $CFG->dataroot.'/diag/public.txt';
553 if (!file_exists($testfile)) {
554 file_put_contents($testfile, 'test file, do not delete');
555 @chmod($testfile, $CFG->filepermissions);
557 $teststr = trim(file_get_contents($testfile));
558 if (empty($teststr)) {
559 // hmm, strange
560 return INSECURE_DATAROOT_WARNING;
563 $testurl = $datarooturl.'/diag/public.txt';
564 if (extension_loaded('curl') and
565 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
566 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
567 ($ch = @curl_init($testurl)) !== false) {
568 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
569 curl_setopt($ch, CURLOPT_HEADER, false);
570 $data = curl_exec($ch);
571 if (!curl_errno($ch)) {
572 $data = trim($data);
573 if ($data === $teststr) {
574 curl_close($ch);
575 return INSECURE_DATAROOT_ERROR;
578 curl_close($ch);
581 if ($data = @file_get_contents($testurl)) {
582 $data = trim($data);
583 if ($data === $teststr) {
584 return INSECURE_DATAROOT_ERROR;
588 preg_match('|https?://([^/]+)|i', $testurl, $matches);
589 $sitename = $matches[1];
590 $error = 0;
591 if ($fp = @fsockopen($sitename, 80, $error)) {
592 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
593 $localurl = $matches[1];
594 $out = "GET $localurl HTTP/1.1\r\n";
595 $out .= "Host: $sitename\r\n";
596 $out .= "Connection: Close\r\n\r\n";
597 fwrite($fp, $out);
598 $data = '';
599 $incoming = false;
600 while (!feof($fp)) {
601 if ($incoming) {
602 $data .= fgets($fp, 1024);
603 } else if (@fgets($fp, 1024) === "\r\n") {
604 $incoming = true;
607 fclose($fp);
608 $data = trim($data);
609 if ($data === $teststr) {
610 return INSECURE_DATAROOT_ERROR;
614 return INSECURE_DATAROOT_WARNING;
618 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
620 function enable_cli_maintenance_mode() {
621 global $CFG;
623 if (file_exists("$CFG->dataroot/climaintenance.html")) {
624 unlink("$CFG->dataroot/climaintenance.html");
627 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
628 $data = $CFG->maintenance_message;
629 $data = bootstrap_renderer::early_error_content($data, null, null, null);
630 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
632 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
633 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
635 } else {
636 $data = get_string('sitemaintenance', 'admin');
637 $data = bootstrap_renderer::early_error_content($data, null, null, null);
638 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
641 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
642 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
645 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
649 * Interface for anything appearing in the admin tree
651 * The interface that is implemented by anything that appears in the admin tree
652 * block. It forces inheriting classes to define a method for checking user permissions
653 * and methods for finding something in the admin tree.
655 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
657 interface part_of_admin_tree {
660 * Finds a named part_of_admin_tree.
662 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
663 * and not parentable_part_of_admin_tree, then this function should only check if
664 * $this->name matches $name. If it does, it should return a reference to $this,
665 * otherwise, it should return a reference to NULL.
667 * If a class inherits parentable_part_of_admin_tree, this method should be called
668 * recursively on all child objects (assuming, of course, the parent object's name
669 * doesn't match the search criterion).
671 * @param string $name The internal name of the part_of_admin_tree we're searching for.
672 * @return mixed An object reference or a NULL reference.
674 public function locate($name);
677 * Removes named part_of_admin_tree.
679 * @param string $name The internal name of the part_of_admin_tree we want to remove.
680 * @return bool success.
682 public function prune($name);
685 * Search using query
686 * @param string $query
687 * @return mixed array-object structure of found settings and pages
689 public function search($query);
692 * Verifies current user's access to this part_of_admin_tree.
694 * Used to check if the current user has access to this part of the admin tree or
695 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
696 * then this method is usually just a call to has_capability() in the site context.
698 * If a class inherits parentable_part_of_admin_tree, this method should return the
699 * logical OR of the return of check_access() on all child objects.
701 * @return bool True if the user has access, false if she doesn't.
703 public function check_access();
706 * Mostly useful for removing of some parts of the tree in admin tree block.
708 * @return True is hidden from normal list view
710 public function is_hidden();
713 * Show we display Save button at the page bottom?
714 * @return bool
716 public function show_save();
721 * Interface implemented by any part_of_admin_tree that has children.
723 * The interface implemented by any part_of_admin_tree that can be a parent
724 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
725 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
726 * include an add method for adding other part_of_admin_tree objects as children.
728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
730 interface parentable_part_of_admin_tree extends part_of_admin_tree {
733 * Adds a part_of_admin_tree object to the admin tree.
735 * Used to add a part_of_admin_tree object to this object or a child of this
736 * object. $something should only be added if $destinationname matches
737 * $this->name. If it doesn't, add should be called on child objects that are
738 * also parentable_part_of_admin_tree's.
740 * $something should be appended as the last child in the $destinationname. If the
741 * $beforesibling is specified, $something should be prepended to it. If the given
742 * sibling is not found, $something should be appended to the end of $destinationname
743 * and a developer debugging message should be displayed.
745 * @param string $destinationname The internal name of the new parent for $something.
746 * @param part_of_admin_tree $something The object to be added.
747 * @return bool True on success, false on failure.
749 public function add($destinationname, $something, $beforesibling = null);
755 * The object used to represent folders (a.k.a. categories) in the admin tree block.
757 * Each admin_category object contains a number of part_of_admin_tree objects.
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
761 class admin_category implements parentable_part_of_admin_tree {
763 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
764 protected $children;
765 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
766 public $name;
767 /** @var string The displayed name for this category. Usually obtained through get_string() */
768 public $visiblename;
769 /** @var bool Should this category be hidden in admin tree block? */
770 public $hidden;
771 /** @var mixed Either a string or an array or strings */
772 public $path;
773 /** @var mixed Either a string or an array or strings */
774 public $visiblepath;
776 /** @var array fast lookup category cache, all categories of one tree point to one cache */
777 protected $category_cache;
779 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
780 protected $sort = false;
781 /** @var bool If set to true children will be sorted in ascending order. */
782 protected $sortasc = true;
783 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
784 protected $sortsplit = true;
785 /** @var bool $sorted True if the children have been sorted and don't need resorting */
786 protected $sorted = false;
789 * Constructor for an empty admin category
791 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
792 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
793 * @param bool $hidden hide category in admin tree block, defaults to false
795 public function __construct($name, $visiblename, $hidden=false) {
796 $this->children = array();
797 $this->name = $name;
798 $this->visiblename = $visiblename;
799 $this->hidden = $hidden;
803 * Returns a reference to the part_of_admin_tree object with internal name $name.
805 * @param string $name The internal name of the object we want.
806 * @param bool $findpath initialize path and visiblepath arrays
807 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
808 * defaults to false
810 public function locate($name, $findpath=false) {
811 if (!isset($this->category_cache[$this->name])) {
812 // somebody much have purged the cache
813 $this->category_cache[$this->name] = $this;
816 if ($this->name == $name) {
817 if ($findpath) {
818 $this->visiblepath[] = $this->visiblename;
819 $this->path[] = $this->name;
821 return $this;
824 // quick category lookup
825 if (!$findpath and isset($this->category_cache[$name])) {
826 return $this->category_cache[$name];
829 $return = NULL;
830 foreach($this->children as $childid=>$unused) {
831 if ($return = $this->children[$childid]->locate($name, $findpath)) {
832 break;
836 if (!is_null($return) and $findpath) {
837 $return->visiblepath[] = $this->visiblename;
838 $return->path[] = $this->name;
841 return $return;
845 * Search using query
847 * @param string query
848 * @return mixed array-object structure of found settings and pages
850 public function search($query) {
851 $result = array();
852 foreach ($this->get_children() as $child) {
853 $subsearch = $child->search($query);
854 if (!is_array($subsearch)) {
855 debugging('Incorrect search result from '.$child->name);
856 continue;
858 $result = array_merge($result, $subsearch);
860 return $result;
864 * Removes part_of_admin_tree object with internal name $name.
866 * @param string $name The internal name of the object we want to remove.
867 * @return bool success
869 public function prune($name) {
871 if ($this->name == $name) {
872 return false; //can not remove itself
875 foreach($this->children as $precedence => $child) {
876 if ($child->name == $name) {
877 // clear cache and delete self
878 while($this->category_cache) {
879 // delete the cache, but keep the original array address
880 array_pop($this->category_cache);
882 unset($this->children[$precedence]);
883 return true;
884 } else if ($this->children[$precedence]->prune($name)) {
885 return true;
888 return false;
892 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
894 * By default the new part of the tree is appended as the last child of the parent. You
895 * can specify a sibling node that the new part should be prepended to. If the given
896 * sibling is not found, the part is appended to the end (as it would be by default) and
897 * a developer debugging message is displayed.
899 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
900 * @param string $destinationame The internal name of the immediate parent that we want for $something.
901 * @param mixed $something A part_of_admin_tree or setting instance to be added.
902 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
903 * @return bool True if successfully added, false if $something can not be added.
905 public function add($parentname, $something, $beforesibling = null) {
906 global $CFG;
908 $parent = $this->locate($parentname);
909 if (is_null($parent)) {
910 debugging('parent does not exist!');
911 return false;
914 if ($something instanceof part_of_admin_tree) {
915 if (!($parent instanceof parentable_part_of_admin_tree)) {
916 debugging('error - parts of tree can be inserted only into parentable parts');
917 return false;
919 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
920 // The name of the node is already used, simply warn the developer that this should not happen.
921 // It is intentional to check for the debug level before performing the check.
922 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
924 if (is_null($beforesibling)) {
925 // Append $something as the parent's last child.
926 $parent->children[] = $something;
927 } else {
928 if (!is_string($beforesibling) or trim($beforesibling) === '') {
929 throw new coding_exception('Unexpected value of the beforesibling parameter');
931 // Try to find the position of the sibling.
932 $siblingposition = null;
933 foreach ($parent->children as $childposition => $child) {
934 if ($child->name === $beforesibling) {
935 $siblingposition = $childposition;
936 break;
939 if (is_null($siblingposition)) {
940 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
941 $parent->children[] = $something;
942 } else {
943 $parent->children = array_merge(
944 array_slice($parent->children, 0, $siblingposition),
945 array($something),
946 array_slice($parent->children, $siblingposition)
950 if ($something instanceof admin_category) {
951 if (isset($this->category_cache[$something->name])) {
952 debugging('Duplicate admin category name: '.$something->name);
953 } else {
954 $this->category_cache[$something->name] = $something;
955 $something->category_cache =& $this->category_cache;
956 foreach ($something->children as $child) {
957 // just in case somebody already added subcategories
958 if ($child instanceof admin_category) {
959 if (isset($this->category_cache[$child->name])) {
960 debugging('Duplicate admin category name: '.$child->name);
961 } else {
962 $this->category_cache[$child->name] = $child;
963 $child->category_cache =& $this->category_cache;
969 return true;
971 } else {
972 debugging('error - can not add this element');
973 return false;
979 * Checks if the user has access to anything in this category.
981 * @return bool True if the user has access to at least one child in this category, false otherwise.
983 public function check_access() {
984 foreach ($this->children as $child) {
985 if ($child->check_access()) {
986 return true;
989 return false;
993 * Is this category hidden in admin tree block?
995 * @return bool True if hidden
997 public function is_hidden() {
998 return $this->hidden;
1002 * Show we display Save button at the page bottom?
1003 * @return bool
1005 public function show_save() {
1006 foreach ($this->children as $child) {
1007 if ($child->show_save()) {
1008 return true;
1011 return false;
1015 * Sets sorting on this category.
1017 * Please note this function doesn't actually do the sorting.
1018 * It can be called anytime.
1019 * Sorting occurs when the user calls get_children.
1020 * Code using the children array directly won't see the sorted results.
1022 * @param bool $sort If set to true children will be sorted, if false they won't be.
1023 * @param bool $asc If true sorting will be ascending, otherwise descending.
1024 * @param bool $split If true we sort pages and sub categories separately.
1026 public function set_sorting($sort, $asc = true, $split = true) {
1027 $this->sort = (bool)$sort;
1028 $this->sortasc = (bool)$asc;
1029 $this->sortsplit = (bool)$split;
1033 * Returns the children associated with this category.
1035 * @return part_of_admin_tree[]
1037 public function get_children() {
1038 // If we should sort and it hasn't already been sorted.
1039 if ($this->sort && !$this->sorted) {
1040 if ($this->sortsplit) {
1041 $categories = array();
1042 $pages = array();
1043 foreach ($this->children as $child) {
1044 if ($child instanceof admin_category) {
1045 $categories[] = $child;
1046 } else {
1047 $pages[] = $child;
1050 core_collator::asort_objects_by_property($categories, 'visiblename');
1051 core_collator::asort_objects_by_property($pages, 'visiblename');
1052 if (!$this->sortasc) {
1053 $categories = array_reverse($categories);
1054 $pages = array_reverse($pages);
1056 $this->children = array_merge($pages, $categories);
1057 } else {
1058 core_collator::asort_objects_by_property($this->children, 'visiblename');
1059 if (!$this->sortasc) {
1060 $this->children = array_reverse($this->children);
1063 $this->sorted = true;
1065 return $this->children;
1069 * Magically gets a property from this object.
1071 * @param $property
1072 * @return part_of_admin_tree[]
1073 * @throws coding_exception
1075 public function __get($property) {
1076 if ($property === 'children') {
1077 return $this->get_children();
1079 throw new coding_exception('Invalid property requested.');
1083 * Magically sets a property against this object.
1085 * @param string $property
1086 * @param mixed $value
1087 * @throws coding_exception
1089 public function __set($property, $value) {
1090 if ($property === 'children') {
1091 $this->sorted = false;
1092 $this->children = $value;
1093 } else {
1094 throw new coding_exception('Invalid property requested.');
1099 * Checks if an inaccessible property is set.
1101 * @param string $property
1102 * @return bool
1103 * @throws coding_exception
1105 public function __isset($property) {
1106 if ($property === 'children') {
1107 return isset($this->children);
1109 throw new coding_exception('Invalid property requested.');
1115 * Root of admin settings tree, does not have any parent.
1117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1119 class admin_root extends admin_category {
1120 /** @var array List of errors */
1121 public $errors;
1122 /** @var string search query */
1123 public $search;
1124 /** @var bool full tree flag - true means all settings required, false only pages required */
1125 public $fulltree;
1126 /** @var bool flag indicating loaded tree */
1127 public $loaded;
1128 /** @var mixed site custom defaults overriding defaults in settings files*/
1129 public $custom_defaults;
1132 * @param bool $fulltree true means all settings required,
1133 * false only pages required
1135 public function __construct($fulltree) {
1136 global $CFG;
1138 parent::__construct('root', get_string('administration'), false);
1139 $this->errors = array();
1140 $this->search = '';
1141 $this->fulltree = $fulltree;
1142 $this->loaded = false;
1144 $this->category_cache = array();
1146 // load custom defaults if found
1147 $this->custom_defaults = null;
1148 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1149 if (is_readable($defaultsfile)) {
1150 $defaults = array();
1151 include($defaultsfile);
1152 if (is_array($defaults) and count($defaults)) {
1153 $this->custom_defaults = $defaults;
1159 * Empties children array, and sets loaded to false
1161 * @param bool $requirefulltree
1163 public function purge_children($requirefulltree) {
1164 $this->children = array();
1165 $this->fulltree = ($requirefulltree || $this->fulltree);
1166 $this->loaded = false;
1167 //break circular dependencies - this helps PHP 5.2
1168 while($this->category_cache) {
1169 array_pop($this->category_cache);
1171 $this->category_cache = array();
1177 * Links external PHP pages into the admin tree.
1179 * See detailed usage example at the top of this document (adminlib.php)
1181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1183 class admin_externalpage implements part_of_admin_tree {
1185 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1186 public $name;
1188 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1189 public $visiblename;
1191 /** @var string The external URL that we should link to when someone requests this external page. */
1192 public $url;
1194 /** @var string The role capability/permission a user must have to access this external page. */
1195 public $req_capability;
1197 /** @var object The context in which capability/permission should be checked, default is site context. */
1198 public $context;
1200 /** @var bool hidden in admin tree block. */
1201 public $hidden;
1203 /** @var mixed either string or array of string */
1204 public $path;
1206 /** @var array list of visible names of page parents */
1207 public $visiblepath;
1210 * Constructor for adding an external page into the admin tree.
1212 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1213 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1214 * @param string $url The external URL that we should link to when someone requests this external page.
1215 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1216 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1217 * @param stdClass $context The context the page relates to. Not sure what happens
1218 * if you specify something other than system or front page. Defaults to system.
1220 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1221 $this->name = $name;
1222 $this->visiblename = $visiblename;
1223 $this->url = $url;
1224 if (is_array($req_capability)) {
1225 $this->req_capability = $req_capability;
1226 } else {
1227 $this->req_capability = array($req_capability);
1229 $this->hidden = $hidden;
1230 $this->context = $context;
1234 * Returns a reference to the part_of_admin_tree object with internal name $name.
1236 * @param string $name The internal name of the object we want.
1237 * @param bool $findpath defaults to false
1238 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1240 public function locate($name, $findpath=false) {
1241 if ($this->name == $name) {
1242 if ($findpath) {
1243 $this->visiblepath = array($this->visiblename);
1244 $this->path = array($this->name);
1246 return $this;
1247 } else {
1248 $return = NULL;
1249 return $return;
1254 * This function always returns false, required function by interface
1256 * @param string $name
1257 * @return false
1259 public function prune($name) {
1260 return false;
1264 * Search using query
1266 * @param string $query
1267 * @return mixed array-object structure of found settings and pages
1269 public function search($query) {
1270 $found = false;
1271 if (strpos(strtolower($this->name), $query) !== false) {
1272 $found = true;
1273 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1274 $found = true;
1276 if ($found) {
1277 $result = new stdClass();
1278 $result->page = $this;
1279 $result->settings = array();
1280 return array($this->name => $result);
1281 } else {
1282 return array();
1287 * Determines if the current user has access to this external page based on $this->req_capability.
1289 * @return bool True if user has access, false otherwise.
1291 public function check_access() {
1292 global $CFG;
1293 $context = empty($this->context) ? context_system::instance() : $this->context;
1294 foreach($this->req_capability as $cap) {
1295 if (has_capability($cap, $context)) {
1296 return true;
1299 return false;
1303 * Is this external page hidden in admin tree block?
1305 * @return bool True if hidden
1307 public function is_hidden() {
1308 return $this->hidden;
1312 * Show we display Save button at the page bottom?
1313 * @return bool
1315 public function show_save() {
1316 return false;
1321 * Used to store details of the dependency between two settings elements.
1323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1324 * @copyright 2017 Davo Smith, Synergy Learning
1326 class admin_settingdependency {
1327 /** @var string the name of the setting to be shown/hidden */
1328 public $settingname;
1329 /** @var string the setting this is dependent on */
1330 public $dependenton;
1331 /** @var string the condition to show/hide the element */
1332 public $condition;
1333 /** @var string the value to compare against */
1334 public $value;
1336 /** @var string[] list of valid conditions */
1337 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1340 * admin_settingdependency constructor.
1341 * @param string $settingname
1342 * @param string $dependenton
1343 * @param string $condition
1344 * @param string $value
1345 * @throws \coding_exception
1347 public function __construct($settingname, $dependenton, $condition, $value) {
1348 $this->settingname = $this->parse_name($settingname);
1349 $this->dependenton = $this->parse_name($dependenton);
1350 $this->condition = $condition;
1351 $this->value = $value;
1353 if (!in_array($this->condition, self::$validconditions)) {
1354 throw new coding_exception("Invalid condition '$condition'");
1359 * Convert the setting name into the form field name.
1360 * @param string $name
1361 * @return string
1363 private function parse_name($name) {
1364 $bits = explode('/', $name);
1365 $name = array_pop($bits);
1366 $plugin = '';
1367 if ($bits) {
1368 $plugin = array_pop($bits);
1369 if ($plugin === 'moodle') {
1370 $plugin = '';
1373 return 's_'.$plugin.'_'.$name;
1377 * Gather together all the dependencies in a format suitable for initialising javascript
1378 * @param admin_settingdependency[] $dependencies
1379 * @return array
1381 public static function prepare_for_javascript($dependencies) {
1382 $result = [];
1383 foreach ($dependencies as $d) {
1384 if (!isset($result[$d->dependenton])) {
1385 $result[$d->dependenton] = [];
1387 if (!isset($result[$d->dependenton][$d->condition])) {
1388 $result[$d->dependenton][$d->condition] = [];
1390 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1391 $result[$d->dependenton][$d->condition][$d->value] = [];
1393 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1395 return $result;
1400 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1402 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1404 class admin_settingpage implements part_of_admin_tree {
1406 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1407 public $name;
1409 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1410 public $visiblename;
1412 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1413 public $settings;
1415 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1416 protected $dependencies = [];
1418 /** @var string The role capability/permission a user must have to access this external page. */
1419 public $req_capability;
1421 /** @var object The context in which capability/permission should be checked, default is site context. */
1422 public $context;
1424 /** @var bool hidden in admin tree block. */
1425 public $hidden;
1427 /** @var mixed string of paths or array of strings of paths */
1428 public $path;
1430 /** @var array list of visible names of page parents */
1431 public $visiblepath;
1434 * see admin_settingpage for details of this function
1436 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1437 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1438 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1439 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1440 * @param stdClass $context The context the page relates to. Not sure what happens
1441 * if you specify something other than system or front page. Defaults to system.
1443 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1444 $this->settings = new stdClass();
1445 $this->name = $name;
1446 $this->visiblename = $visiblename;
1447 if (is_array($req_capability)) {
1448 $this->req_capability = $req_capability;
1449 } else {
1450 $this->req_capability = array($req_capability);
1452 $this->hidden = $hidden;
1453 $this->context = $context;
1457 * see admin_category
1459 * @param string $name
1460 * @param bool $findpath
1461 * @return mixed Object (this) if name == this->name, else returns null
1463 public function locate($name, $findpath=false) {
1464 if ($this->name == $name) {
1465 if ($findpath) {
1466 $this->visiblepath = array($this->visiblename);
1467 $this->path = array($this->name);
1469 return $this;
1470 } else {
1471 $return = NULL;
1472 return $return;
1477 * Search string in settings page.
1479 * @param string $query
1480 * @return array
1482 public function search($query) {
1483 $found = array();
1485 foreach ($this->settings as $setting) {
1486 if ($setting->is_related($query)) {
1487 $found[] = $setting;
1491 if ($found) {
1492 $result = new stdClass();
1493 $result->page = $this;
1494 $result->settings = $found;
1495 return array($this->name => $result);
1498 $found = false;
1499 if (strpos(strtolower($this->name), $query) !== false) {
1500 $found = true;
1501 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1502 $found = true;
1504 if ($found) {
1505 $result = new stdClass();
1506 $result->page = $this;
1507 $result->settings = array();
1508 return array($this->name => $result);
1509 } else {
1510 return array();
1515 * This function always returns false, required by interface
1517 * @param string $name
1518 * @return bool Always false
1520 public function prune($name) {
1521 return false;
1525 * adds an admin_setting to this admin_settingpage
1527 * 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
1528 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1530 * @param object $setting is the admin_setting object you want to add
1531 * @return bool true if successful, false if not
1533 public function add($setting) {
1534 if (!($setting instanceof admin_setting)) {
1535 debugging('error - not a setting instance');
1536 return false;
1539 $name = $setting->name;
1540 if ($setting->plugin) {
1541 $name = $setting->plugin . $name;
1543 $this->settings->{$name} = $setting;
1544 return true;
1548 * Hide the named setting if the specified condition is matched.
1550 * @param string $settingname
1551 * @param string $dependenton
1552 * @param string $condition
1553 * @param string $value
1555 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1556 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1558 // Reformat the dependency name to the plugin | name format used in the display.
1559 $dependenton = str_replace('/', ' | ', $dependenton);
1561 // Let the setting know, so it can be displayed underneath.
1562 $findname = str_replace('/', '', $settingname);
1563 foreach ($this->settings as $name => $setting) {
1564 if ($name === $findname) {
1565 $setting->add_dependent_on($dependenton);
1571 * see admin_externalpage
1573 * @return bool Returns true for yes false for no
1575 public function check_access() {
1576 global $CFG;
1577 $context = empty($this->context) ? context_system::instance() : $this->context;
1578 foreach($this->req_capability as $cap) {
1579 if (has_capability($cap, $context)) {
1580 return true;
1583 return false;
1587 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1588 * @return string Returns an XHTML string
1590 public function output_html() {
1591 $adminroot = admin_get_root();
1592 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1593 foreach($this->settings as $setting) {
1594 $fullname = $setting->get_full_name();
1595 if (array_key_exists($fullname, $adminroot->errors)) {
1596 $data = $adminroot->errors[$fullname]->data;
1597 } else {
1598 $data = $setting->get_setting();
1599 // do not use defaults if settings not available - upgrade settings handles the defaults!
1601 $return .= $setting->output_html($data);
1603 $return .= '</fieldset>';
1604 return $return;
1608 * Is this settings page hidden in admin tree block?
1610 * @return bool True if hidden
1612 public function is_hidden() {
1613 return $this->hidden;
1617 * Show we display Save button at the page bottom?
1618 * @return bool
1620 public function show_save() {
1621 foreach($this->settings as $setting) {
1622 if (empty($setting->nosave)) {
1623 return true;
1626 return false;
1630 * Should any of the settings on this page be shown / hidden based on conditions?
1631 * @return bool
1633 public function has_dependencies() {
1634 return (bool)$this->dependencies;
1638 * Format the setting show/hide conditions ready to initialise the page javascript
1639 * @return array
1641 public function get_dependencies_for_javascript() {
1642 if (!$this->has_dependencies()) {
1643 return [];
1645 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1651 * Admin settings class. Only exists on setting pages.
1652 * Read & write happens at this level; no authentication.
1654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1656 abstract class admin_setting {
1657 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1658 public $name;
1659 /** @var string localised name */
1660 public $visiblename;
1661 /** @var string localised long description in Markdown format */
1662 public $description;
1663 /** @var mixed Can be string or array of string */
1664 public $defaultsetting;
1665 /** @var string */
1666 public $updatedcallback;
1667 /** @var mixed can be String or Null. Null means main config table */
1668 public $plugin; // null means main config table
1669 /** @var bool true indicates this setting does not actually save anything, just information */
1670 public $nosave = false;
1671 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1672 public $affectsmodinfo = false;
1673 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1674 private $flags = array();
1675 /** @var bool Whether this field must be forced LTR. */
1676 private $forceltr = null;
1677 /** @var array list of other settings that may cause this setting to be hidden */
1678 private $dependenton = [];
1681 * Constructor
1682 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1683 * or 'myplugin/mysetting' for ones in config_plugins.
1684 * @param string $visiblename localised name
1685 * @param string $description localised long description
1686 * @param mixed $defaultsetting string or array depending on implementation
1688 public function __construct($name, $visiblename, $description, $defaultsetting) {
1689 $this->parse_setting_name($name);
1690 $this->visiblename = $visiblename;
1691 $this->description = $description;
1692 $this->defaultsetting = $defaultsetting;
1696 * Generic function to add a flag to this admin setting.
1698 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1699 * @param bool $default - The default for the flag
1700 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1701 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1703 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1704 if (empty($this->flags[$shortname])) {
1705 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1706 } else {
1707 $this->flags[$shortname]->set_options($enabled, $default);
1712 * Set the enabled options flag on this admin setting.
1714 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1715 * @param bool $default - The default for the flag
1717 public function set_enabled_flag_options($enabled, $default) {
1718 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1722 * Set the advanced options flag on this admin setting.
1724 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1725 * @param bool $default - The default for the flag
1727 public function set_advanced_flag_options($enabled, $default) {
1728 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1733 * Set the locked options flag on this admin setting.
1735 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1736 * @param bool $default - The default for the flag
1738 public function set_locked_flag_options($enabled, $default) {
1739 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1743 * Get the currently saved value for a setting flag
1745 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1746 * @return bool
1748 public function get_setting_flag_value(admin_setting_flag $flag) {
1749 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1750 if (!isset($value)) {
1751 $value = $flag->get_default();
1754 return !empty($value);
1758 * Get the list of defaults for the flags on this setting.
1760 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1762 public function get_setting_flag_defaults(& $defaults) {
1763 foreach ($this->flags as $flag) {
1764 if ($flag->is_enabled() && $flag->get_default()) {
1765 $defaults[] = $flag->get_displayname();
1771 * Output the input fields for the advanced and locked flags on this setting.
1773 * @param bool $adv - The current value of the advanced flag.
1774 * @param bool $locked - The current value of the locked flag.
1775 * @return string $output - The html for the flags.
1777 public function output_setting_flags() {
1778 $output = '';
1780 foreach ($this->flags as $flag) {
1781 if ($flag->is_enabled()) {
1782 $output .= $flag->output_setting_flag($this);
1786 if (!empty($output)) {
1787 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1789 return $output;
1793 * Write the values of the flags for this admin setting.
1795 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1796 * @return bool - true if successful.
1798 public function write_setting_flags($data) {
1799 $result = true;
1800 foreach ($this->flags as $flag) {
1801 $result = $result && $flag->write_setting_flag($this, $data);
1803 return $result;
1807 * Set up $this->name and potentially $this->plugin
1809 * Set up $this->name and possibly $this->plugin based on whether $name looks
1810 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1811 * on the names, that is, output a developer debug warning if the name
1812 * contains anything other than [a-zA-Z0-9_]+.
1814 * @param string $name the setting name passed in to the constructor.
1816 private function parse_setting_name($name) {
1817 $bits = explode('/', $name);
1818 if (count($bits) > 2) {
1819 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1821 $this->name = array_pop($bits);
1822 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1823 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1825 if (!empty($bits)) {
1826 $this->plugin = array_pop($bits);
1827 if ($this->plugin === 'moodle') {
1828 $this->plugin = null;
1829 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1830 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1836 * Returns the fullname prefixed by the plugin
1837 * @return string
1839 public function get_full_name() {
1840 return 's_'.$this->plugin.'_'.$this->name;
1844 * Returns the ID string based on plugin and name
1845 * @return string
1847 public function get_id() {
1848 return 'id_s_'.$this->plugin.'_'.$this->name;
1852 * @param bool $affectsmodinfo If true, changes to this setting will
1853 * cause the course cache to be rebuilt
1855 public function set_affects_modinfo($affectsmodinfo) {
1856 $this->affectsmodinfo = $affectsmodinfo;
1860 * Returns the config if possible
1862 * @return mixed returns config if successful else null
1864 public function config_read($name) {
1865 global $CFG;
1866 if (!empty($this->plugin)) {
1867 $value = get_config($this->plugin, $name);
1868 return $value === false ? NULL : $value;
1870 } else {
1871 if (isset($CFG->$name)) {
1872 return $CFG->$name;
1873 } else {
1874 return NULL;
1880 * Used to set a config pair and log change
1882 * @param string $name
1883 * @param mixed $value Gets converted to string if not null
1884 * @return bool Write setting to config table
1886 public function config_write($name, $value) {
1887 global $DB, $USER, $CFG;
1889 if ($this->nosave) {
1890 return true;
1893 // make sure it is a real change
1894 $oldvalue = get_config($this->plugin, $name);
1895 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1896 $value = is_null($value) ? null : (string)$value;
1898 if ($oldvalue === $value) {
1899 return true;
1902 // store change
1903 set_config($name, $value, $this->plugin);
1905 // Some admin settings affect course modinfo
1906 if ($this->affectsmodinfo) {
1907 // Clear course cache for all courses
1908 rebuild_course_cache(0, true);
1911 $this->add_to_config_log($name, $oldvalue, $value);
1913 return true; // BC only
1917 * Log config changes if necessary.
1918 * @param string $name
1919 * @param string $oldvalue
1920 * @param string $value
1922 protected function add_to_config_log($name, $oldvalue, $value) {
1923 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1927 * Returns current value of this setting
1928 * @return mixed array or string depending on instance, NULL means not set yet
1930 public abstract function get_setting();
1933 * Returns default setting if exists
1934 * @return mixed array or string depending on instance; NULL means no default, user must supply
1936 public function get_defaultsetting() {
1937 $adminroot = admin_get_root(false, false);
1938 if (!empty($adminroot->custom_defaults)) {
1939 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1940 if (isset($adminroot->custom_defaults[$plugin])) {
1941 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1942 return $adminroot->custom_defaults[$plugin][$this->name];
1946 return $this->defaultsetting;
1950 * Store new setting
1952 * @param mixed $data string or array, must not be NULL
1953 * @return string empty string if ok, string error message otherwise
1955 public abstract function write_setting($data);
1958 * Return part of form with setting
1959 * This function should always be overwritten
1961 * @param mixed $data array or string depending on setting
1962 * @param string $query
1963 * @return string
1965 public function output_html($data, $query='') {
1966 // should be overridden
1967 return;
1971 * Function called if setting updated - cleanup, cache reset, etc.
1972 * @param string $functionname Sets the function name
1973 * @return void
1975 public function set_updatedcallback($functionname) {
1976 $this->updatedcallback = $functionname;
1980 * Execute postupdatecallback if necessary.
1981 * @param mixed $original original value before write_setting()
1982 * @return bool true if changed, false if not.
1984 public function post_write_settings($original) {
1985 // Comparison must work for arrays too.
1986 if (serialize($original) === serialize($this->get_setting())) {
1987 return false;
1990 $callbackfunction = $this->updatedcallback;
1991 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
1992 $callbackfunction($this->get_full_name());
1994 return true;
1998 * Is setting related to query text - used when searching
1999 * @param string $query
2000 * @return bool
2002 public function is_related($query) {
2003 if (strpos(strtolower($this->name), $query) !== false) {
2004 return true;
2006 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2007 return true;
2009 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2010 return true;
2012 $current = $this->get_setting();
2013 if (!is_null($current)) {
2014 if (is_string($current)) {
2015 if (strpos(core_text::strtolower($current), $query) !== false) {
2016 return true;
2020 $default = $this->get_defaultsetting();
2021 if (!is_null($default)) {
2022 if (is_string($default)) {
2023 if (strpos(core_text::strtolower($default), $query) !== false) {
2024 return true;
2028 return false;
2032 * Get whether this should be displayed in LTR mode.
2034 * @return bool|null
2036 public function get_force_ltr() {
2037 return $this->forceltr;
2041 * Set whether to force LTR or not.
2043 * @param bool $value True when forced, false when not force, null when unknown.
2045 public function set_force_ltr($value) {
2046 $this->forceltr = $value;
2050 * Add a setting to the list of those that could cause this one to be hidden
2051 * @param string $dependenton
2053 public function add_dependent_on($dependenton) {
2054 $this->dependenton[] = $dependenton;
2058 * Get a list of the settings that could cause this one to be hidden.
2059 * @return array
2061 public function get_dependent_on() {
2062 return $this->dependenton;
2067 * An additional option that can be applied to an admin setting.
2068 * The currently supported options are 'ADVANCED' and 'LOCKED'.
2070 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2072 class admin_setting_flag {
2073 /** @var bool Flag to indicate if this option can be toggled for this setting */
2074 private $enabled = false;
2075 /** @var bool Flag to indicate if this option defaults to true or false */
2076 private $default = false;
2077 /** @var string Short string used to create setting name - e.g. 'adv' */
2078 private $shortname = '';
2079 /** @var string String used as the label for this flag */
2080 private $displayname = '';
2081 /** @const Checkbox for this flag is displayed in admin page */
2082 const ENABLED = true;
2083 /** @const Checkbox for this flag is not displayed in admin page */
2084 const DISABLED = false;
2087 * Constructor
2089 * @param bool $enabled Can this option can be toggled.
2090 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2091 * @param bool $default The default checked state for this setting option.
2092 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2093 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2095 public function __construct($enabled, $default, $shortname, $displayname) {
2096 $this->shortname = $shortname;
2097 $this->displayname = $displayname;
2098 $this->set_options($enabled, $default);
2102 * Update the values of this setting options class
2104 * @param bool $enabled Can this option can be toggled.
2105 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2106 * @param bool $default The default checked state for this setting option.
2108 public function set_options($enabled, $default) {
2109 $this->enabled = $enabled;
2110 $this->default = $default;
2114 * Should this option appear in the interface and be toggleable?
2116 * @return bool Is it enabled?
2118 public function is_enabled() {
2119 return $this->enabled;
2123 * Should this option be checked by default?
2125 * @return bool Is it on by default?
2127 public function get_default() {
2128 return $this->default;
2132 * Return the short name for this flag. e.g. 'adv' or 'locked'
2134 * @return string
2136 public function get_shortname() {
2137 return $this->shortname;
2141 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2143 * @return string
2145 public function get_displayname() {
2146 return $this->displayname;
2150 * Save the submitted data for this flag - or set it to the default if $data is null.
2152 * @param admin_setting $setting - The admin setting for this flag
2153 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2154 * @return bool
2156 public function write_setting_flag(admin_setting $setting, $data) {
2157 $result = true;
2158 if ($this->is_enabled()) {
2159 if (!isset($data)) {
2160 $value = $this->get_default();
2161 } else {
2162 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2164 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2167 return $result;
2172 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2174 * @param admin_setting $setting - The admin setting for this flag
2175 * @return string - The html for the checkbox.
2177 public function output_setting_flag(admin_setting $setting) {
2178 global $OUTPUT;
2180 $value = $setting->get_setting_flag_value($this);
2182 $context = new stdClass();
2183 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2184 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2185 $context->value = 1;
2186 $context->checked = $value ? true : false;
2187 $context->label = $this->get_displayname();
2189 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2195 * No setting - just heading and text.
2197 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2199 class admin_setting_heading extends admin_setting {
2202 * not a setting, just text
2203 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2204 * @param string $heading heading
2205 * @param string $information text in box
2207 public function __construct($name, $heading, $information) {
2208 $this->nosave = true;
2209 parent::__construct($name, $heading, $information, '');
2213 * Always returns true
2214 * @return bool Always returns true
2216 public function get_setting() {
2217 return true;
2221 * Always returns true
2222 * @return bool Always returns true
2224 public function get_defaultsetting() {
2225 return true;
2229 * Never write settings
2230 * @return string Always returns an empty string
2232 public function write_setting($data) {
2233 // do not write any setting
2234 return '';
2238 * Returns an HTML string
2239 * @return string Returns an HTML string
2241 public function output_html($data, $query='') {
2242 global $OUTPUT;
2243 $context = new stdClass();
2244 $context->title = $this->visiblename;
2245 $context->description = $this->description;
2246 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2247 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2252 * No setting - just name and description in same row.
2254 * @copyright 2018 onwards Amaia Anabitarte
2255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2257 class admin_setting_description extends admin_setting {
2260 * Not a setting, just text
2262 * @param string $name
2263 * @param string $visiblename
2264 * @param string $description
2266 public function __construct($name, $visiblename, $description) {
2267 $this->nosave = true;
2268 parent::__construct($name, $visiblename, $description, '');
2272 * Always returns true
2274 * @return bool Always returns true
2276 public function get_setting() {
2277 return true;
2281 * Always returns true
2283 * @return bool Always returns true
2285 public function get_defaultsetting() {
2286 return true;
2290 * Never write settings
2292 * @param mixed $data Gets converted to str for comparison against yes value
2293 * @return string Always returns an empty string
2295 public function write_setting($data) {
2296 // Do not write any setting.
2297 return '';
2301 * Returns an HTML string
2303 * @param string $data
2304 * @param string $query
2305 * @return string Returns an HTML string
2307 public function output_html($data, $query='') {
2308 global $OUTPUT;
2310 $context = new stdClass();
2311 $context->title = $this->visiblename;
2312 $context->description = $this->description;
2314 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2321 * The most flexible setting, the user enters text.
2323 * This type of field should be used for config settings which are using
2324 * English words and are not localised (passwords, database name, list of values, ...).
2326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2328 class admin_setting_configtext extends admin_setting {
2330 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2331 public $paramtype;
2332 /** @var int default field size */
2333 public $size;
2336 * Config text constructor
2338 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2339 * @param string $visiblename localised
2340 * @param string $description long localised info
2341 * @param string $defaultsetting
2342 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2343 * @param int $size default field size
2345 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2346 $this->paramtype = $paramtype;
2347 if (!is_null($size)) {
2348 $this->size = $size;
2349 } else {
2350 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2352 parent::__construct($name, $visiblename, $description, $defaultsetting);
2356 * Get whether this should be displayed in LTR mode.
2358 * Try to guess from the PARAM type unless specifically set.
2360 public function get_force_ltr() {
2361 $forceltr = parent::get_force_ltr();
2362 if ($forceltr === null) {
2363 return !is_rtl_compatible($this->paramtype);
2365 return $forceltr;
2369 * Return the setting
2371 * @return mixed returns config if successful else null
2373 public function get_setting() {
2374 return $this->config_read($this->name);
2377 public function write_setting($data) {
2378 if ($this->paramtype === PARAM_INT and $data === '') {
2379 // do not complain if '' used instead of 0
2380 $data = 0;
2382 // $data is a string
2383 $validated = $this->validate($data);
2384 if ($validated !== true) {
2385 return $validated;
2387 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2391 * Validate data before storage
2392 * @param string data
2393 * @return mixed true if ok string if error found
2395 public function validate($data) {
2396 // allow paramtype to be a custom regex if it is the form of /pattern/
2397 if (preg_match('#^/.*/$#', $this->paramtype)) {
2398 if (preg_match($this->paramtype, $data)) {
2399 return true;
2400 } else {
2401 return get_string('validateerror', 'admin');
2404 } else if ($this->paramtype === PARAM_RAW) {
2405 return true;
2407 } else {
2408 $cleaned = clean_param($data, $this->paramtype);
2409 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2410 return true;
2411 } else {
2412 return get_string('validateerror', 'admin');
2418 * Return an XHTML string for the setting
2419 * @return string Returns an XHTML string
2421 public function output_html($data, $query='') {
2422 global $OUTPUT;
2424 $default = $this->get_defaultsetting();
2425 $context = (object) [
2426 'size' => $this->size,
2427 'id' => $this->get_id(),
2428 'name' => $this->get_full_name(),
2429 'value' => $data,
2430 'forceltr' => $this->get_force_ltr(),
2432 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2434 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2439 * Text input with a maximum length constraint.
2441 * @copyright 2015 onwards Ankit Agarwal
2442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2444 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2446 /** @var int maximum number of chars allowed. */
2447 protected $maxlength;
2450 * Config text constructor
2452 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2453 * or 'myplugin/mysetting' for ones in config_plugins.
2454 * @param string $visiblename localised
2455 * @param string $description long localised info
2456 * @param string $defaultsetting
2457 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2458 * @param int $size default field size
2459 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2461 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2462 $size=null, $maxlength = 0) {
2463 $this->maxlength = $maxlength;
2464 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2468 * Validate data before storage
2470 * @param string $data data
2471 * @return mixed true if ok string if error found
2473 public function validate($data) {
2474 $parentvalidation = parent::validate($data);
2475 if ($parentvalidation === true) {
2476 if ($this->maxlength > 0) {
2477 // Max length check.
2478 $length = core_text::strlen($data);
2479 if ($length > $this->maxlength) {
2480 return get_string('maximumchars', 'moodle', $this->maxlength);
2482 return true;
2483 } else {
2484 return true; // No max length check needed.
2486 } else {
2487 return $parentvalidation;
2493 * General text area without html editor.
2495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2497 class admin_setting_configtextarea extends admin_setting_configtext {
2498 private $rows;
2499 private $cols;
2502 * @param string $name
2503 * @param string $visiblename
2504 * @param string $description
2505 * @param mixed $defaultsetting string or array
2506 * @param mixed $paramtype
2507 * @param string $cols The number of columns to make the editor
2508 * @param string $rows The number of rows to make the editor
2510 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2511 $this->rows = $rows;
2512 $this->cols = $cols;
2513 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2517 * Returns an XHTML string for the editor
2519 * @param string $data
2520 * @param string $query
2521 * @return string XHTML string for the editor
2523 public function output_html($data, $query='') {
2524 global $OUTPUT;
2526 $default = $this->get_defaultsetting();
2527 $defaultinfo = $default;
2528 if (!is_null($default) and $default !== '') {
2529 $defaultinfo = "\n".$default;
2532 $context = (object) [
2533 'cols' => $this->cols,
2534 'rows' => $this->rows,
2535 'id' => $this->get_id(),
2536 'name' => $this->get_full_name(),
2537 'value' => $data,
2538 'forceltr' => $this->get_force_ltr(),
2540 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2542 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2547 * General text area with html editor.
2549 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2552 * @param string $name
2553 * @param string $visiblename
2554 * @param string $description
2555 * @param mixed $defaultsetting string or array
2556 * @param mixed $paramtype
2558 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2559 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2560 $this->set_force_ltr(false);
2561 editors_head_setup();
2565 * Returns an XHTML string for the editor
2567 * @param string $data
2568 * @param string $query
2569 * @return string XHTML string for the editor
2571 public function output_html($data, $query='') {
2572 $editor = editors_get_preferred_editor(FORMAT_HTML);
2573 $editor->set_text($data);
2574 $editor->use_editor($this->get_id(), array('noclean'=>true));
2575 return parent::output_html($data, $query);
2579 * Checks if data has empty html.
2581 * @param string $data
2582 * @return string Empty when no errors.
2584 public function write_setting($data) {
2585 if (trim(html_to_text($data)) === '') {
2586 $data = '';
2588 return parent::write_setting($data);
2594 * Password field, allows unmasking of password
2596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2598 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2601 * Constructor
2602 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2603 * @param string $visiblename localised
2604 * @param string $description long localised info
2605 * @param string $defaultsetting default password
2607 public function __construct($name, $visiblename, $description, $defaultsetting) {
2608 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2612 * Log config changes if necessary.
2613 * @param string $name
2614 * @param string $oldvalue
2615 * @param string $value
2617 protected function add_to_config_log($name, $oldvalue, $value) {
2618 if ($value !== '') {
2619 $value = '********';
2621 if ($oldvalue !== '' and $oldvalue !== null) {
2622 $oldvalue = '********';
2624 parent::add_to_config_log($name, $oldvalue, $value);
2628 * Returns HTML for the field.
2630 * @param string $data Value for the field
2631 * @param string $query Passed as final argument for format_admin_setting
2632 * @return string Rendered HTML
2634 public function output_html($data, $query='') {
2635 global $OUTPUT;
2636 $context = (object) [
2637 'id' => $this->get_id(),
2638 'name' => $this->get_full_name(),
2639 'size' => $this->size,
2640 'value' => $data,
2641 'forceltr' => $this->get_force_ltr(),
2643 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2644 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2649 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2652 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2654 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2657 * Constructor
2659 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2660 * @param string $visiblename localised
2661 * @param string $description long localised info
2662 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2664 public function __construct($name, $visiblename, $description, $defaultsetting) {
2665 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2666 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2671 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2672 * Note: Only advanced makes sense right now - locked does not.
2674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2676 class admin_setting_configempty extends admin_setting_configtext {
2679 * @param string $name
2680 * @param string $visiblename
2681 * @param string $description
2683 public function __construct($name, $visiblename, $description) {
2684 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2688 * Returns an XHTML string for the hidden field
2690 * @param string $data
2691 * @param string $query
2692 * @return string XHTML string for the editor
2694 public function output_html($data, $query='') {
2695 global $OUTPUT;
2697 $context = (object) [
2698 'id' => $this->get_id(),
2699 'name' => $this->get_full_name()
2701 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2703 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2709 * Path to directory
2711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2713 class admin_setting_configfile extends admin_setting_configtext {
2715 * Constructor
2716 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2717 * @param string $visiblename localised
2718 * @param string $description long localised info
2719 * @param string $defaultdirectory default directory location
2721 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2722 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2726 * Returns XHTML for the field
2728 * Returns XHTML for the field and also checks whether the file
2729 * specified in $data exists using file_exists()
2731 * @param string $data File name and path to use in value attr
2732 * @param string $query
2733 * @return string XHTML field
2735 public function output_html($data, $query='') {
2736 global $CFG, $OUTPUT;
2738 $default = $this->get_defaultsetting();
2739 $context = (object) [
2740 'id' => $this->get_id(),
2741 'name' => $this->get_full_name(),
2742 'size' => $this->size,
2743 'value' => $data,
2744 'showvalidity' => !empty($data),
2745 'valid' => $data && file_exists($data),
2746 'readonly' => !empty($CFG->preventexecpath),
2747 'forceltr' => $this->get_force_ltr(),
2750 if ($context->readonly) {
2751 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2754 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2756 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2760 * Checks if execpatch has been disabled in config.php
2762 public function write_setting($data) {
2763 global $CFG;
2764 if (!empty($CFG->preventexecpath)) {
2765 if ($this->get_setting() === null) {
2766 // Use default during installation.
2767 $data = $this->get_defaultsetting();
2768 if ($data === null) {
2769 $data = '';
2771 } else {
2772 return '';
2775 return parent::write_setting($data);
2782 * Path to executable file
2784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2786 class admin_setting_configexecutable extends admin_setting_configfile {
2789 * Returns an XHTML field
2791 * @param string $data This is the value for the field
2792 * @param string $query
2793 * @return string XHTML field
2795 public function output_html($data, $query='') {
2796 global $CFG, $OUTPUT;
2797 $default = $this->get_defaultsetting();
2798 require_once("$CFG->libdir/filelib.php");
2800 $context = (object) [
2801 'id' => $this->get_id(),
2802 'name' => $this->get_full_name(),
2803 'size' => $this->size,
2804 'value' => $data,
2805 'showvalidity' => !empty($data),
2806 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2807 'readonly' => !empty($CFG->preventexecpath),
2808 'forceltr' => $this->get_force_ltr()
2811 if (!empty($CFG->preventexecpath)) {
2812 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2815 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2817 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2823 * Path to directory
2825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2827 class admin_setting_configdirectory extends admin_setting_configfile {
2830 * Returns an XHTML field
2832 * @param string $data This is the value for the field
2833 * @param string $query
2834 * @return string XHTML
2836 public function output_html($data, $query='') {
2837 global $CFG, $OUTPUT;
2838 $default = $this->get_defaultsetting();
2840 $context = (object) [
2841 'id' => $this->get_id(),
2842 'name' => $this->get_full_name(),
2843 'size' => $this->size,
2844 'value' => $data,
2845 'showvalidity' => !empty($data),
2846 'valid' => $data && file_exists($data) && is_dir($data),
2847 'readonly' => !empty($CFG->preventexecpath),
2848 'forceltr' => $this->get_force_ltr()
2851 if (!empty($CFG->preventexecpath)) {
2852 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2855 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2857 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2863 * Checkbox
2865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2867 class admin_setting_configcheckbox extends admin_setting {
2868 /** @var string Value used when checked */
2869 public $yes;
2870 /** @var string Value used when not checked */
2871 public $no;
2874 * Constructor
2875 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2876 * @param string $visiblename localised
2877 * @param string $description long localised info
2878 * @param string $defaultsetting
2879 * @param string $yes value used when checked
2880 * @param string $no value used when not checked
2882 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2883 parent::__construct($name, $visiblename, $description, $defaultsetting);
2884 $this->yes = (string)$yes;
2885 $this->no = (string)$no;
2889 * Retrieves the current setting using the objects name
2891 * @return string
2893 public function get_setting() {
2894 return $this->config_read($this->name);
2898 * Sets the value for the setting
2900 * Sets the value for the setting to either the yes or no values
2901 * of the object by comparing $data to yes
2903 * @param mixed $data Gets converted to str for comparison against yes value
2904 * @return string empty string or error
2906 public function write_setting($data) {
2907 if ((string)$data === $this->yes) { // convert to strings before comparison
2908 $data = $this->yes;
2909 } else {
2910 $data = $this->no;
2912 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2916 * Returns an XHTML checkbox field
2918 * @param string $data If $data matches yes then checkbox is checked
2919 * @param string $query
2920 * @return string XHTML field
2922 public function output_html($data, $query='') {
2923 global $OUTPUT;
2925 $context = (object) [
2926 'id' => $this->get_id(),
2927 'name' => $this->get_full_name(),
2928 'no' => $this->no,
2929 'value' => $this->yes,
2930 'checked' => (string) $data === $this->yes,
2933 $default = $this->get_defaultsetting();
2934 if (!is_null($default)) {
2935 if ((string)$default === $this->yes) {
2936 $defaultinfo = get_string('checkboxyes', 'admin');
2937 } else {
2938 $defaultinfo = get_string('checkboxno', 'admin');
2940 } else {
2941 $defaultinfo = NULL;
2944 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2946 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2952 * Multiple checkboxes, each represents different value, stored in csv format
2954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2956 class admin_setting_configmulticheckbox extends admin_setting {
2957 /** @var array Array of choices value=>label */
2958 public $choices;
2961 * Constructor: uses parent::__construct
2963 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2964 * @param string $visiblename localised
2965 * @param string $description long localised info
2966 * @param array $defaultsetting array of selected
2967 * @param array $choices array of $value=>$label for each checkbox
2969 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2970 $this->choices = $choices;
2971 parent::__construct($name, $visiblename, $description, $defaultsetting);
2975 * This public function may be used in ancestors for lazy loading of choices
2977 * @todo Check if this function is still required content commented out only returns true
2978 * @return bool true if loaded, false if error
2980 public function load_choices() {
2982 if (is_array($this->choices)) {
2983 return true;
2985 .... load choices here
2987 return true;
2991 * Is setting related to query text - used when searching
2993 * @param string $query
2994 * @return bool true on related, false on not or failure
2996 public function is_related($query) {
2997 if (!$this->load_choices() or empty($this->choices)) {
2998 return false;
3000 if (parent::is_related($query)) {
3001 return true;
3004 foreach ($this->choices as $desc) {
3005 if (strpos(core_text::strtolower($desc), $query) !== false) {
3006 return true;
3009 return false;
3013 * Returns the current setting if it is set
3015 * @return mixed null if null, else an array
3017 public function get_setting() {
3018 $result = $this->config_read($this->name);
3020 if (is_null($result)) {
3021 return NULL;
3023 if ($result === '') {
3024 return array();
3026 $enabled = explode(',', $result);
3027 $setting = array();
3028 foreach ($enabled as $option) {
3029 $setting[$option] = 1;
3031 return $setting;
3035 * Saves the setting(s) provided in $data
3037 * @param array $data An array of data, if not array returns empty str
3038 * @return mixed empty string on useless data or bool true=success, false=failed
3040 public function write_setting($data) {
3041 if (!is_array($data)) {
3042 return ''; // ignore it
3044 if (!$this->load_choices() or empty($this->choices)) {
3045 return '';
3047 unset($data['xxxxx']);
3048 $result = array();
3049 foreach ($data as $key => $value) {
3050 if ($value and array_key_exists($key, $this->choices)) {
3051 $result[] = $key;
3054 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3058 * Returns XHTML field(s) as required by choices
3060 * Relies on data being an array should data ever be another valid vartype with
3061 * acceptable value this may cause a warning/error
3062 * if (!is_array($data)) would fix the problem
3064 * @todo Add vartype handling to ensure $data is an array
3066 * @param array $data An array of checked values
3067 * @param string $query
3068 * @return string XHTML field
3070 public function output_html($data, $query='') {
3071 global $OUTPUT;
3073 if (!$this->load_choices() or empty($this->choices)) {
3074 return '';
3077 $default = $this->get_defaultsetting();
3078 if (is_null($default)) {
3079 $default = array();
3081 if (is_null($data)) {
3082 $data = array();
3085 $context = (object) [
3086 'id' => $this->get_id(),
3087 'name' => $this->get_full_name(),
3090 $options = array();
3091 $defaults = array();
3092 foreach ($this->choices as $key => $description) {
3093 if (!empty($default[$key])) {
3094 $defaults[] = $description;
3097 $options[] = [
3098 'key' => $key,
3099 'checked' => !empty($data[$key]),
3100 'label' => highlightfast($query, $description)
3104 if (is_null($default)) {
3105 $defaultinfo = null;
3106 } else if (!empty($defaults)) {
3107 $defaultinfo = implode(', ', $defaults);
3108 } else {
3109 $defaultinfo = get_string('none');
3112 $context->options = $options;
3113 $context->hasoptions = !empty($options);
3115 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3117 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3124 * Multiple checkboxes 2, value stored as string 00101011
3126 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3128 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3131 * Returns the setting if set
3133 * @return mixed null if not set, else an array of set settings
3135 public function get_setting() {
3136 $result = $this->config_read($this->name);
3137 if (is_null($result)) {
3138 return NULL;
3140 if (!$this->load_choices()) {
3141 return NULL;
3143 $result = str_pad($result, count($this->choices), '0');
3144 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3145 $setting = array();
3146 foreach ($this->choices as $key=>$unused) {
3147 $value = array_shift($result);
3148 if ($value) {
3149 $setting[$key] = 1;
3152 return $setting;
3156 * Save setting(s) provided in $data param
3158 * @param array $data An array of settings to save
3159 * @return mixed empty string for bad data or bool true=>success, false=>error
3161 public function write_setting($data) {
3162 if (!is_array($data)) {
3163 return ''; // ignore it
3165 if (!$this->load_choices() or empty($this->choices)) {
3166 return '';
3168 $result = '';
3169 foreach ($this->choices as $key=>$unused) {
3170 if (!empty($data[$key])) {
3171 $result .= '1';
3172 } else {
3173 $result .= '0';
3176 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3182 * Select one value from list
3184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3186 class admin_setting_configselect extends admin_setting {
3187 /** @var array Array of choices value=>label */
3188 public $choices;
3189 /** @var array Array of choices grouped using optgroups */
3190 public $optgroups;
3193 * Constructor
3194 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3195 * @param string $visiblename localised
3196 * @param string $description long localised info
3197 * @param string|int $defaultsetting
3198 * @param array $choices array of $value=>$label for each selection
3200 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3201 // Look for optgroup and single options.
3202 if (is_array($choices)) {
3203 $this->choices = [];
3204 foreach ($choices as $key => $val) {
3205 if (is_array($val)) {
3206 $this->optgroups[$key] = $val;
3207 $this->choices = array_merge($this->choices, $val);
3208 } else {
3209 $this->choices[$key] = $val;
3214 parent::__construct($name, $visiblename, $description, $defaultsetting);
3218 * This function may be used in ancestors for lazy loading of choices
3220 * Override this method if loading of choices is expensive, such
3221 * as when it requires multiple db requests.
3223 * @return bool true if loaded, false if error
3225 public function load_choices() {
3227 if (is_array($this->choices)) {
3228 return true;
3230 .... load choices here
3232 return true;
3236 * Check if this is $query is related to a choice
3238 * @param string $query
3239 * @return bool true if related, false if not
3241 public function is_related($query) {
3242 if (parent::is_related($query)) {
3243 return true;
3245 if (!$this->load_choices()) {
3246 return false;
3248 foreach ($this->choices as $key=>$value) {
3249 if (strpos(core_text::strtolower($key), $query) !== false) {
3250 return true;
3252 if (strpos(core_text::strtolower($value), $query) !== false) {
3253 return true;
3256 return false;
3260 * Return the setting
3262 * @return mixed returns config if successful else null
3264 public function get_setting() {
3265 return $this->config_read($this->name);
3269 * Save a setting
3271 * @param string $data
3272 * @return string empty of error string
3274 public function write_setting($data) {
3275 if (!$this->load_choices() or empty($this->choices)) {
3276 return '';
3278 if (!array_key_exists($data, $this->choices)) {
3279 return ''; // ignore it
3282 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3286 * Returns XHTML select field
3288 * Ensure the options are loaded, and generate the XHTML for the select
3289 * element and any warning message. Separating this out from output_html
3290 * makes it easier to subclass this class.
3292 * @param string $data the option to show as selected.
3293 * @param string $current the currently selected option in the database, null if none.
3294 * @param string $default the default selected option.
3295 * @return array the HTML for the select element, and a warning message.
3296 * @deprecated since Moodle 3.2
3298 public function output_select_html($data, $current, $default, $extraname = '') {
3299 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3303 * Returns XHTML select field and wrapping div(s)
3305 * @see output_select_html()
3307 * @param string $data the option to show as selected
3308 * @param string $query
3309 * @return string XHTML field and wrapping div
3311 public function output_html($data, $query='') {
3312 global $OUTPUT;
3314 $default = $this->get_defaultsetting();
3315 $current = $this->get_setting();
3317 if (!$this->load_choices() || empty($this->choices)) {
3318 return '';
3321 $context = (object) [
3322 'id' => $this->get_id(),
3323 'name' => $this->get_full_name(),
3326 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3327 $defaultinfo = $this->choices[$default];
3328 } else {
3329 $defaultinfo = NULL;
3332 // Warnings.
3333 $warning = '';
3334 if ($current === null) {
3335 // First run.
3336 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3337 // No warning.
3338 } else if (!array_key_exists($current, $this->choices)) {
3339 $warning = get_string('warningcurrentsetting', 'admin', $current);
3340 if (!is_null($default) && $data == $current) {
3341 $data = $default; // Use default instead of first value when showing the form.
3345 $options = [];
3346 $template = 'core_admin/setting_configselect';
3348 if (!empty($this->optgroups)) {
3349 $optgroups = [];
3350 foreach ($this->optgroups as $label => $choices) {
3351 $optgroup = array('label' => $label, 'options' => []);
3352 foreach ($choices as $value => $name) {
3353 $optgroup['options'][] = [
3354 'value' => $value,
3355 'name' => $name,
3356 'selected' => (string) $value == $data
3358 unset($this->choices[$value]);
3360 $optgroups[] = $optgroup;
3362 $context->options = $options;
3363 $context->optgroups = $optgroups;
3364 $template = 'core_admin/setting_configselect_optgroup';
3367 foreach ($this->choices as $value => $name) {
3368 $options[] = [
3369 'value' => $value,
3370 'name' => $name,
3371 'selected' => (string) $value == $data
3374 $context->options = $options;
3376 $element = $OUTPUT->render_from_template($template, $context);
3378 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3384 * Select multiple items from list
3386 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3388 class admin_setting_configmultiselect extends admin_setting_configselect {
3390 * Constructor
3391 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3392 * @param string $visiblename localised
3393 * @param string $description long localised info
3394 * @param array $defaultsetting array of selected items
3395 * @param array $choices array of $value=>$label for each list item
3397 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3398 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3402 * Returns the select setting(s)
3404 * @return mixed null or array. Null if no settings else array of setting(s)
3406 public function get_setting() {
3407 $result = $this->config_read($this->name);
3408 if (is_null($result)) {
3409 return NULL;
3411 if ($result === '') {
3412 return array();
3414 return explode(',', $result);
3418 * Saves setting(s) provided through $data
3420 * Potential bug in the works should anyone call with this function
3421 * using a vartype that is not an array
3423 * @param array $data
3425 public function write_setting($data) {
3426 if (!is_array($data)) {
3427 return ''; //ignore it
3429 if (!$this->load_choices() or empty($this->choices)) {
3430 return '';
3433 unset($data['xxxxx']);
3435 $save = array();
3436 foreach ($data as $value) {
3437 if (!array_key_exists($value, $this->choices)) {
3438 continue; // ignore it
3440 $save[] = $value;
3443 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3447 * Is setting related to query text - used when searching
3449 * @param string $query
3450 * @return bool true if related, false if not
3452 public function is_related($query) {
3453 if (!$this->load_choices() or empty($this->choices)) {
3454 return false;
3456 if (parent::is_related($query)) {
3457 return true;
3460 foreach ($this->choices as $desc) {
3461 if (strpos(core_text::strtolower($desc), $query) !== false) {
3462 return true;
3465 return false;
3469 * Returns XHTML multi-select field
3471 * @todo Add vartype handling to ensure $data is an array
3472 * @param array $data Array of values to select by default
3473 * @param string $query
3474 * @return string XHTML multi-select field
3476 public function output_html($data, $query='') {
3477 global $OUTPUT;
3479 if (!$this->load_choices() or empty($this->choices)) {
3480 return '';
3483 $default = $this->get_defaultsetting();
3484 if (is_null($default)) {
3485 $default = array();
3487 if (is_null($data)) {
3488 $data = array();
3491 $context = (object) [
3492 'id' => $this->get_id(),
3493 'name' => $this->get_full_name(),
3494 'size' => min(10, count($this->choices))
3497 $defaults = [];
3498 $options = [];
3499 $template = 'core_admin/setting_configmultiselect';
3501 if (!empty($this->optgroups)) {
3502 $optgroups = [];
3503 foreach ($this->optgroups as $label => $choices) {
3504 $optgroup = array('label' => $label, 'options' => []);
3505 foreach ($choices as $value => $name) {
3506 if (in_array($value, $default)) {
3507 $defaults[] = $name;
3509 $optgroup['options'][] = [
3510 'value' => $value,
3511 'name' => $name,
3512 'selected' => in_array($value, $data)
3514 unset($this->choices[$value]);
3516 $optgroups[] = $optgroup;
3518 $context->optgroups = $optgroups;
3519 $template = 'core_admin/setting_configmultiselect_optgroup';
3522 foreach ($this->choices as $value => $name) {
3523 if (in_array($value, $default)) {
3524 $defaults[] = $name;
3526 $options[] = [
3527 'value' => $value,
3528 'name' => $name,
3529 'selected' => in_array($value, $data)
3532 $context->options = $options;
3534 if (is_null($default)) {
3535 $defaultinfo = NULL;
3536 } if (!empty($defaults)) {
3537 $defaultinfo = implode(', ', $defaults);
3538 } else {
3539 $defaultinfo = get_string('none');
3542 $element = $OUTPUT->render_from_template($template, $context);
3544 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3549 * Time selector
3551 * This is a liiitle bit messy. we're using two selects, but we're returning
3552 * them as an array named after $name (so we only use $name2 internally for the setting)
3554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3556 class admin_setting_configtime extends admin_setting {
3557 /** @var string Used for setting second select (minutes) */
3558 public $name2;
3561 * Constructor
3562 * @param string $hoursname setting for hours
3563 * @param string $minutesname setting for hours
3564 * @param string $visiblename localised
3565 * @param string $description long localised info
3566 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3568 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3569 $this->name2 = $minutesname;
3570 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3574 * Get the selected time
3576 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3578 public function get_setting() {
3579 $result1 = $this->config_read($this->name);
3580 $result2 = $this->config_read($this->name2);
3581 if (is_null($result1) or is_null($result2)) {
3582 return NULL;
3585 return array('h' => $result1, 'm' => $result2);
3589 * Store the time (hours and minutes)
3591 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3592 * @return bool true if success, false if not
3594 public function write_setting($data) {
3595 if (!is_array($data)) {
3596 return '';
3599 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3600 return ($result ? '' : get_string('errorsetting', 'admin'));
3604 * Returns XHTML time select fields
3606 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3607 * @param string $query
3608 * @return string XHTML time select fields and wrapping div(s)
3610 public function output_html($data, $query='') {
3611 global $OUTPUT;
3613 $default = $this->get_defaultsetting();
3614 if (is_array($default)) {
3615 $defaultinfo = $default['h'].':'.$default['m'];
3616 } else {
3617 $defaultinfo = NULL;
3620 $context = (object) [
3621 'id' => $this->get_id(),
3622 'name' => $this->get_full_name(),
3623 'hours' => array_map(function($i) use ($data) {
3624 return [
3625 'value' => $i,
3626 'name' => $i,
3627 'selected' => $i == $data['h']
3629 }, range(0, 23)),
3630 'minutes' => array_map(function($i) use ($data) {
3631 return [
3632 'value' => $i,
3633 'name' => $i,
3634 'selected' => $i == $data['m']
3636 }, range(0, 59, 5))
3639 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3641 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3642 $this->get_id() . 'h', '', $defaultinfo, $query);
3649 * Seconds duration setting.
3651 * @copyright 2012 Petr Skoda (http://skodak.org)
3652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3654 class admin_setting_configduration extends admin_setting {
3656 /** @var int default duration unit */
3657 protected $defaultunit;
3660 * Constructor
3661 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3662 * or 'myplugin/mysetting' for ones in config_plugins.
3663 * @param string $visiblename localised name
3664 * @param string $description localised long description
3665 * @param mixed $defaultsetting string or array depending on implementation
3666 * @param int $defaultunit - day, week, etc. (in seconds)
3668 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3669 if (is_number($defaultsetting)) {
3670 $defaultsetting = self::parse_seconds($defaultsetting);
3672 $units = self::get_units();
3673 if (isset($units[$defaultunit])) {
3674 $this->defaultunit = $defaultunit;
3675 } else {
3676 $this->defaultunit = 86400;
3678 parent::__construct($name, $visiblename, $description, $defaultsetting);
3682 * Returns selectable units.
3683 * @static
3684 * @return array
3686 protected static function get_units() {
3687 return array(
3688 604800 => get_string('weeks'),
3689 86400 => get_string('days'),
3690 3600 => get_string('hours'),
3691 60 => get_string('minutes'),
3692 1 => get_string('seconds'),
3697 * Converts seconds to some more user friendly string.
3698 * @static
3699 * @param int $seconds
3700 * @return string
3702 protected static function get_duration_text($seconds) {
3703 if (empty($seconds)) {
3704 return get_string('none');
3706 $data = self::parse_seconds($seconds);
3707 switch ($data['u']) {
3708 case (60*60*24*7):
3709 return get_string('numweeks', '', $data['v']);
3710 case (60*60*24):
3711 return get_string('numdays', '', $data['v']);
3712 case (60*60):
3713 return get_string('numhours', '', $data['v']);
3714 case (60):
3715 return get_string('numminutes', '', $data['v']);
3716 default:
3717 return get_string('numseconds', '', $data['v']*$data['u']);
3722 * Finds suitable units for given duration.
3723 * @static
3724 * @param int $seconds
3725 * @return array
3727 protected static function parse_seconds($seconds) {
3728 foreach (self::get_units() as $unit => $unused) {
3729 if ($seconds % $unit === 0) {
3730 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3733 return array('v'=>(int)$seconds, 'u'=>1);
3737 * Get the selected duration as array.
3739 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3741 public function get_setting() {
3742 $seconds = $this->config_read($this->name);
3743 if (is_null($seconds)) {
3744 return null;
3747 return self::parse_seconds($seconds);
3751 * Store the duration as seconds.
3753 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3754 * @return bool true if success, false if not
3756 public function write_setting($data) {
3757 if (!is_array($data)) {
3758 return '';
3761 $seconds = (int)($data['v']*$data['u']);
3762 if ($seconds < 0) {
3763 return get_string('errorsetting', 'admin');
3766 $result = $this->config_write($this->name, $seconds);
3767 return ($result ? '' : get_string('errorsetting', 'admin'));
3771 * Returns duration text+select fields.
3773 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3774 * @param string $query
3775 * @return string duration text+select fields and wrapping div(s)
3777 public function output_html($data, $query='') {
3778 global $OUTPUT;
3780 $default = $this->get_defaultsetting();
3781 if (is_number($default)) {
3782 $defaultinfo = self::get_duration_text($default);
3783 } else if (is_array($default)) {
3784 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3785 } else {
3786 $defaultinfo = null;
3789 $inputid = $this->get_id() . 'v';
3790 $units = self::get_units();
3791 $defaultunit = $this->defaultunit;
3793 $context = (object) [
3794 'id' => $this->get_id(),
3795 'name' => $this->get_full_name(),
3796 'value' => $data['v'],
3797 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3798 return [
3799 'value' => $unit,
3800 'name' => $units[$unit],
3801 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3803 }, array_keys($units))
3806 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3808 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3814 * Seconds duration setting with an advanced checkbox, that controls a additional
3815 * $name.'_adv' setting.
3817 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3818 * @copyright 2014 The Open University
3820 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3822 * Constructor
3823 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3824 * or 'myplugin/mysetting' for ones in config_plugins.
3825 * @param string $visiblename localised name
3826 * @param string $description localised long description
3827 * @param array $defaultsetting array of int value, and bool whether it is
3828 * is advanced by default.
3829 * @param int $defaultunit - day, week, etc. (in seconds)
3831 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3832 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3833 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3839 * Used to validate a textarea used for ip addresses
3841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3842 * @copyright 2011 Petr Skoda (http://skodak.org)
3844 class admin_setting_configiplist extends admin_setting_configtextarea {
3847 * Validate the contents of the textarea as IP addresses
3849 * Used to validate a new line separated list of IP addresses collected from
3850 * a textarea control
3852 * @param string $data A list of IP Addresses separated by new lines
3853 * @return mixed bool true for success or string:error on failure
3855 public function validate($data) {
3856 if(!empty($data)) {
3857 $lines = explode("\n", $data);
3858 } else {
3859 return true;
3861 $result = true;
3862 $badips = array();
3863 foreach ($lines as $line) {
3864 $tokens = explode('#', $line);
3865 $ip = trim($tokens[0]);
3866 if (empty($ip)) {
3867 continue;
3869 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3870 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3871 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3872 } else {
3873 $result = false;
3874 $badips[] = $ip;
3877 if($result) {
3878 return true;
3879 } else {
3880 return get_string('validateiperror', 'admin', join(', ', $badips));
3886 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3888 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3889 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3891 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3894 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3895 * Used to validate a new line separated list of entries collected from a textarea control.
3897 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3898 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3899 * via the get_setting() method, which has been overriden.
3901 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3902 * @return mixed bool true for success or string:error on failure
3904 public function validate($data) {
3905 if (empty($data)) {
3906 return true;
3908 $entries = explode("\n", $data);
3909 $badentries = [];
3911 foreach ($entries as $key => $entry) {
3912 $entry = trim($entry);
3913 if (empty($entry)) {
3914 return get_string('validateemptylineerror', 'admin');
3917 // Validate each string entry against the supported formats.
3918 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3919 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3920 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3921 continue;
3924 // Otherwise, the entry is invalid.
3925 $badentries[] = $entry;
3928 if ($badentries) {
3929 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3931 return true;
3935 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3937 * @param string $data the setting data, as sent from the web form.
3938 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3940 protected function ace_encode($data) {
3941 if (empty($data)) {
3942 return $data;
3944 $entries = explode("\n", $data);
3945 foreach ($entries as $key => $entry) {
3946 $entry = trim($entry);
3947 // This regex matches any string that has non-ascii character.
3948 if (preg_match('/[^\x00-\x7f]/', $entry)) {
3949 // If we can convert the unicode string to an idn, do so.
3950 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3951 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3952 $entries[$key] = $val ? $val : $entry;
3955 return implode("\n", $entries);
3959 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
3961 * @param string $data the setting data, as found in the database.
3962 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
3964 protected function ace_decode($data) {
3965 $entries = explode("\n", $data);
3966 foreach ($entries as $key => $entry) {
3967 $entry = trim($entry);
3968 if (strpos($entry, 'xn--') !== false) {
3969 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3972 return implode("\n", $entries);
3976 * Override, providing utf8-decoding for ascii-encoded IDN strings.
3978 * @return mixed returns punycode-converted setting string if successful, else null.
3980 public function get_setting() {
3981 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
3982 $data = $this->config_read($this->name);
3983 if (function_exists('idn_to_utf8') && !is_null($data)) {
3984 $data = $this->ace_decode($data);
3986 return $data;
3990 * Override, providing ascii-encoding for utf8 (native) IDN strings.
3992 * @param string $data
3993 * @return string
3995 public function write_setting($data) {
3996 if ($this->paramtype === PARAM_INT and $data === '') {
3997 // Do not complain if '' used instead of 0.
3998 $data = 0;
4001 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4002 if (function_exists('idn_to_ascii')) {
4003 $data = $this->ace_encode($data);
4006 $validated = $this->validate($data);
4007 if ($validated !== true) {
4008 return $validated;
4010 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4015 * Used to validate a textarea used for port numbers.
4017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4018 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4020 class admin_setting_configportlist extends admin_setting_configtextarea {
4023 * Validate the contents of the textarea as port numbers.
4024 * Used to validate a new line separated list of ports collected from a textarea control.
4026 * @param string $data A list of ports separated by new lines
4027 * @return mixed bool true for success or string:error on failure
4029 public function validate($data) {
4030 if (empty($data)) {
4031 return true;
4033 $ports = explode("\n", $data);
4034 $badentries = [];
4035 foreach ($ports as $port) {
4036 $port = trim($port);
4037 if (empty($port)) {
4038 return get_string('validateemptylineerror', 'admin');
4041 // Is the string a valid integer number?
4042 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4043 $badentries[] = $port;
4046 if ($badentries) {
4047 return get_string('validateerrorlist', 'admin', $badentries);
4049 return true;
4055 * An admin setting for selecting one or more users who have a capability
4056 * in the system context
4058 * An admin setting for selecting one or more users, who have a particular capability
4059 * in the system context. Warning, make sure the list will never be too long. There is
4060 * no paging or searching of this list.
4062 * To correctly get a list of users from this config setting, you need to call the
4063 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4065 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4067 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4068 /** @var string The capabilities name */
4069 protected $capability;
4070 /** @var int include admin users too */
4071 protected $includeadmins;
4074 * Constructor.
4076 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4077 * @param string $visiblename localised name
4078 * @param string $description localised long description
4079 * @param array $defaultsetting array of usernames
4080 * @param string $capability string capability name.
4081 * @param bool $includeadmins include administrators
4083 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4084 $this->capability = $capability;
4085 $this->includeadmins = $includeadmins;
4086 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4090 * Load all of the uses who have the capability into choice array
4092 * @return bool Always returns true
4094 function load_choices() {
4095 if (is_array($this->choices)) {
4096 return true;
4098 list($sort, $sortparams) = users_order_by_sql('u');
4099 if (!empty($sortparams)) {
4100 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4101 'This is unexpected, and a problem because there is no way to pass these ' .
4102 'parameters to get_users_by_capability. See MDL-34657.');
4104 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
4105 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4106 $this->choices = array(
4107 '$@NONE@$' => get_string('nobody'),
4108 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4110 if ($this->includeadmins) {
4111 $admins = get_admins();
4112 foreach ($admins as $user) {
4113 $this->choices[$user->id] = fullname($user);
4116 if (is_array($users)) {
4117 foreach ($users as $user) {
4118 $this->choices[$user->id] = fullname($user);
4121 return true;
4125 * Returns the default setting for class
4127 * @return mixed Array, or string. Empty string if no default
4129 public function get_defaultsetting() {
4130 $this->load_choices();
4131 $defaultsetting = parent::get_defaultsetting();
4132 if (empty($defaultsetting)) {
4133 return array('$@NONE@$');
4134 } else if (array_key_exists($defaultsetting, $this->choices)) {
4135 return $defaultsetting;
4136 } else {
4137 return '';
4142 * Returns the current setting
4144 * @return mixed array or string
4146 public function get_setting() {
4147 $result = parent::get_setting();
4148 if ($result === null) {
4149 // this is necessary for settings upgrade
4150 return null;
4152 if (empty($result)) {
4153 $result = array('$@NONE@$');
4155 return $result;
4159 * Save the chosen setting provided as $data
4161 * @param array $data
4162 * @return mixed string or array
4164 public function write_setting($data) {
4165 // If all is selected, remove any explicit options.
4166 if (in_array('$@ALL@$', $data)) {
4167 $data = array('$@ALL@$');
4169 // None never needs to be written to the DB.
4170 if (in_array('$@NONE@$', $data)) {
4171 unset($data[array_search('$@NONE@$', $data)]);
4173 return parent::write_setting($data);
4179 * Special checkbox for calendar - resets SESSION vars.
4181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4183 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4185 * Calls the parent::__construct with default values
4187 * name => calendar_adminseesall
4188 * visiblename => get_string('adminseesall', 'admin')
4189 * description => get_string('helpadminseesall', 'admin')
4190 * defaultsetting => 0
4192 public function __construct() {
4193 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4194 get_string('helpadminseesall', 'admin'), '0');
4198 * Stores the setting passed in $data
4200 * @param mixed gets converted to string for comparison
4201 * @return string empty string or error message
4203 public function write_setting($data) {
4204 global $SESSION;
4205 return parent::write_setting($data);
4210 * Special select for settings that are altered in setup.php and can not be altered on the fly
4212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4214 class admin_setting_special_selectsetup extends admin_setting_configselect {
4216 * Reads the setting directly from the database
4218 * @return mixed
4220 public function get_setting() {
4221 // read directly from db!
4222 return get_config(NULL, $this->name);
4226 * Save the setting passed in $data
4228 * @param string $data The setting to save
4229 * @return string empty or error message
4231 public function write_setting($data) {
4232 global $CFG;
4233 // do not change active CFG setting!
4234 $current = $CFG->{$this->name};
4235 $result = parent::write_setting($data);
4236 $CFG->{$this->name} = $current;
4237 return $result;
4243 * Special select for frontpage - stores data in course table
4245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4247 class admin_setting_sitesetselect extends admin_setting_configselect {
4249 * Returns the site name for the selected site
4251 * @see get_site()
4252 * @return string The site name of the selected site
4254 public function get_setting() {
4255 $site = course_get_format(get_site())->get_course();
4256 return $site->{$this->name};
4260 * Updates the database and save the setting
4262 * @param string data
4263 * @return string empty or error message
4265 public function write_setting($data) {
4266 global $DB, $SITE, $COURSE;
4267 if (!in_array($data, array_keys($this->choices))) {
4268 return get_string('errorsetting', 'admin');
4270 $record = new stdClass();
4271 $record->id = SITEID;
4272 $temp = $this->name;
4273 $record->$temp = $data;
4274 $record->timemodified = time();
4276 course_get_format($SITE)->update_course_format_options($record);
4277 $DB->update_record('course', $record);
4279 // Reset caches.
4280 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4281 if ($SITE->id == $COURSE->id) {
4282 $COURSE = $SITE;
4284 format_base::reset_course_cache($SITE->id);
4286 return '';
4293 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4294 * block to hidden.
4296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4298 class admin_setting_bloglevel extends admin_setting_configselect {
4300 * Updates the database and save the setting
4302 * @param string data
4303 * @return string empty or error message
4305 public function write_setting($data) {
4306 global $DB, $CFG;
4307 if ($data == 0) {
4308 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4309 foreach ($blogblocks as $block) {
4310 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4312 } else {
4313 // reenable all blocks only when switching from disabled blogs
4314 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4315 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4316 foreach ($blogblocks as $block) {
4317 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4321 return parent::write_setting($data);
4327 * Special select - lists on the frontpage - hacky
4329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4331 class admin_setting_courselist_frontpage extends admin_setting {
4332 /** @var array Array of choices value=>label */
4333 public $choices;
4336 * Construct override, requires one param
4338 * @param bool $loggedin Is the user logged in
4340 public function __construct($loggedin) {
4341 global $CFG;
4342 require_once($CFG->dirroot.'/course/lib.php');
4343 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4344 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4345 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4346 $defaults = array(FRONTPAGEALLCOURSELIST);
4347 parent::__construct($name, $visiblename, $description, $defaults);
4351 * Loads the choices available
4353 * @return bool always returns true
4355 public function load_choices() {
4356 if (is_array($this->choices)) {
4357 return true;
4359 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4360 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4361 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4362 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4363 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4364 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4365 'none' => get_string('none'));
4366 if ($this->name === 'frontpage') {
4367 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4369 return true;
4373 * Returns the selected settings
4375 * @param mixed array or setting or null
4377 public function get_setting() {
4378 $result = $this->config_read($this->name);
4379 if (is_null($result)) {
4380 return NULL;
4382 if ($result === '') {
4383 return array();
4385 return explode(',', $result);
4389 * Save the selected options
4391 * @param array $data
4392 * @return mixed empty string (data is not an array) or bool true=success false=failure
4394 public function write_setting($data) {
4395 if (!is_array($data)) {
4396 return '';
4398 $this->load_choices();
4399 $save = array();
4400 foreach($data as $datum) {
4401 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4402 continue;
4404 $save[$datum] = $datum; // no duplicates
4406 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4410 * Return XHTML select field and wrapping div
4412 * @todo Add vartype handling to make sure $data is an array
4413 * @param array $data Array of elements to select by default
4414 * @return string XHTML select field and wrapping div
4416 public function output_html($data, $query='') {
4417 global $OUTPUT;
4419 $this->load_choices();
4420 $currentsetting = array();
4421 foreach ($data as $key) {
4422 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4423 $currentsetting[] = $key; // already selected first
4427 $context = (object) [
4428 'id' => $this->get_id(),
4429 'name' => $this->get_full_name(),
4432 $options = $this->choices;
4433 $selects = [];
4434 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4435 if (!array_key_exists($i, $currentsetting)) {
4436 $currentsetting[$i] = 'none';
4438 $selects[] = [
4439 'key' => $i,
4440 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4441 return [
4442 'name' => $options[$option],
4443 'value' => $option,
4444 'selected' => $currentsetting[$i] == $option
4446 }, array_keys($options))
4449 $context->selects = $selects;
4451 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4453 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4459 * Special checkbox for frontpage - stores data in course table
4461 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4463 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4465 * Returns the current sites name
4467 * @return string
4469 public function get_setting() {
4470 $site = course_get_format(get_site())->get_course();
4471 return $site->{$this->name};
4475 * Save the selected setting
4477 * @param string $data The selected site
4478 * @return string empty string or error message
4480 public function write_setting($data) {
4481 global $DB, $SITE, $COURSE;
4482 $record = new stdClass();
4483 $record->id = $SITE->id;
4484 $record->{$this->name} = ($data == '1' ? 1 : 0);
4485 $record->timemodified = time();
4487 course_get_format($SITE)->update_course_format_options($record);
4488 $DB->update_record('course', $record);
4490 // Reset caches.
4491 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4492 if ($SITE->id == $COURSE->id) {
4493 $COURSE = $SITE;
4495 format_base::reset_course_cache($SITE->id);
4497 return '';
4502 * Special text for frontpage - stores data in course table.
4503 * Empty string means not set here. Manual setting is required.
4505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4507 class admin_setting_sitesettext extends admin_setting_configtext {
4510 * Constructor.
4512 public function __construct() {
4513 call_user_func_array(['parent', '__construct'], func_get_args());
4514 $this->set_force_ltr(false);
4518 * Return the current setting
4520 * @return mixed string or null
4522 public function get_setting() {
4523 $site = course_get_format(get_site())->get_course();
4524 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4528 * Validate the selected data
4530 * @param string $data The selected value to validate
4531 * @return mixed true or message string
4533 public function validate($data) {
4534 global $DB, $SITE;
4535 $cleaned = clean_param($data, PARAM_TEXT);
4536 if ($cleaned === '') {
4537 return get_string('required');
4539 if ($this->name ==='shortname' &&
4540 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4541 return get_string('shortnametaken', 'error', $data);
4543 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4544 return true;
4545 } else {
4546 return get_string('validateerror', 'admin');
4551 * Save the selected setting
4553 * @param string $data The selected value
4554 * @return string empty or error message
4556 public function write_setting($data) {
4557 global $DB, $SITE, $COURSE;
4558 $data = trim($data);
4559 $validated = $this->validate($data);
4560 if ($validated !== true) {
4561 return $validated;
4564 $record = new stdClass();
4565 $record->id = $SITE->id;
4566 $record->{$this->name} = $data;
4567 $record->timemodified = time();
4569 course_get_format($SITE)->update_course_format_options($record);
4570 $DB->update_record('course', $record);
4572 // Reset caches.
4573 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4574 if ($SITE->id == $COURSE->id) {
4575 $COURSE = $SITE;
4577 format_base::reset_course_cache($SITE->id);
4579 return '';
4585 * Special text editor for site description.
4587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4589 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4592 * Calls parent::__construct with specific arguments
4594 public function __construct() {
4595 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4596 PARAM_RAW, 60, 15);
4600 * Return the current setting
4601 * @return string The current setting
4603 public function get_setting() {
4604 $site = course_get_format(get_site())->get_course();
4605 return $site->{$this->name};
4609 * Save the new setting
4611 * @param string $data The new value to save
4612 * @return string empty or error message
4614 public function write_setting($data) {
4615 global $DB, $SITE, $COURSE;
4616 $record = new stdClass();
4617 $record->id = $SITE->id;
4618 $record->{$this->name} = $data;
4619 $record->timemodified = time();
4621 course_get_format($SITE)->update_course_format_options($record);
4622 $DB->update_record('course', $record);
4624 // Reset caches.
4625 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4626 if ($SITE->id == $COURSE->id) {
4627 $COURSE = $SITE;
4629 format_base::reset_course_cache($SITE->id);
4631 return '';
4637 * Administration interface for emoticon_manager settings.
4639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4641 class admin_setting_emoticons extends admin_setting {
4644 * Calls parent::__construct with specific args
4646 public function __construct() {
4647 global $CFG;
4649 $manager = get_emoticon_manager();
4650 $defaults = $this->prepare_form_data($manager->default_emoticons());
4651 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4655 * Return the current setting(s)
4657 * @return array Current settings array
4659 public function get_setting() {
4660 global $CFG;
4662 $manager = get_emoticon_manager();
4664 $config = $this->config_read($this->name);
4665 if (is_null($config)) {
4666 return null;
4669 $config = $manager->decode_stored_config($config);
4670 if (is_null($config)) {
4671 return null;
4674 return $this->prepare_form_data($config);
4678 * Save selected settings
4680 * @param array $data Array of settings to save
4681 * @return bool
4683 public function write_setting($data) {
4685 $manager = get_emoticon_manager();
4686 $emoticons = $this->process_form_data($data);
4688 if ($emoticons === false) {
4689 return false;
4692 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4693 return ''; // success
4694 } else {
4695 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4700 * Return XHTML field(s) for options
4702 * @param array $data Array of options to set in HTML
4703 * @return string XHTML string for the fields and wrapping div(s)
4705 public function output_html($data, $query='') {
4706 global $OUTPUT;
4708 $context = (object) [
4709 'name' => $this->get_full_name(),
4710 'emoticons' => [],
4711 'forceltr' => true,
4714 $i = 0;
4715 foreach ($data as $field => $value) {
4717 // When $i == 0: text.
4718 // When $i == 1: imagename.
4719 // When $i == 2: imagecomponent.
4720 // When $i == 3: altidentifier.
4721 // When $i == 4: altcomponent.
4722 $fields[$i] = (object) [
4723 'field' => $field,
4724 'value' => $value,
4725 'index' => $i
4727 $i++;
4729 if ($i > 4) {
4730 $icon = null;
4731 if (!empty($fields[1]->value)) {
4732 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4733 $alt = get_string($fields[3]->value, $fields[4]->value);
4734 } else {
4735 $alt = $fields[0]->value;
4737 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4739 $context->emoticons[] = [
4740 'fields' => $fields,
4741 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4743 $fields = [];
4744 $i = 0;
4748 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4749 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4750 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4754 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4756 * @see self::process_form_data()
4757 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4758 * @return array of form fields and their values
4760 protected function prepare_form_data(array $emoticons) {
4762 $form = array();
4763 $i = 0;
4764 foreach ($emoticons as $emoticon) {
4765 $form['text'.$i] = $emoticon->text;
4766 $form['imagename'.$i] = $emoticon->imagename;
4767 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4768 $form['altidentifier'.$i] = $emoticon->altidentifier;
4769 $form['altcomponent'.$i] = $emoticon->altcomponent;
4770 $i++;
4772 // add one more blank field set for new object
4773 $form['text'.$i] = '';
4774 $form['imagename'.$i] = '';
4775 $form['imagecomponent'.$i] = '';
4776 $form['altidentifier'.$i] = '';
4777 $form['altcomponent'.$i] = '';
4779 return $form;
4783 * Converts the data from admin settings form into an array of emoticon objects
4785 * @see self::prepare_form_data()
4786 * @param array $data array of admin form fields and values
4787 * @return false|array of emoticon objects
4789 protected function process_form_data(array $form) {
4791 $count = count($form); // number of form field values
4793 if ($count % 5) {
4794 // we must get five fields per emoticon object
4795 return false;
4798 $emoticons = array();
4799 for ($i = 0; $i < $count / 5; $i++) {
4800 $emoticon = new stdClass();
4801 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4802 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4803 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4804 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4805 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4807 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4808 // prevent from breaking http://url.addresses by accident
4809 $emoticon->text = '';
4812 if (strlen($emoticon->text) < 2) {
4813 // do not allow single character emoticons
4814 $emoticon->text = '';
4817 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4818 // emoticon text must contain some non-alphanumeric character to prevent
4819 // breaking HTML tags
4820 $emoticon->text = '';
4823 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4824 $emoticons[] = $emoticon;
4827 return $emoticons;
4834 * Special setting for limiting of the list of available languages.
4836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4838 class admin_setting_langlist extends admin_setting_configtext {
4840 * Calls parent::__construct with specific arguments
4842 public function __construct() {
4843 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4847 * Save the new setting
4849 * @param string $data The new setting
4850 * @return bool
4852 public function write_setting($data) {
4853 $return = parent::write_setting($data);
4854 get_string_manager()->reset_caches();
4855 return $return;
4861 * Selection of one of the recognised countries using the list
4862 * returned by {@link get_list_of_countries()}.
4864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4866 class admin_settings_country_select extends admin_setting_configselect {
4867 protected $includeall;
4868 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4869 $this->includeall = $includeall;
4870 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4874 * Lazy-load the available choices for the select box
4876 public function load_choices() {
4877 global $CFG;
4878 if (is_array($this->choices)) {
4879 return true;
4881 $this->choices = array_merge(
4882 array('0' => get_string('choosedots')),
4883 get_string_manager()->get_list_of_countries($this->includeall));
4884 return true;
4890 * admin_setting_configselect for the default number of sections in a course,
4891 * simply so we can lazy-load the choices.
4893 * @copyright 2011 The Open University
4894 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4896 class admin_settings_num_course_sections extends admin_setting_configselect {
4897 public function __construct($name, $visiblename, $description, $defaultsetting) {
4898 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4901 /** Lazy-load the available choices for the select box */
4902 public function load_choices() {
4903 $max = get_config('moodlecourse', 'maxsections');
4904 if (!isset($max) || !is_numeric($max)) {
4905 $max = 52;
4907 for ($i = 0; $i <= $max; $i++) {
4908 $this->choices[$i] = "$i";
4910 return true;
4916 * Course category selection
4918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4920 class admin_settings_coursecat_select extends admin_setting_configselect {
4922 * Calls parent::__construct with specific arguments
4924 public function __construct($name, $visiblename, $description, $defaultsetting) {
4925 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4929 * Load the available choices for the select box
4931 * @return bool
4933 public function load_choices() {
4934 global $CFG;
4935 require_once($CFG->dirroot.'/course/lib.php');
4936 if (is_array($this->choices)) {
4937 return true;
4939 $this->choices = make_categories_options();
4940 return true;
4946 * Special control for selecting days to backup
4948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4950 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4952 * Calls parent::__construct with specific arguments
4954 public function __construct() {
4955 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4956 $this->plugin = 'backup';
4960 * Load the available choices for the select box
4962 * @return bool Always returns true
4964 public function load_choices() {
4965 if (is_array($this->choices)) {
4966 return true;
4968 $this->choices = array();
4969 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4970 foreach ($days as $day) {
4971 $this->choices[$day] = get_string($day, 'calendar');
4973 return true;
4978 * Special setting for backup auto destination.
4980 * @package core
4981 * @subpackage admin
4982 * @copyright 2014 Frédéric Massart - FMCorz.net
4983 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4985 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4988 * Calls parent::__construct with specific arguments.
4990 public function __construct() {
4991 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4995 * Check if the directory must be set, depending on backup/backup_auto_storage.
4997 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4998 * there will be conflicts if this validation happens before the other one.
5000 * @param string $data Form data.
5001 * @return string Empty when no errors.
5003 public function write_setting($data) {
5004 $storage = (int) get_config('backup', 'backup_auto_storage');
5005 if ($storage !== 0) {
5006 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5007 // The directory must exist and be writable.
5008 return get_string('backuperrorinvaliddestination');
5011 return parent::write_setting($data);
5017 * Special debug setting
5019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5021 class admin_setting_special_debug extends admin_setting_configselect {
5023 * Calls parent::__construct with specific arguments
5025 public function __construct() {
5026 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5030 * Load the available choices for the select box
5032 * @return bool
5034 public function load_choices() {
5035 if (is_array($this->choices)) {
5036 return true;
5038 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5039 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5040 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5041 DEBUG_ALL => get_string('debugall', 'admin'),
5042 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5043 return true;
5049 * Special admin control
5051 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5053 class admin_setting_special_calendar_weekend extends admin_setting {
5055 * Calls parent::__construct with specific arguments
5057 public function __construct() {
5058 $name = 'calendar_weekend';
5059 $visiblename = get_string('calendar_weekend', 'admin');
5060 $description = get_string('helpweekenddays', 'admin');
5061 $default = array ('0', '6'); // Saturdays and Sundays
5062 parent::__construct($name, $visiblename, $description, $default);
5066 * Gets the current settings as an array
5068 * @return mixed Null if none, else array of settings
5070 public function get_setting() {
5071 $result = $this->config_read($this->name);
5072 if (is_null($result)) {
5073 return NULL;
5075 if ($result === '') {
5076 return array();
5078 $settings = array();
5079 for ($i=0; $i<7; $i++) {
5080 if ($result & (1 << $i)) {
5081 $settings[] = $i;
5084 return $settings;
5088 * Save the new settings
5090 * @param array $data Array of new settings
5091 * @return bool
5093 public function write_setting($data) {
5094 if (!is_array($data)) {
5095 return '';
5097 unset($data['xxxxx']);
5098 $result = 0;
5099 foreach($data as $index) {
5100 $result |= 1 << $index;
5102 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5106 * Return XHTML to display the control
5108 * @param array $data array of selected days
5109 * @param string $query
5110 * @return string XHTML for display (field + wrapping div(s)
5112 public function output_html($data, $query='') {
5113 global $OUTPUT;
5115 // The order matters very much because of the implied numeric keys.
5116 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5117 $context = (object) [
5118 'name' => $this->get_full_name(),
5119 'id' => $this->get_id(),
5120 'days' => array_map(function($index) use ($days, $data) {
5121 return [
5122 'index' => $index,
5123 'label' => get_string($days[$index], 'calendar'),
5124 'checked' => in_array($index, $data)
5126 }, array_keys($days))
5129 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5131 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5138 * Admin setting that allows a user to pick a behaviour.
5140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5142 class admin_setting_question_behaviour extends admin_setting_configselect {
5144 * @param string $name name of config variable
5145 * @param string $visiblename display name
5146 * @param string $description description
5147 * @param string $default default.
5149 public function __construct($name, $visiblename, $description, $default) {
5150 parent::__construct($name, $visiblename, $description, $default, null);
5154 * Load list of behaviours as choices
5155 * @return bool true => success, false => error.
5157 public function load_choices() {
5158 global $CFG;
5159 require_once($CFG->dirroot . '/question/engine/lib.php');
5160 $this->choices = question_engine::get_behaviour_options('');
5161 return true;
5167 * Admin setting that allows a user to pick appropriate roles for something.
5169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5171 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5172 /** @var array Array of capabilities which identify roles */
5173 private $types;
5176 * @param string $name Name of config variable
5177 * @param string $visiblename Display name
5178 * @param string $description Description
5179 * @param array $types Array of archetypes which identify
5180 * roles that will be enabled by default.
5182 public function __construct($name, $visiblename, $description, $types) {
5183 parent::__construct($name, $visiblename, $description, NULL, NULL);
5184 $this->types = $types;
5188 * Load roles as choices
5190 * @return bool true=>success, false=>error
5192 public function load_choices() {
5193 global $CFG, $DB;
5194 if (during_initial_install()) {
5195 return false;
5197 if (is_array($this->choices)) {
5198 return true;
5200 if ($roles = get_all_roles()) {
5201 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5202 return true;
5203 } else {
5204 return false;
5209 * Return the default setting for this control
5211 * @return array Array of default settings
5213 public function get_defaultsetting() {
5214 global $CFG;
5216 if (during_initial_install()) {
5217 return null;
5219 $result = array();
5220 foreach($this->types as $archetype) {
5221 if ($caproles = get_archetype_roles($archetype)) {
5222 foreach ($caproles as $caprole) {
5223 $result[$caprole->id] = 1;
5227 return $result;
5233 * Admin setting that is a list of installed filter plugins.
5235 * @copyright 2015 The Open University
5236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5238 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5241 * Constructor
5243 * @param string $name unique ascii name, either 'mysetting' for settings
5244 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5245 * @param string $visiblename localised name
5246 * @param string $description localised long description
5247 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5249 public function __construct($name, $visiblename, $description, $default) {
5250 if (empty($default)) {
5251 $default = array();
5253 $this->load_choices();
5254 foreach ($default as $plugin) {
5255 if (!isset($this->choices[$plugin])) {
5256 unset($default[$plugin]);
5259 parent::__construct($name, $visiblename, $description, $default, null);
5262 public function load_choices() {
5263 if (is_array($this->choices)) {
5264 return true;
5266 $this->choices = array();
5268 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5269 $this->choices[$plugin] = filter_get_name($plugin);
5271 return true;
5277 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5279 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5281 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5283 * Constructor
5284 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5285 * @param string $visiblename localised
5286 * @param string $description long localised info
5287 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5288 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5289 * @param int $size default field size
5291 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5292 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5293 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5299 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5301 * @copyright 2009 Petr Skoda (http://skodak.org)
5302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5304 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5307 * Constructor
5308 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5309 * @param string $visiblename localised
5310 * @param string $description long localised info
5311 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5312 * @param string $yes value used when checked
5313 * @param string $no value used when not checked
5315 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5316 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5317 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5324 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5326 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5328 * @copyright 2010 Sam Hemelryk
5329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5331 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5333 * Constructor
5334 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5335 * @param string $visiblename localised
5336 * @param string $description long localised info
5337 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5338 * @param string $yes value used when checked
5339 * @param string $no value used when not checked
5341 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5342 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5343 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5350 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5354 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5356 * Calls parent::__construct with specific arguments
5358 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5359 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5360 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5366 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5368 * @copyright 2017 Marina Glancy
5369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5371 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5373 * Constructor
5374 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5375 * or 'myplugin/mysetting' for ones in config_plugins.
5376 * @param string $visiblename localised
5377 * @param string $description long localised info
5378 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5379 * @param array $choices array of $value=>$label for each selection
5381 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5382 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5383 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5389 * Graded roles in gradebook
5391 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5393 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5395 * Calls parent::__construct with specific arguments
5397 public function __construct() {
5398 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5399 get_string('configgradebookroles', 'admin'),
5400 array('student'));
5407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5409 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5411 * Saves the new settings passed in $data
5413 * @param string $data
5414 * @return mixed string or Array
5416 public function write_setting($data) {
5417 global $CFG, $DB;
5419 $oldvalue = $this->config_read($this->name);
5420 $return = parent::write_setting($data);
5421 $newvalue = $this->config_read($this->name);
5423 if ($oldvalue !== $newvalue) {
5424 // force full regrading
5425 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5428 return $return;
5434 * Which roles to show on course description page
5436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5438 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5440 * Calls parent::__construct with specific arguments
5442 public function __construct() {
5443 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5444 get_string('coursecontact_desc', 'admin'),
5445 array('editingteacher'));
5446 $this->set_updatedcallback(function (){
5447 cache::make('core', 'coursecontacts')->purge();
5455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5457 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5459 * Calls parent::__construct with specific arguments
5461 public function __construct() {
5462 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5463 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5467 * Old syntax of class constructor. Deprecated in PHP7.
5469 * @deprecated since Moodle 3.1
5471 public function admin_setting_special_gradelimiting() {
5472 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5473 self::__construct();
5477 * Force site regrading
5479 function regrade_all() {
5480 global $CFG;
5481 require_once("$CFG->libdir/gradelib.php");
5482 grade_force_site_regrading();
5486 * Saves the new settings
5488 * @param mixed $data
5489 * @return string empty string or error message
5491 function write_setting($data) {
5492 $previous = $this->get_setting();
5494 if ($previous === null) {
5495 if ($data) {
5496 $this->regrade_all();
5498 } else {
5499 if ($data != $previous) {
5500 $this->regrade_all();
5503 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5509 * Special setting for $CFG->grade_minmaxtouse.
5511 * @package core
5512 * @copyright 2015 Frédéric Massart - FMCorz.net
5513 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5515 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5518 * Constructor.
5520 public function __construct() {
5521 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5522 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5523 array(
5524 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5525 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5531 * Saves the new setting.
5533 * @param mixed $data
5534 * @return string empty string or error message
5536 function write_setting($data) {
5537 global $CFG;
5539 $previous = $this->get_setting();
5540 $result = parent::write_setting($data);
5542 // If saved and the value has changed.
5543 if (empty($result) && $previous != $data) {
5544 require_once($CFG->libdir . '/gradelib.php');
5545 grade_force_site_regrading();
5548 return $result;
5555 * Primary grade export plugin - has state tracking.
5557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5559 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5561 * Calls parent::__construct with specific arguments
5563 public function __construct() {
5564 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5565 get_string('configgradeexport', 'admin'), array(), NULL);
5569 * Load the available choices for the multicheckbox
5571 * @return bool always returns true
5573 public function load_choices() {
5574 if (is_array($this->choices)) {
5575 return true;
5577 $this->choices = array();
5579 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5580 foreach($plugins as $plugin => $unused) {
5581 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5584 return true;
5590 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5592 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5594 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5596 * Config gradepointmax constructor
5598 * @param string $name Overidden by "gradepointmax"
5599 * @param string $visiblename Overridden by "gradepointmax" language string.
5600 * @param string $description Overridden by "gradepointmax_help" language string.
5601 * @param string $defaultsetting Not used, overridden by 100.
5602 * @param mixed $paramtype Overridden by PARAM_INT.
5603 * @param int $size Overridden by 5.
5605 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5606 $name = 'gradepointdefault';
5607 $visiblename = get_string('gradepointdefault', 'grades');
5608 $description = get_string('gradepointdefault_help', 'grades');
5609 $defaultsetting = 100;
5610 $paramtype = PARAM_INT;
5611 $size = 5;
5612 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5616 * Validate data before storage
5617 * @param string $data The submitted data
5618 * @return bool|string true if ok, string if error found
5620 public function validate($data) {
5621 global $CFG;
5622 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5623 return true;
5624 } else {
5625 return get_string('gradepointdefault_validateerror', 'grades');
5632 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5636 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5639 * Config gradepointmax constructor
5641 * @param string $name Overidden by "gradepointmax"
5642 * @param string $visiblename Overridden by "gradepointmax" language string.
5643 * @param string $description Overridden by "gradepointmax_help" language string.
5644 * @param string $defaultsetting Not used, overridden by 100.
5645 * @param mixed $paramtype Overridden by PARAM_INT.
5646 * @param int $size Overridden by 5.
5648 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5649 $name = 'gradepointmax';
5650 $visiblename = get_string('gradepointmax', 'grades');
5651 $description = get_string('gradepointmax_help', 'grades');
5652 $defaultsetting = 100;
5653 $paramtype = PARAM_INT;
5654 $size = 5;
5655 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5659 * Save the selected setting
5661 * @param string $data The selected site
5662 * @return string empty string or error message
5664 public function write_setting($data) {
5665 if ($data === '') {
5666 $data = (int)$this->defaultsetting;
5667 } else {
5668 $data = $data;
5670 return parent::write_setting($data);
5674 * Validate data before storage
5675 * @param string $data The submitted data
5676 * @return bool|string true if ok, string if error found
5678 public function validate($data) {
5679 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5680 return true;
5681 } else {
5682 return get_string('gradepointmax_validateerror', 'grades');
5687 * Return an XHTML string for the setting
5688 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5689 * @param string $query search query to be highlighted
5690 * @return string XHTML to display control
5692 public function output_html($data, $query = '') {
5693 global $OUTPUT;
5695 $default = $this->get_defaultsetting();
5696 $context = (object) [
5697 'size' => $this->size,
5698 'id' => $this->get_id(),
5699 'name' => $this->get_full_name(),
5700 'value' => $data,
5701 'attributes' => [
5702 'maxlength' => 5
5704 'forceltr' => $this->get_force_ltr()
5706 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5708 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5714 * Grade category settings
5716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5718 class admin_setting_gradecat_combo extends admin_setting {
5719 /** @var array Array of choices */
5720 public $choices;
5723 * Sets choices and calls parent::__construct with passed arguments
5724 * @param string $name
5725 * @param string $visiblename
5726 * @param string $description
5727 * @param mixed $defaultsetting string or array depending on implementation
5728 * @param array $choices An array of choices for the control
5730 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5731 $this->choices = $choices;
5732 parent::__construct($name, $visiblename, $description, $defaultsetting);
5736 * Return the current setting(s) array
5738 * @return array Array of value=>xx, forced=>xx, adv=>xx
5740 public function get_setting() {
5741 global $CFG;
5743 $value = $this->config_read($this->name);
5744 $flag = $this->config_read($this->name.'_flag');
5746 if (is_null($value) or is_null($flag)) {
5747 return NULL;
5750 $flag = (int)$flag;
5751 $forced = (boolean)(1 & $flag); // first bit
5752 $adv = (boolean)(2 & $flag); // second bit
5754 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5758 * Save the new settings passed in $data
5760 * @todo Add vartype handling to ensure $data is array
5761 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5762 * @return string empty or error message
5764 public function write_setting($data) {
5765 global $CFG;
5767 $value = $data['value'];
5768 $forced = empty($data['forced']) ? 0 : 1;
5769 $adv = empty($data['adv']) ? 0 : 2;
5770 $flag = ($forced | $adv); //bitwise or
5772 if (!in_array($value, array_keys($this->choices))) {
5773 return 'Error setting ';
5776 $oldvalue = $this->config_read($this->name);
5777 $oldflag = (int)$this->config_read($this->name.'_flag');
5778 $oldforced = (1 & $oldflag); // first bit
5780 $result1 = $this->config_write($this->name, $value);
5781 $result2 = $this->config_write($this->name.'_flag', $flag);
5783 // force regrade if needed
5784 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5785 require_once($CFG->libdir.'/gradelib.php');
5786 grade_category::updated_forced_settings();
5789 if ($result1 and $result2) {
5790 return '';
5791 } else {
5792 return get_string('errorsetting', 'admin');
5797 * Return XHTML to display the field and wrapping div
5799 * @todo Add vartype handling to ensure $data is array
5800 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5801 * @param string $query
5802 * @return string XHTML to display control
5804 public function output_html($data, $query='') {
5805 global $OUTPUT;
5807 $value = $data['value'];
5809 $default = $this->get_defaultsetting();
5810 if (!is_null($default)) {
5811 $defaultinfo = array();
5812 if (isset($this->choices[$default['value']])) {
5813 $defaultinfo[] = $this->choices[$default['value']];
5815 if (!empty($default['forced'])) {
5816 $defaultinfo[] = get_string('force');
5818 if (!empty($default['adv'])) {
5819 $defaultinfo[] = get_string('advanced');
5821 $defaultinfo = implode(', ', $defaultinfo);
5823 } else {
5824 $defaultinfo = NULL;
5827 $options = $this->choices;
5828 $context = (object) [
5829 'id' => $this->get_id(),
5830 'name' => $this->get_full_name(),
5831 'forced' => !empty($data['forced']),
5832 'advanced' => !empty($data['adv']),
5833 'options' => array_map(function($option) use ($options, $value) {
5834 return [
5835 'value' => $option,
5836 'name' => $options[$option],
5837 'selected' => $option == $value
5839 }, array_keys($options)),
5842 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5844 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5850 * Selection of grade report in user profiles
5852 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5854 class admin_setting_grade_profilereport extends admin_setting_configselect {
5856 * Calls parent::__construct with specific arguments
5858 public function __construct() {
5859 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5863 * Loads an array of choices for the configselect control
5865 * @return bool always return true
5867 public function load_choices() {
5868 if (is_array($this->choices)) {
5869 return true;
5871 $this->choices = array();
5873 global $CFG;
5874 require_once($CFG->libdir.'/gradelib.php');
5876 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5877 if (file_exists($plugindir.'/lib.php')) {
5878 require_once($plugindir.'/lib.php');
5879 $functionname = 'grade_report_'.$plugin.'_profilereport';
5880 if (function_exists($functionname)) {
5881 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5885 return true;
5890 * Provides a selection of grade reports to be used for "grades".
5892 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5893 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5895 class admin_setting_my_grades_report extends admin_setting_configselect {
5898 * Calls parent::__construct with specific arguments.
5900 public function __construct() {
5901 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5902 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5906 * Loads an array of choices for the configselect control.
5908 * @return bool always returns true.
5910 public function load_choices() {
5911 global $CFG; // Remove this line and behold the horror of behat test failures!
5912 $this->choices = array();
5913 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5914 if (file_exists($plugindir . '/lib.php')) {
5915 require_once($plugindir . '/lib.php');
5916 // Check to see if the class exists. Check the correct plugin convention first.
5917 if (class_exists('gradereport_' . $plugin)) {
5918 $classname = 'gradereport_' . $plugin;
5919 } else if (class_exists('grade_report_' . $plugin)) {
5920 // We are using the old plugin naming convention.
5921 $classname = 'grade_report_' . $plugin;
5922 } else {
5923 continue;
5925 if ($classname::supports_mygrades()) {
5926 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5930 // Add an option to specify an external url.
5931 $this->choices['external'] = get_string('externalurl', 'grades');
5932 return true;
5937 * Special class for register auth selection
5939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5941 class admin_setting_special_registerauth extends admin_setting_configselect {
5943 * Calls parent::__construct with specific arguments
5945 public function __construct() {
5946 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5950 * Returns the default option
5952 * @return string empty or default option
5954 public function get_defaultsetting() {
5955 $this->load_choices();
5956 $defaultsetting = parent::get_defaultsetting();
5957 if (array_key_exists($defaultsetting, $this->choices)) {
5958 return $defaultsetting;
5959 } else {
5960 return '';
5965 * Loads the possible choices for the array
5967 * @return bool always returns true
5969 public function load_choices() {
5970 global $CFG;
5972 if (is_array($this->choices)) {
5973 return true;
5975 $this->choices = array();
5976 $this->choices[''] = get_string('disable');
5978 $authsenabled = get_enabled_auth_plugins(true);
5980 foreach ($authsenabled as $auth) {
5981 $authplugin = get_auth_plugin($auth);
5982 if (!$authplugin->can_signup()) {
5983 continue;
5985 // Get the auth title (from core or own auth lang files)
5986 $authtitle = $authplugin->get_title();
5987 $this->choices[$auth] = $authtitle;
5989 return true;
5995 * General plugins manager
5997 class admin_page_pluginsoverview extends admin_externalpage {
6000 * Sets basic information about the external page
6002 public function __construct() {
6003 global $CFG;
6004 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6005 "$CFG->wwwroot/$CFG->admin/plugins.php");
6010 * Module manage page
6012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6014 class admin_page_managemods extends admin_externalpage {
6016 * Calls parent::__construct with specific arguments
6018 public function __construct() {
6019 global $CFG;
6020 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6024 * Try to find the specified module
6026 * @param string $query The module to search for
6027 * @return array
6029 public function search($query) {
6030 global $CFG, $DB;
6031 if ($result = parent::search($query)) {
6032 return $result;
6035 $found = false;
6036 if ($modules = $DB->get_records('modules')) {
6037 foreach ($modules as $module) {
6038 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6039 continue;
6041 if (strpos($module->name, $query) !== false) {
6042 $found = true;
6043 break;
6045 $strmodulename = get_string('modulename', $module->name);
6046 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6047 $found = true;
6048 break;
6052 if ($found) {
6053 $result = new stdClass();
6054 $result->page = $this;
6055 $result->settings = array();
6056 return array($this->name => $result);
6057 } else {
6058 return array();
6065 * Special class for enrol plugins management.
6067 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6070 class admin_setting_manageenrols extends admin_setting {
6072 * Calls parent::__construct with specific arguments
6074 public function __construct() {
6075 $this->nosave = true;
6076 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6080 * Always returns true, does nothing
6082 * @return true
6084 public function get_setting() {
6085 return true;
6089 * Always returns true, does nothing
6091 * @return true
6093 public function get_defaultsetting() {
6094 return true;
6098 * Always returns '', does not write anything
6100 * @return string Always returns ''
6102 public function write_setting($data) {
6103 // do not write any setting
6104 return '';
6108 * Checks if $query is one of the available enrol plugins
6110 * @param string $query The string to search for
6111 * @return bool Returns true if found, false if not
6113 public function is_related($query) {
6114 if (parent::is_related($query)) {
6115 return true;
6118 $query = core_text::strtolower($query);
6119 $enrols = enrol_get_plugins(false);
6120 foreach ($enrols as $name=>$enrol) {
6121 $localised = get_string('pluginname', 'enrol_'.$name);
6122 if (strpos(core_text::strtolower($name), $query) !== false) {
6123 return true;
6125 if (strpos(core_text::strtolower($localised), $query) !== false) {
6126 return true;
6129 return false;
6133 * Builds the XHTML to display the control
6135 * @param string $data Unused
6136 * @param string $query
6137 * @return string
6139 public function output_html($data, $query='') {
6140 global $CFG, $OUTPUT, $DB, $PAGE;
6142 // Display strings.
6143 $strup = get_string('up');
6144 $strdown = get_string('down');
6145 $strsettings = get_string('settings');
6146 $strenable = get_string('enable');
6147 $strdisable = get_string('disable');
6148 $struninstall = get_string('uninstallplugin', 'core_admin');
6149 $strusage = get_string('enrolusage', 'enrol');
6150 $strversion = get_string('version');
6151 $strtest = get_string('testsettings', 'core_enrol');
6153 $pluginmanager = core_plugin_manager::instance();
6155 $enrols_available = enrol_get_plugins(false);
6156 $active_enrols = enrol_get_plugins(true);
6158 $allenrols = array();
6159 foreach ($active_enrols as $key=>$enrol) {
6160 $allenrols[$key] = true;
6162 foreach ($enrols_available as $key=>$enrol) {
6163 $allenrols[$key] = true;
6165 // Now find all borked plugins and at least allow then to uninstall.
6166 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6167 foreach ($condidates as $candidate) {
6168 if (empty($allenrols[$candidate])) {
6169 $allenrols[$candidate] = true;
6173 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6174 $return .= $OUTPUT->box_start('generalbox enrolsui');
6176 $table = new html_table();
6177 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6178 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6179 $table->id = 'courseenrolmentplugins';
6180 $table->attributes['class'] = 'admintable generaltable';
6181 $table->data = array();
6183 // Iterate through enrol plugins and add to the display table.
6184 $updowncount = 1;
6185 $enrolcount = count($active_enrols);
6186 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6187 $printed = array();
6188 foreach($allenrols as $enrol => $unused) {
6189 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6190 $version = get_config('enrol_'.$enrol, 'version');
6191 if ($version === false) {
6192 $version = '';
6195 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6196 $name = get_string('pluginname', 'enrol_'.$enrol);
6197 } else {
6198 $name = $enrol;
6200 // Usage.
6201 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6202 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6203 $usage = "$ci / $cp";
6205 // Hide/show links.
6206 $class = '';
6207 if (isset($active_enrols[$enrol])) {
6208 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6209 $hideshow = "<a href=\"$aurl\">";
6210 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6211 $enabled = true;
6212 $displayname = $name;
6213 } else if (isset($enrols_available[$enrol])) {
6214 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6215 $hideshow = "<a href=\"$aurl\">";
6216 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6217 $enabled = false;
6218 $displayname = $name;
6219 $class = 'dimmed_text';
6220 } else {
6221 $hideshow = '';
6222 $enabled = false;
6223 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6225 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6226 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6227 } else {
6228 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6231 // Up/down link (only if enrol is enabled).
6232 $updown = '';
6233 if ($enabled) {
6234 if ($updowncount > 1) {
6235 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6236 $updown .= "<a href=\"$aurl\">";
6237 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6238 } else {
6239 $updown .= $OUTPUT->spacer() . '&nbsp;';
6241 if ($updowncount < $enrolcount) {
6242 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6243 $updown .= "<a href=\"$aurl\">";
6244 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6245 } else {
6246 $updown .= $OUTPUT->spacer() . '&nbsp;';
6248 ++$updowncount;
6251 // Add settings link.
6252 if (!$version) {
6253 $settings = '';
6254 } else if ($surl = $plugininfo->get_settings_url()) {
6255 $settings = html_writer::link($surl, $strsettings);
6256 } else {
6257 $settings = '';
6260 // Add uninstall info.
6261 $uninstall = '';
6262 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6263 $uninstall = html_writer::link($uninstallurl, $struninstall);
6266 $test = '';
6267 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6268 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6269 $test = html_writer::link($testsettingsurl, $strtest);
6272 // Add a row to the table.
6273 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6274 if ($class) {
6275 $row->attributes['class'] = $class;
6277 $table->data[] = $row;
6279 $printed[$enrol] = true;
6282 $return .= html_writer::table($table);
6283 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6284 $return .= $OUTPUT->box_end();
6285 return highlight($query, $return);
6291 * Blocks manage page
6293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6295 class admin_page_manageblocks extends admin_externalpage {
6297 * Calls parent::__construct with specific arguments
6299 public function __construct() {
6300 global $CFG;
6301 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6305 * Search for a specific block
6307 * @param string $query The string to search for
6308 * @return array
6310 public function search($query) {
6311 global $CFG, $DB;
6312 if ($result = parent::search($query)) {
6313 return $result;
6316 $found = false;
6317 if ($blocks = $DB->get_records('block')) {
6318 foreach ($blocks as $block) {
6319 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6320 continue;
6322 if (strpos($block->name, $query) !== false) {
6323 $found = true;
6324 break;
6326 $strblockname = get_string('pluginname', 'block_'.$block->name);
6327 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6328 $found = true;
6329 break;
6333 if ($found) {
6334 $result = new stdClass();
6335 $result->page = $this;
6336 $result->settings = array();
6337 return array($this->name => $result);
6338 } else {
6339 return array();
6345 * Message outputs configuration
6347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6349 class admin_page_managemessageoutputs extends admin_externalpage {
6351 * Calls parent::__construct with specific arguments
6353 public function __construct() {
6354 global $CFG;
6355 parent::__construct('managemessageoutputs',
6356 get_string('defaultmessageoutputs', 'message'),
6357 new moodle_url('/admin/message.php')
6362 * Search for a specific message processor
6364 * @param string $query The string to search for
6365 * @return array
6367 public function search($query) {
6368 global $CFG, $DB;
6369 if ($result = parent::search($query)) {
6370 return $result;
6373 $found = false;
6374 if ($processors = get_message_processors()) {
6375 foreach ($processors as $processor) {
6376 if (!$processor->available) {
6377 continue;
6379 if (strpos($processor->name, $query) !== false) {
6380 $found = true;
6381 break;
6383 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6384 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6385 $found = true;
6386 break;
6390 if ($found) {
6391 $result = new stdClass();
6392 $result->page = $this;
6393 $result->settings = array();
6394 return array($this->name => $result);
6395 } else {
6396 return array();
6402 * Default message outputs configuration
6404 * @deprecated since Moodle 3.7 MDL-64495. Please use admin_page_managemessageoutputs instead.
6405 * @todo MDL-64866 This will be deleted in Moodle 4.1.
6407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6409 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6411 * Calls parent::__construct with specific arguments
6413 * @deprecated since Moodle 3.7 MDL-64495. Please use admin_page_managemessageoutputs instead.
6414 * @todo MDL-64866 This will be deleted in Moodle 4.1.
6416 public function __construct() {
6417 global $CFG;
6419 debugging('admin_page_defaultmessageoutputs class is deprecated. Please use admin_page_managemessageoutputs instead.',
6420 DEBUG_DEVELOPER);
6422 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6428 * Manage question behaviours page
6430 * @copyright 2011 The Open University
6431 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6433 class admin_page_manageqbehaviours extends admin_externalpage {
6435 * Constructor
6437 public function __construct() {
6438 global $CFG;
6439 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6440 new moodle_url('/admin/qbehaviours.php'));
6444 * Search question behaviours for the specified string
6446 * @param string $query The string to search for in question behaviours
6447 * @return array
6449 public function search($query) {
6450 global $CFG;
6451 if ($result = parent::search($query)) {
6452 return $result;
6455 $found = false;
6456 require_once($CFG->dirroot . '/question/engine/lib.php');
6457 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6458 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6459 $query) !== false) {
6460 $found = true;
6461 break;
6464 if ($found) {
6465 $result = new stdClass();
6466 $result->page = $this;
6467 $result->settings = array();
6468 return array($this->name => $result);
6469 } else {
6470 return array();
6477 * Question type manage page
6479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6481 class admin_page_manageqtypes extends admin_externalpage {
6483 * Calls parent::__construct with specific arguments
6485 public function __construct() {
6486 global $CFG;
6487 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6488 new moodle_url('/admin/qtypes.php'));
6492 * Search question types for the specified string
6494 * @param string $query The string to search for in question types
6495 * @return array
6497 public function search($query) {
6498 global $CFG;
6499 if ($result = parent::search($query)) {
6500 return $result;
6503 $found = false;
6504 require_once($CFG->dirroot . '/question/engine/bank.php');
6505 foreach (question_bank::get_all_qtypes() as $qtype) {
6506 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6507 $found = true;
6508 break;
6511 if ($found) {
6512 $result = new stdClass();
6513 $result->page = $this;
6514 $result->settings = array();
6515 return array($this->name => $result);
6516 } else {
6517 return array();
6523 class admin_page_manageportfolios extends admin_externalpage {
6525 * Calls parent::__construct with specific arguments
6527 public function __construct() {
6528 global $CFG;
6529 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6530 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6534 * Searches page for the specified string.
6535 * @param string $query The string to search for
6536 * @return bool True if it is found on this page
6538 public function search($query) {
6539 global $CFG;
6540 if ($result = parent::search($query)) {
6541 return $result;
6544 $found = false;
6545 $portfolios = core_component::get_plugin_list('portfolio');
6546 foreach ($portfolios as $p => $dir) {
6547 if (strpos($p, $query) !== false) {
6548 $found = true;
6549 break;
6552 if (!$found) {
6553 foreach (portfolio_instances(false, false) as $instance) {
6554 $title = $instance->get('name');
6555 if (strpos(core_text::strtolower($title), $query) !== false) {
6556 $found = true;
6557 break;
6562 if ($found) {
6563 $result = new stdClass();
6564 $result->page = $this;
6565 $result->settings = array();
6566 return array($this->name => $result);
6567 } else {
6568 return array();
6574 class admin_page_managerepositories extends admin_externalpage {
6576 * Calls parent::__construct with specific arguments
6578 public function __construct() {
6579 global $CFG;
6580 parent::__construct('managerepositories', get_string('manage',
6581 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6585 * Searches page for the specified string.
6586 * @param string $query The string to search for
6587 * @return bool True if it is found on this page
6589 public function search($query) {
6590 global $CFG;
6591 if ($result = parent::search($query)) {
6592 return $result;
6595 $found = false;
6596 $repositories= core_component::get_plugin_list('repository');
6597 foreach ($repositories as $p => $dir) {
6598 if (strpos($p, $query) !== false) {
6599 $found = true;
6600 break;
6603 if (!$found) {
6604 foreach (repository::get_types() as $instance) {
6605 $title = $instance->get_typename();
6606 if (strpos(core_text::strtolower($title), $query) !== false) {
6607 $found = true;
6608 break;
6613 if ($found) {
6614 $result = new stdClass();
6615 $result->page = $this;
6616 $result->settings = array();
6617 return array($this->name => $result);
6618 } else {
6619 return array();
6626 * Special class for authentication administration.
6628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6630 class admin_setting_manageauths extends admin_setting {
6632 * Calls parent::__construct with specific arguments
6634 public function __construct() {
6635 $this->nosave = true;
6636 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6640 * Always returns true
6642 * @return true
6644 public function get_setting() {
6645 return true;
6649 * Always returns true
6651 * @return true
6653 public function get_defaultsetting() {
6654 return true;
6658 * Always returns '' and doesn't write anything
6660 * @return string Always returns ''
6662 public function write_setting($data) {
6663 // do not write any setting
6664 return '';
6668 * Search to find if Query is related to auth plugin
6670 * @param string $query The string to search for
6671 * @return bool true for related false for not
6673 public function is_related($query) {
6674 if (parent::is_related($query)) {
6675 return true;
6678 $authsavailable = core_component::get_plugin_list('auth');
6679 foreach ($authsavailable as $auth => $dir) {
6680 if (strpos($auth, $query) !== false) {
6681 return true;
6683 $authplugin = get_auth_plugin($auth);
6684 $authtitle = $authplugin->get_title();
6685 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6686 return true;
6689 return false;
6693 * Return XHTML to display control
6695 * @param mixed $data Unused
6696 * @param string $query
6697 * @return string highlight
6699 public function output_html($data, $query='') {
6700 global $CFG, $OUTPUT, $DB;
6702 // display strings
6703 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6704 'settings', 'edit', 'name', 'enable', 'disable',
6705 'up', 'down', 'none', 'users'));
6706 $txt->updown = "$txt->up/$txt->down";
6707 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6708 $txt->testsettings = get_string('testsettings', 'core_auth');
6710 $authsavailable = core_component::get_plugin_list('auth');
6711 get_enabled_auth_plugins(true); // fix the list of enabled auths
6712 if (empty($CFG->auth)) {
6713 $authsenabled = array();
6714 } else {
6715 $authsenabled = explode(',', $CFG->auth);
6718 // construct the display array, with enabled auth plugins at the top, in order
6719 $displayauths = array();
6720 $registrationauths = array();
6721 $registrationauths[''] = $txt->disable;
6722 $authplugins = array();
6723 foreach ($authsenabled as $auth) {
6724 $authplugin = get_auth_plugin($auth);
6725 $authplugins[$auth] = $authplugin;
6726 /// Get the auth title (from core or own auth lang files)
6727 $authtitle = $authplugin->get_title();
6728 /// Apply titles
6729 $displayauths[$auth] = $authtitle;
6730 if ($authplugin->can_signup()) {
6731 $registrationauths[$auth] = $authtitle;
6735 foreach ($authsavailable as $auth => $dir) {
6736 if (array_key_exists($auth, $displayauths)) {
6737 continue; //already in the list
6739 $authplugin = get_auth_plugin($auth);
6740 $authplugins[$auth] = $authplugin;
6741 /// Get the auth title (from core or own auth lang files)
6742 $authtitle = $authplugin->get_title();
6743 /// Apply titles
6744 $displayauths[$auth] = $authtitle;
6745 if ($authplugin->can_signup()) {
6746 $registrationauths[$auth] = $authtitle;
6750 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6751 $return .= $OUTPUT->box_start('generalbox authsui');
6753 $table = new html_table();
6754 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6755 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6756 $table->data = array();
6757 $table->attributes['class'] = 'admintable generaltable';
6758 $table->id = 'manageauthtable';
6760 //add always enabled plugins first
6761 $displayname = $displayauths['manual'];
6762 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6763 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6764 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6765 $displayname = $displayauths['nologin'];
6766 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6767 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6770 // iterate through auth plugins and add to the display table
6771 $updowncount = 1;
6772 $authcount = count($authsenabled);
6773 $url = "auth.php?sesskey=" . sesskey();
6774 foreach ($displayauths as $auth => $name) {
6775 if ($auth == 'manual' or $auth == 'nologin') {
6776 continue;
6778 $class = '';
6779 // hide/show link
6780 if (in_array($auth, $authsenabled)) {
6781 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6782 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6783 $enabled = true;
6784 $displayname = $name;
6786 else {
6787 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6788 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6789 $enabled = false;
6790 $displayname = $name;
6791 $class = 'dimmed_text';
6794 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6796 // up/down link (only if auth is enabled)
6797 $updown = '';
6798 if ($enabled) {
6799 if ($updowncount > 1) {
6800 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6801 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6803 else {
6804 $updown .= $OUTPUT->spacer() . '&nbsp;';
6806 if ($updowncount < $authcount) {
6807 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6808 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6810 else {
6811 $updown .= $OUTPUT->spacer() . '&nbsp;';
6813 ++ $updowncount;
6816 // settings link
6817 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6818 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6819 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6820 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6821 } else {
6822 $settings = '';
6825 // Uninstall link.
6826 $uninstall = '';
6827 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6828 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6831 $test = '';
6832 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6833 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6834 $test = html_writer::link($testurl, $txt->testsettings);
6837 // Add a row to the table.
6838 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6839 if ($class) {
6840 $row->attributes['class'] = $class;
6842 $table->data[] = $row;
6844 $return .= html_writer::table($table);
6845 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6846 $return .= $OUTPUT->box_end();
6847 return highlight($query, $return);
6853 * Special class for authentication administration.
6855 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6857 class admin_setting_manageeditors extends admin_setting {
6859 * Calls parent::__construct with specific arguments
6861 public function __construct() {
6862 $this->nosave = true;
6863 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6867 * Always returns true, does nothing
6869 * @return true
6871 public function get_setting() {
6872 return true;
6876 * Always returns true, does nothing
6878 * @return true
6880 public function get_defaultsetting() {
6881 return true;
6885 * Always returns '', does not write anything
6887 * @return string Always returns ''
6889 public function write_setting($data) {
6890 // do not write any setting
6891 return '';
6895 * Checks if $query is one of the available editors
6897 * @param string $query The string to search for
6898 * @return bool Returns true if found, false if not
6900 public function is_related($query) {
6901 if (parent::is_related($query)) {
6902 return true;
6905 $editors_available = editors_get_available();
6906 foreach ($editors_available as $editor=>$editorstr) {
6907 if (strpos($editor, $query) !== false) {
6908 return true;
6910 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6911 return true;
6914 return false;
6918 * Builds the XHTML to display the control
6920 * @param string $data Unused
6921 * @param string $query
6922 * @return string
6924 public function output_html($data, $query='') {
6925 global $CFG, $OUTPUT;
6927 // display strings
6928 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6929 'up', 'down', 'none'));
6930 $struninstall = get_string('uninstallplugin', 'core_admin');
6932 $txt->updown = "$txt->up/$txt->down";
6934 $editors_available = editors_get_available();
6935 $active_editors = explode(',', $CFG->texteditors);
6937 $active_editors = array_reverse($active_editors);
6938 foreach ($active_editors as $key=>$editor) {
6939 if (empty($editors_available[$editor])) {
6940 unset($active_editors[$key]);
6941 } else {
6942 $name = $editors_available[$editor];
6943 unset($editors_available[$editor]);
6944 $editors_available[$editor] = $name;
6947 if (empty($active_editors)) {
6948 //$active_editors = array('textarea');
6950 $editors_available = array_reverse($editors_available, true);
6951 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6952 $return .= $OUTPUT->box_start('generalbox editorsui');
6954 $table = new html_table();
6955 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6956 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6957 $table->id = 'editormanagement';
6958 $table->attributes['class'] = 'admintable generaltable';
6959 $table->data = array();
6961 // iterate through auth plugins and add to the display table
6962 $updowncount = 1;
6963 $editorcount = count($active_editors);
6964 $url = "editors.php?sesskey=" . sesskey();
6965 foreach ($editors_available as $editor => $name) {
6966 // hide/show link
6967 $class = '';
6968 if (in_array($editor, $active_editors)) {
6969 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6970 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6971 $enabled = true;
6972 $displayname = $name;
6974 else {
6975 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6976 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6977 $enabled = false;
6978 $displayname = $name;
6979 $class = 'dimmed_text';
6982 // up/down link (only if auth is enabled)
6983 $updown = '';
6984 if ($enabled) {
6985 if ($updowncount > 1) {
6986 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6987 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6989 else {
6990 $updown .= $OUTPUT->spacer() . '&nbsp;';
6992 if ($updowncount < $editorcount) {
6993 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6994 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6996 else {
6997 $updown .= $OUTPUT->spacer() . '&nbsp;';
6999 ++ $updowncount;
7002 // settings link
7003 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
7004 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7005 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7006 } else {
7007 $settings = '';
7010 $uninstall = '';
7011 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7012 $uninstall = html_writer::link($uninstallurl, $struninstall);
7015 // Add a row to the table.
7016 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7017 if ($class) {
7018 $row->attributes['class'] = $class;
7020 $table->data[] = $row;
7022 $return .= html_writer::table($table);
7023 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7024 $return .= $OUTPUT->box_end();
7025 return highlight($query, $return);
7030 * Special class for antiviruses administration.
7032 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7035 class admin_setting_manageantiviruses extends admin_setting {
7037 * Calls parent::__construct with specific arguments
7039 public function __construct() {
7040 $this->nosave = true;
7041 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7045 * Always returns true, does nothing
7047 * @return true
7049 public function get_setting() {
7050 return true;
7054 * Always returns true, does nothing
7056 * @return true
7058 public function get_defaultsetting() {
7059 return true;
7063 * Always returns '', does not write anything
7065 * @param string $data Unused
7066 * @return string Always returns ''
7068 public function write_setting($data) {
7069 // Do not write any setting.
7070 return '';
7074 * Checks if $query is one of the available editors
7076 * @param string $query The string to search for
7077 * @return bool Returns true if found, false if not
7079 public function is_related($query) {
7080 if (parent::is_related($query)) {
7081 return true;
7084 $antivirusesavailable = \core\antivirus\manager::get_available();
7085 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7086 if (strpos($antivirus, $query) !== false) {
7087 return true;
7089 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7090 return true;
7093 return false;
7097 * Builds the XHTML to display the control
7099 * @param string $data Unused
7100 * @param string $query
7101 * @return string
7103 public function output_html($data, $query='') {
7104 global $CFG, $OUTPUT;
7106 // Display strings.
7107 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7108 'up', 'down', 'none'));
7109 $struninstall = get_string('uninstallplugin', 'core_admin');
7111 $txt->updown = "$txt->up/$txt->down";
7113 $antivirusesavailable = \core\antivirus\manager::get_available();
7114 $activeantiviruses = explode(',', $CFG->antiviruses);
7116 $activeantiviruses = array_reverse($activeantiviruses);
7117 foreach ($activeantiviruses as $key => $antivirus) {
7118 if (empty($antivirusesavailable[$antivirus])) {
7119 unset($activeantiviruses[$key]);
7120 } else {
7121 $name = $antivirusesavailable[$antivirus];
7122 unset($antivirusesavailable[$antivirus]);
7123 $antivirusesavailable[$antivirus] = $name;
7126 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7127 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7128 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7130 $table = new html_table();
7131 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7132 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7133 $table->id = 'antivirusmanagement';
7134 $table->attributes['class'] = 'admintable generaltable';
7135 $table->data = array();
7137 // Iterate through auth plugins and add to the display table.
7138 $updowncount = 1;
7139 $antiviruscount = count($activeantiviruses);
7140 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7141 foreach ($antivirusesavailable as $antivirus => $name) {
7142 // Hide/show link.
7143 $class = '';
7144 if (in_array($antivirus, $activeantiviruses)) {
7145 $hideshowurl = $baseurl;
7146 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7147 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7148 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7149 $enabled = true;
7150 $displayname = $name;
7151 } else {
7152 $hideshowurl = $baseurl;
7153 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7154 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7155 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7156 $enabled = false;
7157 $displayname = $name;
7158 $class = 'dimmed_text';
7161 // Up/down link.
7162 $updown = '';
7163 if ($enabled) {
7164 if ($updowncount > 1) {
7165 $updownurl = $baseurl;
7166 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7167 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7168 $updown = html_writer::link($updownurl, $updownimg);
7169 } else {
7170 $updownimg = $OUTPUT->spacer();
7172 if ($updowncount < $antiviruscount) {
7173 $updownurl = $baseurl;
7174 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7175 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7176 $updown = html_writer::link($updownurl, $updownimg);
7177 } else {
7178 $updownimg = $OUTPUT->spacer();
7180 ++ $updowncount;
7183 // Settings link.
7184 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7185 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7186 $settings = html_writer::link($eurl, $txt->settings);
7187 } else {
7188 $settings = '';
7191 $uninstall = '';
7192 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7193 $uninstall = html_writer::link($uninstallurl, $struninstall);
7196 // Add a row to the table.
7197 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7198 if ($class) {
7199 $row->attributes['class'] = $class;
7201 $table->data[] = $row;
7203 $return .= html_writer::table($table);
7204 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7205 $return .= $OUTPUT->box_end();
7206 return highlight($query, $return);
7211 * Special class for license administration.
7213 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7215 class admin_setting_managelicenses extends admin_setting {
7217 * Calls parent::__construct with specific arguments
7219 public function __construct() {
7220 $this->nosave = true;
7221 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
7225 * Always returns true, does nothing
7227 * @return true
7229 public function get_setting() {
7230 return true;
7234 * Always returns true, does nothing
7236 * @return true
7238 public function get_defaultsetting() {
7239 return true;
7243 * Always returns '', does not write anything
7245 * @return string Always returns ''
7247 public function write_setting($data) {
7248 // do not write any setting
7249 return '';
7253 * Builds the XHTML to display the control
7255 * @param string $data Unused
7256 * @param string $query
7257 * @return string
7259 public function output_html($data, $query='') {
7260 global $CFG, $OUTPUT;
7261 require_once($CFG->libdir . '/licenselib.php');
7262 $url = "licenses.php?sesskey=" . sesskey();
7264 // display strings
7265 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
7266 $licenses = license_manager::get_licenses();
7268 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
7270 $return .= $OUTPUT->box_start('generalbox editorsui');
7272 $table = new html_table();
7273 $table->head = array($txt->name, $txt->enable);
7274 $table->colclasses = array('leftalign', 'centeralign');
7275 $table->id = 'availablelicenses';
7276 $table->attributes['class'] = 'admintable generaltable';
7277 $table->data = array();
7279 foreach ($licenses as $value) {
7280 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
7282 if ($value->enabled == 1) {
7283 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
7284 $OUTPUT->pix_icon('t/hide', get_string('disable')));
7285 } else {
7286 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
7287 $OUTPUT->pix_icon('t/show', get_string('enable')));
7290 if ($value->shortname == $CFG->sitedefaultlicense) {
7291 $displayname .= ' '.$OUTPUT->pix_icon('t/locked', get_string('default'));
7292 $hideshow = '';
7295 $enabled = true;
7297 $table->data[] =array($displayname, $hideshow);
7299 $return .= html_writer::table($table);
7300 $return .= $OUTPUT->box_end();
7301 return highlight($query, $return);
7306 * Course formats manager. Allows to enable/disable formats and jump to settings
7308 class admin_setting_manageformats extends admin_setting {
7311 * Calls parent::__construct with specific arguments
7313 public function __construct() {
7314 $this->nosave = true;
7315 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7319 * Always returns true
7321 * @return true
7323 public function get_setting() {
7324 return true;
7328 * Always returns true
7330 * @return true
7332 public function get_defaultsetting() {
7333 return true;
7337 * Always returns '' and doesn't write anything
7339 * @param mixed $data string or array, must not be NULL
7340 * @return string Always returns ''
7342 public function write_setting($data) {
7343 // do not write any setting
7344 return '';
7348 * Search to find if Query is related to format plugin
7350 * @param string $query The string to search for
7351 * @return bool true for related false for not
7353 public function is_related($query) {
7354 if (parent::is_related($query)) {
7355 return true;
7357 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7358 foreach ($formats as $format) {
7359 if (strpos($format->component, $query) !== false ||
7360 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7361 return true;
7364 return false;
7368 * Return XHTML to display control
7370 * @param mixed $data Unused
7371 * @param string $query
7372 * @return string highlight
7374 public function output_html($data, $query='') {
7375 global $CFG, $OUTPUT;
7376 $return = '';
7377 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7378 $return .= $OUTPUT->box_start('generalbox formatsui');
7380 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7382 // display strings
7383 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7384 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7385 $txt->updown = "$txt->up/$txt->down";
7387 $table = new html_table();
7388 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7389 $table->align = array('left', 'center', 'center', 'center', 'center');
7390 $table->attributes['class'] = 'manageformattable generaltable admintable';
7391 $table->data = array();
7393 $cnt = 0;
7394 $defaultformat = get_config('moodlecourse', 'format');
7395 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7396 foreach ($formats as $format) {
7397 $url = new moodle_url('/admin/courseformats.php',
7398 array('sesskey' => sesskey(), 'format' => $format->name));
7399 $isdefault = '';
7400 $class = '';
7401 if ($format->is_enabled()) {
7402 $strformatname = $format->displayname;
7403 if ($defaultformat === $format->name) {
7404 $hideshow = $txt->default;
7405 } else {
7406 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7407 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7409 } else {
7410 $strformatname = $format->displayname;
7411 $class = 'dimmed_text';
7412 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7413 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7415 $updown = '';
7416 if ($cnt) {
7417 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7418 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7419 } else {
7420 $updown .= $spacer;
7422 if ($cnt < count($formats) - 1) {
7423 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7424 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7425 } else {
7426 $updown .= $spacer;
7428 $cnt++;
7429 $settings = '';
7430 if ($format->get_settings_url()) {
7431 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7433 $uninstall = '';
7434 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7435 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7437 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7438 if ($class) {
7439 $row->attributes['class'] = $class;
7441 $table->data[] = $row;
7443 $return .= html_writer::table($table);
7444 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7445 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7446 $return .= $OUTPUT->box_end();
7447 return highlight($query, $return);
7452 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7454 * @package core
7455 * @copyright 2018 Toni Barbera
7456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7458 class admin_setting_managecustomfields extends admin_setting {
7461 * Calls parent::__construct with specific arguments
7463 public function __construct() {
7464 $this->nosave = true;
7465 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7469 * Always returns true
7471 * @return true
7473 public function get_setting() {
7474 return true;
7478 * Always returns true
7480 * @return true
7482 public function get_defaultsetting() {
7483 return true;
7487 * Always returns '' and doesn't write anything
7489 * @param mixed $data string or array, must not be NULL
7490 * @return string Always returns ''
7492 public function write_setting($data) {
7493 // Do not write any setting.
7494 return '';
7498 * Search to find if Query is related to format plugin
7500 * @param string $query The string to search for
7501 * @return bool true for related false for not
7503 public function is_related($query) {
7504 if (parent::is_related($query)) {
7505 return true;
7507 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7508 foreach ($formats as $format) {
7509 if (strpos($format->component, $query) !== false ||
7510 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7511 return true;
7514 return false;
7518 * Return XHTML to display control
7520 * @param mixed $data Unused
7521 * @param string $query
7522 * @return string highlight
7524 public function output_html($data, $query='') {
7525 global $CFG, $OUTPUT;
7526 $return = '';
7527 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7528 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7530 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7532 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7533 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7534 $txt->updown = "$txt->up/$txt->down";
7536 $table = new html_table();
7537 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7538 $table->align = array('left', 'center', 'center', 'center');
7539 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7540 $table->data = array();
7542 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7543 foreach ($fields as $field) {
7544 $url = new moodle_url('/admin/customfields.php',
7545 array('sesskey' => sesskey(), 'field' => $field->name));
7547 if ($field->is_enabled()) {
7548 $strfieldname = $field->displayname;
7549 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7550 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7551 } else {
7552 $strfieldname = $field->displayname;
7553 $class = 'dimmed_text';
7554 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7555 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7557 $settings = '';
7558 if ($field->get_settings_url()) {
7559 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7561 $uninstall = '';
7562 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7563 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7565 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7566 $table->data[] = $row;
7568 $return .= html_writer::table($table);
7569 $return .= $OUTPUT->box_end();
7570 return highlight($query, $return);
7575 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7577 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7578 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7580 class admin_setting_managedataformats extends admin_setting {
7583 * Calls parent::__construct with specific arguments
7585 public function __construct() {
7586 $this->nosave = true;
7587 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7591 * Always returns true
7593 * @return true
7595 public function get_setting() {
7596 return true;
7600 * Always returns true
7602 * @return true
7604 public function get_defaultsetting() {
7605 return true;
7609 * Always returns '' and doesn't write anything
7611 * @param mixed $data string or array, must not be NULL
7612 * @return string Always returns ''
7614 public function write_setting($data) {
7615 // Do not write any setting.
7616 return '';
7620 * Search to find if Query is related to format plugin
7622 * @param string $query The string to search for
7623 * @return bool true for related false for not
7625 public function is_related($query) {
7626 if (parent::is_related($query)) {
7627 return true;
7629 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7630 foreach ($formats as $format) {
7631 if (strpos($format->component, $query) !== false ||
7632 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7633 return true;
7636 return false;
7640 * Return XHTML to display control
7642 * @param mixed $data Unused
7643 * @param string $query
7644 * @return string highlight
7646 public function output_html($data, $query='') {
7647 global $CFG, $OUTPUT;
7648 $return = '';
7650 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7652 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7653 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7654 $txt->updown = "$txt->up/$txt->down";
7656 $table = new html_table();
7657 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7658 $table->align = array('left', 'center', 'center', 'center', 'center');
7659 $table->attributes['class'] = 'manageformattable generaltable admintable';
7660 $table->data = array();
7662 $cnt = 0;
7663 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7664 $totalenabled = 0;
7665 foreach ($formats as $format) {
7666 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7667 $totalenabled++;
7670 foreach ($formats as $format) {
7671 $status = $format->get_status();
7672 $url = new moodle_url('/admin/dataformats.php',
7673 array('sesskey' => sesskey(), 'name' => $format->name));
7675 $class = '';
7676 if ($format->is_enabled()) {
7677 $strformatname = $format->displayname;
7678 if ($totalenabled == 1&& $format->is_enabled()) {
7679 $hideshow = '';
7680 } else {
7681 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7682 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7684 } else {
7685 $class = 'dimmed_text';
7686 $strformatname = $format->displayname;
7687 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7688 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7691 $updown = '';
7692 if ($cnt) {
7693 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7694 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7695 } else {
7696 $updown .= $spacer;
7698 if ($cnt < count($formats) - 1) {
7699 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7700 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7701 } else {
7702 $updown .= $spacer;
7705 $uninstall = '';
7706 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7707 $uninstall = get_string('status_missing', 'core_plugin');
7708 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7709 $uninstall = get_string('status_new', 'core_plugin');
7710 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7711 if ($totalenabled != 1 || !$format->is_enabled()) {
7712 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7716 $settings = '';
7717 if ($format->get_settings_url()) {
7718 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7721 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7722 if ($class) {
7723 $row->attributes['class'] = $class;
7725 $table->data[] = $row;
7726 $cnt++;
7728 $return .= html_writer::table($table);
7729 return highlight($query, $return);
7734 * Special class for filter administration.
7736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7738 class admin_page_managefilters extends admin_externalpage {
7740 * Calls parent::__construct with specific arguments
7742 public function __construct() {
7743 global $CFG;
7744 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7748 * Searches all installed filters for specified filter
7750 * @param string $query The filter(string) to search for
7751 * @param string $query
7753 public function search($query) {
7754 global $CFG;
7755 if ($result = parent::search($query)) {
7756 return $result;
7759 $found = false;
7760 $filternames = filter_get_all_installed();
7761 foreach ($filternames as $path => $strfiltername) {
7762 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7763 $found = true;
7764 break;
7766 if (strpos($path, $query) !== false) {
7767 $found = true;
7768 break;
7772 if ($found) {
7773 $result = new stdClass;
7774 $result->page = $this;
7775 $result->settings = array();
7776 return array($this->name => $result);
7777 } else {
7778 return array();
7784 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7785 * Requires a get_rank method on the plugininfo class for sorting.
7787 * @copyright 2017 Damyon Wiese
7788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7790 abstract class admin_setting_manage_plugins extends admin_setting {
7793 * Get the admin settings section name (just a unique string)
7795 * @return string
7797 public function get_section_name() {
7798 return 'manage' . $this->get_plugin_type() . 'plugins';
7802 * Get the admin settings section title (use get_string).
7804 * @return string
7806 abstract public function get_section_title();
7809 * Get the type of plugin to manage.
7811 * @return string
7813 abstract public function get_plugin_type();
7816 * Get the name of the second column.
7818 * @return string
7820 public function get_info_column_name() {
7821 return '';
7825 * Get the type of plugin to manage.
7827 * @param plugininfo The plugin info class.
7828 * @return string
7830 abstract public function get_info_column($plugininfo);
7833 * Calls parent::__construct with specific arguments
7835 public function __construct() {
7836 $this->nosave = true;
7837 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7841 * Always returns true, does nothing
7843 * @return true
7845 public function get_setting() {
7846 return true;
7850 * Always returns true, does nothing
7852 * @return true
7854 public function get_defaultsetting() {
7855 return true;
7859 * Always returns '', does not write anything
7861 * @param mixed $data
7862 * @return string Always returns ''
7864 public function write_setting($data) {
7865 // Do not write any setting.
7866 return '';
7870 * Checks if $query is one of the available plugins of this type
7872 * @param string $query The string to search for
7873 * @return bool Returns true if found, false if not
7875 public function is_related($query) {
7876 if (parent::is_related($query)) {
7877 return true;
7880 $query = core_text::strtolower($query);
7881 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7882 foreach ($plugins as $name => $plugin) {
7883 $localised = $plugin->displayname;
7884 if (strpos(core_text::strtolower($name), $query) !== false) {
7885 return true;
7887 if (strpos(core_text::strtolower($localised), $query) !== false) {
7888 return true;
7891 return false;
7895 * The URL for the management page for this plugintype.
7897 * @return moodle_url
7899 protected function get_manage_url() {
7900 return new moodle_url('/admin/updatesetting.php');
7904 * Builds the HTML to display the control.
7906 * @param string $data Unused
7907 * @param string $query
7908 * @return string
7910 public function output_html($data, $query = '') {
7911 global $CFG, $OUTPUT, $DB, $PAGE;
7913 $context = (object) [
7914 'manageurl' => new moodle_url($this->get_manage_url(), [
7915 'type' => $this->get_plugin_type(),
7916 'sesskey' => sesskey(),
7918 'infocolumnname' => $this->get_info_column_name(),
7919 'plugins' => [],
7922 $pluginmanager = core_plugin_manager::instance();
7923 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7924 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7925 $plugins = array_merge($enabled, $allplugins);
7926 foreach ($plugins as $key => $plugin) {
7927 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7929 $pluginkey = (object) [
7930 'plugin' => $plugin->displayname,
7931 'enabled' => $plugin->is_enabled(),
7932 'togglelink' => '',
7933 'moveuplink' => '',
7934 'movedownlink' => '',
7935 'settingslink' => $plugin->get_settings_url(),
7936 'uninstalllink' => '',
7937 'info' => '',
7940 // Enable/Disable link.
7941 $togglelink = new moodle_url($pluginlink);
7942 if ($plugin->is_enabled()) {
7943 $toggletarget = false;
7944 $togglelink->param('action', 'disable');
7946 if (count($context->plugins)) {
7947 // This is not the first plugin.
7948 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7951 if (count($enabled) > count($context->plugins) + 1) {
7952 // This is not the last plugin.
7953 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7956 $pluginkey->info = $this->get_info_column($plugin);
7957 } else {
7958 $toggletarget = true;
7959 $togglelink->param('action', 'enable');
7962 $pluginkey->toggletarget = $toggletarget;
7963 $pluginkey->togglelink = $togglelink;
7965 $frankenstyle = $plugin->type . '_' . $plugin->name;
7966 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
7967 // This plugin supports uninstallation.
7968 $pluginkey->uninstalllink = $uninstalllink;
7971 if (!empty($this->get_info_column_name())) {
7972 // This plugintype has an info column.
7973 $pluginkey->info = $this->get_info_column($plugin);
7976 $context->plugins[] = $pluginkey;
7979 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
7980 return highlight($query, $str);
7985 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7986 * Requires a get_rank method on the plugininfo class for sorting.
7988 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
7989 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7991 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
7992 public function get_section_title() {
7993 return get_string('type_fileconverter_plural', 'plugin');
7996 public function get_plugin_type() {
7997 return 'fileconverter';
8000 public function get_info_column_name() {
8001 return get_string('supportedconversions', 'plugin');
8004 public function get_info_column($plugininfo) {
8005 return $plugininfo->get_supported_conversions();
8010 * Special class for media player plugins management.
8012 * @copyright 2016 Marina Glancy
8013 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8015 class admin_setting_managemediaplayers extends admin_setting {
8017 * Calls parent::__construct with specific arguments
8019 public function __construct() {
8020 $this->nosave = true;
8021 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8025 * Always returns true, does nothing
8027 * @return true
8029 public function get_setting() {
8030 return true;
8034 * Always returns true, does nothing
8036 * @return true
8038 public function get_defaultsetting() {
8039 return true;
8043 * Always returns '', does not write anything
8045 * @param mixed $data
8046 * @return string Always returns ''
8048 public function write_setting($data) {
8049 // Do not write any setting.
8050 return '';
8054 * Checks if $query is one of the available enrol plugins
8056 * @param string $query The string to search for
8057 * @return bool Returns true if found, false if not
8059 public function is_related($query) {
8060 if (parent::is_related($query)) {
8061 return true;
8064 $query = core_text::strtolower($query);
8065 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8066 foreach ($plugins as $name => $plugin) {
8067 $localised = $plugin->displayname;
8068 if (strpos(core_text::strtolower($name), $query) !== false) {
8069 return true;
8071 if (strpos(core_text::strtolower($localised), $query) !== false) {
8072 return true;
8075 return false;
8079 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8080 * @return \core\plugininfo\media[]
8082 protected function get_sorted_plugins() {
8083 $pluginmanager = core_plugin_manager::instance();
8085 $plugins = $pluginmanager->get_plugins_of_type('media');
8086 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8088 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8089 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8091 $order = array_values($enabledplugins);
8092 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8094 $sortedplugins = array();
8095 foreach ($order as $name) {
8096 $sortedplugins[$name] = $plugins[$name];
8099 return $sortedplugins;
8103 * Builds the XHTML to display the control
8105 * @param string $data Unused
8106 * @param string $query
8107 * @return string
8109 public function output_html($data, $query='') {
8110 global $CFG, $OUTPUT, $DB, $PAGE;
8112 // Display strings.
8113 $strup = get_string('up');
8114 $strdown = get_string('down');
8115 $strsettings = get_string('settings');
8116 $strenable = get_string('enable');
8117 $strdisable = get_string('disable');
8118 $struninstall = get_string('uninstallplugin', 'core_admin');
8119 $strversion = get_string('version');
8120 $strname = get_string('name');
8121 $strsupports = get_string('supports', 'core_media');
8123 $pluginmanager = core_plugin_manager::instance();
8125 $plugins = $this->get_sorted_plugins();
8126 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8128 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8130 $table = new html_table();
8131 $table->head = array($strname, $strsupports, $strversion,
8132 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8133 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8134 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8135 $table->id = 'mediaplayerplugins';
8136 $table->attributes['class'] = 'admintable generaltable';
8137 $table->data = array();
8139 // Iterate through media plugins and add to the display table.
8140 $updowncount = 1;
8141 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8142 $printed = array();
8143 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8145 $usedextensions = [];
8146 foreach ($plugins as $name => $plugin) {
8147 $url->param('media', $name);
8148 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8149 $version = $plugininfo->versiondb;
8150 $supports = $plugininfo->supports($usedextensions);
8152 // Hide/show links.
8153 $class = '';
8154 if (!$plugininfo->is_installed_and_upgraded()) {
8155 $hideshow = '';
8156 $enabled = false;
8157 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8158 } else {
8159 $enabled = $plugininfo->is_enabled();
8160 if ($enabled) {
8161 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8162 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8163 } else {
8164 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8165 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8166 $class = 'dimmed_text';
8168 $displayname = $plugin->displayname;
8169 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8170 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8173 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8174 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8175 } else {
8176 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8179 // Up/down link (only if enrol is enabled).
8180 $updown = '';
8181 if ($enabled) {
8182 if ($updowncount > 1) {
8183 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8184 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8185 } else {
8186 $updown = $spacer;
8188 if ($updowncount < count($enabledplugins)) {
8189 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8190 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8191 } else {
8192 $updown .= $spacer;
8194 ++$updowncount;
8197 $uninstall = '';
8198 $status = $plugininfo->get_status();
8199 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8200 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8202 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8203 $uninstall = get_string('status_new', 'core_plugin');
8204 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8205 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8208 $settings = '';
8209 if ($plugininfo->get_settings_url()) {
8210 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8213 // Add a row to the table.
8214 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8215 if ($class) {
8216 $row->attributes['class'] = $class;
8218 $table->data[] = $row;
8220 $printed[$name] = true;
8223 $return .= html_writer::table($table);
8224 $return .= $OUTPUT->box_end();
8225 return highlight($query, $return);
8230 * Initialise admin page - this function does require login and permission
8231 * checks specified in page definition.
8233 * This function must be called on each admin page before other code.
8235 * @global moodle_page $PAGE
8237 * @param string $section name of page
8238 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8239 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8240 * added to the turn blocks editing on/off form, so this page reloads correctly.
8241 * @param string $actualurl if the actual page being viewed is not the normal one for this
8242 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8243 * @param array $options Additional options that can be specified for page setup.
8244 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8246 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8247 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8249 $PAGE->set_context(null); // hack - set context to something, by default to system context
8251 $site = get_site();
8252 require_login();
8254 if (!empty($options['pagelayout'])) {
8255 // A specific page layout has been requested.
8256 $PAGE->set_pagelayout($options['pagelayout']);
8257 } else if ($section === 'upgradesettings') {
8258 $PAGE->set_pagelayout('maintenance');
8259 } else {
8260 $PAGE->set_pagelayout('admin');
8263 $adminroot = admin_get_root(false, false); // settings not required for external pages
8264 $extpage = $adminroot->locate($section, true);
8266 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8267 // The requested section isn't in the admin tree
8268 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8269 if (!has_capability('moodle/site:config', context_system::instance())) {
8270 // The requested section could depend on a different capability
8271 // but most likely the user has inadequate capabilities
8272 print_error('accessdenied', 'admin');
8273 } else {
8274 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8278 // this eliminates our need to authenticate on the actual pages
8279 if (!$extpage->check_access()) {
8280 print_error('accessdenied', 'admin');
8281 die;
8284 navigation_node::require_admin_tree();
8286 // $PAGE->set_extra_button($extrabutton); TODO
8288 if (!$actualurl) {
8289 $actualurl = $extpage->url;
8292 $PAGE->set_url($actualurl, $extraurlparams);
8293 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8294 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8297 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8298 // During initial install.
8299 $strinstallation = get_string('installation', 'install');
8300 $strsettings = get_string('settings');
8301 $PAGE->navbar->add($strsettings);
8302 $PAGE->set_title($strinstallation);
8303 $PAGE->set_heading($strinstallation);
8304 $PAGE->set_cacheable(false);
8305 return;
8308 // Locate the current item on the navigation and make it active when found.
8309 $path = $extpage->path;
8310 $node = $PAGE->settingsnav;
8311 while ($node && count($path) > 0) {
8312 $node = $node->get(array_pop($path));
8314 if ($node) {
8315 $node->make_active();
8318 // Normal case.
8319 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8320 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8321 $USER->editing = $adminediting;
8324 $visiblepathtosection = array_reverse($extpage->visiblepath);
8326 if ($PAGE->user_allowed_editing()) {
8327 if ($PAGE->user_is_editing()) {
8328 $caption = get_string('blockseditoff');
8329 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8330 } else {
8331 $caption = get_string('blocksediton');
8332 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8334 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8337 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8338 $PAGE->set_heading($SITE->fullname);
8340 // prevent caching in nav block
8341 $PAGE->navigation->clear_cache();
8345 * Returns the reference to admin tree root
8347 * @return object admin_root object
8349 function admin_get_root($reload=false, $requirefulltree=true) {
8350 global $CFG, $DB, $OUTPUT, $ADMIN;
8352 if (is_null($ADMIN)) {
8353 // create the admin tree!
8354 $ADMIN = new admin_root($requirefulltree);
8357 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8358 $ADMIN->purge_children($requirefulltree);
8361 if (!$ADMIN->loaded) {
8362 // we process this file first to create categories first and in correct order
8363 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8365 // now we process all other files in admin/settings to build the admin tree
8366 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8367 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8368 continue;
8370 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8371 // plugins are loaded last - they may insert pages anywhere
8372 continue;
8374 require($file);
8376 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8378 $ADMIN->loaded = true;
8381 return $ADMIN;
8384 /// settings utility functions
8387 * This function applies default settings.
8388 * Because setting the defaults of some settings can enable other settings,
8389 * this function is called recursively until no more new settings are found.
8391 * @param object $node, NULL means complete tree, null by default
8392 * @param bool $unconditional if true overrides all values with defaults, true by default
8393 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8394 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8395 * @return array $settingsoutput The names and values of the changed settings
8397 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8399 if (is_null($node)) {
8400 core_plugin_manager::reset_caches();
8401 $node = admin_get_root(true, true);
8404 if ($node instanceof admin_category) {
8405 $entries = array_keys($node->children);
8406 foreach ($entries as $entry) {
8407 $settingsoutput = admin_apply_default_settings(
8408 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8412 } else if ($node instanceof admin_settingpage) {
8413 foreach ($node->settings as $setting) {
8414 if (!$unconditional and !is_null($setting->get_setting())) {
8415 // Do not override existing defaults.
8416 continue;
8418 $defaultsetting = $setting->get_defaultsetting();
8419 if (is_null($defaultsetting)) {
8420 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8421 continue;
8424 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8426 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8427 $admindefaultsettings[$settingname] = $settingname;
8428 $settingsoutput[$settingname] = $defaultsetting;
8430 // Set the default for this setting.
8431 $setting->write_setting($defaultsetting);
8432 $setting->write_setting_flags(null);
8433 } else {
8434 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8439 // Call this function recursively until all settings are processed.
8440 if (($node instanceof admin_root) && (!empty($admindefaultsettings))) {
8441 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8443 // Just in case somebody modifies the list of active plugins directly.
8444 core_plugin_manager::reset_caches();
8446 return $settingsoutput;
8450 * Store changed settings, this function updates the errors variable in $ADMIN
8452 * @param object $formdata from form
8453 * @return int number of changed settings
8455 function admin_write_settings($formdata) {
8456 global $CFG, $SITE, $DB;
8458 $olddbsessions = !empty($CFG->dbsessions);
8459 $formdata = (array)$formdata;
8461 $data = array();
8462 foreach ($formdata as $fullname=>$value) {
8463 if (strpos($fullname, 's_') !== 0) {
8464 continue; // not a config value
8466 $data[$fullname] = $value;
8469 $adminroot = admin_get_root();
8470 $settings = admin_find_write_settings($adminroot, $data);
8472 $count = 0;
8473 foreach ($settings as $fullname=>$setting) {
8474 /** @var $setting admin_setting */
8475 $original = $setting->get_setting();
8476 $error = $setting->write_setting($data[$fullname]);
8477 if ($error !== '') {
8478 $adminroot->errors[$fullname] = new stdClass();
8479 $adminroot->errors[$fullname]->data = $data[$fullname];
8480 $adminroot->errors[$fullname]->id = $setting->get_id();
8481 $adminroot->errors[$fullname]->error = $error;
8482 } else {
8483 $setting->write_setting_flags($data);
8485 if ($setting->post_write_settings($original)) {
8486 $count++;
8490 if ($olddbsessions != !empty($CFG->dbsessions)) {
8491 require_logout();
8494 // Now update $SITE - just update the fields, in case other people have a
8495 // a reference to it (e.g. $PAGE, $COURSE).
8496 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8497 foreach (get_object_vars($newsite) as $field => $value) {
8498 $SITE->$field = $value;
8501 // now reload all settings - some of them might depend on the changed
8502 admin_get_root(true);
8503 return $count;
8507 * Internal recursive function - finds all settings from submitted form
8509 * @param object $node Instance of admin_category, or admin_settingpage
8510 * @param array $data
8511 * @return array
8513 function admin_find_write_settings($node, $data) {
8514 $return = array();
8516 if (empty($data)) {
8517 return $return;
8520 if ($node instanceof admin_category) {
8521 if ($node->check_access()) {
8522 $entries = array_keys($node->children);
8523 foreach ($entries as $entry) {
8524 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8528 } else if ($node instanceof admin_settingpage) {
8529 if ($node->check_access()) {
8530 foreach ($node->settings as $setting) {
8531 $fullname = $setting->get_full_name();
8532 if (array_key_exists($fullname, $data)) {
8533 $return[$fullname] = $setting;
8540 return $return;
8544 * Internal function - prints the search results
8546 * @param string $query String to search for
8547 * @return string empty or XHTML
8549 function admin_search_settings_html($query) {
8550 global $CFG, $OUTPUT, $PAGE;
8552 if (core_text::strlen($query) < 2) {
8553 return '';
8555 $query = core_text::strtolower($query);
8557 $adminroot = admin_get_root();
8558 $findings = $adminroot->search($query);
8559 $savebutton = false;
8561 $tpldata = (object) [
8562 'actionurl' => $PAGE->url->out(false),
8563 'results' => [],
8564 'sesskey' => sesskey(),
8567 foreach ($findings as $found) {
8568 $page = $found->page;
8569 $settings = $found->settings;
8570 if ($page->is_hidden()) {
8571 // hidden pages are not displayed in search results
8572 continue;
8575 $heading = highlight($query, $page->visiblename);
8576 $headingurl = null;
8577 if ($page instanceof admin_externalpage) {
8578 $headingurl = new moodle_url($page->url);
8579 } else if ($page instanceof admin_settingpage) {
8580 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8581 } else {
8582 continue;
8585 // Locate the page in the admin root and populate its visiblepath attribute.
8586 $path = array();
8587 $located = $adminroot->locate($page->name, true);
8588 if ($located) {
8589 foreach ($located->visiblepath as $pathitem) {
8590 array_unshift($path, (string) $pathitem);
8594 $sectionsettings = [];
8595 if (!empty($settings)) {
8596 foreach ($settings as $setting) {
8597 if (empty($setting->nosave)) {
8598 $savebutton = true;
8600 $fullname = $setting->get_full_name();
8601 if (array_key_exists($fullname, $adminroot->errors)) {
8602 $data = $adminroot->errors[$fullname]->data;
8603 } else {
8604 $data = $setting->get_setting();
8605 $data = $setting->get_setting();
8606 // do not use defaults if settings not available - upgradesettings handles the defaults!
8608 $sectionsettings[] = $setting->output_html($data, $query);
8612 $tpldata->results[] = (object) [
8613 'title' => $heading,
8614 'path' => $path,
8615 'url' => $headingurl->out(false),
8616 'settings' => $sectionsettings
8620 $tpldata->showsave = $savebutton;
8621 $tpldata->hasresults = !empty($tpldata->results);
8623 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8627 * Internal function - returns arrays of html pages with uninitialised settings
8629 * @param object $node Instance of admin_category or admin_settingpage
8630 * @return array
8632 function admin_output_new_settings_by_page($node) {
8633 global $OUTPUT;
8634 $return = array();
8636 if ($node instanceof admin_category) {
8637 $entries = array_keys($node->children);
8638 foreach ($entries as $entry) {
8639 $return += admin_output_new_settings_by_page($node->children[$entry]);
8642 } else if ($node instanceof admin_settingpage) {
8643 $newsettings = array();
8644 foreach ($node->settings as $setting) {
8645 if (is_null($setting->get_setting())) {
8646 $newsettings[] = $setting;
8649 if (count($newsettings) > 0) {
8650 $adminroot = admin_get_root();
8651 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8652 $page .= '<fieldset class="adminsettings">'."\n";
8653 foreach ($newsettings as $setting) {
8654 $fullname = $setting->get_full_name();
8655 if (array_key_exists($fullname, $adminroot->errors)) {
8656 $data = $adminroot->errors[$fullname]->data;
8657 } else {
8658 $data = $setting->get_setting();
8659 if (is_null($data)) {
8660 $data = $setting->get_defaultsetting();
8663 $page .= '<div class="clearer"><!-- --></div>'."\n";
8664 $page .= $setting->output_html($data);
8666 $page .= '</fieldset>';
8667 $return[$node->name] = $page;
8671 return $return;
8675 * Format admin settings
8677 * @param object $setting
8678 * @param string $title label element
8679 * @param string $form form fragment, html code - not highlighted automatically
8680 * @param string $description
8681 * @param mixed $label link label to id, true by default or string being the label to connect it to
8682 * @param string $warning warning text
8683 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8684 * @param string $query search query to be highlighted
8685 * @return string XHTML
8687 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8688 global $CFG, $OUTPUT;
8690 $context = (object) [
8691 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8692 'fullname' => $setting->get_full_name(),
8695 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8696 if ($label === true) {
8697 $context->labelfor = $setting->get_id();
8698 } else if ($label === false) {
8699 $context->labelfor = '';
8700 } else {
8701 $context->labelfor = $label;
8704 $form .= $setting->output_setting_flags();
8706 $context->warning = $warning;
8707 $context->override = '';
8708 if (empty($setting->plugin)) {
8709 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8710 $context->override = get_string('configoverride', 'admin');
8712 } else {
8713 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8714 $context->override = get_string('configoverride', 'admin');
8718 $defaults = array();
8719 if (!is_null($defaultinfo)) {
8720 if ($defaultinfo === '') {
8721 $defaultinfo = get_string('emptysettingvalue', 'admin');
8723 $defaults[] = $defaultinfo;
8726 $context->default = null;
8727 $setting->get_setting_flag_defaults($defaults);
8728 if (!empty($defaults)) {
8729 $defaultinfo = implode(', ', $defaults);
8730 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8731 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8735 $context->error = '';
8736 $adminroot = admin_get_root();
8737 if (array_key_exists($context->fullname, $adminroot->errors)) {
8738 $context->error = $adminroot->errors[$context->fullname]->error;
8741 if ($dependenton = $setting->get_dependent_on()) {
8742 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
8745 $context->id = 'admin-' . $setting->name;
8746 $context->title = highlightfast($query, $title);
8747 $context->name = highlightfast($query, $context->name);
8748 $context->description = highlight($query, markdown_to_html($description));
8749 $context->element = $form;
8750 $context->forceltr = $setting->get_force_ltr();
8752 return $OUTPUT->render_from_template('core_admin/setting', $context);
8756 * Based on find_new_settings{@link ()} in upgradesettings.php
8757 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8759 * @param object $node Instance of admin_category, or admin_settingpage
8760 * @return boolean true if any settings haven't been initialised, false if they all have
8762 function any_new_admin_settings($node) {
8764 if ($node instanceof admin_category) {
8765 $entries = array_keys($node->children);
8766 foreach ($entries as $entry) {
8767 if (any_new_admin_settings($node->children[$entry])) {
8768 return true;
8772 } else if ($node instanceof admin_settingpage) {
8773 foreach ($node->settings as $setting) {
8774 if ($setting->get_setting() === NULL) {
8775 return true;
8780 return false;
8784 * Moved from admin/replace.php so that we can use this in cron
8786 * @param string $search string to look for
8787 * @param string $replace string to replace
8788 * @return bool success or fail
8790 function db_replace($search, $replace) {
8791 global $DB, $CFG, $OUTPUT;
8793 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8794 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
8795 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
8796 'block_instances', '');
8798 // Turn off time limits, sometimes upgrades can be slow.
8799 core_php_time_limit::raise();
8801 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
8802 return false;
8804 foreach ($tables as $table) {
8806 if (in_array($table, $skiptables)) { // Don't process these
8807 continue;
8810 if ($columns = $DB->get_columns($table)) {
8811 $DB->set_debug(true);
8812 foreach ($columns as $column) {
8813 $DB->replace_all_text($table, $column, $search, $replace);
8815 $DB->set_debug(false);
8819 // delete modinfo caches
8820 rebuild_course_cache(0, true);
8822 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
8823 $blocks = core_component::get_plugin_list('block');
8824 foreach ($blocks as $blockname=>$fullblock) {
8825 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8826 continue;
8829 if (!is_readable($fullblock.'/lib.php')) {
8830 continue;
8833 $function = 'block_'.$blockname.'_global_db_replace';
8834 include_once($fullblock.'/lib.php');
8835 if (!function_exists($function)) {
8836 continue;
8839 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
8840 $function($search, $replace);
8841 echo $OUTPUT->notification("...finished", 'notifysuccess');
8844 purge_all_caches();
8846 return true;
8850 * Manage repository settings
8852 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8854 class admin_setting_managerepository extends admin_setting {
8855 /** @var string */
8856 private $baseurl;
8859 * calls parent::__construct with specific arguments
8861 public function __construct() {
8862 global $CFG;
8863 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
8864 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
8868 * Always returns true, does nothing
8870 * @return true
8872 public function get_setting() {
8873 return true;
8877 * Always returns true does nothing
8879 * @return true
8881 public function get_defaultsetting() {
8882 return true;
8886 * Always returns s_managerepository
8888 * @return string Always return 's_managerepository'
8890 public function get_full_name() {
8891 return 's_managerepository';
8895 * Always returns '' doesn't do anything
8897 public function write_setting($data) {
8898 $url = $this->baseurl . '&amp;new=' . $data;
8899 return '';
8900 // TODO
8901 // Should not use redirect and exit here
8902 // Find a better way to do this.
8903 // redirect($url);
8904 // exit;
8908 * Searches repository plugins for one that matches $query
8910 * @param string $query The string to search for
8911 * @return bool true if found, false if not
8913 public function is_related($query) {
8914 if (parent::is_related($query)) {
8915 return true;
8918 $repositories= core_component::get_plugin_list('repository');
8919 foreach ($repositories as $p => $dir) {
8920 if (strpos($p, $query) !== false) {
8921 return true;
8924 foreach (repository::get_types() as $instance) {
8925 $title = $instance->get_typename();
8926 if (strpos(core_text::strtolower($title), $query) !== false) {
8927 return true;
8930 return false;
8934 * Helper function that generates a moodle_url object
8935 * relevant to the repository
8938 function repository_action_url($repository) {
8939 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
8943 * Builds XHTML to display the control
8945 * @param string $data Unused
8946 * @param string $query
8947 * @return string XHTML
8949 public function output_html($data, $query='') {
8950 global $CFG, $USER, $OUTPUT;
8952 // Get strings that are used
8953 $strshow = get_string('on', 'repository');
8954 $strhide = get_string('off', 'repository');
8955 $strdelete = get_string('disabled', 'repository');
8957 $actionchoicesforexisting = array(
8958 'show' => $strshow,
8959 'hide' => $strhide,
8960 'delete' => $strdelete
8963 $actionchoicesfornew = array(
8964 'newon' => $strshow,
8965 'newoff' => $strhide,
8966 'delete' => $strdelete
8969 $return = '';
8970 $return .= $OUTPUT->box_start('generalbox');
8972 // Set strings that are used multiple times
8973 $settingsstr = get_string('settings');
8974 $disablestr = get_string('disable');
8976 // Table to list plug-ins
8977 $table = new html_table();
8978 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
8979 $table->align = array('left', 'center', 'center', 'center', 'center');
8980 $table->data = array();
8982 // Get list of used plug-ins
8983 $repositorytypes = repository::get_types();
8984 if (!empty($repositorytypes)) {
8985 // Array to store plugins being used
8986 $alreadyplugins = array();
8987 $totalrepositorytypes = count($repositorytypes);
8988 $updowncount = 1;
8989 foreach ($repositorytypes as $i) {
8990 $settings = '';
8991 $typename = $i->get_typename();
8992 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
8993 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
8994 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
8996 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
8997 // Calculate number of instances in order to display them for the Moodle administrator
8998 if (!empty($instanceoptionnames)) {
8999 $params = array();
9000 $params['context'] = array(context_system::instance());
9001 $params['onlyvisible'] = false;
9002 $params['type'] = $typename;
9003 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9004 // site instances
9005 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9006 $params['context'] = array();
9007 $instances = repository::static_function($typename, 'get_instances', $params);
9008 $courseinstances = array();
9009 $userinstances = array();
9011 foreach ($instances as $instance) {
9012 $repocontext = context::instance_by_id($instance->instance->contextid);
9013 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9014 $courseinstances[] = $instance;
9015 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9016 $userinstances[] = $instance;
9019 // course instances
9020 $instancenumber = count($courseinstances);
9021 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9023 // user private instances
9024 $instancenumber = count($userinstances);
9025 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9026 } else {
9027 $admininstancenumbertext = "";
9028 $courseinstancenumbertext = "";
9029 $userinstancenumbertext = "";
9032 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9034 $settings .= $OUTPUT->container_start('mdl-left');
9035 $settings .= '<br/>';
9036 $settings .= $admininstancenumbertext;
9037 $settings .= '<br/>';
9038 $settings .= $courseinstancenumbertext;
9039 $settings .= '<br/>';
9040 $settings .= $userinstancenumbertext;
9041 $settings .= $OUTPUT->container_end();
9043 // Get the current visibility
9044 if ($i->get_visible()) {
9045 $currentaction = 'show';
9046 } else {
9047 $currentaction = 'hide';
9050 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9052 // Display up/down link
9053 $updown = '';
9054 // Should be done with CSS instead.
9055 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9057 if ($updowncount > 1) {
9058 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9059 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9061 else {
9062 $updown .= $spacer;
9064 if ($updowncount < $totalrepositorytypes) {
9065 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9066 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9068 else {
9069 $updown .= $spacer;
9072 $updowncount++;
9074 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9076 if (!in_array($typename, $alreadyplugins)) {
9077 $alreadyplugins[] = $typename;
9082 // Get all the plugins that exist on disk
9083 $plugins = core_component::get_plugin_list('repository');
9084 if (!empty($plugins)) {
9085 foreach ($plugins as $plugin => $dir) {
9086 // Check that it has not already been listed
9087 if (!in_array($plugin, $alreadyplugins)) {
9088 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9089 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9094 $return .= html_writer::table($table);
9095 $return .= $OUTPUT->box_end();
9096 return highlight($query, $return);
9101 * Special checkbox for enable mobile web service
9102 * If enable then we store the service id of the mobile service into config table
9103 * If disable then we unstore the service id from the config table
9105 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9107 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9108 private $restuse;
9111 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9113 * @return boolean
9115 private function is_protocol_cap_allowed() {
9116 global $DB, $CFG;
9118 // If the $this->restuse variable is not set, it needs to be set.
9119 if (empty($this->restuse) and $this->restuse!==false) {
9120 $params = array();
9121 $params['permission'] = CAP_ALLOW;
9122 $params['roleid'] = $CFG->defaultuserroleid;
9123 $params['capability'] = 'webservice/rest:use';
9124 $this->restuse = $DB->record_exists('role_capabilities', $params);
9127 return $this->restuse;
9131 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9132 * @param type $status true to allow, false to not set
9134 private function set_protocol_cap($status) {
9135 global $CFG;
9136 if ($status and !$this->is_protocol_cap_allowed()) {
9137 //need to allow the cap
9138 $permission = CAP_ALLOW;
9139 $assign = true;
9140 } else if (!$status and $this->is_protocol_cap_allowed()){
9141 //need to disallow the cap
9142 $permission = CAP_INHERIT;
9143 $assign = true;
9145 if (!empty($assign)) {
9146 $systemcontext = context_system::instance();
9147 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9152 * Builds XHTML to display the control.
9153 * The main purpose of this overloading is to display a warning when https
9154 * is not supported by the server
9155 * @param string $data Unused
9156 * @param string $query
9157 * @return string XHTML
9159 public function output_html($data, $query='') {
9160 global $OUTPUT;
9161 $html = parent::output_html($data, $query);
9163 if ((string)$data === $this->yes) {
9164 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9165 foreach ($notifications as $notification) {
9166 $message = get_string($notification[0], $notification[1]);
9167 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9171 return $html;
9175 * Retrieves the current setting using the objects name
9177 * @return string
9179 public function get_setting() {
9180 global $CFG;
9182 // First check if is not set.
9183 $result = $this->config_read($this->name);
9184 if (is_null($result)) {
9185 return null;
9188 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9189 // Or if web services aren't enabled this can't be,
9190 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9191 return 0;
9194 require_once($CFG->dirroot . '/webservice/lib.php');
9195 $webservicemanager = new webservice();
9196 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9197 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9198 return $result;
9199 } else {
9200 return 0;
9205 * Save the selected setting
9207 * @param string $data The selected site
9208 * @return string empty string or error message
9210 public function write_setting($data) {
9211 global $DB, $CFG;
9213 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9214 if (empty($CFG->defaultuserroleid)) {
9215 return '';
9218 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9220 require_once($CFG->dirroot . '/webservice/lib.php');
9221 $webservicemanager = new webservice();
9223 $updateprotocol = false;
9224 if ((string)$data === $this->yes) {
9225 //code run when enable mobile web service
9226 //enable web service systeme if necessary
9227 set_config('enablewebservices', true);
9229 //enable mobile service
9230 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9231 $mobileservice->enabled = 1;
9232 $webservicemanager->update_external_service($mobileservice);
9234 // Enable REST server.
9235 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9237 if (!in_array('rest', $activeprotocols)) {
9238 $activeprotocols[] = 'rest';
9239 $updateprotocol = true;
9242 if ($updateprotocol) {
9243 set_config('webserviceprotocols', implode(',', $activeprotocols));
9246 // Allow rest:use capability for authenticated user.
9247 $this->set_protocol_cap(true);
9249 } else {
9250 //disable web service system if no other services are enabled
9251 $otherenabledservices = $DB->get_records_select('external_services',
9252 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
9253 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
9254 if (empty($otherenabledservices)) {
9255 set_config('enablewebservices', false);
9257 // Also disable REST server.
9258 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9260 $protocolkey = array_search('rest', $activeprotocols);
9261 if ($protocolkey !== false) {
9262 unset($activeprotocols[$protocolkey]);
9263 $updateprotocol = true;
9266 if ($updateprotocol) {
9267 set_config('webserviceprotocols', implode(',', $activeprotocols));
9270 // Disallow rest:use capability for authenticated user.
9271 $this->set_protocol_cap(false);
9274 //disable the mobile service
9275 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9276 $mobileservice->enabled = 0;
9277 $webservicemanager->update_external_service($mobileservice);
9280 return (parent::write_setting($data));
9285 * Special class for management of external services
9287 * @author Petr Skoda (skodak)
9289 class admin_setting_manageexternalservices extends admin_setting {
9291 * Calls parent::__construct with specific arguments
9293 public function __construct() {
9294 $this->nosave = true;
9295 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9299 * Always returns true, does nothing
9301 * @return true
9303 public function get_setting() {
9304 return true;
9308 * Always returns true, does nothing
9310 * @return true
9312 public function get_defaultsetting() {
9313 return true;
9317 * Always returns '', does not write anything
9319 * @return string Always returns ''
9321 public function write_setting($data) {
9322 // do not write any setting
9323 return '';
9327 * Checks if $query is one of the available external services
9329 * @param string $query The string to search for
9330 * @return bool Returns true if found, false if not
9332 public function is_related($query) {
9333 global $DB;
9335 if (parent::is_related($query)) {
9336 return true;
9339 $services = $DB->get_records('external_services', array(), 'id, name');
9340 foreach ($services as $service) {
9341 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9342 return true;
9345 return false;
9349 * Builds the XHTML to display the control
9351 * @param string $data Unused
9352 * @param string $query
9353 * @return string
9355 public function output_html($data, $query='') {
9356 global $CFG, $OUTPUT, $DB;
9358 // display strings
9359 $stradministration = get_string('administration');
9360 $stredit = get_string('edit');
9361 $strservice = get_string('externalservice', 'webservice');
9362 $strdelete = get_string('delete');
9363 $strplugin = get_string('plugin', 'admin');
9364 $stradd = get_string('add');
9365 $strfunctions = get_string('functions', 'webservice');
9366 $strusers = get_string('users');
9367 $strserviceusers = get_string('serviceusers', 'webservice');
9369 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9370 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9371 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9373 // built in services
9374 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9375 $return = "";
9376 if (!empty($services)) {
9377 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9381 $table = new html_table();
9382 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9383 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9384 $table->id = 'builtinservices';
9385 $table->attributes['class'] = 'admintable externalservices generaltable';
9386 $table->data = array();
9388 // iterate through auth plugins and add to the display table
9389 foreach ($services as $service) {
9390 $name = $service->name;
9392 // hide/show link
9393 if ($service->enabled) {
9394 $displayname = "<span>$name</span>";
9395 } else {
9396 $displayname = "<span class=\"dimmed_text\">$name</span>";
9399 $plugin = $service->component;
9401 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9403 if ($service->restrictedusers) {
9404 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9405 } else {
9406 $users = get_string('allusers', 'webservice');
9409 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9411 // add a row to the table
9412 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9414 $return .= html_writer::table($table);
9417 // Custom services
9418 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9419 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9421 $table = new html_table();
9422 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9423 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9424 $table->id = 'customservices';
9425 $table->attributes['class'] = 'admintable externalservices generaltable';
9426 $table->data = array();
9428 // iterate through auth plugins and add to the display table
9429 foreach ($services as $service) {
9430 $name = $service->name;
9432 // hide/show link
9433 if ($service->enabled) {
9434 $displayname = "<span>$name</span>";
9435 } else {
9436 $displayname = "<span class=\"dimmed_text\">$name</span>";
9439 // delete link
9440 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9442 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9444 if ($service->restrictedusers) {
9445 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9446 } else {
9447 $users = get_string('allusers', 'webservice');
9450 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9452 // add a row to the table
9453 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9455 // add new custom service option
9456 $return .= html_writer::table($table);
9458 $return .= '<br />';
9459 // add a token to the table
9460 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9462 return highlight($query, $return);
9467 * Special class for overview of external services
9469 * @author Jerome Mouneyrac
9471 class admin_setting_webservicesoverview extends admin_setting {
9474 * Calls parent::__construct with specific arguments
9476 public function __construct() {
9477 $this->nosave = true;
9478 parent::__construct('webservicesoverviewui',
9479 get_string('webservicesoverview', 'webservice'), '', '');
9483 * Always returns true, does nothing
9485 * @return true
9487 public function get_setting() {
9488 return true;
9492 * Always returns true, does nothing
9494 * @return true
9496 public function get_defaultsetting() {
9497 return true;
9501 * Always returns '', does not write anything
9503 * @return string Always returns ''
9505 public function write_setting($data) {
9506 // do not write any setting
9507 return '';
9511 * Builds the XHTML to display the control
9513 * @param string $data Unused
9514 * @param string $query
9515 * @return string
9517 public function output_html($data, $query='') {
9518 global $CFG, $OUTPUT;
9520 $return = "";
9521 $brtag = html_writer::empty_tag('br');
9523 /// One system controlling Moodle with Token
9524 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9525 $table = new html_table();
9526 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9527 get_string('description'));
9528 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9529 $table->id = 'onesystemcontrol';
9530 $table->attributes['class'] = 'admintable wsoverview generaltable';
9531 $table->data = array();
9533 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9534 . $brtag . $brtag;
9536 /// 1. Enable Web Services
9537 $row = array();
9538 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9539 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9540 array('href' => $url));
9541 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9542 if ($CFG->enablewebservices) {
9543 $status = get_string('yes');
9545 $row[1] = $status;
9546 $row[2] = get_string('enablewsdescription', 'webservice');
9547 $table->data[] = $row;
9549 /// 2. Enable protocols
9550 $row = array();
9551 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9552 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9553 array('href' => $url));
9554 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9555 //retrieve activated protocol
9556 $active_protocols = empty($CFG->webserviceprotocols) ?
9557 array() : explode(',', $CFG->webserviceprotocols);
9558 if (!empty($active_protocols)) {
9559 $status = "";
9560 foreach ($active_protocols as $protocol) {
9561 $status .= $protocol . $brtag;
9564 $row[1] = $status;
9565 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9566 $table->data[] = $row;
9568 /// 3. Create user account
9569 $row = array();
9570 $url = new moodle_url("/user/editadvanced.php?id=-1");
9571 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9572 array('href' => $url));
9573 $row[1] = "";
9574 $row[2] = get_string('createuserdescription', 'webservice');
9575 $table->data[] = $row;
9577 /// 4. Add capability to users
9578 $row = array();
9579 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9580 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9581 array('href' => $url));
9582 $row[1] = "";
9583 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9584 $table->data[] = $row;
9586 /// 5. Select a web service
9587 $row = array();
9588 $url = new moodle_url("/admin/settings.php?section=externalservices");
9589 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9590 array('href' => $url));
9591 $row[1] = "";
9592 $row[2] = get_string('createservicedescription', 'webservice');
9593 $table->data[] = $row;
9595 /// 6. Add functions
9596 $row = array();
9597 $url = new moodle_url("/admin/settings.php?section=externalservices");
9598 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9599 array('href' => $url));
9600 $row[1] = "";
9601 $row[2] = get_string('addfunctionsdescription', 'webservice');
9602 $table->data[] = $row;
9604 /// 7. Add the specific user
9605 $row = array();
9606 $url = new moodle_url("/admin/settings.php?section=externalservices");
9607 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9608 array('href' => $url));
9609 $row[1] = "";
9610 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9611 $table->data[] = $row;
9613 /// 8. Create token for the specific user
9614 $row = array();
9615 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9616 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9617 array('href' => $url));
9618 $row[1] = "";
9619 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9620 $table->data[] = $row;
9622 /// 9. Enable the documentation
9623 $row = array();
9624 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9625 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9626 array('href' => $url));
9627 $status = '<span class="warning">' . get_string('no') . '</span>';
9628 if ($CFG->enablewsdocumentation) {
9629 $status = get_string('yes');
9631 $row[1] = $status;
9632 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9633 $table->data[] = $row;
9635 /// 10. Test the service
9636 $row = array();
9637 $url = new moodle_url("/admin/webservice/testclient.php");
9638 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9639 array('href' => $url));
9640 $row[1] = "";
9641 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9642 $table->data[] = $row;
9644 $return .= html_writer::table($table);
9646 /// Users as clients with token
9647 $return .= $brtag . $brtag . $brtag;
9648 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9649 $table = new html_table();
9650 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9651 get_string('description'));
9652 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9653 $table->id = 'userasclients';
9654 $table->attributes['class'] = 'admintable wsoverview generaltable';
9655 $table->data = array();
9657 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9658 $brtag . $brtag;
9660 /// 1. Enable Web Services
9661 $row = array();
9662 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9663 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9664 array('href' => $url));
9665 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9666 if ($CFG->enablewebservices) {
9667 $status = get_string('yes');
9669 $row[1] = $status;
9670 $row[2] = get_string('enablewsdescription', 'webservice');
9671 $table->data[] = $row;
9673 /// 2. Enable protocols
9674 $row = array();
9675 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9676 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9677 array('href' => $url));
9678 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9679 //retrieve activated protocol
9680 $active_protocols = empty($CFG->webserviceprotocols) ?
9681 array() : explode(',', $CFG->webserviceprotocols);
9682 if (!empty($active_protocols)) {
9683 $status = "";
9684 foreach ($active_protocols as $protocol) {
9685 $status .= $protocol . $brtag;
9688 $row[1] = $status;
9689 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9690 $table->data[] = $row;
9693 /// 3. Select a web service
9694 $row = array();
9695 $url = new moodle_url("/admin/settings.php?section=externalservices");
9696 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9697 array('href' => $url));
9698 $row[1] = "";
9699 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9700 $table->data[] = $row;
9702 /// 4. Add functions
9703 $row = array();
9704 $url = new moodle_url("/admin/settings.php?section=externalservices");
9705 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9706 array('href' => $url));
9707 $row[1] = "";
9708 $row[2] = get_string('addfunctionsdescription', 'webservice');
9709 $table->data[] = $row;
9711 /// 5. Add capability to users
9712 $row = array();
9713 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9714 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9715 array('href' => $url));
9716 $row[1] = "";
9717 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9718 $table->data[] = $row;
9720 /// 6. Test the service
9721 $row = array();
9722 $url = new moodle_url("/admin/webservice/testclient.php");
9723 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9724 array('href' => $url));
9725 $row[1] = "";
9726 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9727 $table->data[] = $row;
9729 $return .= html_writer::table($table);
9731 return highlight($query, $return);
9738 * Special class for web service protocol administration.
9740 * @author Petr Skoda (skodak)
9742 class admin_setting_managewebserviceprotocols extends admin_setting {
9745 * Calls parent::__construct with specific arguments
9747 public function __construct() {
9748 $this->nosave = true;
9749 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9753 * Always returns true, does nothing
9755 * @return true
9757 public function get_setting() {
9758 return true;
9762 * Always returns true, does nothing
9764 * @return true
9766 public function get_defaultsetting() {
9767 return true;
9771 * Always returns '', does not write anything
9773 * @return string Always returns ''
9775 public function write_setting($data) {
9776 // do not write any setting
9777 return '';
9781 * Checks if $query is one of the available webservices
9783 * @param string $query The string to search for
9784 * @return bool Returns true if found, false if not
9786 public function is_related($query) {
9787 if (parent::is_related($query)) {
9788 return true;
9791 $protocols = core_component::get_plugin_list('webservice');
9792 foreach ($protocols as $protocol=>$location) {
9793 if (strpos($protocol, $query) !== false) {
9794 return true;
9796 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
9797 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
9798 return true;
9801 return false;
9805 * Builds the XHTML to display the control
9807 * @param string $data Unused
9808 * @param string $query
9809 * @return string
9811 public function output_html($data, $query='') {
9812 global $CFG, $OUTPUT;
9814 // display strings
9815 $stradministration = get_string('administration');
9816 $strsettings = get_string('settings');
9817 $stredit = get_string('edit');
9818 $strprotocol = get_string('protocol', 'webservice');
9819 $strenable = get_string('enable');
9820 $strdisable = get_string('disable');
9821 $strversion = get_string('version');
9823 $protocols_available = core_component::get_plugin_list('webservice');
9824 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9825 ksort($protocols_available);
9827 foreach ($active_protocols as $key=>$protocol) {
9828 if (empty($protocols_available[$protocol])) {
9829 unset($active_protocols[$key]);
9833 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
9834 $return .= $OUTPUT->box_start('generalbox webservicesui');
9836 $table = new html_table();
9837 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
9838 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
9839 $table->id = 'webserviceprotocols';
9840 $table->attributes['class'] = 'admintable generaltable';
9841 $table->data = array();
9843 // iterate through auth plugins and add to the display table
9844 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
9845 foreach ($protocols_available as $protocol => $location) {
9846 $name = get_string('pluginname', 'webservice_'.$protocol);
9848 $plugin = new stdClass();
9849 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
9850 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
9852 $version = isset($plugin->version) ? $plugin->version : '';
9854 // hide/show link
9855 if (in_array($protocol, $active_protocols)) {
9856 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
9857 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
9858 $displayname = "<span>$name</span>";
9859 } else {
9860 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
9861 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
9862 $displayname = "<span class=\"dimmed_text\">$name</span>";
9865 // settings link
9866 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
9867 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
9868 } else {
9869 $settings = '';
9872 // add a row to the table
9873 $table->data[] = array($displayname, $version, $hideshow, $settings);
9875 $return .= html_writer::table($table);
9876 $return .= get_string('configwebserviceplugins', 'webservice');
9877 $return .= $OUTPUT->box_end();
9879 return highlight($query, $return);
9885 * Special class for web service token administration.
9887 * @author Jerome Mouneyrac
9889 class admin_setting_managewebservicetokens extends admin_setting {
9892 * Calls parent::__construct with specific arguments
9894 public function __construct() {
9895 $this->nosave = true;
9896 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
9900 * Always returns true, does nothing
9902 * @return true
9904 public function get_setting() {
9905 return true;
9909 * Always returns true, does nothing
9911 * @return true
9913 public function get_defaultsetting() {
9914 return true;
9918 * Always returns '', does not write anything
9920 * @return string Always returns ''
9922 public function write_setting($data) {
9923 // do not write any setting
9924 return '';
9928 * Builds the XHTML to display the control
9930 * @param string $data Unused
9931 * @param string $query
9932 * @return string
9934 public function output_html($data, $query='') {
9935 global $CFG, $OUTPUT;
9937 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
9938 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
9940 $return = $OUTPUT->box_start('generalbox webservicestokenui');
9942 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
9943 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
9946 $table = new \webservice\token_table('webservicetokens');
9947 $table->define_baseurl($baseurl);
9948 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
9949 $table->data = array();
9950 ob_start();
9951 $table->out(10, false);
9952 $tablehtml = ob_get_contents();
9953 ob_end_clean();
9954 $return .= $tablehtml;
9956 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
9958 $return .= $OUTPUT->box_end();
9959 // add a token to the table
9960 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
9961 $return .= get_string('add')."</a>";
9963 return highlight($query, $return);
9969 * Colour picker
9971 * @copyright 2010 Sam Hemelryk
9972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9974 class admin_setting_configcolourpicker extends admin_setting {
9977 * Information for previewing the colour
9979 * @var array|null
9981 protected $previewconfig = null;
9984 * Use default when empty.
9986 protected $usedefaultwhenempty = true;
9990 * @param string $name
9991 * @param string $visiblename
9992 * @param string $description
9993 * @param string $defaultsetting
9994 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
9996 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
9997 $usedefaultwhenempty = true) {
9998 $this->previewconfig = $previewconfig;
9999 $this->usedefaultwhenempty = $usedefaultwhenempty;
10000 parent::__construct($name, $visiblename, $description, $defaultsetting);
10001 $this->set_force_ltr(true);
10005 * Return the setting
10007 * @return mixed returns config if successful else null
10009 public function get_setting() {
10010 return $this->config_read($this->name);
10014 * Saves the setting
10016 * @param string $data
10017 * @return bool
10019 public function write_setting($data) {
10020 $data = $this->validate($data);
10021 if ($data === false) {
10022 return get_string('validateerror', 'admin');
10024 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10028 * Validates the colour that was entered by the user
10030 * @param string $data
10031 * @return string|false
10033 protected function validate($data) {
10035 * List of valid HTML colour names
10037 * @var array
10039 $colornames = array(
10040 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10041 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10042 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10043 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10044 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10045 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10046 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10047 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10048 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10049 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10050 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10051 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10052 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10053 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10054 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10055 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10056 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10057 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10058 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10059 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10060 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10061 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10062 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10063 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10064 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10065 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10066 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10067 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10068 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10069 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10070 'whitesmoke', 'yellow', 'yellowgreen'
10073 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10074 if (strpos($data, '#')!==0) {
10075 $data = '#'.$data;
10077 return $data;
10078 } else if (in_array(strtolower($data), $colornames)) {
10079 return $data;
10080 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10081 return $data;
10082 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10083 return $data;
10084 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10085 return $data;
10086 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10087 return $data;
10088 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10089 return $data;
10090 } else if (empty($data)) {
10091 if ($this->usedefaultwhenempty){
10092 return $this->defaultsetting;
10093 } else {
10094 return '';
10096 } else {
10097 return false;
10102 * Generates the HTML for the setting
10104 * @global moodle_page $PAGE
10105 * @global core_renderer $OUTPUT
10106 * @param string $data
10107 * @param string $query
10109 public function output_html($data, $query = '') {
10110 global $PAGE, $OUTPUT;
10112 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10113 $context = (object) [
10114 'id' => $this->get_id(),
10115 'name' => $this->get_full_name(),
10116 'value' => $data,
10117 'icon' => $icon->export_for_template($OUTPUT),
10118 'haspreviewconfig' => !empty($this->previewconfig),
10119 'forceltr' => $this->get_force_ltr()
10122 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10123 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10125 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10126 $this->get_defaultsetting(), $query);
10133 * Class used for uploading of one file into file storage,
10134 * the file name is stored in config table.
10136 * Please note you need to implement your own '_pluginfile' callback function,
10137 * this setting only stores the file, it does not deal with file serving.
10139 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10142 class admin_setting_configstoredfile extends admin_setting {
10143 /** @var array file area options - should be one file only */
10144 protected $options;
10145 /** @var string name of the file area */
10146 protected $filearea;
10147 /** @var int intemid */
10148 protected $itemid;
10149 /** @var string used for detection of changes */
10150 protected $oldhashes;
10153 * Create new stored file setting.
10155 * @param string $name low level setting name
10156 * @param string $visiblename human readable setting name
10157 * @param string $description description of setting
10158 * @param mixed $filearea file area for file storage
10159 * @param int $itemid itemid for file storage
10160 * @param array $options file area options
10162 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10163 parent::__construct($name, $visiblename, $description, '');
10164 $this->filearea = $filearea;
10165 $this->itemid = $itemid;
10166 $this->options = (array)$options;
10170 * Applies defaults and returns all options.
10171 * @return array
10173 protected function get_options() {
10174 global $CFG;
10176 require_once("$CFG->libdir/filelib.php");
10177 require_once("$CFG->dirroot/repository/lib.php");
10178 $defaults = array(
10179 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10180 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10181 'context' => context_system::instance());
10182 foreach($this->options as $k => $v) {
10183 $defaults[$k] = $v;
10186 return $defaults;
10189 public function get_setting() {
10190 return $this->config_read($this->name);
10193 public function write_setting($data) {
10194 global $USER;
10196 // Let's not deal with validation here, this is for admins only.
10197 $current = $this->get_setting();
10198 if (empty($data) && $current === null) {
10199 // This will be the case when applying default settings (installation).
10200 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10201 } else if (!is_number($data)) {
10202 // Draft item id is expected here!
10203 return get_string('errorsetting', 'admin');
10206 $options = $this->get_options();
10207 $fs = get_file_storage();
10208 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10210 $this->oldhashes = null;
10211 if ($current) {
10212 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10213 if ($file = $fs->get_file_by_hash($hash)) {
10214 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10216 unset($file);
10219 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10220 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10221 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10222 // with an error because the draft area does not exist, as he did not use it.
10223 $usercontext = context_user::instance($USER->id);
10224 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10225 return get_string('errorsetting', 'admin');
10229 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10230 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10232 $filepath = '';
10233 if ($files) {
10234 /** @var stored_file $file */
10235 $file = reset($files);
10236 $filepath = $file->get_filepath().$file->get_filename();
10239 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10242 public function post_write_settings($original) {
10243 $options = $this->get_options();
10244 $fs = get_file_storage();
10245 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10247 $current = $this->get_setting();
10248 $newhashes = null;
10249 if ($current) {
10250 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10251 if ($file = $fs->get_file_by_hash($hash)) {
10252 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10254 unset($file);
10257 if ($this->oldhashes === $newhashes) {
10258 $this->oldhashes = null;
10259 return false;
10261 $this->oldhashes = null;
10263 $callbackfunction = $this->updatedcallback;
10264 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10265 $callbackfunction($this->get_full_name());
10267 return true;
10270 public function output_html($data, $query = '') {
10271 global $PAGE, $CFG;
10273 $options = $this->get_options();
10274 $id = $this->get_id();
10275 $elname = $this->get_full_name();
10276 $draftitemid = file_get_submitted_draft_itemid($elname);
10277 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10278 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10280 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10281 require_once("$CFG->dirroot/lib/form/filemanager.php");
10283 $fmoptions = new stdClass();
10284 $fmoptions->mainfile = $options['mainfile'];
10285 $fmoptions->maxbytes = $options['maxbytes'];
10286 $fmoptions->maxfiles = $options['maxfiles'];
10287 $fmoptions->client_id = uniqid();
10288 $fmoptions->itemid = $draftitemid;
10289 $fmoptions->subdirs = $options['subdirs'];
10290 $fmoptions->target = $id;
10291 $fmoptions->accepted_types = $options['accepted_types'];
10292 $fmoptions->return_types = $options['return_types'];
10293 $fmoptions->context = $options['context'];
10294 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10296 $fm = new form_filemanager($fmoptions);
10297 $output = $PAGE->get_renderer('core', 'files');
10298 $html = $output->render($fm);
10300 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
10301 $html .= '<input value="" id="'.$id.'" type="hidden" />';
10303 return format_admin_setting($this, $this->visiblename,
10304 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
10305 $this->description, true, '', '', $query);
10311 * Administration interface for user specified regular expressions for device detection.
10313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10315 class admin_setting_devicedetectregex extends admin_setting {
10318 * Calls parent::__construct with specific args
10320 * @param string $name
10321 * @param string $visiblename
10322 * @param string $description
10323 * @param mixed $defaultsetting
10325 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10326 global $CFG;
10327 parent::__construct($name, $visiblename, $description, $defaultsetting);
10331 * Return the current setting(s)
10333 * @return array Current settings array
10335 public function get_setting() {
10336 global $CFG;
10338 $config = $this->config_read($this->name);
10339 if (is_null($config)) {
10340 return null;
10343 return $this->prepare_form_data($config);
10347 * Save selected settings
10349 * @param array $data Array of settings to save
10350 * @return bool
10352 public function write_setting($data) {
10353 if (empty($data)) {
10354 $data = array();
10357 if ($this->config_write($this->name, $this->process_form_data($data))) {
10358 return ''; // success
10359 } else {
10360 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10365 * Return XHTML field(s) for regexes
10367 * @param array $data Array of options to set in HTML
10368 * @return string XHTML string for the fields and wrapping div(s)
10370 public function output_html($data, $query='') {
10371 global $OUTPUT;
10373 $context = (object) [
10374 'expressions' => [],
10375 'name' => $this->get_full_name()
10378 if (empty($data)) {
10379 $looplimit = 1;
10380 } else {
10381 $looplimit = (count($data)/2)+1;
10384 for ($i=0; $i<$looplimit; $i++) {
10386 $expressionname = 'expression'.$i;
10388 if (!empty($data[$expressionname])){
10389 $expression = $data[$expressionname];
10390 } else {
10391 $expression = '';
10394 $valuename = 'value'.$i;
10396 if (!empty($data[$valuename])){
10397 $value = $data[$valuename];
10398 } else {
10399 $value= '';
10402 $context->expressions[] = [
10403 'index' => $i,
10404 'expression' => $expression,
10405 'value' => $value
10409 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10411 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10415 * Converts the string of regexes
10417 * @see self::process_form_data()
10418 * @param $regexes string of regexes
10419 * @return array of form fields and their values
10421 protected function prepare_form_data($regexes) {
10423 $regexes = json_decode($regexes);
10425 $form = array();
10427 $i = 0;
10429 foreach ($regexes as $value => $regex) {
10430 $expressionname = 'expression'.$i;
10431 $valuename = 'value'.$i;
10433 $form[$expressionname] = $regex;
10434 $form[$valuename] = $value;
10435 $i++;
10438 return $form;
10442 * Converts the data from admin settings form into a string of regexes
10444 * @see self::prepare_form_data()
10445 * @param array $data array of admin form fields and values
10446 * @return false|string of regexes
10448 protected function process_form_data(array $form) {
10450 $count = count($form); // number of form field values
10452 if ($count % 2) {
10453 // we must get five fields per expression
10454 return false;
10457 $regexes = array();
10458 for ($i = 0; $i < $count / 2; $i++) {
10459 $expressionname = "expression".$i;
10460 $valuename = "value".$i;
10462 $expression = trim($form['expression'.$i]);
10463 $value = trim($form['value'.$i]);
10465 if (empty($expression)){
10466 continue;
10469 $regexes[$value] = $expression;
10472 $regexes = json_encode($regexes);
10474 return $regexes;
10480 * Multiselect for current modules
10482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10484 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10485 private $excludesystem;
10488 * Calls parent::__construct - note array $choices is not required
10490 * @param string $name setting name
10491 * @param string $visiblename localised setting name
10492 * @param string $description setting description
10493 * @param array $defaultsetting a plain array of default module ids
10494 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10496 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10497 $excludesystem = true) {
10498 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10499 $this->excludesystem = $excludesystem;
10503 * Loads an array of current module choices
10505 * @return bool always return true
10507 public function load_choices() {
10508 if (is_array($this->choices)) {
10509 return true;
10511 $this->choices = array();
10513 global $CFG, $DB;
10514 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10515 foreach ($records as $record) {
10516 // Exclude modules if the code doesn't exist
10517 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10518 // Also exclude system modules (if specified)
10519 if (!($this->excludesystem &&
10520 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10521 MOD_ARCHETYPE_SYSTEM)) {
10522 $this->choices[$record->id] = $record->name;
10526 return true;
10531 * Admin setting to show if a php extension is enabled or not.
10533 * @copyright 2013 Damyon Wiese
10534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10536 class admin_setting_php_extension_enabled extends admin_setting {
10538 /** @var string The name of the extension to check for */
10539 private $extension;
10542 * Calls parent::__construct with specific arguments
10544 public function __construct($name, $visiblename, $description, $extension) {
10545 $this->extension = $extension;
10546 $this->nosave = true;
10547 parent::__construct($name, $visiblename, $description, '');
10551 * Always returns true, does nothing
10553 * @return true
10555 public function get_setting() {
10556 return true;
10560 * Always returns true, does nothing
10562 * @return true
10564 public function get_defaultsetting() {
10565 return true;
10569 * Always returns '', does not write anything
10571 * @return string Always returns ''
10573 public function write_setting($data) {
10574 // Do not write any setting.
10575 return '';
10579 * Outputs the html for this setting.
10580 * @return string Returns an XHTML string
10582 public function output_html($data, $query='') {
10583 global $OUTPUT;
10585 $o = '';
10586 if (!extension_loaded($this->extension)) {
10587 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10589 $o .= format_admin_setting($this, $this->visiblename, $warning);
10591 return $o;
10596 * Server timezone setting.
10598 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10600 * @author Petr Skoda <petr.skoda@totaralms.com>
10602 class admin_setting_servertimezone extends admin_setting_configselect {
10604 * Constructor.
10606 public function __construct() {
10607 $default = core_date::get_default_php_timezone();
10608 if ($default === 'UTC') {
10609 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10610 $default = 'Europe/London';
10613 parent::__construct('timezone',
10614 new lang_string('timezone', 'core_admin'),
10615 new lang_string('configtimezone', 'core_admin'), $default, null);
10619 * Lazy load timezone options.
10620 * @return bool true if loaded, false if error
10622 public function load_choices() {
10623 global $CFG;
10624 if (is_array($this->choices)) {
10625 return true;
10628 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10629 $this->choices = core_date::get_list_of_timezones($current, false);
10630 if ($current == 99) {
10631 // Do not show 99 unless it is current value, we want to get rid of it over time.
10632 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10633 core_date::get_default_php_timezone());
10636 return true;
10641 * Forced user timezone setting.
10643 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10645 * @author Petr Skoda <petr.skoda@totaralms.com>
10647 class admin_setting_forcetimezone extends admin_setting_configselect {
10649 * Constructor.
10651 public function __construct() {
10652 parent::__construct('forcetimezone',
10653 new lang_string('forcetimezone', 'core_admin'),
10654 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10658 * Lazy load timezone options.
10659 * @return bool true if loaded, false if error
10661 public function load_choices() {
10662 global $CFG;
10663 if (is_array($this->choices)) {
10664 return true;
10667 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10668 $this->choices = core_date::get_list_of_timezones($current, true);
10669 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10671 return true;
10677 * Search setup steps info.
10679 * @package core
10680 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10681 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10683 class admin_setting_searchsetupinfo extends admin_setting {
10686 * Calls parent::__construct with specific arguments
10688 public function __construct() {
10689 $this->nosave = true;
10690 parent::__construct('searchsetupinfo', '', '', '');
10694 * Always returns true, does nothing
10696 * @return true
10698 public function get_setting() {
10699 return true;
10703 * Always returns true, does nothing
10705 * @return true
10707 public function get_defaultsetting() {
10708 return true;
10712 * Always returns '', does not write anything
10714 * @param array $data
10715 * @return string Always returns ''
10717 public function write_setting($data) {
10718 // Do not write any setting.
10719 return '';
10723 * Builds the HTML to display the control
10725 * @param string $data Unused
10726 * @param string $query
10727 * @return string
10729 public function output_html($data, $query='') {
10730 global $CFG, $OUTPUT;
10732 $return = '';
10733 $brtag = html_writer::empty_tag('br');
10735 $searchareas = \core_search\manager::get_search_areas_list();
10736 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10737 $anyindexed = false;
10738 foreach ($searchareas as $areaid => $searcharea) {
10739 list($componentname, $varname) = $searcharea->get_config_var_name();
10740 if (get_config($componentname, $varname . '_indexingstart')) {
10741 $anyindexed = true;
10742 break;
10746 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10748 $table = new html_table();
10749 $table->head = array(get_string('step', 'search'), get_string('status'));
10750 $table->colclasses = array('leftalign step', 'leftalign status');
10751 $table->id = 'searchsetup';
10752 $table->attributes['class'] = 'admintable generaltable';
10753 $table->data = array();
10755 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10757 // Select a search engine.
10758 $row = array();
10759 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10760 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10761 array('href' => $url));
10763 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10764 if (!empty($CFG->searchengine)) {
10765 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
10766 array('class' => 'statusok'));
10769 $row[1] = $status;
10770 $table->data[] = $row;
10772 // Available areas.
10773 $row = array();
10774 $url = new moodle_url('/admin/searchareas.php');
10775 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
10776 array('href' => $url));
10778 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10779 if ($anyenabled) {
10780 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10783 $row[1] = $status;
10784 $table->data[] = $row;
10786 // Setup search engine.
10787 $row = array();
10788 if (empty($CFG->searchengine)) {
10789 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
10790 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10791 } else {
10792 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
10793 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
10794 array('href' => $url));
10795 // Check the engine status.
10796 $searchengine = \core_search\manager::search_engine_instance();
10797 try {
10798 $serverstatus = $searchengine->is_server_ready();
10799 } catch (\moodle_exception $e) {
10800 $serverstatus = $e->getMessage();
10802 if ($serverstatus === true) {
10803 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10804 } else {
10805 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
10807 $row[1] = $status;
10809 $table->data[] = $row;
10811 // Indexed data.
10812 $row = array();
10813 $url = new moodle_url('/admin/searchareas.php');
10814 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
10815 if ($anyindexed) {
10816 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10817 } else {
10818 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10820 $row[1] = $status;
10821 $table->data[] = $row;
10823 // Enable global search.
10824 $row = array();
10825 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
10826 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
10827 array('href' => $url));
10828 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10829 if (\core_search\manager::is_global_search_enabled()) {
10830 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10832 $row[1] = $status;
10833 $table->data[] = $row;
10835 $return .= html_writer::table($table);
10837 return highlight($query, $return);
10843 * Used to validate the contents of SCSS code and ensuring they are parsable.
10845 * It does not attempt to detect undefined SCSS variables because it is designed
10846 * to be used without knowledge of other config/scss included.
10848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10849 * @copyright 2016 Dan Poltawski <dan@moodle.com>
10851 class admin_setting_scsscode extends admin_setting_configtextarea {
10854 * Validate the contents of the SCSS to ensure its parsable. Does not
10855 * attempt to detect undefined scss variables.
10857 * @param string $data The scss code from text field.
10858 * @return mixed bool true for success or string:error on failure.
10860 public function validate($data) {
10861 if (empty($data)) {
10862 return true;
10865 $scss = new core_scss();
10866 try {
10867 $scss->compile($data);
10868 } catch (Leafo\ScssPhp\Exception\ParserException $e) {
10869 return get_string('scssinvalid', 'admin', $e->getMessage());
10870 } catch (Leafo\ScssPhp\Exception\CompilerException $e) {
10871 // Silently ignore this - it could be a scss variable defined from somewhere
10872 // else which we are not examining here.
10873 return true;
10876 return true;
10882 * Administration setting to define a list of file types.
10884 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
10885 * @copyright 2017 David Mudrák <david@moodle.com>
10886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10888 class admin_setting_filetypes extends admin_setting_configtext {
10890 /** @var array Allow selection from these file types only. */
10891 protected $onlytypes = [];
10893 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
10894 protected $allowall = true;
10896 /** @var core_form\filetypes_util instance to use as a helper. */
10897 protected $util = null;
10900 * Constructor.
10902 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
10903 * @param string $visiblename Localised label of the setting
10904 * @param string $description Localised description of the setting
10905 * @param string $defaultsetting Default setting value.
10906 * @param array $options Setting widget options, an array with optional keys:
10907 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
10908 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
10910 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
10912 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
10914 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
10915 $this->onlytypes = $options['onlytypes'];
10918 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
10919 $this->allowall = (bool)$options['allowall'];
10922 $this->util = new \core_form\filetypes_util();
10926 * Normalize the user's input and write it to the database as comma separated list.
10928 * Comma separated list as a text representation of the array was chosen to
10929 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
10931 * @param string $data Value submitted by the admin.
10932 * @return string Epty string if all good, error message otherwise.
10934 public function write_setting($data) {
10935 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
10939 * Validate data before storage
10941 * @param string $data The setting values provided by the admin
10942 * @return bool|string True if ok, the string if error found
10944 public function validate($data) {
10946 // No need to call parent's validation here as we are PARAM_RAW.
10948 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
10949 return true;
10951 } else {
10952 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
10953 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
10958 * Return an HTML string for the setting element.
10960 * @param string $data The current setting value
10961 * @param string $query Admin search query to be highlighted
10962 * @return string HTML to be displayed
10964 public function output_html($data, $query='') {
10965 global $OUTPUT, $PAGE;
10967 $default = $this->get_defaultsetting();
10968 $context = (object) [
10969 'id' => $this->get_id(),
10970 'name' => $this->get_full_name(),
10971 'value' => $data,
10972 'descriptions' => $this->util->describe_file_types($data),
10974 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
10976 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
10977 $this->get_id(),
10978 $this->visiblename->out(),
10979 $this->onlytypes,
10980 $this->allowall,
10983 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
10987 * Should the values be always displayed in LTR mode?
10989 * We always return true here because these values are not RTL compatible.
10991 * @return bool True because these values are not RTL compatible.
10993 public function get_force_ltr() {
10994 return true;
10999 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11001 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11002 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11004 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11007 * Constructor.
11009 * @param string $name
11010 * @param string $visiblename
11011 * @param string $description
11012 * @param mixed $defaultsetting string or array
11013 * @param mixed $paramtype
11014 * @param string $cols
11015 * @param string $rows
11017 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11018 $cols = '60', $rows = '8') {
11019 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11020 // Pre-set force LTR to false.
11021 $this->set_force_ltr(false);
11025 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11027 * @param string $data The age of digital consent map from text field.
11028 * @return mixed bool true for success or string:error on failure.
11030 public function validate($data) {
11031 if (empty($data)) {
11032 return true;
11035 try {
11036 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11037 } catch (\moodle_exception $e) {
11038 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11041 return true;
11046 * Selection of plugins that can work as site policy handlers
11048 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11049 * @copyright 2018 Marina Glancy
11051 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11054 * Constructor
11055 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11056 * for ones in config_plugins.
11057 * @param string $visiblename localised
11058 * @param string $description long localised info
11059 * @param string $defaultsetting
11061 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11062 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11066 * Lazy-load the available choices for the select box
11068 public function load_choices() {
11069 if (during_initial_install()) {
11070 return false;
11072 if (is_array($this->choices)) {
11073 return true;
11076 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11077 $manager = new \core_privacy\local\sitepolicy\manager();
11078 $plugins = $manager->get_all_handlers();
11079 foreach ($plugins as $pname => $unused) {
11080 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11081 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11084 return true;