Merge branch 'MDL-73646-master-v2' of https://github.com/sharidas/moodle
[moodle.git] / lib / adminlib.php
blobfdc812747e78e18da7d5b90a5d48b1f41f487daa
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 use core_admin\local\settings\linkable_settings_page;
107 defined('MOODLE_INTERNAL') || die();
109 /// Add libraries
110 require_once($CFG->libdir.'/ddllib.php');
111 require_once($CFG->libdir.'/xmlize.php');
112 require_once($CFG->libdir.'/messagelib.php');
114 // Add classes, traits, and interfaces which should be autoloaded.
115 // The autoloader is configured late in setup.php, after ABORT_AFTER_CONFIG.
116 // This is also required where the setup system is not included at all.
117 require_once($CFG->dirroot.'/'.$CFG->admin.'/classes/local/settings/linkable_settings_page.php');
119 define('INSECURE_DATAROOT_WARNING', 1);
120 define('INSECURE_DATAROOT_ERROR', 2);
123 * Automatically clean-up all plugin data and remove the plugin DB tables
125 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
127 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
128 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
129 * @uses global $OUTPUT to produce notices and other messages
130 * @return void
132 function uninstall_plugin($type, $name) {
133 global $CFG, $DB, $OUTPUT;
135 // This may take a long time.
136 core_php_time_limit::raise();
138 // Recursively uninstall all subplugins first.
139 $subplugintypes = core_component::get_plugin_types_with_subplugins();
140 if (isset($subplugintypes[$type])) {
141 $base = core_component::get_plugin_directory($type, $name);
143 $subpluginsfile = "{$base}/db/subplugins.json";
144 if (file_exists($subpluginsfile)) {
145 $subplugins = (array) json_decode(file_get_contents($subpluginsfile))->plugintypes;
146 } else if (file_exists("{$base}/db/subplugins.php")) {
147 debugging('Use of subplugins.php has been deprecated. ' .
148 'Please update your plugin to provide a subplugins.json file instead.',
149 DEBUG_DEVELOPER);
150 $subplugins = [];
151 include("{$base}/db/subplugins.php");
154 if (!empty($subplugins)) {
155 foreach (array_keys($subplugins) as $subplugintype) {
156 $instances = core_component::get_plugin_list($subplugintype);
157 foreach ($instances as $subpluginname => $notusedpluginpath) {
158 uninstall_plugin($subplugintype, $subpluginname);
164 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
166 if ($type === 'mod') {
167 $pluginname = $name; // eg. 'forum'
168 if (get_string_manager()->string_exists('modulename', $component)) {
169 $strpluginname = get_string('modulename', $component);
170 } else {
171 $strpluginname = $component;
174 } else {
175 $pluginname = $component;
176 if (get_string_manager()->string_exists('pluginname', $component)) {
177 $strpluginname = get_string('pluginname', $component);
178 } else {
179 $strpluginname = $component;
183 echo $OUTPUT->heading($pluginname);
185 // Delete all tag areas, collections and instances associated with this plugin.
186 core_tag_area::uninstall($component);
188 // Custom plugin uninstall.
189 $plugindirectory = core_component::get_plugin_directory($type, $name);
190 $uninstalllib = $plugindirectory . '/db/uninstall.php';
191 if (file_exists($uninstalllib)) {
192 require_once($uninstalllib);
193 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
194 if (function_exists($uninstallfunction)) {
195 // Do not verify result, let plugin complain if necessary.
196 $uninstallfunction();
200 // Specific plugin type cleanup.
201 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
202 if ($plugininfo) {
203 $plugininfo->uninstall_cleanup();
204 core_plugin_manager::reset_caches();
206 $plugininfo = null;
208 // perform clean-up task common for all the plugin/subplugin types
210 //delete the web service functions and pre-built services
211 require_once($CFG->dirroot.'/lib/externallib.php');
212 external_delete_descriptions($component);
214 // delete calendar events
215 $DB->delete_records('event', array('modulename' => $pluginname));
216 $DB->delete_records('event', ['component' => $component]);
218 // Delete scheduled tasks.
219 $DB->delete_records('task_adhoc', ['component' => $component]);
220 $DB->delete_records('task_scheduled', array('component' => $component));
222 // Delete Inbound Message datakeys.
223 $DB->delete_records_select('messageinbound_datakeys',
224 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
226 // Delete Inbound Message handlers.
227 $DB->delete_records('messageinbound_handlers', array('component' => $component));
229 // delete all the logs
230 $DB->delete_records('log', array('module' => $pluginname));
232 // delete log_display information
233 $DB->delete_records('log_display', array('component' => $component));
235 // delete the module configuration records
236 unset_all_config_for_plugin($component);
237 if ($type === 'mod') {
238 unset_all_config_for_plugin($pluginname);
241 // delete message provider
242 message_provider_uninstall($component);
244 // delete the plugin tables
245 $xmldbfilepath = $plugindirectory . '/db/install.xml';
246 drop_plugin_tables($component, $xmldbfilepath, false);
247 if ($type === 'mod' or $type === 'block') {
248 // non-frankenstyle table prefixes
249 drop_plugin_tables($name, $xmldbfilepath, false);
252 // delete the capabilities that were defined by this module
253 capabilities_cleanup($component);
255 // Delete all remaining files in the filepool owned by the component.
256 $fs = get_file_storage();
257 $fs->delete_component_files($component);
259 // Finally purge all caches.
260 purge_all_caches();
262 // Invalidate the hash used for upgrade detections.
263 set_config('allversionshash', '');
265 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
269 * Returns the version of installed component
271 * @param string $component component name
272 * @param string $source either 'disk' or 'installed' - where to get the version information from
273 * @return string|bool version number or false if the component is not found
275 function get_component_version($component, $source='installed') {
276 global $CFG, $DB;
278 list($type, $name) = core_component::normalize_component($component);
280 // moodle core or a core subsystem
281 if ($type === 'core') {
282 if ($source === 'installed') {
283 if (empty($CFG->version)) {
284 return false;
285 } else {
286 return $CFG->version;
288 } else {
289 if (!is_readable($CFG->dirroot.'/version.php')) {
290 return false;
291 } else {
292 $version = null; //initialize variable for IDEs
293 include($CFG->dirroot.'/version.php');
294 return $version;
299 // activity module
300 if ($type === 'mod') {
301 if ($source === 'installed') {
302 if ($CFG->version < 2013092001.02) {
303 return $DB->get_field('modules', 'version', array('name'=>$name));
304 } else {
305 return get_config('mod_'.$name, 'version');
308 } else {
309 $mods = core_component::get_plugin_list('mod');
310 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
311 return false;
312 } else {
313 $plugin = new stdClass();
314 $plugin->version = null;
315 $module = $plugin;
316 include($mods[$name].'/version.php');
317 return $plugin->version;
322 // block
323 if ($type === 'block') {
324 if ($source === 'installed') {
325 if ($CFG->version < 2013092001.02) {
326 return $DB->get_field('block', 'version', array('name'=>$name));
327 } else {
328 return get_config('block_'.$name, 'version');
330 } else {
331 $blocks = core_component::get_plugin_list('block');
332 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($blocks[$name].'/version.php');
337 return $plugin->version;
342 // all other plugin types
343 if ($source === 'installed') {
344 return get_config($type.'_'.$name, 'version');
345 } else {
346 $plugins = core_component::get_plugin_list($type);
347 if (empty($plugins[$name])) {
348 return false;
349 } else {
350 $plugin = new stdclass();
351 include($plugins[$name].'/version.php');
352 return $plugin->version;
358 * Delete all plugin tables
360 * @param string $name Name of plugin, used as table prefix
361 * @param string $file Path to install.xml file
362 * @param bool $feedback defaults to true
363 * @return bool Always returns true
365 function drop_plugin_tables($name, $file, $feedback=true) {
366 global $CFG, $DB;
368 // first try normal delete
369 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
370 return true;
373 // then try to find all tables that start with name and are not in any xml file
374 $used_tables = get_used_table_names();
376 $tables = $DB->get_tables();
378 /// Iterate over, fixing id fields as necessary
379 foreach ($tables as $table) {
380 if (in_array($table, $used_tables)) {
381 continue;
384 if (strpos($table, $name) !== 0) {
385 continue;
388 // found orphan table --> delete it
389 if ($DB->get_manager()->table_exists($table)) {
390 $xmldb_table = new xmldb_table($table);
391 $DB->get_manager()->drop_table($xmldb_table);
395 return true;
399 * Returns names of all known tables == tables that moodle knows about.
401 * @return array Array of lowercase table names
403 function get_used_table_names() {
404 $table_names = array();
405 $dbdirs = get_db_directories();
407 foreach ($dbdirs as $dbdir) {
408 $file = $dbdir.'/install.xml';
410 $xmldb_file = new xmldb_file($file);
412 if (!$xmldb_file->fileExists()) {
413 continue;
416 $loaded = $xmldb_file->loadXMLStructure();
417 $structure = $xmldb_file->getStructure();
419 if ($loaded and $tables = $structure->getTables()) {
420 foreach($tables as $table) {
421 $table_names[] = strtolower($table->getName());
426 return $table_names;
430 * Returns list of all directories where we expect install.xml files
431 * @return array Array of paths
433 function get_db_directories() {
434 global $CFG;
436 $dbdirs = array();
438 /// First, the main one (lib/db)
439 $dbdirs[] = $CFG->libdir.'/db';
441 /// Then, all the ones defined by core_component::get_plugin_types()
442 $plugintypes = core_component::get_plugin_types();
443 foreach ($plugintypes as $plugintype => $pluginbasedir) {
444 if ($plugins = core_component::get_plugin_list($plugintype)) {
445 foreach ($plugins as $plugin => $plugindir) {
446 $dbdirs[] = $plugindir.'/db';
451 return $dbdirs;
455 * Try to obtain or release the cron lock.
456 * @param string $name name of lock
457 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
458 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
459 * @return bool true if lock obtained
461 function set_cron_lock($name, $until, $ignorecurrent=false) {
462 global $DB;
463 if (empty($name)) {
464 debugging("Tried to get a cron lock for a null fieldname");
465 return false;
468 // remove lock by force == remove from config table
469 if (is_null($until)) {
470 set_config($name, null);
471 return true;
474 if (!$ignorecurrent) {
475 // read value from db - other processes might have changed it
476 $value = $DB->get_field('config', 'value', array('name'=>$name));
478 if ($value and $value > time()) {
479 //lock active
480 return false;
484 set_config($name, $until);
485 return true;
489 * Test if and critical warnings are present
490 * @return bool
492 function admin_critical_warnings_present() {
493 global $SESSION;
495 if (!has_capability('moodle/site:config', context_system::instance())) {
496 return 0;
499 if (!isset($SESSION->admin_critical_warning)) {
500 $SESSION->admin_critical_warning = 0;
501 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
502 $SESSION->admin_critical_warning = 1;
506 return $SESSION->admin_critical_warning;
510 * Detects if float supports at least 10 decimal digits
512 * Detects if float supports at least 10 decimal digits
513 * and also if float-->string conversion works as expected.
515 * @return bool true if problem found
517 function is_float_problem() {
518 $num1 = 2009010200.01;
519 $num2 = 2009010200.02;
521 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
525 * Try to verify that dataroot is not accessible from web.
527 * Try to verify that dataroot is not accessible from web.
528 * It is not 100% correct but might help to reduce number of vulnerable sites.
529 * Protection from httpd.conf and .htaccess is not detected properly.
531 * @uses INSECURE_DATAROOT_WARNING
532 * @uses INSECURE_DATAROOT_ERROR
533 * @param bool $fetchtest try to test public access by fetching file, default false
534 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
536 function is_dataroot_insecure($fetchtest=false) {
537 global $CFG;
539 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
541 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
542 $rp = strrev(trim($rp, '/'));
543 $rp = explode('/', $rp);
544 foreach($rp as $r) {
545 if (strpos($siteroot, '/'.$r.'/') === 0) {
546 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
547 } else {
548 break; // probably alias root
552 $siteroot = strrev($siteroot);
553 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
555 if (strpos($dataroot, $siteroot) !== 0) {
556 return false;
559 if (!$fetchtest) {
560 return INSECURE_DATAROOT_WARNING;
563 // now try all methods to fetch a test file using http protocol
565 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
566 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
567 $httpdocroot = $matches[1];
568 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
569 make_upload_directory('diag');
570 $testfile = $CFG->dataroot.'/diag/public.txt';
571 if (!file_exists($testfile)) {
572 file_put_contents($testfile, 'test file, do not delete');
573 @chmod($testfile, $CFG->filepermissions);
575 $teststr = trim(file_get_contents($testfile));
576 if (empty($teststr)) {
577 // hmm, strange
578 return INSECURE_DATAROOT_WARNING;
581 $testurl = $datarooturl.'/diag/public.txt';
582 if (extension_loaded('curl') and
583 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
584 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
585 ($ch = @curl_init($testurl)) !== false) {
586 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
587 curl_setopt($ch, CURLOPT_HEADER, false);
588 $data = curl_exec($ch);
589 if (!curl_errno($ch)) {
590 $data = trim($data);
591 if ($data === $teststr) {
592 curl_close($ch);
593 return INSECURE_DATAROOT_ERROR;
596 curl_close($ch);
599 if ($data = @file_get_contents($testurl)) {
600 $data = trim($data);
601 if ($data === $teststr) {
602 return INSECURE_DATAROOT_ERROR;
606 preg_match('|https?://([^/]+)|i', $testurl, $matches);
607 $sitename = $matches[1];
608 $error = 0;
609 if ($fp = @fsockopen($sitename, 80, $error)) {
610 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
611 $localurl = $matches[1];
612 $out = "GET $localurl HTTP/1.1\r\n";
613 $out .= "Host: $sitename\r\n";
614 $out .= "Connection: Close\r\n\r\n";
615 fwrite($fp, $out);
616 $data = '';
617 $incoming = false;
618 while (!feof($fp)) {
619 if ($incoming) {
620 $data .= fgets($fp, 1024);
621 } else if (@fgets($fp, 1024) === "\r\n") {
622 $incoming = true;
625 fclose($fp);
626 $data = trim($data);
627 if ($data === $teststr) {
628 return INSECURE_DATAROOT_ERROR;
632 return INSECURE_DATAROOT_WARNING;
636 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
638 function enable_cli_maintenance_mode() {
639 global $CFG, $SITE;
641 if (file_exists("$CFG->dataroot/climaintenance.html")) {
642 unlink("$CFG->dataroot/climaintenance.html");
645 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
646 $data = $CFG->maintenance_message;
647 $data = bootstrap_renderer::early_error_content($data, null, null, null);
648 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
650 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
651 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
653 } else {
654 $data = get_string('sitemaintenance', 'admin');
655 $data = bootstrap_renderer::early_error_content($data, null, null, null);
656 $data = bootstrap_renderer::plain_page(get_string('sitemaintenancetitle', 'admin',
657 format_string($SITE->fullname, true, ['context' => context_system::instance()])), $data);
660 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
661 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
664 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
668 * Interface for anything appearing in the admin tree
670 * The interface that is implemented by anything that appears in the admin tree
671 * block. It forces inheriting classes to define a method for checking user permissions
672 * and methods for finding something in the admin tree.
674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676 interface part_of_admin_tree {
679 * Finds a named part_of_admin_tree.
681 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
682 * and not parentable_part_of_admin_tree, then this function should only check if
683 * $this->name matches $name. If it does, it should return a reference to $this,
684 * otherwise, it should return a reference to NULL.
686 * If a class inherits parentable_part_of_admin_tree, this method should be called
687 * recursively on all child objects (assuming, of course, the parent object's name
688 * doesn't match the search criterion).
690 * @param string $name The internal name of the part_of_admin_tree we're searching for.
691 * @return mixed An object reference or a NULL reference.
693 public function locate($name);
696 * Removes named part_of_admin_tree.
698 * @param string $name The internal name of the part_of_admin_tree we want to remove.
699 * @return bool success.
701 public function prune($name);
704 * Search using query
705 * @param string $query
706 * @return mixed array-object structure of found settings and pages
708 public function search($query);
711 * Verifies current user's access to this part_of_admin_tree.
713 * Used to check if the current user has access to this part of the admin tree or
714 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
715 * then this method is usually just a call to has_capability() in the site context.
717 * If a class inherits parentable_part_of_admin_tree, this method should return the
718 * logical OR of the return of check_access() on all child objects.
720 * @return bool True if the user has access, false if she doesn't.
722 public function check_access();
725 * Mostly useful for removing of some parts of the tree in admin tree block.
727 * @return True is hidden from normal list view
729 public function is_hidden();
732 * Show we display Save button at the page bottom?
733 * @return bool
735 public function show_save();
740 * Interface implemented by any part_of_admin_tree that has children.
742 * The interface implemented by any part_of_admin_tree that can be a parent
743 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
744 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
745 * include an add method for adding other part_of_admin_tree objects as children.
747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
749 interface parentable_part_of_admin_tree extends part_of_admin_tree {
752 * Adds a part_of_admin_tree object to the admin tree.
754 * Used to add a part_of_admin_tree object to this object or a child of this
755 * object. $something should only be added if $destinationname matches
756 * $this->name. If it doesn't, add should be called on child objects that are
757 * also parentable_part_of_admin_tree's.
759 * $something should be appended as the last child in the $destinationname. If the
760 * $beforesibling is specified, $something should be prepended to it. If the given
761 * sibling is not found, $something should be appended to the end of $destinationname
762 * and a developer debugging message should be displayed.
764 * @param string $destinationname The internal name of the new parent for $something.
765 * @param part_of_admin_tree $something The object to be added.
766 * @return bool True on success, false on failure.
768 public function add($destinationname, $something, $beforesibling = null);
774 * The object used to represent folders (a.k.a. categories) in the admin tree block.
776 * Each admin_category object contains a number of part_of_admin_tree objects.
778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
780 class admin_category implements parentable_part_of_admin_tree, linkable_settings_page {
782 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
783 protected $children;
784 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
785 public $name;
786 /** @var string The displayed name for this category. Usually obtained through get_string() */
787 public $visiblename;
788 /** @var bool Should this category be hidden in admin tree block? */
789 public $hidden;
790 /** @var mixed Either a string or an array or strings */
791 public $path;
792 /** @var mixed Either a string or an array or strings */
793 public $visiblepath;
795 /** @var array fast lookup category cache, all categories of one tree point to one cache */
796 protected $category_cache;
798 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
799 protected $sort = false;
800 /** @var bool If set to true children will be sorted in ascending order. */
801 protected $sortasc = true;
802 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
803 protected $sortsplit = true;
804 /** @var bool $sorted True if the children have been sorted and don't need resorting */
805 protected $sorted = false;
808 * Constructor for an empty admin category
810 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
811 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
812 * @param bool $hidden hide category in admin tree block, defaults to false
814 public function __construct($name, $visiblename, $hidden=false) {
815 $this->children = array();
816 $this->name = $name;
817 $this->visiblename = $visiblename;
818 $this->hidden = $hidden;
822 * Get the URL to view this settings page.
824 * @return moodle_url
826 public function get_settings_page_url(): moodle_url {
827 return new moodle_url(
828 '/admin/category.php',
830 'category' => $this->name,
836 * Returns a reference to the part_of_admin_tree object with internal name $name.
838 * @param string $name The internal name of the object we want.
839 * @param bool $findpath initialize path and visiblepath arrays
840 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
841 * defaults to false
843 public function locate($name, $findpath=false) {
844 if (!isset($this->category_cache[$this->name])) {
845 // somebody much have purged the cache
846 $this->category_cache[$this->name] = $this;
849 if ($this->name == $name) {
850 if ($findpath) {
851 $this->visiblepath[] = $this->visiblename;
852 $this->path[] = $this->name;
854 return $this;
857 // quick category lookup
858 if (!$findpath and isset($this->category_cache[$name])) {
859 return $this->category_cache[$name];
862 $return = NULL;
863 foreach($this->children as $childid=>$unused) {
864 if ($return = $this->children[$childid]->locate($name, $findpath)) {
865 break;
869 if (!is_null($return) and $findpath) {
870 $return->visiblepath[] = $this->visiblename;
871 $return->path[] = $this->name;
874 return $return;
878 * Search using query
880 * @param string query
881 * @return mixed array-object structure of found settings and pages
883 public function search($query) {
884 $result = array();
885 foreach ($this->get_children() as $child) {
886 $subsearch = $child->search($query);
887 if (!is_array($subsearch)) {
888 debugging('Incorrect search result from '.$child->name);
889 continue;
891 $result = array_merge($result, $subsearch);
893 return $result;
897 * Removes part_of_admin_tree object with internal name $name.
899 * @param string $name The internal name of the object we want to remove.
900 * @return bool success
902 public function prune($name) {
904 if ($this->name == $name) {
905 return false; //can not remove itself
908 foreach($this->children as $precedence => $child) {
909 if ($child->name == $name) {
910 // clear cache and delete self
911 while($this->category_cache) {
912 // delete the cache, but keep the original array address
913 array_pop($this->category_cache);
915 unset($this->children[$precedence]);
916 return true;
917 } else if ($this->children[$precedence]->prune($name)) {
918 return true;
921 return false;
925 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
927 * By default the new part of the tree is appended as the last child of the parent. You
928 * can specify a sibling node that the new part should be prepended to. If the given
929 * sibling is not found, the part is appended to the end (as it would be by default) and
930 * a developer debugging message is displayed.
932 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
933 * @param string $destinationame The internal name of the immediate parent that we want for $something.
934 * @param mixed $something A part_of_admin_tree or setting instance to be added.
935 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
936 * @return bool True if successfully added, false if $something can not be added.
938 public function add($parentname, $something, $beforesibling = null) {
939 global $CFG;
941 $parent = $this->locate($parentname);
942 if (is_null($parent)) {
943 debugging('parent does not exist!');
944 return false;
947 if ($something instanceof part_of_admin_tree) {
948 if (!($parent instanceof parentable_part_of_admin_tree)) {
949 debugging('error - parts of tree can be inserted only into parentable parts');
950 return false;
952 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
953 // The name of the node is already used, simply warn the developer that this should not happen.
954 // It is intentional to check for the debug level before performing the check.
955 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
957 if (is_null($beforesibling)) {
958 // Append $something as the parent's last child.
959 $parent->children[] = $something;
960 } else {
961 if (!is_string($beforesibling) or trim($beforesibling) === '') {
962 throw new coding_exception('Unexpected value of the beforesibling parameter');
964 // Try to find the position of the sibling.
965 $siblingposition = null;
966 foreach ($parent->children as $childposition => $child) {
967 if ($child->name === $beforesibling) {
968 $siblingposition = $childposition;
969 break;
972 if (is_null($siblingposition)) {
973 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
974 $parent->children[] = $something;
975 } else {
976 $parent->children = array_merge(
977 array_slice($parent->children, 0, $siblingposition),
978 array($something),
979 array_slice($parent->children, $siblingposition)
983 if ($something instanceof admin_category) {
984 if (isset($this->category_cache[$something->name])) {
985 debugging('Duplicate admin category name: '.$something->name);
986 } else {
987 $this->category_cache[$something->name] = $something;
988 $something->category_cache =& $this->category_cache;
989 foreach ($something->children as $child) {
990 // just in case somebody already added subcategories
991 if ($child instanceof admin_category) {
992 if (isset($this->category_cache[$child->name])) {
993 debugging('Duplicate admin category name: '.$child->name);
994 } else {
995 $this->category_cache[$child->name] = $child;
996 $child->category_cache =& $this->category_cache;
1002 return true;
1004 } else {
1005 debugging('error - can not add this element');
1006 return false;
1012 * Checks if the user has access to anything in this category.
1014 * @return bool True if the user has access to at least one child in this category, false otherwise.
1016 public function check_access() {
1017 foreach ($this->children as $child) {
1018 if ($child->check_access()) {
1019 return true;
1022 return false;
1026 * Is this category hidden in admin tree block?
1028 * @return bool True if hidden
1030 public function is_hidden() {
1031 return $this->hidden;
1035 * Show we display Save button at the page bottom?
1036 * @return bool
1038 public function show_save() {
1039 foreach ($this->children as $child) {
1040 if ($child->show_save()) {
1041 return true;
1044 return false;
1048 * Sets sorting on this category.
1050 * Please note this function doesn't actually do the sorting.
1051 * It can be called anytime.
1052 * Sorting occurs when the user calls get_children.
1053 * Code using the children array directly won't see the sorted results.
1055 * @param bool $sort If set to true children will be sorted, if false they won't be.
1056 * @param bool $asc If true sorting will be ascending, otherwise descending.
1057 * @param bool $split If true we sort pages and sub categories separately.
1059 public function set_sorting($sort, $asc = true, $split = true) {
1060 $this->sort = (bool)$sort;
1061 $this->sortasc = (bool)$asc;
1062 $this->sortsplit = (bool)$split;
1066 * Returns the children associated with this category.
1068 * @return part_of_admin_tree[]
1070 public function get_children() {
1071 // If we should sort and it hasn't already been sorted.
1072 if ($this->sort && !$this->sorted) {
1073 if ($this->sortsplit) {
1074 $categories = array();
1075 $pages = array();
1076 foreach ($this->children as $child) {
1077 if ($child instanceof admin_category) {
1078 $categories[] = $child;
1079 } else {
1080 $pages[] = $child;
1083 core_collator::asort_objects_by_property($categories, 'visiblename');
1084 core_collator::asort_objects_by_property($pages, 'visiblename');
1085 if (!$this->sortasc) {
1086 $categories = array_reverse($categories);
1087 $pages = array_reverse($pages);
1089 $this->children = array_merge($pages, $categories);
1090 } else {
1091 core_collator::asort_objects_by_property($this->children, 'visiblename');
1092 if (!$this->sortasc) {
1093 $this->children = array_reverse($this->children);
1096 $this->sorted = true;
1098 return $this->children;
1102 * Magically gets a property from this object.
1104 * @param $property
1105 * @return part_of_admin_tree[]
1106 * @throws coding_exception
1108 public function __get($property) {
1109 if ($property === 'children') {
1110 return $this->get_children();
1112 throw new coding_exception('Invalid property requested.');
1116 * Magically sets a property against this object.
1118 * @param string $property
1119 * @param mixed $value
1120 * @throws coding_exception
1122 public function __set($property, $value) {
1123 if ($property === 'children') {
1124 $this->sorted = false;
1125 $this->children = $value;
1126 } else {
1127 throw new coding_exception('Invalid property requested.');
1132 * Checks if an inaccessible property is set.
1134 * @param string $property
1135 * @return bool
1136 * @throws coding_exception
1138 public function __isset($property) {
1139 if ($property === 'children') {
1140 return isset($this->children);
1142 throw new coding_exception('Invalid property requested.');
1148 * Root of admin settings tree, does not have any parent.
1150 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1152 class admin_root extends admin_category {
1153 /** @var array List of errors */
1154 public $errors;
1155 /** @var string search query */
1156 public $search;
1157 /** @var bool full tree flag - true means all settings required, false only pages required */
1158 public $fulltree;
1159 /** @var bool flag indicating loaded tree */
1160 public $loaded;
1161 /** @var mixed site custom defaults overriding defaults in settings files*/
1162 public $custom_defaults;
1165 * @param bool $fulltree true means all settings required,
1166 * false only pages required
1168 public function __construct($fulltree) {
1169 global $CFG;
1171 parent::__construct('root', get_string('administration'), false);
1172 $this->errors = array();
1173 $this->search = '';
1174 $this->fulltree = $fulltree;
1175 $this->loaded = false;
1177 $this->category_cache = array();
1179 // load custom defaults if found
1180 $this->custom_defaults = null;
1181 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1182 if (is_readable($defaultsfile)) {
1183 $defaults = array();
1184 include($defaultsfile);
1185 if (is_array($defaults) and count($defaults)) {
1186 $this->custom_defaults = $defaults;
1192 * Empties children array, and sets loaded to false
1194 * @param bool $requirefulltree
1196 public function purge_children($requirefulltree) {
1197 $this->children = array();
1198 $this->fulltree = ($requirefulltree || $this->fulltree);
1199 $this->loaded = false;
1200 //break circular dependencies - this helps PHP 5.2
1201 while($this->category_cache) {
1202 array_pop($this->category_cache);
1204 $this->category_cache = array();
1210 * Links external PHP pages into the admin tree.
1212 * See detailed usage example at the top of this document (adminlib.php)
1214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1216 class admin_externalpage implements part_of_admin_tree, linkable_settings_page {
1218 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1219 public $name;
1221 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1222 public $visiblename;
1224 /** @var string The external URL that we should link to when someone requests this external page. */
1225 public $url;
1227 /** @var array The role capability/permission a user must have to access this external page. */
1228 public $req_capability;
1230 /** @var object The context in which capability/permission should be checked, default is site context. */
1231 public $context;
1233 /** @var bool hidden in admin tree block. */
1234 public $hidden;
1236 /** @var mixed either string or array of string */
1237 public $path;
1239 /** @var array list of visible names of page parents */
1240 public $visiblepath;
1243 * Constructor for adding an external page into the admin tree.
1245 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1246 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1247 * @param string $url The external URL that we should link to when someone requests this external page.
1248 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1249 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1250 * @param stdClass $context The context the page relates to. Not sure what happens
1251 * if you specify something other than system or front page. Defaults to system.
1253 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1254 $this->name = $name;
1255 $this->visiblename = $visiblename;
1256 $this->url = $url;
1257 if (is_array($req_capability)) {
1258 $this->req_capability = $req_capability;
1259 } else {
1260 $this->req_capability = array($req_capability);
1262 $this->hidden = $hidden;
1263 $this->context = $context;
1267 * Get the URL to view this settings page.
1269 * @return moodle_url
1271 public function get_settings_page_url(): moodle_url {
1272 return new moodle_url($this->url);
1276 * Returns a reference to the part_of_admin_tree object with internal name $name.
1278 * @param string $name The internal name of the object we want.
1279 * @param bool $findpath defaults to false
1280 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1282 public function locate($name, $findpath=false) {
1283 if ($this->name == $name) {
1284 if ($findpath) {
1285 $this->visiblepath = array($this->visiblename);
1286 $this->path = array($this->name);
1288 return $this;
1289 } else {
1290 $return = NULL;
1291 return $return;
1296 * This function always returns false, required function by interface
1298 * @param string $name
1299 * @return false
1301 public function prune($name) {
1302 return false;
1306 * Search using query
1308 * @param string $query
1309 * @return mixed array-object structure of found settings and pages
1311 public function search($query) {
1312 $found = false;
1313 if (strpos(strtolower($this->name), $query) !== false) {
1314 $found = true;
1315 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1316 $found = true;
1318 if ($found) {
1319 $result = new stdClass();
1320 $result->page = $this;
1321 $result->settings = array();
1322 return array($this->name => $result);
1323 } else {
1324 return array();
1329 * Determines if the current user has access to this external page based on $this->req_capability.
1331 * @return bool True if user has access, false otherwise.
1333 public function check_access() {
1334 global $CFG;
1335 $context = empty($this->context) ? context_system::instance() : $this->context;
1336 foreach($this->req_capability as $cap) {
1337 if (has_capability($cap, $context)) {
1338 return true;
1341 return false;
1345 * Is this external page hidden in admin tree block?
1347 * @return bool True if hidden
1349 public function is_hidden() {
1350 return $this->hidden;
1354 * Show we display Save button at the page bottom?
1355 * @return bool
1357 public function show_save() {
1358 return false;
1363 * Used to store details of the dependency between two settings elements.
1365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1366 * @copyright 2017 Davo Smith, Synergy Learning
1368 class admin_settingdependency {
1369 /** @var string the name of the setting to be shown/hidden */
1370 public $settingname;
1371 /** @var string the setting this is dependent on */
1372 public $dependenton;
1373 /** @var string the condition to show/hide the element */
1374 public $condition;
1375 /** @var string the value to compare against */
1376 public $value;
1378 /** @var string[] list of valid conditions */
1379 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1382 * admin_settingdependency constructor.
1383 * @param string $settingname
1384 * @param string $dependenton
1385 * @param string $condition
1386 * @param string $value
1387 * @throws \coding_exception
1389 public function __construct($settingname, $dependenton, $condition, $value) {
1390 $this->settingname = $this->parse_name($settingname);
1391 $this->dependenton = $this->parse_name($dependenton);
1392 $this->condition = $condition;
1393 $this->value = $value;
1395 if (!in_array($this->condition, self::$validconditions)) {
1396 throw new coding_exception("Invalid condition '$condition'");
1401 * Convert the setting name into the form field name.
1402 * @param string $name
1403 * @return string
1405 private function parse_name($name) {
1406 $bits = explode('/', $name);
1407 $name = array_pop($bits);
1408 $plugin = '';
1409 if ($bits) {
1410 $plugin = array_pop($bits);
1411 if ($plugin === 'moodle') {
1412 $plugin = '';
1415 return 's_'.$plugin.'_'.$name;
1419 * Gather together all the dependencies in a format suitable for initialising javascript
1420 * @param admin_settingdependency[] $dependencies
1421 * @return array
1423 public static function prepare_for_javascript($dependencies) {
1424 $result = [];
1425 foreach ($dependencies as $d) {
1426 if (!isset($result[$d->dependenton])) {
1427 $result[$d->dependenton] = [];
1429 if (!isset($result[$d->dependenton][$d->condition])) {
1430 $result[$d->dependenton][$d->condition] = [];
1432 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1433 $result[$d->dependenton][$d->condition][$d->value] = [];
1435 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1437 return $result;
1442 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1446 class admin_settingpage implements part_of_admin_tree, linkable_settings_page {
1448 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1449 public $name;
1451 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1452 public $visiblename;
1454 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1455 public $settings;
1457 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1458 protected $dependencies = [];
1460 /** @var array The role capability/permission a user must have to access this external page. */
1461 public $req_capability;
1463 /** @var object The context in which capability/permission should be checked, default is site context. */
1464 public $context;
1466 /** @var bool hidden in admin tree block. */
1467 public $hidden;
1469 /** @var mixed string of paths or array of strings of paths */
1470 public $path;
1472 /** @var array list of visible names of page parents */
1473 public $visiblepath;
1476 * see admin_settingpage for details of this function
1478 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1479 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1480 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1481 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1482 * @param stdClass $context The context the page relates to. Not sure what happens
1483 * if you specify something other than system or front page. Defaults to system.
1485 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1486 $this->settings = new stdClass();
1487 $this->name = $name;
1488 $this->visiblename = $visiblename;
1489 if (is_array($req_capability)) {
1490 $this->req_capability = $req_capability;
1491 } else {
1492 $this->req_capability = array($req_capability);
1494 $this->hidden = $hidden;
1495 $this->context = $context;
1499 * Get the URL to view this page.
1501 * @return moodle_url
1503 public function get_settings_page_url(): moodle_url {
1504 return new moodle_url(
1505 '/admin/settings.php',
1507 'section' => $this->name,
1513 * see admin_category
1515 * @param string $name
1516 * @param bool $findpath
1517 * @return mixed Object (this) if name == this->name, else returns null
1519 public function locate($name, $findpath=false) {
1520 if ($this->name == $name) {
1521 if ($findpath) {
1522 $this->visiblepath = array($this->visiblename);
1523 $this->path = array($this->name);
1525 return $this;
1526 } else {
1527 $return = NULL;
1528 return $return;
1533 * Search string in settings page.
1535 * @param string $query
1536 * @return array
1538 public function search($query) {
1539 $found = array();
1541 foreach ($this->settings as $setting) {
1542 if ($setting->is_related($query)) {
1543 $found[] = $setting;
1547 if ($found) {
1548 $result = new stdClass();
1549 $result->page = $this;
1550 $result->settings = $found;
1551 return array($this->name => $result);
1554 $found = false;
1555 if (strpos(strtolower($this->name), $query) !== false) {
1556 $found = true;
1557 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1558 $found = true;
1560 if ($found) {
1561 $result = new stdClass();
1562 $result->page = $this;
1563 $result->settings = array();
1564 return array($this->name => $result);
1565 } else {
1566 return array();
1571 * This function always returns false, required by interface
1573 * @param string $name
1574 * @return bool Always false
1576 public function prune($name) {
1577 return false;
1581 * adds an admin_setting to this admin_settingpage
1583 * 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
1584 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1586 * @param object $setting is the admin_setting object you want to add
1587 * @return bool true if successful, false if not
1589 public function add($setting) {
1590 if (!($setting instanceof admin_setting)) {
1591 debugging('error - not a setting instance');
1592 return false;
1595 $name = $setting->name;
1596 if ($setting->plugin) {
1597 $name = $setting->plugin . $name;
1599 $this->settings->{$name} = $setting;
1600 return true;
1604 * Hide the named setting if the specified condition is matched.
1606 * @param string $settingname
1607 * @param string $dependenton
1608 * @param string $condition
1609 * @param string $value
1611 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1612 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1614 // Reformat the dependency name to the plugin | name format used in the display.
1615 $dependenton = str_replace('/', ' | ', $dependenton);
1617 // Let the setting know, so it can be displayed underneath.
1618 $findname = str_replace('/', '', $settingname);
1619 foreach ($this->settings as $name => $setting) {
1620 if ($name === $findname) {
1621 $setting->add_dependent_on($dependenton);
1627 * see admin_externalpage
1629 * @return bool Returns true for yes false for no
1631 public function check_access() {
1632 global $CFG;
1633 $context = empty($this->context) ? context_system::instance() : $this->context;
1634 foreach($this->req_capability as $cap) {
1635 if (has_capability($cap, $context)) {
1636 return true;
1639 return false;
1643 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1644 * @return string Returns an XHTML string
1646 public function output_html() {
1647 $adminroot = admin_get_root();
1648 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1649 foreach($this->settings as $setting) {
1650 $fullname = $setting->get_full_name();
1651 if (array_key_exists($fullname, $adminroot->errors)) {
1652 $data = $adminroot->errors[$fullname]->data;
1653 } else {
1654 $data = $setting->get_setting();
1655 // do not use defaults if settings not available - upgrade settings handles the defaults!
1657 $return .= $setting->output_html($data);
1659 $return .= '</fieldset>';
1660 return $return;
1664 * Is this settings page hidden in admin tree block?
1666 * @return bool True if hidden
1668 public function is_hidden() {
1669 return $this->hidden;
1673 * Show we display Save button at the page bottom?
1674 * @return bool
1676 public function show_save() {
1677 foreach($this->settings as $setting) {
1678 if (empty($setting->nosave)) {
1679 return true;
1682 return false;
1686 * Should any of the settings on this page be shown / hidden based on conditions?
1687 * @return bool
1689 public function has_dependencies() {
1690 return (bool)$this->dependencies;
1694 * Format the setting show/hide conditions ready to initialise the page javascript
1695 * @return array
1697 public function get_dependencies_for_javascript() {
1698 if (!$this->has_dependencies()) {
1699 return [];
1701 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1707 * Admin settings class. Only exists on setting pages.
1708 * Read & write happens at this level; no authentication.
1710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1712 abstract class admin_setting {
1713 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1714 public $name;
1715 /** @var string localised name */
1716 public $visiblename;
1717 /** @var string localised long description in Markdown format */
1718 public $description;
1719 /** @var mixed Can be string or array of string */
1720 public $defaultsetting;
1721 /** @var string */
1722 public $updatedcallback;
1723 /** @var mixed can be String or Null. Null means main config table */
1724 public $plugin; // null means main config table
1725 /** @var bool true indicates this setting does not actually save anything, just information */
1726 public $nosave = false;
1727 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1728 public $affectsmodinfo = false;
1729 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1730 private $flags = array();
1731 /** @var bool Whether this field must be forced LTR. */
1732 private $forceltr = null;
1733 /** @var array list of other settings that may cause this setting to be hidden */
1734 private $dependenton = [];
1735 /** @var bool Whether this setting uses a custom form control */
1736 protected $customcontrol = false;
1739 * Constructor
1740 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1741 * or 'myplugin/mysetting' for ones in config_plugins.
1742 * @param string $visiblename localised name
1743 * @param string $description localised long description
1744 * @param mixed $defaultsetting string or array depending on implementation
1746 public function __construct($name, $visiblename, $description, $defaultsetting) {
1747 $this->parse_setting_name($name);
1748 $this->visiblename = $visiblename;
1749 $this->description = $description;
1750 $this->defaultsetting = $defaultsetting;
1754 * Generic function to add a flag to this admin setting.
1756 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1757 * @param bool $default - The default for the flag
1758 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1759 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1761 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1762 if (empty($this->flags[$shortname])) {
1763 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1764 } else {
1765 $this->flags[$shortname]->set_options($enabled, $default);
1770 * Set the enabled options flag on this admin setting.
1772 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1773 * @param bool $default - The default for the flag
1775 public function set_enabled_flag_options($enabled, $default) {
1776 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1780 * Set the advanced options flag on this admin setting.
1782 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1783 * @param bool $default - The default for the flag
1785 public function set_advanced_flag_options($enabled, $default) {
1786 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1791 * Set the locked options flag on this admin setting.
1793 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1794 * @param bool $default - The default for the flag
1796 public function set_locked_flag_options($enabled, $default) {
1797 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1801 * Set the required options flag on this admin setting.
1803 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1804 * @param bool $default - The default for the flag.
1806 public function set_required_flag_options($enabled, $default) {
1807 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1811 * Is this option forced in config.php?
1813 * @return bool
1815 public function is_readonly(): bool {
1816 global $CFG;
1818 if (empty($this->plugin)) {
1819 if (array_key_exists($this->name, $CFG->config_php_settings)) {
1820 return true;
1822 } else {
1823 if (array_key_exists($this->plugin, $CFG->forced_plugin_settings)
1824 and array_key_exists($this->name, $CFG->forced_plugin_settings[$this->plugin])) {
1825 return true;
1828 return false;
1832 * Get the currently saved value for a setting flag
1834 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1835 * @return bool
1837 public function get_setting_flag_value(admin_setting_flag $flag) {
1838 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1839 if (!isset($value)) {
1840 $value = $flag->get_default();
1843 return !empty($value);
1847 * Get the list of defaults for the flags on this setting.
1849 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1851 public function get_setting_flag_defaults(& $defaults) {
1852 foreach ($this->flags as $flag) {
1853 if ($flag->is_enabled() && $flag->get_default()) {
1854 $defaults[] = $flag->get_displayname();
1860 * Output the input fields for the advanced and locked flags on this setting.
1862 * @param bool $adv - The current value of the advanced flag.
1863 * @param bool $locked - The current value of the locked flag.
1864 * @return string $output - The html for the flags.
1866 public function output_setting_flags() {
1867 $output = '';
1869 foreach ($this->flags as $flag) {
1870 if ($flag->is_enabled()) {
1871 $output .= $flag->output_setting_flag($this);
1875 if (!empty($output)) {
1876 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1878 return $output;
1882 * Write the values of the flags for this admin setting.
1884 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1885 * @return bool - true if successful.
1887 public function write_setting_flags($data) {
1888 $result = true;
1889 foreach ($this->flags as $flag) {
1890 $result = $result && $flag->write_setting_flag($this, $data);
1892 return $result;
1896 * Set up $this->name and potentially $this->plugin
1898 * Set up $this->name and possibly $this->plugin based on whether $name looks
1899 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1900 * on the names, that is, output a developer debug warning if the name
1901 * contains anything other than [a-zA-Z0-9_]+.
1903 * @param string $name the setting name passed in to the constructor.
1905 private function parse_setting_name($name) {
1906 $bits = explode('/', $name);
1907 if (count($bits) > 2) {
1908 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1910 $this->name = array_pop($bits);
1911 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1912 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1914 if (!empty($bits)) {
1915 $this->plugin = array_pop($bits);
1916 if ($this->plugin === 'moodle') {
1917 $this->plugin = null;
1918 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1919 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1925 * Returns the fullname prefixed by the plugin
1926 * @return string
1928 public function get_full_name() {
1929 return 's_'.$this->plugin.'_'.$this->name;
1933 * Returns the ID string based on plugin and name
1934 * @return string
1936 public function get_id() {
1937 return 'id_s_'.$this->plugin.'_'.$this->name;
1941 * @param bool $affectsmodinfo If true, changes to this setting will
1942 * cause the course cache to be rebuilt
1944 public function set_affects_modinfo($affectsmodinfo) {
1945 $this->affectsmodinfo = $affectsmodinfo;
1949 * Returns the config if possible
1951 * @return mixed returns config if successful else null
1953 public function config_read($name) {
1954 global $CFG;
1955 if (!empty($this->plugin)) {
1956 $value = get_config($this->plugin, $name);
1957 return $value === false ? NULL : $value;
1959 } else {
1960 if (isset($CFG->$name)) {
1961 return $CFG->$name;
1962 } else {
1963 return NULL;
1969 * Used to set a config pair and log change
1971 * @param string $name
1972 * @param mixed $value Gets converted to string if not null
1973 * @return bool Write setting to config table
1975 public function config_write($name, $value) {
1976 global $DB, $USER, $CFG;
1978 if ($this->nosave) {
1979 return true;
1982 // make sure it is a real change
1983 $oldvalue = get_config($this->plugin, $name);
1984 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1985 $value = is_null($value) ? null : (string)$value;
1987 if ($oldvalue === $value) {
1988 return true;
1991 // store change
1992 set_config($name, $value, $this->plugin);
1994 // Some admin settings affect course modinfo
1995 if ($this->affectsmodinfo) {
1996 // Clear course cache for all courses
1997 rebuild_course_cache(0, true);
2000 $this->add_to_config_log($name, $oldvalue, $value);
2002 return true; // BC only
2006 * Log config changes if necessary.
2007 * @param string $name
2008 * @param string $oldvalue
2009 * @param string $value
2011 protected function add_to_config_log($name, $oldvalue, $value) {
2012 add_to_config_log($name, $oldvalue, $value, $this->plugin);
2016 * Returns current value of this setting
2017 * @return mixed array or string depending on instance, NULL means not set yet
2019 public abstract function get_setting();
2022 * Returns default setting if exists
2023 * @return mixed array or string depending on instance; NULL means no default, user must supply
2025 public function get_defaultsetting() {
2026 $adminroot = admin_get_root(false, false);
2027 if (!empty($adminroot->custom_defaults)) {
2028 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
2029 if (isset($adminroot->custom_defaults[$plugin])) {
2030 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
2031 return $adminroot->custom_defaults[$plugin][$this->name];
2035 return $this->defaultsetting;
2039 * Store new setting
2041 * @param mixed $data string or array, must not be NULL
2042 * @return string empty string if ok, string error message otherwise
2044 public abstract function write_setting($data);
2047 * Return part of form with setting
2048 * This function should always be overwritten
2050 * @param mixed $data array or string depending on setting
2051 * @param string $query
2052 * @return string
2054 public function output_html($data, $query='') {
2055 // should be overridden
2056 return;
2060 * Function called if setting updated - cleanup, cache reset, etc.
2061 * @param string $functionname Sets the function name
2062 * @return void
2064 public function set_updatedcallback($functionname) {
2065 $this->updatedcallback = $functionname;
2069 * Execute postupdatecallback if necessary.
2070 * @param mixed $original original value before write_setting()
2071 * @return bool true if changed, false if not.
2073 public function post_write_settings($original) {
2074 // Comparison must work for arrays too.
2075 if (serialize($original) === serialize($this->get_setting())) {
2076 return false;
2079 $callbackfunction = $this->updatedcallback;
2080 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2081 $callbackfunction($this->get_full_name());
2083 return true;
2087 * Is setting related to query text - used when searching
2088 * @param string $query
2089 * @return bool
2091 public function is_related($query) {
2092 if (strpos(strtolower($this->name), $query) !== false) {
2093 return true;
2095 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2096 return true;
2098 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2099 return true;
2101 $current = $this->get_setting();
2102 if (!is_null($current)) {
2103 if (is_string($current)) {
2104 if (strpos(core_text::strtolower($current), $query) !== false) {
2105 return true;
2109 $default = $this->get_defaultsetting();
2110 if (!is_null($default)) {
2111 if (is_string($default)) {
2112 if (strpos(core_text::strtolower($default), $query) !== false) {
2113 return true;
2117 return false;
2121 * Get whether this should be displayed in LTR mode.
2123 * @return bool|null
2125 public function get_force_ltr() {
2126 return $this->forceltr;
2130 * Set whether to force LTR or not.
2132 * @param bool $value True when forced, false when not force, null when unknown.
2134 public function set_force_ltr($value) {
2135 $this->forceltr = $value;
2139 * Add a setting to the list of those that could cause this one to be hidden
2140 * @param string $dependenton
2142 public function add_dependent_on($dependenton) {
2143 $this->dependenton[] = $dependenton;
2147 * Get a list of the settings that could cause this one to be hidden.
2148 * @return array
2150 public function get_dependent_on() {
2151 return $this->dependenton;
2155 * Whether this setting uses a custom form control.
2156 * This function is especially useful to decide if we should render a label element for this setting or not.
2158 * @return bool
2160 public function has_custom_form_control(): bool {
2161 return $this->customcontrol;
2166 * An additional option that can be applied to an admin setting.
2167 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2171 class admin_setting_flag {
2172 /** @var bool Flag to indicate if this option can be toggled for this setting */
2173 private $enabled = false;
2174 /** @var bool Flag to indicate if this option defaults to true or false */
2175 private $default = false;
2176 /** @var string Short string used to create setting name - e.g. 'adv' */
2177 private $shortname = '';
2178 /** @var string String used as the label for this flag */
2179 private $displayname = '';
2180 /** @const Checkbox for this flag is displayed in admin page */
2181 const ENABLED = true;
2182 /** @const Checkbox for this flag is not displayed in admin page */
2183 const DISABLED = false;
2186 * Constructor
2188 * @param bool $enabled Can this option can be toggled.
2189 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2190 * @param bool $default The default checked state for this setting option.
2191 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2192 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2194 public function __construct($enabled, $default, $shortname, $displayname) {
2195 $this->shortname = $shortname;
2196 $this->displayname = $displayname;
2197 $this->set_options($enabled, $default);
2201 * Update the values of this setting options class
2203 * @param bool $enabled Can this option can be toggled.
2204 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2205 * @param bool $default The default checked state for this setting option.
2207 public function set_options($enabled, $default) {
2208 $this->enabled = $enabled;
2209 $this->default = $default;
2213 * Should this option appear in the interface and be toggleable?
2215 * @return bool Is it enabled?
2217 public function is_enabled() {
2218 return $this->enabled;
2222 * Should this option be checked by default?
2224 * @return bool Is it on by default?
2226 public function get_default() {
2227 return $this->default;
2231 * Return the short name for this flag. e.g. 'adv' or 'locked'
2233 * @return string
2235 public function get_shortname() {
2236 return $this->shortname;
2240 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2242 * @return string
2244 public function get_displayname() {
2245 return $this->displayname;
2249 * Save the submitted data for this flag - or set it to the default if $data is null.
2251 * @param admin_setting $setting - The admin setting for this flag
2252 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2253 * @return bool
2255 public function write_setting_flag(admin_setting $setting, $data) {
2256 $result = true;
2257 if ($this->is_enabled()) {
2258 if (!isset($data)) {
2259 $value = $this->get_default();
2260 } else {
2261 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2263 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2266 return $result;
2271 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2273 * @param admin_setting $setting - The admin setting for this flag
2274 * @return string - The html for the checkbox.
2276 public function output_setting_flag(admin_setting $setting) {
2277 global $OUTPUT;
2279 $value = $setting->get_setting_flag_value($this);
2281 $context = new stdClass();
2282 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2283 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2284 $context->value = 1;
2285 $context->checked = $value ? true : false;
2286 $context->label = $this->get_displayname();
2288 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2294 * No setting - just heading and text.
2296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2298 class admin_setting_heading extends admin_setting {
2301 * not a setting, just text
2302 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2303 * @param string $heading heading
2304 * @param string $information text in box
2306 public function __construct($name, $heading, $information) {
2307 $this->nosave = true;
2308 parent::__construct($name, $heading, $information, '');
2312 * Always returns true
2313 * @return bool Always returns true
2315 public function get_setting() {
2316 return true;
2320 * Always returns true
2321 * @return bool Always returns true
2323 public function get_defaultsetting() {
2324 return true;
2328 * Never write settings
2329 * @return string Always returns an empty string
2331 public function write_setting($data) {
2332 // do not write any setting
2333 return '';
2337 * Returns an HTML string
2338 * @return string Returns an HTML string
2340 public function output_html($data, $query='') {
2341 global $OUTPUT;
2342 $context = new stdClass();
2343 $context->title = $this->visiblename;
2344 $context->description = $this->description;
2345 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2346 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2351 * No setting - just name and description in same row.
2353 * @copyright 2018 onwards Amaia Anabitarte
2354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2356 class admin_setting_description extends admin_setting {
2359 * Not a setting, just text
2361 * @param string $name
2362 * @param string $visiblename
2363 * @param string $description
2365 public function __construct($name, $visiblename, $description) {
2366 $this->nosave = true;
2367 parent::__construct($name, $visiblename, $description, '');
2371 * Always returns true
2373 * @return bool Always returns true
2375 public function get_setting() {
2376 return true;
2380 * Always returns true
2382 * @return bool Always returns true
2384 public function get_defaultsetting() {
2385 return true;
2389 * Never write settings
2391 * @param mixed $data Gets converted to str for comparison against yes value
2392 * @return string Always returns an empty string
2394 public function write_setting($data) {
2395 // Do not write any setting.
2396 return '';
2400 * Returns an HTML string
2402 * @param string $data
2403 * @param string $query
2404 * @return string Returns an HTML string
2406 public function output_html($data, $query='') {
2407 global $OUTPUT;
2409 $context = new stdClass();
2410 $context->title = $this->visiblename;
2411 $context->description = $this->description;
2413 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2420 * The most flexible setting, the user enters text.
2422 * This type of field should be used for config settings which are using
2423 * English words and are not localised (passwords, database name, list of values, ...).
2425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2427 class admin_setting_configtext extends admin_setting {
2429 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2430 public $paramtype;
2431 /** @var int default field size */
2432 public $size;
2435 * Config text constructor
2437 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2438 * @param string $visiblename localised
2439 * @param string $description long localised info
2440 * @param string $defaultsetting
2441 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2442 * @param int $size default field size
2444 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2445 $this->paramtype = $paramtype;
2446 if (!is_null($size)) {
2447 $this->size = $size;
2448 } else {
2449 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2451 parent::__construct($name, $visiblename, $description, $defaultsetting);
2455 * Get whether this should be displayed in LTR mode.
2457 * Try to guess from the PARAM type unless specifically set.
2459 public function get_force_ltr() {
2460 $forceltr = parent::get_force_ltr();
2461 if ($forceltr === null) {
2462 return !is_rtl_compatible($this->paramtype);
2464 return $forceltr;
2468 * Return the setting
2470 * @return mixed returns config if successful else null
2472 public function get_setting() {
2473 return $this->config_read($this->name);
2476 public function write_setting($data) {
2477 if ($this->paramtype === PARAM_INT and $data === '') {
2478 // do not complain if '' used instead of 0
2479 $data = 0;
2481 // $data is a string
2482 $validated = $this->validate($data);
2483 if ($validated !== true) {
2484 return $validated;
2486 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2490 * Validate data before storage
2491 * @param string data
2492 * @return mixed true if ok string if error found
2494 public function validate($data) {
2495 // allow paramtype to be a custom regex if it is the form of /pattern/
2496 if (preg_match('#^/.*/$#', $this->paramtype)) {
2497 if (preg_match($this->paramtype, $data)) {
2498 return true;
2499 } else {
2500 return get_string('validateerror', 'admin');
2503 } else if ($this->paramtype === PARAM_RAW) {
2504 return true;
2506 } else {
2507 $cleaned = clean_param($data, $this->paramtype);
2508 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2509 return true;
2510 } else {
2511 return get_string('validateerror', 'admin');
2517 * Return an XHTML string for the setting
2518 * @return string Returns an XHTML string
2520 public function output_html($data, $query='') {
2521 global $OUTPUT;
2523 $default = $this->get_defaultsetting();
2524 $context = (object) [
2525 'size' => $this->size,
2526 'id' => $this->get_id(),
2527 'name' => $this->get_full_name(),
2528 'value' => $data,
2529 'forceltr' => $this->get_force_ltr(),
2530 'readonly' => $this->is_readonly(),
2532 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2534 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2539 * Text input with a maximum length constraint.
2541 * @copyright 2015 onwards Ankit Agarwal
2542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2544 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2546 /** @var int maximum number of chars allowed. */
2547 protected $maxlength;
2550 * Config text constructor
2552 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2553 * or 'myplugin/mysetting' for ones in config_plugins.
2554 * @param string $visiblename localised
2555 * @param string $description long localised info
2556 * @param string $defaultsetting
2557 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2558 * @param int $size default field size
2559 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2561 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2562 $size=null, $maxlength = 0) {
2563 $this->maxlength = $maxlength;
2564 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2568 * Validate data before storage
2570 * @param string $data data
2571 * @return mixed true if ok string if error found
2573 public function validate($data) {
2574 $parentvalidation = parent::validate($data);
2575 if ($parentvalidation === true) {
2576 if ($this->maxlength > 0) {
2577 // Max length check.
2578 $length = core_text::strlen($data);
2579 if ($length > $this->maxlength) {
2580 return get_string('maximumchars', 'moodle', $this->maxlength);
2582 return true;
2583 } else {
2584 return true; // No max length check needed.
2586 } else {
2587 return $parentvalidation;
2593 * General text area without html editor.
2595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2597 class admin_setting_configtextarea extends admin_setting_configtext {
2598 private $rows;
2599 private $cols;
2602 * @param string $name
2603 * @param string $visiblename
2604 * @param string $description
2605 * @param mixed $defaultsetting string or array
2606 * @param mixed $paramtype
2607 * @param string $cols The number of columns to make the editor
2608 * @param string $rows The number of rows to make the editor
2610 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2611 $this->rows = $rows;
2612 $this->cols = $cols;
2613 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2617 * Returns an XHTML string for the editor
2619 * @param string $data
2620 * @param string $query
2621 * @return string XHTML string for the editor
2623 public function output_html($data, $query='') {
2624 global $OUTPUT;
2626 $default = $this->get_defaultsetting();
2627 $defaultinfo = $default;
2628 if (!is_null($default) and $default !== '') {
2629 $defaultinfo = "\n".$default;
2632 $context = (object) [
2633 'cols' => $this->cols,
2634 'rows' => $this->rows,
2635 'id' => $this->get_id(),
2636 'name' => $this->get_full_name(),
2637 'value' => $data,
2638 'forceltr' => $this->get_force_ltr(),
2639 'readonly' => $this->is_readonly(),
2641 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2643 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2648 * General text area with html editor.
2650 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2653 * @param string $name
2654 * @param string $visiblename
2655 * @param string $description
2656 * @param mixed $defaultsetting string or array
2657 * @param mixed $paramtype
2659 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2660 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2661 $this->set_force_ltr(false);
2662 editors_head_setup();
2666 * Returns an XHTML string for the editor
2668 * @param string $data
2669 * @param string $query
2670 * @return string XHTML string for the editor
2672 public function output_html($data, $query='') {
2673 $editor = editors_get_preferred_editor(FORMAT_HTML);
2674 $editor->set_text($data);
2675 $editor->use_editor($this->get_id(), array('noclean'=>true));
2676 return parent::output_html($data, $query);
2680 * Checks if data has empty html.
2682 * @param string $data
2683 * @return string Empty when no errors.
2685 public function write_setting($data) {
2686 if (trim(html_to_text($data)) === '') {
2687 $data = '';
2689 return parent::write_setting($data);
2695 * Password field, allows unmasking of password
2697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2699 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2702 * Constructor
2703 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2704 * @param string $visiblename localised
2705 * @param string $description long localised info
2706 * @param string $defaultsetting default password
2708 public function __construct($name, $visiblename, $description, $defaultsetting) {
2709 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2713 * Log config changes if necessary.
2714 * @param string $name
2715 * @param string $oldvalue
2716 * @param string $value
2718 protected function add_to_config_log($name, $oldvalue, $value) {
2719 if ($value !== '') {
2720 $value = '********';
2722 if ($oldvalue !== '' and $oldvalue !== null) {
2723 $oldvalue = '********';
2725 parent::add_to_config_log($name, $oldvalue, $value);
2729 * Returns HTML for the field.
2731 * @param string $data Value for the field
2732 * @param string $query Passed as final argument for format_admin_setting
2733 * @return string Rendered HTML
2735 public function output_html($data, $query='') {
2736 global $OUTPUT;
2738 $context = (object) [
2739 'id' => $this->get_id(),
2740 'name' => $this->get_full_name(),
2741 'size' => $this->size,
2742 'value' => $this->is_readonly() ? null : $data,
2743 'forceltr' => $this->get_force_ltr(),
2744 'readonly' => $this->is_readonly(),
2746 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2747 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2752 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2755 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2757 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2760 * Constructor
2762 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2763 * @param string $visiblename localised
2764 * @param string $description long localised info
2765 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2767 public function __construct($name, $visiblename, $description, $defaultsetting) {
2768 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2769 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2774 * Admin setting class for encrypted values using secure encryption.
2776 * @copyright 2019 The Open University
2777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2779 class admin_setting_encryptedpassword extends admin_setting {
2782 * Constructor. Same as parent except that the default value is always an empty string.
2784 * @param string $name Internal name used in config table
2785 * @param string $visiblename Name shown on form
2786 * @param string $description Description that appears below field
2788 public function __construct(string $name, string $visiblename, string $description) {
2789 parent::__construct($name, $visiblename, $description, '');
2792 public function get_setting() {
2793 return $this->config_read($this->name);
2796 public function write_setting($data) {
2797 $data = trim($data);
2798 if ($data === '') {
2799 // Value can really be set to nothing.
2800 $savedata = '';
2801 } else {
2802 // Encrypt value before saving it.
2803 $savedata = \core\encryption::encrypt($data);
2805 return ($this->config_write($this->name, $savedata) ? '' : get_string('errorsetting', 'admin'));
2808 public function output_html($data, $query='') {
2809 global $OUTPUT;
2811 $default = $this->get_defaultsetting();
2812 $context = (object) [
2813 'id' => $this->get_id(),
2814 'name' => $this->get_full_name(),
2815 'set' => $data !== '',
2816 'novalue' => $this->get_setting() === null
2818 $element = $OUTPUT->render_from_template('core_admin/setting_encryptedpassword', $context);
2820 return format_admin_setting($this, $this->visiblename, $element, $this->description,
2821 true, '', $default, $query);
2826 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2827 * Note: Only advanced makes sense right now - locked does not.
2829 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2831 class admin_setting_configempty extends admin_setting_configtext {
2834 * @param string $name
2835 * @param string $visiblename
2836 * @param string $description
2838 public function __construct($name, $visiblename, $description) {
2839 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2843 * Returns an XHTML string for the hidden field
2845 * @param string $data
2846 * @param string $query
2847 * @return string XHTML string for the editor
2849 public function output_html($data, $query='') {
2850 global $OUTPUT;
2852 $context = (object) [
2853 'id' => $this->get_id(),
2854 'name' => $this->get_full_name()
2856 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2858 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2864 * Path to directory
2866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2868 class admin_setting_configfile extends admin_setting_configtext {
2870 * Constructor
2871 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2872 * @param string $visiblename localised
2873 * @param string $description long localised info
2874 * @param string $defaultdirectory default directory location
2876 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2877 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2881 * Returns XHTML for the field
2883 * Returns XHTML for the field and also checks whether the file
2884 * specified in $data exists using file_exists()
2886 * @param string $data File name and path to use in value attr
2887 * @param string $query
2888 * @return string XHTML field
2890 public function output_html($data, $query='') {
2891 global $CFG, $OUTPUT;
2893 $default = $this->get_defaultsetting();
2894 $context = (object) [
2895 'id' => $this->get_id(),
2896 'name' => $this->get_full_name(),
2897 'size' => $this->size,
2898 'value' => $data,
2899 'showvalidity' => !empty($data),
2900 'valid' => $data && file_exists($data),
2901 'readonly' => !empty($CFG->preventexecpath) || $this->is_readonly(),
2902 'forceltr' => $this->get_force_ltr(),
2905 if ($context->readonly) {
2906 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2909 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2911 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2915 * Checks if execpatch has been disabled in config.php
2917 public function write_setting($data) {
2918 global $CFG;
2919 if (!empty($CFG->preventexecpath)) {
2920 if ($this->get_setting() === null) {
2921 // Use default during installation.
2922 $data = $this->get_defaultsetting();
2923 if ($data === null) {
2924 $data = '';
2926 } else {
2927 return '';
2930 return parent::write_setting($data);
2937 * Path to executable file
2939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2941 class admin_setting_configexecutable extends admin_setting_configfile {
2944 * Returns an XHTML field
2946 * @param string $data This is the value for the field
2947 * @param string $query
2948 * @return string XHTML field
2950 public function output_html($data, $query='') {
2951 global $CFG, $OUTPUT;
2952 $default = $this->get_defaultsetting();
2953 require_once("$CFG->libdir/filelib.php");
2955 $context = (object) [
2956 'id' => $this->get_id(),
2957 'name' => $this->get_full_name(),
2958 'size' => $this->size,
2959 'value' => $data,
2960 'showvalidity' => !empty($data),
2961 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2962 'readonly' => !empty($CFG->preventexecpath),
2963 'forceltr' => $this->get_force_ltr()
2966 if (!empty($CFG->preventexecpath)) {
2967 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2970 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2972 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2978 * Path to directory
2980 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2982 class admin_setting_configdirectory extends admin_setting_configfile {
2985 * Returns an XHTML field
2987 * @param string $data This is the value for the field
2988 * @param string $query
2989 * @return string XHTML
2991 public function output_html($data, $query='') {
2992 global $CFG, $OUTPUT;
2993 $default = $this->get_defaultsetting();
2995 $context = (object) [
2996 'id' => $this->get_id(),
2997 'name' => $this->get_full_name(),
2998 'size' => $this->size,
2999 'value' => $data,
3000 'showvalidity' => !empty($data),
3001 'valid' => $data && file_exists($data) && is_dir($data),
3002 'readonly' => !empty($CFG->preventexecpath),
3003 'forceltr' => $this->get_force_ltr()
3006 if (!empty($CFG->preventexecpath)) {
3007 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
3010 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
3012 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
3018 * Checkbox
3020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3022 class admin_setting_configcheckbox extends admin_setting {
3023 /** @var string Value used when checked */
3024 public $yes;
3025 /** @var string Value used when not checked */
3026 public $no;
3029 * Constructor
3030 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3031 * @param string $visiblename localised
3032 * @param string $description long localised info
3033 * @param string $defaultsetting
3034 * @param string $yes value used when checked
3035 * @param string $no value used when not checked
3037 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3038 parent::__construct($name, $visiblename, $description, $defaultsetting);
3039 $this->yes = (string)$yes;
3040 $this->no = (string)$no;
3044 * Retrieves the current setting using the objects name
3046 * @return string
3048 public function get_setting() {
3049 return $this->config_read($this->name);
3053 * Sets the value for the setting
3055 * Sets the value for the setting to either the yes or no values
3056 * of the object by comparing $data to yes
3058 * @param mixed $data Gets converted to str for comparison against yes value
3059 * @return string empty string or error
3061 public function write_setting($data) {
3062 if ((string)$data === $this->yes) { // convert to strings before comparison
3063 $data = $this->yes;
3064 } else {
3065 $data = $this->no;
3067 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3071 * Returns an XHTML checkbox field
3073 * @param string $data If $data matches yes then checkbox is checked
3074 * @param string $query
3075 * @return string XHTML field
3077 public function output_html($data, $query='') {
3078 global $OUTPUT;
3080 $context = (object) [
3081 'id' => $this->get_id(),
3082 'name' => $this->get_full_name(),
3083 'no' => $this->no,
3084 'value' => $this->yes,
3085 'checked' => (string) $data === $this->yes,
3086 'readonly' => $this->is_readonly(),
3089 $default = $this->get_defaultsetting();
3090 if (!is_null($default)) {
3091 if ((string)$default === $this->yes) {
3092 $defaultinfo = get_string('checkboxyes', 'admin');
3093 } else {
3094 $defaultinfo = get_string('checkboxno', 'admin');
3096 } else {
3097 $defaultinfo = NULL;
3100 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
3102 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3108 * Multiple checkboxes, each represents different value, stored in csv format
3110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3112 class admin_setting_configmulticheckbox extends admin_setting {
3113 /** @var array Array of choices value=>label */
3114 public $choices;
3115 /** @var callable|null Loader function for choices */
3116 protected $choiceloader = null;
3119 * Constructor: uses parent::__construct
3121 * The $choices parameter may be either an array of $value => $label format,
3122 * e.g. [1 => get_string('yes')], or a callback function which takes no parameters and
3123 * returns an array in that format.
3125 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3126 * @param string $visiblename localised
3127 * @param string $description long localised info
3128 * @param array $defaultsetting array of selected
3129 * @param array|callable $choices array of $value => $label for each checkbox, or a callback
3131 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3132 if (is_array($choices)) {
3133 $this->choices = $choices;
3135 if (is_callable($choices)) {
3136 $this->choiceloader = $choices;
3138 parent::__construct($name, $visiblename, $description, $defaultsetting);
3142 * This function may be used in ancestors for lazy loading of choices
3144 * Override this method if loading of choices is expensive, such
3145 * as when it requires multiple db requests.
3147 * @return bool true if loaded, false if error
3149 public function load_choices() {
3150 if ($this->choiceloader) {
3151 if (!is_array($this->choices)) {
3152 $this->choices = call_user_func($this->choiceloader);
3155 return true;
3159 * Is setting related to query text - used when searching
3161 * @param string $query
3162 * @return bool true on related, false on not or failure
3164 public function is_related($query) {
3165 if (!$this->load_choices() or empty($this->choices)) {
3166 return false;
3168 if (parent::is_related($query)) {
3169 return true;
3172 foreach ($this->choices as $desc) {
3173 if (strpos(core_text::strtolower($desc), $query) !== false) {
3174 return true;
3177 return false;
3181 * Returns the current setting if it is set
3183 * @return mixed null if null, else an array
3185 public function get_setting() {
3186 $result = $this->config_read($this->name);
3188 if (is_null($result)) {
3189 return NULL;
3191 if ($result === '') {
3192 return array();
3194 $enabled = explode(',', $result);
3195 $setting = array();
3196 foreach ($enabled as $option) {
3197 $setting[$option] = 1;
3199 return $setting;
3203 * Saves the setting(s) provided in $data
3205 * @param array $data An array of data, if not array returns empty str
3206 * @return mixed empty string on useless data or bool true=success, false=failed
3208 public function write_setting($data) {
3209 if (!is_array($data)) {
3210 return ''; // ignore it
3212 if (!$this->load_choices() or empty($this->choices)) {
3213 return '';
3215 unset($data['xxxxx']);
3216 $result = array();
3217 foreach ($data as $key => $value) {
3218 if ($value and array_key_exists($key, $this->choices)) {
3219 $result[] = $key;
3222 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3226 * Returns XHTML field(s) as required by choices
3228 * Relies on data being an array should data ever be another valid vartype with
3229 * acceptable value this may cause a warning/error
3230 * if (!is_array($data)) would fix the problem
3232 * @todo Add vartype handling to ensure $data is an array
3234 * @param array $data An array of checked values
3235 * @param string $query
3236 * @return string XHTML field
3238 public function output_html($data, $query='') {
3239 global $OUTPUT;
3241 if (!$this->load_choices() or empty($this->choices)) {
3242 return '';
3245 $default = $this->get_defaultsetting();
3246 if (is_null($default)) {
3247 $default = array();
3249 if (is_null($data)) {
3250 $data = array();
3253 $context = (object) [
3254 'id' => $this->get_id(),
3255 'name' => $this->get_full_name(),
3258 $options = array();
3259 $defaults = array();
3260 foreach ($this->choices as $key => $description) {
3261 if (!empty($default[$key])) {
3262 $defaults[] = $description;
3265 $options[] = [
3266 'key' => $key,
3267 'checked' => !empty($data[$key]),
3268 'label' => highlightfast($query, $description)
3272 if (is_null($default)) {
3273 $defaultinfo = null;
3274 } else if (!empty($defaults)) {
3275 $defaultinfo = implode(', ', $defaults);
3276 } else {
3277 $defaultinfo = get_string('none');
3280 $context->options = $options;
3281 $context->hasoptions = !empty($options);
3283 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3285 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3292 * Multiple checkboxes 2, value stored as string 00101011
3294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3296 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3299 * Returns the setting if set
3301 * @return mixed null if not set, else an array of set settings
3303 public function get_setting() {
3304 $result = $this->config_read($this->name);
3305 if (is_null($result)) {
3306 return NULL;
3308 if (!$this->load_choices()) {
3309 return NULL;
3311 $result = str_pad($result, count($this->choices), '0');
3312 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3313 $setting = array();
3314 foreach ($this->choices as $key=>$unused) {
3315 $value = array_shift($result);
3316 if ($value) {
3317 $setting[$key] = 1;
3320 return $setting;
3324 * Save setting(s) provided in $data param
3326 * @param array $data An array of settings to save
3327 * @return mixed empty string for bad data or bool true=>success, false=>error
3329 public function write_setting($data) {
3330 if (!is_array($data)) {
3331 return ''; // ignore it
3333 if (!$this->load_choices() or empty($this->choices)) {
3334 return '';
3336 $result = '';
3337 foreach ($this->choices as $key=>$unused) {
3338 if (!empty($data[$key])) {
3339 $result .= '1';
3340 } else {
3341 $result .= '0';
3344 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3350 * Select one value from list
3352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3354 class admin_setting_configselect extends admin_setting {
3355 /** @var array Array of choices value=>label */
3356 public $choices;
3357 /** @var array Array of choices grouped using optgroups */
3358 public $optgroups;
3359 /** @var callable|null Loader function for choices */
3360 protected $choiceloader = null;
3361 /** @var callable|null Validation function */
3362 protected $validatefunction = null;
3365 * Constructor.
3367 * If you want to lazy-load the choices, pass a callback function that returns a choice
3368 * array for the $choices parameter.
3370 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3371 * @param string $visiblename localised
3372 * @param string $description long localised info
3373 * @param string|int $defaultsetting
3374 * @param array|callable|null $choices array of $value=>$label for each selection, or callback
3376 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3377 // Look for optgroup and single options.
3378 if (is_array($choices)) {
3379 $this->choices = [];
3380 foreach ($choices as $key => $val) {
3381 if (is_array($val)) {
3382 $this->optgroups[$key] = $val;
3383 $this->choices = array_merge($this->choices, $val);
3384 } else {
3385 $this->choices[$key] = $val;
3389 if (is_callable($choices)) {
3390 $this->choiceloader = $choices;
3393 parent::__construct($name, $visiblename, $description, $defaultsetting);
3397 * Sets a validate function.
3399 * The callback will be passed one parameter, the new setting value, and should return either
3400 * an empty string '' if the value is OK, or an error message if not.
3402 * @param callable|null $validatefunction Validate function or null to clear
3403 * @since Moodle 3.10
3405 public function set_validate_function(?callable $validatefunction = null) {
3406 $this->validatefunction = $validatefunction;
3410 * This function may be used in ancestors for lazy loading of choices
3412 * Override this method if loading of choices is expensive, such
3413 * as when it requires multiple db requests.
3415 * @return bool true if loaded, false if error
3417 public function load_choices() {
3418 if ($this->choiceloader) {
3419 if (!is_array($this->choices)) {
3420 $this->choices = call_user_func($this->choiceloader);
3422 return true;
3424 return true;
3428 * Check if this is $query is related to a choice
3430 * @param string $query
3431 * @return bool true if related, false if not
3433 public function is_related($query) {
3434 if (parent::is_related($query)) {
3435 return true;
3437 if (!$this->load_choices()) {
3438 return false;
3440 foreach ($this->choices as $key=>$value) {
3441 if (strpos(core_text::strtolower($key), $query) !== false) {
3442 return true;
3444 if (strpos(core_text::strtolower($value), $query) !== false) {
3445 return true;
3448 return false;
3452 * Return the setting
3454 * @return mixed returns config if successful else null
3456 public function get_setting() {
3457 return $this->config_read($this->name);
3461 * Save a setting
3463 * @param string $data
3464 * @return string empty of error string
3466 public function write_setting($data) {
3467 if (!$this->load_choices() or empty($this->choices)) {
3468 return '';
3470 if (!array_key_exists($data, $this->choices)) {
3471 return ''; // ignore it
3474 // Validate the new setting.
3475 $error = $this->validate_setting($data);
3476 if ($error) {
3477 return $error;
3480 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3484 * Validate the setting. This uses the callback function if provided; subclasses could override
3485 * to carry out validation directly in the class.
3487 * @param string $data New value being set
3488 * @return string Empty string if valid, or error message text
3489 * @since Moodle 3.10
3491 protected function validate_setting(string $data): string {
3492 // If validation function is specified, call it now.
3493 if ($this->validatefunction) {
3494 return call_user_func($this->validatefunction, $data);
3495 } else {
3496 return '';
3501 * Returns XHTML select field
3503 * Ensure the options are loaded, and generate the XHTML for the select
3504 * element and any warning message. Separating this out from output_html
3505 * makes it easier to subclass this class.
3507 * @param string $data the option to show as selected.
3508 * @param string $current the currently selected option in the database, null if none.
3509 * @param string $default the default selected option.
3510 * @return array the HTML for the select element, and a warning message.
3511 * @deprecated since Moodle 3.2
3513 public function output_select_html($data, $current, $default, $extraname = '') {
3514 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3518 * Returns XHTML select field and wrapping div(s)
3520 * @see output_select_html()
3522 * @param string $data the option to show as selected
3523 * @param string $query
3524 * @return string XHTML field and wrapping div
3526 public function output_html($data, $query='') {
3527 global $OUTPUT;
3529 $default = $this->get_defaultsetting();
3530 $current = $this->get_setting();
3532 if (!$this->load_choices() || empty($this->choices)) {
3533 return '';
3536 $context = (object) [
3537 'id' => $this->get_id(),
3538 'name' => $this->get_full_name(),
3541 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3542 $defaultinfo = $this->choices[$default];
3543 } else {
3544 $defaultinfo = NULL;
3547 // Warnings.
3548 $warning = '';
3549 if ($current === null) {
3550 // First run.
3551 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3552 // No warning.
3553 } else if (!array_key_exists($current, $this->choices)) {
3554 $warning = get_string('warningcurrentsetting', 'admin', $current);
3555 if (!is_null($default) && $data == $current) {
3556 $data = $default; // Use default instead of first value when showing the form.
3560 $options = [];
3561 $template = 'core_admin/setting_configselect';
3563 if (!empty($this->optgroups)) {
3564 $optgroups = [];
3565 foreach ($this->optgroups as $label => $choices) {
3566 $optgroup = array('label' => $label, 'options' => []);
3567 foreach ($choices as $value => $name) {
3568 $optgroup['options'][] = [
3569 'value' => $value,
3570 'name' => $name,
3571 'selected' => (string) $value == $data
3573 unset($this->choices[$value]);
3575 $optgroups[] = $optgroup;
3577 $context->options = $options;
3578 $context->optgroups = $optgroups;
3579 $template = 'core_admin/setting_configselect_optgroup';
3582 foreach ($this->choices as $value => $name) {
3583 $options[] = [
3584 'value' => $value,
3585 'name' => $name,
3586 'selected' => (string) $value == $data
3589 $context->options = $options;
3590 $context->readonly = $this->is_readonly();
3592 $element = $OUTPUT->render_from_template($template, $context);
3594 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3599 * Select multiple items from list
3601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3603 class admin_setting_configmultiselect extends admin_setting_configselect {
3605 * Constructor
3606 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3607 * @param string $visiblename localised
3608 * @param string $description long localised info
3609 * @param array $defaultsetting array of selected items
3610 * @param array $choices array of $value=>$label for each list item
3612 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3613 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3617 * Returns the select setting(s)
3619 * @return mixed null or array. Null if no settings else array of setting(s)
3621 public function get_setting() {
3622 $result = $this->config_read($this->name);
3623 if (is_null($result)) {
3624 return NULL;
3626 if ($result === '') {
3627 return array();
3629 return explode(',', $result);
3633 * Saves setting(s) provided through $data
3635 * Potential bug in the works should anyone call with this function
3636 * using a vartype that is not an array
3638 * @param array $data
3640 public function write_setting($data) {
3641 if (!is_array($data)) {
3642 return ''; //ignore it
3644 if (!$this->load_choices() or empty($this->choices)) {
3645 return '';
3648 unset($data['xxxxx']);
3650 $save = array();
3651 foreach ($data as $value) {
3652 if (!array_key_exists($value, $this->choices)) {
3653 continue; // ignore it
3655 $save[] = $value;
3658 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3662 * Is setting related to query text - used when searching
3664 * @param string $query
3665 * @return bool true if related, false if not
3667 public function is_related($query) {
3668 if (!$this->load_choices() or empty($this->choices)) {
3669 return false;
3671 if (parent::is_related($query)) {
3672 return true;
3675 foreach ($this->choices as $desc) {
3676 if (strpos(core_text::strtolower($desc), $query) !== false) {
3677 return true;
3680 return false;
3684 * Returns XHTML multi-select field
3686 * @todo Add vartype handling to ensure $data is an array
3687 * @param array $data Array of values to select by default
3688 * @param string $query
3689 * @return string XHTML multi-select field
3691 public function output_html($data, $query='') {
3692 global $OUTPUT;
3694 if (!$this->load_choices() or empty($this->choices)) {
3695 return '';
3698 $default = $this->get_defaultsetting();
3699 if (is_null($default)) {
3700 $default = array();
3702 if (is_null($data)) {
3703 $data = array();
3706 $context = (object) [
3707 'id' => $this->get_id(),
3708 'name' => $this->get_full_name(),
3709 'size' => min(10, count($this->choices))
3712 $defaults = [];
3713 $options = [];
3714 $template = 'core_admin/setting_configmultiselect';
3716 if (!empty($this->optgroups)) {
3717 $optgroups = [];
3718 foreach ($this->optgroups as $label => $choices) {
3719 $optgroup = array('label' => $label, 'options' => []);
3720 foreach ($choices as $value => $name) {
3721 if (in_array($value, $default)) {
3722 $defaults[] = $name;
3724 $optgroup['options'][] = [
3725 'value' => $value,
3726 'name' => $name,
3727 'selected' => in_array($value, $data)
3729 unset($this->choices[$value]);
3731 $optgroups[] = $optgroup;
3733 $context->optgroups = $optgroups;
3734 $template = 'core_admin/setting_configmultiselect_optgroup';
3737 foreach ($this->choices as $value => $name) {
3738 if (in_array($value, $default)) {
3739 $defaults[] = $name;
3741 $options[] = [
3742 'value' => $value,
3743 'name' => $name,
3744 'selected' => in_array($value, $data)
3747 $context->options = $options;
3748 $context->readonly = $this->is_readonly();
3750 if (is_null($default)) {
3751 $defaultinfo = NULL;
3752 } if (!empty($defaults)) {
3753 $defaultinfo = implode(', ', $defaults);
3754 } else {
3755 $defaultinfo = get_string('none');
3758 $element = $OUTPUT->render_from_template($template, $context);
3760 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3765 * Time selector
3767 * This is a liiitle bit messy. we're using two selects, but we're returning
3768 * them as an array named after $name (so we only use $name2 internally for the setting)
3770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3772 class admin_setting_configtime extends admin_setting {
3773 /** @var string Used for setting second select (minutes) */
3774 public $name2;
3777 * Constructor
3778 * @param string $hoursname setting for hours
3779 * @param string $minutesname setting for hours
3780 * @param string $visiblename localised
3781 * @param string $description long localised info
3782 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3784 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3785 $this->name2 = $minutesname;
3786 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3790 * Get the selected time
3792 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3794 public function get_setting() {
3795 $result1 = $this->config_read($this->name);
3796 $result2 = $this->config_read($this->name2);
3797 if (is_null($result1) or is_null($result2)) {
3798 return NULL;
3801 return array('h' => $result1, 'm' => $result2);
3805 * Store the time (hours and minutes)
3807 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3808 * @return bool true if success, false if not
3810 public function write_setting($data) {
3811 if (!is_array($data)) {
3812 return '';
3815 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3816 return ($result ? '' : get_string('errorsetting', 'admin'));
3820 * Returns XHTML time select fields
3822 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3823 * @param string $query
3824 * @return string XHTML time select fields and wrapping div(s)
3826 public function output_html($data, $query='') {
3827 global $OUTPUT;
3829 $default = $this->get_defaultsetting();
3830 if (is_array($default)) {
3831 $defaultinfo = $default['h'].':'.$default['m'];
3832 } else {
3833 $defaultinfo = NULL;
3836 $context = (object) [
3837 'id' => $this->get_id(),
3838 'name' => $this->get_full_name(),
3839 'readonly' => $this->is_readonly(),
3840 'hours' => array_map(function($i) use ($data) {
3841 return [
3842 'value' => $i,
3843 'name' => $i,
3844 'selected' => $i == $data['h']
3846 }, range(0, 23)),
3847 'minutes' => array_map(function($i) use ($data) {
3848 return [
3849 'value' => $i,
3850 'name' => $i,
3851 'selected' => $i == $data['m']
3853 }, range(0, 59, 5))
3856 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3858 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3859 $this->get_id() . 'h', '', $defaultinfo, $query);
3866 * Seconds duration setting.
3868 * @copyright 2012 Petr Skoda (http://skodak.org)
3869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3871 class admin_setting_configduration extends admin_setting {
3873 /** @var int default duration unit */
3874 protected $defaultunit;
3875 /** @var callable|null Validation function */
3876 protected $validatefunction = null;
3879 * Constructor
3880 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3881 * or 'myplugin/mysetting' for ones in config_plugins.
3882 * @param string $visiblename localised name
3883 * @param string $description localised long description
3884 * @param mixed $defaultsetting string or array depending on implementation
3885 * @param int $defaultunit - day, week, etc. (in seconds)
3887 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3888 if (is_number($defaultsetting)) {
3889 $defaultsetting = self::parse_seconds($defaultsetting);
3891 $units = self::get_units();
3892 if (isset($units[$defaultunit])) {
3893 $this->defaultunit = $defaultunit;
3894 } else {
3895 $this->defaultunit = 86400;
3897 parent::__construct($name, $visiblename, $description, $defaultsetting);
3901 * Sets a validate function.
3903 * The callback will be passed one parameter, the new setting value, and should return either
3904 * an empty string '' if the value is OK, or an error message if not.
3906 * @param callable|null $validatefunction Validate function or null to clear
3907 * @since Moodle 3.10
3909 public function set_validate_function(?callable $validatefunction = null) {
3910 $this->validatefunction = $validatefunction;
3914 * Validate the setting. This uses the callback function if provided; subclasses could override
3915 * to carry out validation directly in the class.
3917 * @param int $data New value being set
3918 * @return string Empty string if valid, or error message text
3919 * @since Moodle 3.10
3921 protected function validate_setting(int $data): string {
3922 // If validation function is specified, call it now.
3923 if ($this->validatefunction) {
3924 return call_user_func($this->validatefunction, $data);
3925 } else {
3926 if ($data < 0) {
3927 return get_string('errorsetting', 'admin');
3929 return '';
3934 * Returns selectable units.
3935 * @static
3936 * @return array
3938 protected static function get_units() {
3939 return array(
3940 604800 => get_string('weeks'),
3941 86400 => get_string('days'),
3942 3600 => get_string('hours'),
3943 60 => get_string('minutes'),
3944 1 => get_string('seconds'),
3949 * Converts seconds to some more user friendly string.
3950 * @static
3951 * @param int $seconds
3952 * @return string
3954 protected static function get_duration_text($seconds) {
3955 if (empty($seconds)) {
3956 return get_string('none');
3958 $data = self::parse_seconds($seconds);
3959 switch ($data['u']) {
3960 case (60*60*24*7):
3961 return get_string('numweeks', '', $data['v']);
3962 case (60*60*24):
3963 return get_string('numdays', '', $data['v']);
3964 case (60*60):
3965 return get_string('numhours', '', $data['v']);
3966 case (60):
3967 return get_string('numminutes', '', $data['v']);
3968 default:
3969 return get_string('numseconds', '', $data['v']*$data['u']);
3974 * Finds suitable units for given duration.
3975 * @static
3976 * @param int $seconds
3977 * @return array
3979 protected static function parse_seconds($seconds) {
3980 foreach (self::get_units() as $unit => $unused) {
3981 if ($seconds % $unit === 0) {
3982 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3985 return array('v'=>(int)$seconds, 'u'=>1);
3989 * Get the selected duration as array.
3991 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3993 public function get_setting() {
3994 $seconds = $this->config_read($this->name);
3995 if (is_null($seconds)) {
3996 return null;
3999 return self::parse_seconds($seconds);
4003 * Store the duration as seconds.
4005 * @param array $data Must be form 'h'=>xx, 'm'=>xx
4006 * @return bool true if success, false if not
4008 public function write_setting($data) {
4009 if (!is_array($data)) {
4010 return '';
4013 $seconds = (int)($data['v']*$data['u']);
4015 // Validate the new setting.
4016 $error = $this->validate_setting($seconds);
4017 if ($error) {
4018 return $error;
4021 $result = $this->config_write($this->name, $seconds);
4022 return ($result ? '' : get_string('errorsetting', 'admin'));
4026 * Returns duration text+select fields.
4028 * @param array $data Must be form 'v'=>xx, 'u'=>xx
4029 * @param string $query
4030 * @return string duration text+select fields and wrapping div(s)
4032 public function output_html($data, $query='') {
4033 global $OUTPUT;
4035 $default = $this->get_defaultsetting();
4036 if (is_number($default)) {
4037 $defaultinfo = self::get_duration_text($default);
4038 } else if (is_array($default)) {
4039 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
4040 } else {
4041 $defaultinfo = null;
4044 $inputid = $this->get_id() . 'v';
4045 $units = self::get_units();
4046 $defaultunit = $this->defaultunit;
4048 $context = (object) [
4049 'id' => $this->get_id(),
4050 'name' => $this->get_full_name(),
4051 'value' => $data['v'],
4052 'readonly' => $this->is_readonly(),
4053 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
4054 return [
4055 'value' => $unit,
4056 'name' => $units[$unit],
4057 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
4059 }, array_keys($units))
4062 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
4064 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
4070 * Seconds duration setting with an advanced checkbox, that controls a additional
4071 * $name.'_adv' setting.
4073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4074 * @copyright 2014 The Open University
4076 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
4078 * Constructor
4079 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
4080 * or 'myplugin/mysetting' for ones in config_plugins.
4081 * @param string $visiblename localised name
4082 * @param string $description localised long description
4083 * @param array $defaultsetting array of int value, and bool whether it is
4084 * is advanced by default.
4085 * @param int $defaultunit - day, week, etc. (in seconds)
4087 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
4088 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
4089 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4095 * Used to validate a textarea used for ip addresses
4097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4098 * @copyright 2011 Petr Skoda (http://skodak.org)
4100 class admin_setting_configiplist extends admin_setting_configtextarea {
4103 * Validate the contents of the textarea as IP addresses
4105 * Used to validate a new line separated list of IP addresses collected from
4106 * a textarea control
4108 * @param string $data A list of IP Addresses separated by new lines
4109 * @return mixed bool true for success or string:error on failure
4111 public function validate($data) {
4112 if(!empty($data)) {
4113 $lines = explode("\n", $data);
4114 } else {
4115 return true;
4117 $result = true;
4118 $badips = array();
4119 foreach ($lines as $line) {
4120 $tokens = explode('#', $line);
4121 $ip = trim($tokens[0]);
4122 if (empty($ip)) {
4123 continue;
4125 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
4126 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
4127 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4128 } else {
4129 $result = false;
4130 $badips[] = $ip;
4133 if($result) {
4134 return true;
4135 } else {
4136 return get_string('validateiperror', 'admin', join(', ', $badips));
4142 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
4144 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4145 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4147 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
4150 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
4151 * Used to validate a new line separated list of entries collected from a textarea control.
4153 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
4154 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
4155 * via the get_setting() method, which has been overriden.
4157 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
4158 * @return mixed bool true for success or string:error on failure
4160 public function validate($data) {
4161 if (empty($data)) {
4162 return true;
4164 $entries = explode("\n", $data);
4165 $badentries = [];
4167 foreach ($entries as $key => $entry) {
4168 $entry = trim($entry);
4169 if (empty($entry)) {
4170 return get_string('validateemptylineerror', 'admin');
4173 // Validate each string entry against the supported formats.
4174 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
4175 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
4176 || \core\ip_utils::is_domain_matching_pattern($entry)) {
4177 continue;
4180 // Otherwise, the entry is invalid.
4181 $badentries[] = $entry;
4184 if ($badentries) {
4185 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
4187 return true;
4191 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
4193 * @param string $data the setting data, as sent from the web form.
4194 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
4196 protected function ace_encode($data) {
4197 if (empty($data)) {
4198 return $data;
4200 $entries = explode("\n", $data);
4201 foreach ($entries as $key => $entry) {
4202 $entry = trim($entry);
4203 // This regex matches any string that has non-ascii character.
4204 if (preg_match('/[^\x00-\x7f]/', $entry)) {
4205 // If we can convert the unicode string to an idn, do so.
4206 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
4207 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4208 $entries[$key] = $val ? $val : $entry;
4211 return implode("\n", $entries);
4215 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4217 * @param string $data the setting data, as found in the database.
4218 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4220 protected function ace_decode($data) {
4221 $entries = explode("\n", $data);
4222 foreach ($entries as $key => $entry) {
4223 $entry = trim($entry);
4224 if (strpos($entry, 'xn--') !== false) {
4225 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4228 return implode("\n", $entries);
4232 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4234 * @return mixed returns punycode-converted setting string if successful, else null.
4236 public function get_setting() {
4237 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4238 $data = $this->config_read($this->name);
4239 if (function_exists('idn_to_utf8') && !is_null($data)) {
4240 $data = $this->ace_decode($data);
4242 return $data;
4246 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4248 * @param string $data
4249 * @return string
4251 public function write_setting($data) {
4252 if ($this->paramtype === PARAM_INT and $data === '') {
4253 // Do not complain if '' used instead of 0.
4254 $data = 0;
4257 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4258 if (function_exists('idn_to_ascii')) {
4259 $data = $this->ace_encode($data);
4262 $validated = $this->validate($data);
4263 if ($validated !== true) {
4264 return $validated;
4266 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4271 * Used to validate a textarea used for port numbers.
4273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4274 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4276 class admin_setting_configportlist extends admin_setting_configtextarea {
4279 * Validate the contents of the textarea as port numbers.
4280 * Used to validate a new line separated list of ports collected from a textarea control.
4282 * @param string $data A list of ports separated by new lines
4283 * @return mixed bool true for success or string:error on failure
4285 public function validate($data) {
4286 if (empty($data)) {
4287 return true;
4289 $ports = explode("\n", $data);
4290 $badentries = [];
4291 foreach ($ports as $port) {
4292 $port = trim($port);
4293 if (empty($port)) {
4294 return get_string('validateemptylineerror', 'admin');
4297 // Is the string a valid integer number?
4298 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4299 $badentries[] = $port;
4302 if ($badentries) {
4303 return get_string('validateerrorlist', 'admin', $badentries);
4305 return true;
4311 * An admin setting for selecting one or more users who have a capability
4312 * in the system context
4314 * An admin setting for selecting one or more users, who have a particular capability
4315 * in the system context. Warning, make sure the list will never be too long. There is
4316 * no paging or searching of this list.
4318 * To correctly get a list of users from this config setting, you need to call the
4319 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4323 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4324 /** @var string The capabilities name */
4325 protected $capability;
4326 /** @var int include admin users too */
4327 protected $includeadmins;
4330 * Constructor.
4332 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4333 * @param string $visiblename localised name
4334 * @param string $description localised long description
4335 * @param array $defaultsetting array of usernames
4336 * @param string $capability string capability name.
4337 * @param bool $includeadmins include administrators
4339 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4340 $this->capability = $capability;
4341 $this->includeadmins = $includeadmins;
4342 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4346 * Load all of the uses who have the capability into choice array
4348 * @return bool Always returns true
4350 function load_choices() {
4351 if (is_array($this->choices)) {
4352 return true;
4354 list($sort, $sortparams) = users_order_by_sql('u');
4355 if (!empty($sortparams)) {
4356 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4357 'This is unexpected, and a problem because there is no way to pass these ' .
4358 'parameters to get_users_by_capability. See MDL-34657.');
4360 $userfieldsapi = \core_user\fields::for_name();
4361 $userfields = 'u.id, u.username, ' . $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4362 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4363 $this->choices = array(
4364 '$@NONE@$' => get_string('nobody'),
4365 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4367 if ($this->includeadmins) {
4368 $admins = get_admins();
4369 foreach ($admins as $user) {
4370 $this->choices[$user->id] = fullname($user);
4373 if (is_array($users)) {
4374 foreach ($users as $user) {
4375 $this->choices[$user->id] = fullname($user);
4378 return true;
4382 * Returns the default setting for class
4384 * @return mixed Array, or string. Empty string if no default
4386 public function get_defaultsetting() {
4387 $this->load_choices();
4388 $defaultsetting = parent::get_defaultsetting();
4389 if (empty($defaultsetting)) {
4390 return array('$@NONE@$');
4391 } else if (array_key_exists($defaultsetting, $this->choices)) {
4392 return $defaultsetting;
4393 } else {
4394 return '';
4399 * Returns the current setting
4401 * @return mixed array or string
4403 public function get_setting() {
4404 $result = parent::get_setting();
4405 if ($result === null) {
4406 // this is necessary for settings upgrade
4407 return null;
4409 if (empty($result)) {
4410 $result = array('$@NONE@$');
4412 return $result;
4416 * Save the chosen setting provided as $data
4418 * @param array $data
4419 * @return mixed string or array
4421 public function write_setting($data) {
4422 // If all is selected, remove any explicit options.
4423 if (in_array('$@ALL@$', $data)) {
4424 $data = array('$@ALL@$');
4426 // None never needs to be written to the DB.
4427 if (in_array('$@NONE@$', $data)) {
4428 unset($data[array_search('$@NONE@$', $data)]);
4430 return parent::write_setting($data);
4436 * Special checkbox for calendar - resets SESSION vars.
4438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4440 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4442 * Calls the parent::__construct with default values
4444 * name => calendar_adminseesall
4445 * visiblename => get_string('adminseesall', 'admin')
4446 * description => get_string('helpadminseesall', 'admin')
4447 * defaultsetting => 0
4449 public function __construct() {
4450 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4451 get_string('helpadminseesall', 'admin'), '0');
4455 * Stores the setting passed in $data
4457 * @param mixed gets converted to string for comparison
4458 * @return string empty string or error message
4460 public function write_setting($data) {
4461 global $SESSION;
4462 return parent::write_setting($data);
4467 * Special select for settings that are altered in setup.php and can not be altered on the fly
4469 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4471 class admin_setting_special_selectsetup extends admin_setting_configselect {
4473 * Reads the setting directly from the database
4475 * @return mixed
4477 public function get_setting() {
4478 // read directly from db!
4479 return get_config(NULL, $this->name);
4483 * Save the setting passed in $data
4485 * @param string $data The setting to save
4486 * @return string empty or error message
4488 public function write_setting($data) {
4489 global $CFG;
4490 // do not change active CFG setting!
4491 $current = $CFG->{$this->name};
4492 $result = parent::write_setting($data);
4493 $CFG->{$this->name} = $current;
4494 return $result;
4500 * Special select for frontpage - stores data in course table
4502 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4504 class admin_setting_sitesetselect extends admin_setting_configselect {
4506 * Returns the site name for the selected site
4508 * @see get_site()
4509 * @return string The site name of the selected site
4511 public function get_setting() {
4512 $site = course_get_format(get_site())->get_course();
4513 return $site->{$this->name};
4517 * Updates the database and save the setting
4519 * @param string data
4520 * @return string empty or error message
4522 public function write_setting($data) {
4523 global $DB, $SITE, $COURSE;
4524 if (!in_array($data, array_keys($this->choices))) {
4525 return get_string('errorsetting', 'admin');
4527 $record = new stdClass();
4528 $record->id = SITEID;
4529 $temp = $this->name;
4530 $record->$temp = $data;
4531 $record->timemodified = time();
4533 course_get_format($SITE)->update_course_format_options($record);
4534 $DB->update_record('course', $record);
4536 // Reset caches.
4537 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4538 if ($SITE->id == $COURSE->id) {
4539 $COURSE = $SITE;
4541 core_courseformat\base::reset_course_cache($SITE->id);
4543 return '';
4550 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4551 * block to hidden.
4553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4555 class admin_setting_bloglevel extends admin_setting_configselect {
4557 * Updates the database and save the setting
4559 * @param string data
4560 * @return string empty or error message
4562 public function write_setting($data) {
4563 global $DB, $CFG;
4564 if ($data == 0) {
4565 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4566 foreach ($blogblocks as $block) {
4567 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4569 } else {
4570 // reenable all blocks only when switching from disabled blogs
4571 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4572 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4573 foreach ($blogblocks as $block) {
4574 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4578 return parent::write_setting($data);
4584 * Special select - lists on the frontpage - hacky
4586 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4588 class admin_setting_courselist_frontpage extends admin_setting {
4589 /** @var array Array of choices value=>label */
4590 public $choices;
4593 * Construct override, requires one param
4595 * @param bool $loggedin Is the user logged in
4597 public function __construct($loggedin) {
4598 global $CFG;
4599 require_once($CFG->dirroot.'/course/lib.php');
4600 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4601 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4602 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4603 $defaults = array(FRONTPAGEALLCOURSELIST);
4604 parent::__construct($name, $visiblename, $description, $defaults);
4608 * Loads the choices available
4610 * @return bool always returns true
4612 public function load_choices() {
4613 if (is_array($this->choices)) {
4614 return true;
4616 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4617 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4618 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4619 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4620 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4621 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4622 'none' => get_string('none'));
4623 if ($this->name === 'frontpage') {
4624 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4626 return true;
4630 * Returns the selected settings
4632 * @param mixed array or setting or null
4634 public function get_setting() {
4635 $result = $this->config_read($this->name);
4636 if (is_null($result)) {
4637 return NULL;
4639 if ($result === '') {
4640 return array();
4642 return explode(',', $result);
4646 * Save the selected options
4648 * @param array $data
4649 * @return mixed empty string (data is not an array) or bool true=success false=failure
4651 public function write_setting($data) {
4652 if (!is_array($data)) {
4653 return '';
4655 $this->load_choices();
4656 $save = array();
4657 foreach($data as $datum) {
4658 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4659 continue;
4661 $save[$datum] = $datum; // no duplicates
4663 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4667 * Return XHTML select field and wrapping div
4669 * @todo Add vartype handling to make sure $data is an array
4670 * @param array $data Array of elements to select by default
4671 * @return string XHTML select field and wrapping div
4673 public function output_html($data, $query='') {
4674 global $OUTPUT;
4676 $this->load_choices();
4677 $currentsetting = array();
4678 foreach ($data as $key) {
4679 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4680 $currentsetting[] = $key; // already selected first
4684 $context = (object) [
4685 'id' => $this->get_id(),
4686 'name' => $this->get_full_name(),
4689 $options = $this->choices;
4690 $selects = [];
4691 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4692 if (!array_key_exists($i, $currentsetting)) {
4693 $currentsetting[$i] = 'none';
4695 $selects[] = [
4696 'key' => $i,
4697 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4698 return [
4699 'name' => $options[$option],
4700 'value' => $option,
4701 'selected' => $currentsetting[$i] == $option
4703 }, array_keys($options))
4706 $context->selects = $selects;
4708 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4710 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4716 * Special checkbox for frontpage - stores data in course table
4718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4720 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4722 * Returns the current sites name
4724 * @return string
4726 public function get_setting() {
4727 $site = course_get_format(get_site())->get_course();
4728 return $site->{$this->name};
4732 * Save the selected setting
4734 * @param string $data The selected site
4735 * @return string empty string or error message
4737 public function write_setting($data) {
4738 global $DB, $SITE, $COURSE;
4739 $record = new stdClass();
4740 $record->id = $SITE->id;
4741 $record->{$this->name} = ($data == '1' ? 1 : 0);
4742 $record->timemodified = time();
4744 course_get_format($SITE)->update_course_format_options($record);
4745 $DB->update_record('course', $record);
4747 // Reset caches.
4748 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4749 if ($SITE->id == $COURSE->id) {
4750 $COURSE = $SITE;
4752 core_courseformat\base::reset_course_cache($SITE->id);
4754 return '';
4759 * Special text for frontpage - stores data in course table.
4760 * Empty string means not set here. Manual setting is required.
4762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4764 class admin_setting_sitesettext extends admin_setting_configtext {
4767 * Constructor.
4769 public function __construct() {
4770 call_user_func_array(['parent', '__construct'], func_get_args());
4771 $this->set_force_ltr(false);
4775 * Return the current setting
4777 * @return mixed string or null
4779 public function get_setting() {
4780 $site = course_get_format(get_site())->get_course();
4781 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4785 * Validate the selected data
4787 * @param string $data The selected value to validate
4788 * @return mixed true or message string
4790 public function validate($data) {
4791 global $DB, $SITE;
4792 $cleaned = clean_param($data, PARAM_TEXT);
4793 if ($cleaned === '') {
4794 return get_string('required');
4796 if ($this->name ==='shortname' &&
4797 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4798 return get_string('shortnametaken', 'error', $data);
4800 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4801 return true;
4802 } else {
4803 return get_string('validateerror', 'admin');
4808 * Save the selected setting
4810 * @param string $data The selected value
4811 * @return string empty or error message
4813 public function write_setting($data) {
4814 global $DB, $SITE, $COURSE;
4815 $data = trim($data);
4816 $validated = $this->validate($data);
4817 if ($validated !== true) {
4818 return $validated;
4821 $record = new stdClass();
4822 $record->id = $SITE->id;
4823 $record->{$this->name} = $data;
4824 $record->timemodified = time();
4826 course_get_format($SITE)->update_course_format_options($record);
4827 $DB->update_record('course', $record);
4829 // Reset caches.
4830 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4831 if ($SITE->id == $COURSE->id) {
4832 $COURSE = $SITE;
4834 core_courseformat\base::reset_course_cache($SITE->id);
4836 return '';
4842 * This type of field should be used for mandatory config settings.
4844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4846 class admin_setting_requiredtext extends admin_setting_configtext {
4849 * Validate data before storage.
4851 * @param string $data The string to be validated.
4852 * @return bool|string true for success or error string if invalid.
4854 public function validate($data) {
4855 $cleaned = clean_param($data, PARAM_TEXT);
4856 if ($cleaned === '') {
4857 return get_string('required');
4860 return parent::validate($data);
4865 * Special text editor for site description.
4867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4869 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4872 * Calls parent::__construct with specific arguments
4874 public function __construct() {
4875 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4876 PARAM_RAW, 60, 15);
4880 * Return the current setting
4881 * @return string The current setting
4883 public function get_setting() {
4884 $site = course_get_format(get_site())->get_course();
4885 return $site->{$this->name};
4889 * Save the new setting
4891 * @param string $data The new value to save
4892 * @return string empty or error message
4894 public function write_setting($data) {
4895 global $DB, $SITE, $COURSE;
4896 $record = new stdClass();
4897 $record->id = $SITE->id;
4898 $record->{$this->name} = $data;
4899 $record->timemodified = time();
4901 course_get_format($SITE)->update_course_format_options($record);
4902 $DB->update_record('course', $record);
4904 // Reset caches.
4905 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4906 if ($SITE->id == $COURSE->id) {
4907 $COURSE = $SITE;
4909 core_courseformat\base::reset_course_cache($SITE->id);
4911 return '';
4917 * Administration interface for emoticon_manager settings.
4919 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4921 class admin_setting_emoticons extends admin_setting {
4924 * Calls parent::__construct with specific args
4926 public function __construct() {
4927 global $CFG;
4929 $manager = get_emoticon_manager();
4930 $defaults = $this->prepare_form_data($manager->default_emoticons());
4931 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4935 * Return the current setting(s)
4937 * @return array Current settings array
4939 public function get_setting() {
4940 global $CFG;
4942 $manager = get_emoticon_manager();
4944 $config = $this->config_read($this->name);
4945 if (is_null($config)) {
4946 return null;
4949 $config = $manager->decode_stored_config($config);
4950 if (is_null($config)) {
4951 return null;
4954 return $this->prepare_form_data($config);
4958 * Save selected settings
4960 * @param array $data Array of settings to save
4961 * @return bool
4963 public function write_setting($data) {
4965 $manager = get_emoticon_manager();
4966 $emoticons = $this->process_form_data($data);
4968 if ($emoticons === false) {
4969 return false;
4972 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4973 return ''; // success
4974 } else {
4975 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4980 * Return XHTML field(s) for options
4982 * @param array $data Array of options to set in HTML
4983 * @return string XHTML string for the fields and wrapping div(s)
4985 public function output_html($data, $query='') {
4986 global $OUTPUT;
4988 $context = (object) [
4989 'name' => $this->get_full_name(),
4990 'emoticons' => [],
4991 'forceltr' => true,
4994 $i = 0;
4995 foreach ($data as $field => $value) {
4997 // When $i == 0: text.
4998 // When $i == 1: imagename.
4999 // When $i == 2: imagecomponent.
5000 // When $i == 3: altidentifier.
5001 // When $i == 4: altcomponent.
5002 $fields[$i] = (object) [
5003 'field' => $field,
5004 'value' => $value,
5005 'index' => $i
5007 $i++;
5009 if ($i > 4) {
5010 $icon = null;
5011 if (!empty($fields[1]->value)) {
5012 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
5013 $alt = get_string($fields[3]->value, $fields[4]->value);
5014 } else {
5015 $alt = $fields[0]->value;
5017 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
5019 $context->emoticons[] = [
5020 'fields' => $fields,
5021 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
5023 $fields = [];
5024 $i = 0;
5028 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
5029 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
5030 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5034 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
5036 * @see self::process_form_data()
5037 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
5038 * @return array of form fields and their values
5040 protected function prepare_form_data(array $emoticons) {
5042 $form = array();
5043 $i = 0;
5044 foreach ($emoticons as $emoticon) {
5045 $form['text'.$i] = $emoticon->text;
5046 $form['imagename'.$i] = $emoticon->imagename;
5047 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
5048 $form['altidentifier'.$i] = $emoticon->altidentifier;
5049 $form['altcomponent'.$i] = $emoticon->altcomponent;
5050 $i++;
5052 // add one more blank field set for new object
5053 $form['text'.$i] = '';
5054 $form['imagename'.$i] = '';
5055 $form['imagecomponent'.$i] = '';
5056 $form['altidentifier'.$i] = '';
5057 $form['altcomponent'.$i] = '';
5059 return $form;
5063 * Converts the data from admin settings form into an array of emoticon objects
5065 * @see self::prepare_form_data()
5066 * @param array $data array of admin form fields and values
5067 * @return false|array of emoticon objects
5069 protected function process_form_data(array $form) {
5071 $count = count($form); // number of form field values
5073 if ($count % 5) {
5074 // we must get five fields per emoticon object
5075 return false;
5078 $emoticons = array();
5079 for ($i = 0; $i < $count / 5; $i++) {
5080 $emoticon = new stdClass();
5081 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
5082 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
5083 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
5084 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
5085 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
5087 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
5088 // prevent from breaking http://url.addresses by accident
5089 $emoticon->text = '';
5092 if (strlen($emoticon->text) < 2) {
5093 // do not allow single character emoticons
5094 $emoticon->text = '';
5097 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
5098 // emoticon text must contain some non-alphanumeric character to prevent
5099 // breaking HTML tags
5100 $emoticon->text = '';
5103 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
5104 $emoticons[] = $emoticon;
5107 return $emoticons;
5114 * Special setting for limiting of the list of available languages.
5116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5118 class admin_setting_langlist extends admin_setting_configtext {
5120 * Calls parent::__construct with specific arguments
5122 public function __construct() {
5123 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
5127 * Validate that each language identifier exists on the site
5129 * @param string $data
5130 * @return bool|string True if validation successful, otherwise error string
5132 public function validate($data) {
5133 $parentcheck = parent::validate($data);
5134 if ($parentcheck !== true) {
5135 return $parentcheck;
5138 if ($data === '') {
5139 return true;
5142 // Normalize language identifiers.
5143 $langcodes = array_map('trim', explode(',', $data));
5144 foreach ($langcodes as $langcode) {
5145 // If the langcode contains optional alias, split it out.
5146 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5148 if (!get_string_manager()->translation_exists($langcode)) {
5149 return get_string('invalidlanguagecode', 'error', $langcode);
5153 return true;
5157 * Save the new setting
5159 * @param string $data The new setting
5160 * @return bool
5162 public function write_setting($data) {
5163 $return = parent::write_setting($data);
5164 get_string_manager()->reset_caches();
5165 return $return;
5171 * Allows to specify comma separated list of known country codes.
5173 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5174 * known codes.
5176 * @package core
5177 * @category admin
5178 * @copyright 2020 David Mudrák <david@moodle.com>
5179 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5181 class admin_setting_countrycodes extends admin_setting_configtext {
5184 * Construct the instance of the setting.
5186 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5187 * @param lang_string|string $visiblename Language string with the field label text.
5188 * @param lang_string|string $description Language string with the field description text.
5189 * @param string $defaultsetting Default value of the setting.
5190 * @param int $size Input text field size.
5192 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5193 parent::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5197 * Validate the setting value before storing it.
5199 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5200 * a comma separated list of such words.
5202 * @param string $data Value inserted into the setting field.
5203 * @return bool|string True if the value is OK, error string otherwise.
5205 public function validate($data) {
5207 $parentcheck = parent::validate($data);
5209 if ($parentcheck !== true) {
5210 return $parentcheck;
5213 if ($data === '') {
5214 return true;
5217 $allcountries = get_string_manager()->get_list_of_countries(true);
5219 foreach (explode(',', $data) as $code) {
5220 if (!isset($allcountries[$code])) {
5221 return get_string('invalidcountrycode', 'core_error', $code);
5225 return true;
5231 * Selection of one of the recognised countries using the list
5232 * returned by {@link get_list_of_countries()}.
5234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5236 class admin_settings_country_select extends admin_setting_configselect {
5237 protected $includeall;
5238 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5239 $this->includeall = $includeall;
5240 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
5244 * Lazy-load the available choices for the select box
5246 public function load_choices() {
5247 global $CFG;
5248 if (is_array($this->choices)) {
5249 return true;
5251 $this->choices = array_merge(
5252 array('0' => get_string('choosedots')),
5253 get_string_manager()->get_list_of_countries($this->includeall));
5254 return true;
5260 * admin_setting_configselect for the default number of sections in a course,
5261 * simply so we can lazy-load the choices.
5263 * @copyright 2011 The Open University
5264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5266 class admin_settings_num_course_sections extends admin_setting_configselect {
5267 public function __construct($name, $visiblename, $description, $defaultsetting) {
5268 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
5271 /** Lazy-load the available choices for the select box */
5272 public function load_choices() {
5273 $max = get_config('moodlecourse', 'maxsections');
5274 if (!isset($max) || !is_numeric($max)) {
5275 $max = 52;
5277 for ($i = 0; $i <= $max; $i++) {
5278 $this->choices[$i] = "$i";
5280 return true;
5286 * Course category selection
5288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5290 class admin_settings_coursecat_select extends admin_setting_configselect_autocomplete {
5292 * Calls parent::__construct with specific arguments
5294 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5295 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5299 * Load the available choices for the select box
5301 * @return bool
5303 public function load_choices() {
5304 if (is_array($this->choices)) {
5305 return true;
5307 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
5308 return true;
5314 * Special control for selecting days to backup
5316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5318 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
5320 * Calls parent::__construct with specific arguments
5322 public function __construct() {
5323 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5324 $this->plugin = 'backup';
5328 * Load the available choices for the select box
5330 * @return bool Always returns true
5332 public function load_choices() {
5333 if (is_array($this->choices)) {
5334 return true;
5336 $this->choices = array();
5337 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5338 foreach ($days as $day) {
5339 $this->choices[$day] = get_string($day, 'calendar');
5341 return true;
5346 * Special setting for backup auto destination.
5348 * @package core
5349 * @subpackage admin
5350 * @copyright 2014 Frédéric Massart - FMCorz.net
5351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5353 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5356 * Calls parent::__construct with specific arguments.
5358 public function __construct() {
5359 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5363 * Check if the directory must be set, depending on backup/backup_auto_storage.
5365 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5366 * there will be conflicts if this validation happens before the other one.
5368 * @param string $data Form data.
5369 * @return string Empty when no errors.
5371 public function write_setting($data) {
5372 $storage = (int) get_config('backup', 'backup_auto_storage');
5373 if ($storage !== 0) {
5374 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5375 // The directory must exist and be writable.
5376 return get_string('backuperrorinvaliddestination');
5379 return parent::write_setting($data);
5385 * Special debug setting
5387 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5389 class admin_setting_special_debug extends admin_setting_configselect {
5391 * Calls parent::__construct with specific arguments
5393 public function __construct() {
5394 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5398 * Load the available choices for the select box
5400 * @return bool
5402 public function load_choices() {
5403 if (is_array($this->choices)) {
5404 return true;
5406 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5407 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5408 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5409 DEBUG_ALL => get_string('debugall', 'admin'),
5410 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5411 return true;
5417 * Special admin control
5419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5421 class admin_setting_special_calendar_weekend extends admin_setting {
5423 * Calls parent::__construct with specific arguments
5425 public function __construct() {
5426 $name = 'calendar_weekend';
5427 $visiblename = get_string('calendar_weekend', 'admin');
5428 $description = get_string('helpweekenddays', 'admin');
5429 $default = array ('0', '6'); // Saturdays and Sundays
5430 parent::__construct($name, $visiblename, $description, $default);
5434 * Gets the current settings as an array
5436 * @return mixed Null if none, else array of settings
5438 public function get_setting() {
5439 $result = $this->config_read($this->name);
5440 if (is_null($result)) {
5441 return NULL;
5443 if ($result === '') {
5444 return array();
5446 $settings = array();
5447 for ($i=0; $i<7; $i++) {
5448 if ($result & (1 << $i)) {
5449 $settings[] = $i;
5452 return $settings;
5456 * Save the new settings
5458 * @param array $data Array of new settings
5459 * @return bool
5461 public function write_setting($data) {
5462 if (!is_array($data)) {
5463 return '';
5465 unset($data['xxxxx']);
5466 $result = 0;
5467 foreach($data as $index) {
5468 $result |= 1 << $index;
5470 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5474 * Return XHTML to display the control
5476 * @param array $data array of selected days
5477 * @param string $query
5478 * @return string XHTML for display (field + wrapping div(s)
5480 public function output_html($data, $query='') {
5481 global $OUTPUT;
5483 // The order matters very much because of the implied numeric keys.
5484 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5485 $context = (object) [
5486 'name' => $this->get_full_name(),
5487 'id' => $this->get_id(),
5488 'days' => array_map(function($index) use ($days, $data) {
5489 return [
5490 'index' => $index,
5491 'label' => get_string($days[$index], 'calendar'),
5492 'checked' => in_array($index, $data)
5494 }, array_keys($days))
5497 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5499 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5506 * Admin setting that allows a user to pick a behaviour.
5508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5510 class admin_setting_question_behaviour extends admin_setting_configselect {
5512 * @param string $name name of config variable
5513 * @param string $visiblename display name
5514 * @param string $description description
5515 * @param string $default default.
5517 public function __construct($name, $visiblename, $description, $default) {
5518 parent::__construct($name, $visiblename, $description, $default, null);
5522 * Load list of behaviours as choices
5523 * @return bool true => success, false => error.
5525 public function load_choices() {
5526 global $CFG;
5527 require_once($CFG->dirroot . '/question/engine/lib.php');
5528 $this->choices = question_engine::get_behaviour_options('');
5529 return true;
5535 * Admin setting that allows a user to pick appropriate roles for something.
5537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5539 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5540 /** @var array Array of capabilities which identify roles */
5541 private $types;
5544 * @param string $name Name of config variable
5545 * @param string $visiblename Display name
5546 * @param string $description Description
5547 * @param array $types Array of archetypes which identify
5548 * roles that will be enabled by default.
5550 public function __construct($name, $visiblename, $description, $types) {
5551 parent::__construct($name, $visiblename, $description, NULL, NULL);
5552 $this->types = $types;
5556 * Load roles as choices
5558 * @return bool true=>success, false=>error
5560 public function load_choices() {
5561 global $CFG, $DB;
5562 if (during_initial_install()) {
5563 return false;
5565 if (is_array($this->choices)) {
5566 return true;
5568 if ($roles = get_all_roles()) {
5569 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5570 return true;
5571 } else {
5572 return false;
5577 * Return the default setting for this control
5579 * @return array Array of default settings
5581 public function get_defaultsetting() {
5582 global $CFG;
5584 if (during_initial_install()) {
5585 return null;
5587 $result = array();
5588 foreach($this->types as $archetype) {
5589 if ($caproles = get_archetype_roles($archetype)) {
5590 foreach ($caproles as $caprole) {
5591 $result[$caprole->id] = 1;
5595 return $result;
5601 * Admin setting that is a list of installed filter plugins.
5603 * @copyright 2015 The Open University
5604 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5606 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5609 * Constructor
5611 * @param string $name unique ascii name, either 'mysetting' for settings
5612 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5613 * @param string $visiblename localised name
5614 * @param string $description localised long description
5615 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5617 public function __construct($name, $visiblename, $description, $default) {
5618 if (empty($default)) {
5619 $default = array();
5621 $this->load_choices();
5622 foreach ($default as $plugin) {
5623 if (!isset($this->choices[$plugin])) {
5624 unset($default[$plugin]);
5627 parent::__construct($name, $visiblename, $description, $default, null);
5630 public function load_choices() {
5631 if (is_array($this->choices)) {
5632 return true;
5634 $this->choices = array();
5636 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5637 $this->choices[$plugin] = filter_get_name($plugin);
5639 return true;
5645 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5649 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5651 * Constructor
5652 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5653 * @param string $visiblename localised
5654 * @param string $description long localised info
5655 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5656 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5657 * @param int $size default field size
5659 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5660 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5661 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5667 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5669 * @copyright 2009 Petr Skoda (http://skodak.org)
5670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5672 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5675 * Constructor
5676 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5677 * @param string $visiblename localised
5678 * @param string $description long localised info
5679 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5680 * @param string $yes value used when checked
5681 * @param string $no value used when not checked
5683 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5684 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5685 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5692 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5694 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5696 * @copyright 2010 Sam Hemelryk
5697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5699 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5701 * Constructor
5702 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5703 * @param string $visiblename localised
5704 * @param string $description long localised info
5705 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5706 * @param string $yes value used when checked
5707 * @param string $no value used when not checked
5709 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5710 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5711 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5717 * Autocomplete as you type form element.
5719 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5721 class admin_setting_configselect_autocomplete extends admin_setting_configselect {
5722 /** @var boolean $tags Should we allow typing new entries to the field? */
5723 protected $tags = false;
5724 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5725 protected $ajax = '';
5726 /** @var string $placeholder Placeholder text for an empty list. */
5727 protected $placeholder = '';
5728 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5729 protected $casesensitive = false;
5730 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5731 protected $showsuggestions = true;
5732 /** @var string $noselectionstring String that is shown when there are no selections. */
5733 protected $noselectionstring = '';
5736 * Returns XHTML select field and wrapping div(s)
5738 * @see output_select_html()
5740 * @param string $data the option to show as selected
5741 * @param string $query
5742 * @return string XHTML field and wrapping div
5744 public function output_html($data, $query='') {
5745 global $PAGE;
5747 $html = parent::output_html($data, $query);
5749 if ($html === '') {
5750 return $html;
5753 $this->placeholder = get_string('search');
5755 $params = array('#' . $this->get_id(), $this->tags, $this->ajax,
5756 $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring);
5758 // Load autocomplete wrapper for select2 library.
5759 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params);
5761 return $html;
5766 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5770 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5772 * Calls parent::__construct with specific arguments
5774 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5775 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5776 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5782 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5784 * @copyright 2017 Marina Glancy
5785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5787 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5789 * Constructor
5790 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5791 * or 'myplugin/mysetting' for ones in config_plugins.
5792 * @param string $visiblename localised
5793 * @param string $description long localised info
5794 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5795 * @param array $choices array of $value=>$label for each selection
5797 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5798 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5799 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5805 * Graded roles in gradebook
5807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5809 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5811 * Calls parent::__construct with specific arguments
5813 public function __construct() {
5814 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5815 get_string('configgradebookroles', 'admin'),
5816 array('student'));
5823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5825 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5827 * Saves the new settings passed in $data
5829 * @param string $data
5830 * @return mixed string or Array
5832 public function write_setting($data) {
5833 global $CFG, $DB;
5835 $oldvalue = $this->config_read($this->name);
5836 $return = parent::write_setting($data);
5837 $newvalue = $this->config_read($this->name);
5839 if ($oldvalue !== $newvalue) {
5840 // force full regrading
5841 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5844 return $return;
5850 * Which roles to show on course description page
5852 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5854 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5856 * Calls parent::__construct with specific arguments
5858 public function __construct() {
5859 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5860 get_string('coursecontact_desc', 'admin'),
5861 array('editingteacher'));
5862 $this->set_updatedcallback(function (){
5863 cache::make('core', 'coursecontacts')->purge();
5871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5873 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5875 * Calls parent::__construct with specific arguments
5877 public function __construct() {
5878 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5879 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5883 * Old syntax of class constructor. Deprecated in PHP7.
5885 * @deprecated since Moodle 3.1
5887 public function admin_setting_special_gradelimiting() {
5888 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5889 self::__construct();
5893 * Force site regrading
5895 function regrade_all() {
5896 global $CFG;
5897 require_once("$CFG->libdir/gradelib.php");
5898 grade_force_site_regrading();
5902 * Saves the new settings
5904 * @param mixed $data
5905 * @return string empty string or error message
5907 function write_setting($data) {
5908 $previous = $this->get_setting();
5910 if ($previous === null) {
5911 if ($data) {
5912 $this->regrade_all();
5914 } else {
5915 if ($data != $previous) {
5916 $this->regrade_all();
5919 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5925 * Special setting for $CFG->grade_minmaxtouse.
5927 * @package core
5928 * @copyright 2015 Frédéric Massart - FMCorz.net
5929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5931 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5934 * Constructor.
5936 public function __construct() {
5937 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5938 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5939 array(
5940 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5941 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5947 * Saves the new setting.
5949 * @param mixed $data
5950 * @return string empty string or error message
5952 function write_setting($data) {
5953 global $CFG;
5955 $previous = $this->get_setting();
5956 $result = parent::write_setting($data);
5958 // If saved and the value has changed.
5959 if (empty($result) && $previous != $data) {
5960 require_once($CFG->libdir . '/gradelib.php');
5961 grade_force_site_regrading();
5964 return $result;
5971 * Primary grade export plugin - has state tracking.
5973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5975 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5977 * Calls parent::__construct with specific arguments
5979 public function __construct() {
5980 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5981 get_string('configgradeexport', 'admin'), array(), NULL);
5985 * Load the available choices for the multicheckbox
5987 * @return bool always returns true
5989 public function load_choices() {
5990 if (is_array($this->choices)) {
5991 return true;
5993 $this->choices = array();
5995 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5996 foreach($plugins as $plugin => $unused) {
5997 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
6000 return true;
6006 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
6008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6010 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
6012 * Config gradepointmax constructor
6014 * @param string $name Overidden by "gradepointmax"
6015 * @param string $visiblename Overridden by "gradepointmax" language string.
6016 * @param string $description Overridden by "gradepointmax_help" language string.
6017 * @param string $defaultsetting Not used, overridden by 100.
6018 * @param mixed $paramtype Overridden by PARAM_INT.
6019 * @param int $size Overridden by 5.
6021 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6022 $name = 'gradepointdefault';
6023 $visiblename = get_string('gradepointdefault', 'grades');
6024 $description = get_string('gradepointdefault_help', 'grades');
6025 $defaultsetting = 100;
6026 $paramtype = PARAM_INT;
6027 $size = 5;
6028 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6032 * Validate data before storage
6033 * @param string $data The submitted data
6034 * @return bool|string true if ok, string if error found
6036 public function validate($data) {
6037 global $CFG;
6038 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
6039 return true;
6040 } else {
6041 return get_string('gradepointdefault_validateerror', 'grades');
6048 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
6050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6052 class admin_setting_special_gradepointmax extends admin_setting_configtext {
6055 * Config gradepointmax constructor
6057 * @param string $name Overidden by "gradepointmax"
6058 * @param string $visiblename Overridden by "gradepointmax" language string.
6059 * @param string $description Overridden by "gradepointmax_help" language string.
6060 * @param string $defaultsetting Not used, overridden by 100.
6061 * @param mixed $paramtype Overridden by PARAM_INT.
6062 * @param int $size Overridden by 5.
6064 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6065 $name = 'gradepointmax';
6066 $visiblename = get_string('gradepointmax', 'grades');
6067 $description = get_string('gradepointmax_help', 'grades');
6068 $defaultsetting = 100;
6069 $paramtype = PARAM_INT;
6070 $size = 5;
6071 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6075 * Save the selected setting
6077 * @param string $data The selected site
6078 * @return string empty string or error message
6080 public function write_setting($data) {
6081 if ($data === '') {
6082 $data = (int)$this->defaultsetting;
6083 } else {
6084 $data = $data;
6086 return parent::write_setting($data);
6090 * Validate data before storage
6091 * @param string $data The submitted data
6092 * @return bool|string true if ok, string if error found
6094 public function validate($data) {
6095 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6096 return true;
6097 } else {
6098 return get_string('gradepointmax_validateerror', 'grades');
6103 * Return an XHTML string for the setting
6104 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6105 * @param string $query search query to be highlighted
6106 * @return string XHTML to display control
6108 public function output_html($data, $query = '') {
6109 global $OUTPUT;
6111 $default = $this->get_defaultsetting();
6112 $context = (object) [
6113 'size' => $this->size,
6114 'id' => $this->get_id(),
6115 'name' => $this->get_full_name(),
6116 'value' => $data,
6117 'attributes' => [
6118 'maxlength' => 5
6120 'forceltr' => $this->get_force_ltr()
6122 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6124 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
6130 * Grade category settings
6132 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6134 class admin_setting_gradecat_combo extends admin_setting {
6135 /** @var array Array of choices */
6136 public $choices;
6139 * Sets choices and calls parent::__construct with passed arguments
6140 * @param string $name
6141 * @param string $visiblename
6142 * @param string $description
6143 * @param mixed $defaultsetting string or array depending on implementation
6144 * @param array $choices An array of choices for the control
6146 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6147 $this->choices = $choices;
6148 parent::__construct($name, $visiblename, $description, $defaultsetting);
6152 * Return the current setting(s) array
6154 * @return array Array of value=>xx, forced=>xx, adv=>xx
6156 public function get_setting() {
6157 global $CFG;
6159 $value = $this->config_read($this->name);
6160 $flag = $this->config_read($this->name.'_flag');
6162 if (is_null($value) or is_null($flag)) {
6163 return NULL;
6166 $flag = (int)$flag;
6167 $forced = (boolean)(1 & $flag); // first bit
6168 $adv = (boolean)(2 & $flag); // second bit
6170 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6174 * Save the new settings passed in $data
6176 * @todo Add vartype handling to ensure $data is array
6177 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6178 * @return string empty or error message
6180 public function write_setting($data) {
6181 global $CFG;
6183 $value = $data['value'];
6184 $forced = empty($data['forced']) ? 0 : 1;
6185 $adv = empty($data['adv']) ? 0 : 2;
6186 $flag = ($forced | $adv); //bitwise or
6188 if (!in_array($value, array_keys($this->choices))) {
6189 return 'Error setting ';
6192 $oldvalue = $this->config_read($this->name);
6193 $oldflag = (int)$this->config_read($this->name.'_flag');
6194 $oldforced = (1 & $oldflag); // first bit
6196 $result1 = $this->config_write($this->name, $value);
6197 $result2 = $this->config_write($this->name.'_flag', $flag);
6199 // force regrade if needed
6200 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6201 require_once($CFG->libdir.'/gradelib.php');
6202 grade_category::updated_forced_settings();
6205 if ($result1 and $result2) {
6206 return '';
6207 } else {
6208 return get_string('errorsetting', 'admin');
6213 * Return XHTML to display the field and wrapping div
6215 * @todo Add vartype handling to ensure $data is array
6216 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6217 * @param string $query
6218 * @return string XHTML to display control
6220 public function output_html($data, $query='') {
6221 global $OUTPUT;
6223 $value = $data['value'];
6225 $default = $this->get_defaultsetting();
6226 if (!is_null($default)) {
6227 $defaultinfo = array();
6228 if (isset($this->choices[$default['value']])) {
6229 $defaultinfo[] = $this->choices[$default['value']];
6231 if (!empty($default['forced'])) {
6232 $defaultinfo[] = get_string('force');
6234 if (!empty($default['adv'])) {
6235 $defaultinfo[] = get_string('advanced');
6237 $defaultinfo = implode(', ', $defaultinfo);
6239 } else {
6240 $defaultinfo = NULL;
6243 $options = $this->choices;
6244 $context = (object) [
6245 'id' => $this->get_id(),
6246 'name' => $this->get_full_name(),
6247 'forced' => !empty($data['forced']),
6248 'advanced' => !empty($data['adv']),
6249 'options' => array_map(function($option) use ($options, $value) {
6250 return [
6251 'value' => $option,
6252 'name' => $options[$option],
6253 'selected' => $option == $value
6255 }, array_keys($options)),
6258 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6260 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
6266 * Selection of grade report in user profiles
6268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6270 class admin_setting_grade_profilereport extends admin_setting_configselect {
6272 * Calls parent::__construct with specific arguments
6274 public function __construct() {
6275 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6279 * Loads an array of choices for the configselect control
6281 * @return bool always return true
6283 public function load_choices() {
6284 if (is_array($this->choices)) {
6285 return true;
6287 $this->choices = array();
6289 global $CFG;
6290 require_once($CFG->libdir.'/gradelib.php');
6292 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6293 if (file_exists($plugindir.'/lib.php')) {
6294 require_once($plugindir.'/lib.php');
6295 $functionname = 'grade_report_'.$plugin.'_profilereport';
6296 if (function_exists($functionname)) {
6297 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6301 return true;
6306 * Provides a selection of grade reports to be used for "grades".
6308 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6309 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6311 class admin_setting_my_grades_report extends admin_setting_configselect {
6314 * Calls parent::__construct with specific arguments.
6316 public function __construct() {
6317 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6318 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6322 * Loads an array of choices for the configselect control.
6324 * @return bool always returns true.
6326 public function load_choices() {
6327 global $CFG; // Remove this line and behold the horror of behat test failures!
6328 $this->choices = array();
6329 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6330 if (file_exists($plugindir . '/lib.php')) {
6331 require_once($plugindir . '/lib.php');
6332 // Check to see if the class exists. Check the correct plugin convention first.
6333 if (class_exists('gradereport_' . $plugin)) {
6334 $classname = 'gradereport_' . $plugin;
6335 } else if (class_exists('grade_report_' . $plugin)) {
6336 // We are using the old plugin naming convention.
6337 $classname = 'grade_report_' . $plugin;
6338 } else {
6339 continue;
6341 if ($classname::supports_mygrades()) {
6342 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6346 // Add an option to specify an external url.
6347 $this->choices['external'] = get_string('externalurl', 'grades');
6348 return true;
6353 * Special class for register auth selection
6355 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6357 class admin_setting_special_registerauth extends admin_setting_configselect {
6359 * Calls parent::__construct with specific arguments
6361 public function __construct() {
6362 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6366 * Returns the default option
6368 * @return string empty or default option
6370 public function get_defaultsetting() {
6371 $this->load_choices();
6372 $defaultsetting = parent::get_defaultsetting();
6373 if (array_key_exists($defaultsetting, $this->choices)) {
6374 return $defaultsetting;
6375 } else {
6376 return '';
6381 * Loads the possible choices for the array
6383 * @return bool always returns true
6385 public function load_choices() {
6386 global $CFG;
6388 if (is_array($this->choices)) {
6389 return true;
6391 $this->choices = array();
6392 $this->choices[''] = get_string('disable');
6394 $authsenabled = get_enabled_auth_plugins();
6396 foreach ($authsenabled as $auth) {
6397 $authplugin = get_auth_plugin($auth);
6398 if (!$authplugin->can_signup()) {
6399 continue;
6401 // Get the auth title (from core or own auth lang files)
6402 $authtitle = $authplugin->get_title();
6403 $this->choices[$auth] = $authtitle;
6405 return true;
6411 * General plugins manager
6413 class admin_page_pluginsoverview extends admin_externalpage {
6416 * Sets basic information about the external page
6418 public function __construct() {
6419 global $CFG;
6420 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6421 "$CFG->wwwroot/$CFG->admin/plugins.php");
6426 * Module manage page
6428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6430 class admin_page_managemods extends admin_externalpage {
6432 * Calls parent::__construct with specific arguments
6434 public function __construct() {
6435 global $CFG;
6436 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6440 * Try to find the specified module
6442 * @param string $query The module to search for
6443 * @return array
6445 public function search($query) {
6446 global $CFG, $DB;
6447 if ($result = parent::search($query)) {
6448 return $result;
6451 $found = false;
6452 if ($modules = $DB->get_records('modules')) {
6453 foreach ($modules as $module) {
6454 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6455 continue;
6457 if (strpos($module->name, $query) !== false) {
6458 $found = true;
6459 break;
6461 $strmodulename = get_string('modulename', $module->name);
6462 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6463 $found = true;
6464 break;
6468 if ($found) {
6469 $result = new stdClass();
6470 $result->page = $this;
6471 $result->settings = array();
6472 return array($this->name => $result);
6473 } else {
6474 return array();
6481 * Special class for enrol plugins management.
6483 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6486 class admin_setting_manageenrols extends admin_setting {
6488 * Calls parent::__construct with specific arguments
6490 public function __construct() {
6491 $this->nosave = true;
6492 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6496 * Always returns true, does nothing
6498 * @return true
6500 public function get_setting() {
6501 return true;
6505 * Always returns true, does nothing
6507 * @return true
6509 public function get_defaultsetting() {
6510 return true;
6514 * Always returns '', does not write anything
6516 * @return string Always returns ''
6518 public function write_setting($data) {
6519 // do not write any setting
6520 return '';
6524 * Checks if $query is one of the available enrol plugins
6526 * @param string $query The string to search for
6527 * @return bool Returns true if found, false if not
6529 public function is_related($query) {
6530 if (parent::is_related($query)) {
6531 return true;
6534 $query = core_text::strtolower($query);
6535 $enrols = enrol_get_plugins(false);
6536 foreach ($enrols as $name=>$enrol) {
6537 $localised = get_string('pluginname', 'enrol_'.$name);
6538 if (strpos(core_text::strtolower($name), $query) !== false) {
6539 return true;
6541 if (strpos(core_text::strtolower($localised), $query) !== false) {
6542 return true;
6545 return false;
6549 * Builds the XHTML to display the control
6551 * @param string $data Unused
6552 * @param string $query
6553 * @return string
6555 public function output_html($data, $query='') {
6556 global $CFG, $OUTPUT, $DB, $PAGE;
6558 // Display strings.
6559 $strup = get_string('up');
6560 $strdown = get_string('down');
6561 $strsettings = get_string('settings');
6562 $strenable = get_string('enable');
6563 $strdisable = get_string('disable');
6564 $struninstall = get_string('uninstallplugin', 'core_admin');
6565 $strusage = get_string('enrolusage', 'enrol');
6566 $strversion = get_string('version');
6567 $strtest = get_string('testsettings', 'core_enrol');
6569 $pluginmanager = core_plugin_manager::instance();
6571 $enrols_available = enrol_get_plugins(false);
6572 $active_enrols = enrol_get_plugins(true);
6574 $allenrols = array();
6575 foreach ($active_enrols as $key=>$enrol) {
6576 $allenrols[$key] = true;
6578 foreach ($enrols_available as $key=>$enrol) {
6579 $allenrols[$key] = true;
6581 // Now find all borked plugins and at least allow then to uninstall.
6582 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6583 foreach ($condidates as $candidate) {
6584 if (empty($allenrols[$candidate])) {
6585 $allenrols[$candidate] = true;
6589 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6590 $return .= $OUTPUT->box_start('generalbox enrolsui');
6592 $table = new html_table();
6593 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6594 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6595 $table->id = 'courseenrolmentplugins';
6596 $table->attributes['class'] = 'admintable generaltable';
6597 $table->data = array();
6599 // Iterate through enrol plugins and add to the display table.
6600 $updowncount = 1;
6601 $enrolcount = count($active_enrols);
6602 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6603 $printed = array();
6604 foreach($allenrols as $enrol => $unused) {
6605 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6606 $version = get_config('enrol_'.$enrol, 'version');
6607 if ($version === false) {
6608 $version = '';
6611 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6612 $name = get_string('pluginname', 'enrol_'.$enrol);
6613 } else {
6614 $name = $enrol;
6616 // Usage.
6617 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6618 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6619 $usage = "$ci / $cp";
6621 // Hide/show links.
6622 $class = '';
6623 if (isset($active_enrols[$enrol])) {
6624 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6625 $hideshow = "<a href=\"$aurl\">";
6626 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6627 $enabled = true;
6628 $displayname = $name;
6629 } else if (isset($enrols_available[$enrol])) {
6630 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6631 $hideshow = "<a href=\"$aurl\">";
6632 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6633 $enabled = false;
6634 $displayname = $name;
6635 $class = 'dimmed_text';
6636 } else {
6637 $hideshow = '';
6638 $enabled = false;
6639 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6641 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6642 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6643 } else {
6644 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6647 // Up/down link (only if enrol is enabled).
6648 $updown = '';
6649 if ($enabled) {
6650 if ($updowncount > 1) {
6651 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6652 $updown .= "<a href=\"$aurl\">";
6653 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6654 } else {
6655 $updown .= $OUTPUT->spacer() . '&nbsp;';
6657 if ($updowncount < $enrolcount) {
6658 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6659 $updown .= "<a href=\"$aurl\">";
6660 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6661 } else {
6662 $updown .= $OUTPUT->spacer() . '&nbsp;';
6664 ++$updowncount;
6667 // Add settings link.
6668 if (!$version) {
6669 $settings = '';
6670 } else if ($surl = $plugininfo->get_settings_url()) {
6671 $settings = html_writer::link($surl, $strsettings);
6672 } else {
6673 $settings = '';
6676 // Add uninstall info.
6677 $uninstall = '';
6678 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6679 $uninstall = html_writer::link($uninstallurl, $struninstall);
6682 $test = '';
6683 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6684 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6685 $test = html_writer::link($testsettingsurl, $strtest);
6688 // Add a row to the table.
6689 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6690 if ($class) {
6691 $row->attributes['class'] = $class;
6693 $table->data[] = $row;
6695 $printed[$enrol] = true;
6698 $return .= html_writer::table($table);
6699 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6700 $return .= $OUTPUT->box_end();
6701 return highlight($query, $return);
6707 * Blocks manage page
6709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6711 class admin_page_manageblocks extends admin_externalpage {
6713 * Calls parent::__construct with specific arguments
6715 public function __construct() {
6716 global $CFG;
6717 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6721 * Search for a specific block
6723 * @param string $query The string to search for
6724 * @return array
6726 public function search($query) {
6727 global $CFG, $DB;
6728 if ($result = parent::search($query)) {
6729 return $result;
6732 $found = false;
6733 if ($blocks = $DB->get_records('block')) {
6734 foreach ($blocks as $block) {
6735 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6736 continue;
6738 if (strpos($block->name, $query) !== false) {
6739 $found = true;
6740 break;
6742 $strblockname = get_string('pluginname', 'block_'.$block->name);
6743 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6744 $found = true;
6745 break;
6749 if ($found) {
6750 $result = new stdClass();
6751 $result->page = $this;
6752 $result->settings = array();
6753 return array($this->name => $result);
6754 } else {
6755 return array();
6761 * Message outputs configuration
6763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6765 class admin_page_managemessageoutputs extends admin_externalpage {
6767 * Calls parent::__construct with specific arguments
6769 public function __construct() {
6770 global $CFG;
6771 parent::__construct('managemessageoutputs',
6772 get_string('defaultmessageoutputs', 'message'),
6773 new moodle_url('/admin/message.php')
6778 * Search for a specific message processor
6780 * @param string $query The string to search for
6781 * @return array
6783 public function search($query) {
6784 global $CFG, $DB;
6785 if ($result = parent::search($query)) {
6786 return $result;
6789 $found = false;
6790 if ($processors = get_message_processors()) {
6791 foreach ($processors as $processor) {
6792 if (!$processor->available) {
6793 continue;
6795 if (strpos($processor->name, $query) !== false) {
6796 $found = true;
6797 break;
6799 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6800 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6801 $found = true;
6802 break;
6806 if ($found) {
6807 $result = new stdClass();
6808 $result->page = $this;
6809 $result->settings = array();
6810 return array($this->name => $result);
6811 } else {
6812 return array();
6818 * Manage question behaviours page
6820 * @copyright 2011 The Open University
6821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6823 class admin_page_manageqbehaviours extends admin_externalpage {
6825 * Constructor
6827 public function __construct() {
6828 global $CFG;
6829 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6830 new moodle_url('/admin/qbehaviours.php'));
6834 * Search question behaviours for the specified string
6836 * @param string $query The string to search for in question behaviours
6837 * @return array
6839 public function search($query) {
6840 global $CFG;
6841 if ($result = parent::search($query)) {
6842 return $result;
6845 $found = false;
6846 require_once($CFG->dirroot . '/question/engine/lib.php');
6847 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6848 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6849 $query) !== false) {
6850 $found = true;
6851 break;
6854 if ($found) {
6855 $result = new stdClass();
6856 $result->page = $this;
6857 $result->settings = array();
6858 return array($this->name => $result);
6859 } else {
6860 return array();
6867 * Question type manage page
6869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6871 class admin_page_manageqtypes extends admin_externalpage {
6873 * Calls parent::__construct with specific arguments
6875 public function __construct() {
6876 global $CFG;
6877 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6878 new moodle_url('/admin/qtypes.php'));
6882 * Search question types for the specified string
6884 * @param string $query The string to search for in question types
6885 * @return array
6887 public function search($query) {
6888 global $CFG;
6889 if ($result = parent::search($query)) {
6890 return $result;
6893 $found = false;
6894 require_once($CFG->dirroot . '/question/engine/bank.php');
6895 foreach (question_bank::get_all_qtypes() as $qtype) {
6896 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6897 $found = true;
6898 break;
6901 if ($found) {
6902 $result = new stdClass();
6903 $result->page = $this;
6904 $result->settings = array();
6905 return array($this->name => $result);
6906 } else {
6907 return array();
6913 class admin_page_manageportfolios extends admin_externalpage {
6915 * Calls parent::__construct with specific arguments
6917 public function __construct() {
6918 global $CFG;
6919 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6920 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6924 * Searches page for the specified string.
6925 * @param string $query The string to search for
6926 * @return bool True if it is found on this page
6928 public function search($query) {
6929 global $CFG;
6930 if ($result = parent::search($query)) {
6931 return $result;
6934 $found = false;
6935 $portfolios = core_component::get_plugin_list('portfolio');
6936 foreach ($portfolios as $p => $dir) {
6937 if (strpos($p, $query) !== false) {
6938 $found = true;
6939 break;
6942 if (!$found) {
6943 foreach (portfolio_instances(false, false) as $instance) {
6944 $title = $instance->get('name');
6945 if (strpos(core_text::strtolower($title), $query) !== false) {
6946 $found = true;
6947 break;
6952 if ($found) {
6953 $result = new stdClass();
6954 $result->page = $this;
6955 $result->settings = array();
6956 return array($this->name => $result);
6957 } else {
6958 return array();
6964 class admin_page_managerepositories extends admin_externalpage {
6966 * Calls parent::__construct with specific arguments
6968 public function __construct() {
6969 global $CFG;
6970 parent::__construct('managerepositories', get_string('manage',
6971 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6975 * Searches page for the specified string.
6976 * @param string $query The string to search for
6977 * @return bool True if it is found on this page
6979 public function search($query) {
6980 global $CFG;
6981 if ($result = parent::search($query)) {
6982 return $result;
6985 $found = false;
6986 $repositories= core_component::get_plugin_list('repository');
6987 foreach ($repositories as $p => $dir) {
6988 if (strpos($p, $query) !== false) {
6989 $found = true;
6990 break;
6993 if (!$found) {
6994 foreach (repository::get_types() as $instance) {
6995 $title = $instance->get_typename();
6996 if (strpos(core_text::strtolower($title), $query) !== false) {
6997 $found = true;
6998 break;
7003 if ($found) {
7004 $result = new stdClass();
7005 $result->page = $this;
7006 $result->settings = array();
7007 return array($this->name => $result);
7008 } else {
7009 return array();
7016 * Special class for authentication administration.
7018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7020 class admin_setting_manageauths extends admin_setting {
7022 * Calls parent::__construct with specific arguments
7024 public function __construct() {
7025 $this->nosave = true;
7026 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
7030 * Always returns true
7032 * @return true
7034 public function get_setting() {
7035 return true;
7039 * Always returns true
7041 * @return true
7043 public function get_defaultsetting() {
7044 return true;
7048 * Always returns '' and doesn't write anything
7050 * @return string Always returns ''
7052 public function write_setting($data) {
7053 // do not write any setting
7054 return '';
7058 * Search to find if Query is related to auth plugin
7060 * @param string $query The string to search for
7061 * @return bool true for related false for not
7063 public function is_related($query) {
7064 if (parent::is_related($query)) {
7065 return true;
7068 $authsavailable = core_component::get_plugin_list('auth');
7069 foreach ($authsavailable as $auth => $dir) {
7070 if (strpos($auth, $query) !== false) {
7071 return true;
7073 $authplugin = get_auth_plugin($auth);
7074 $authtitle = $authplugin->get_title();
7075 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
7076 return true;
7079 return false;
7083 * Return XHTML to display control
7085 * @param mixed $data Unused
7086 * @param string $query
7087 * @return string highlight
7089 public function output_html($data, $query='') {
7090 global $CFG, $OUTPUT, $DB;
7092 // display strings
7093 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7094 'settings', 'edit', 'name', 'enable', 'disable',
7095 'up', 'down', 'none', 'users'));
7096 $txt->updown = "$txt->up/$txt->down";
7097 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7098 $txt->testsettings = get_string('testsettings', 'core_auth');
7100 $authsavailable = core_component::get_plugin_list('auth');
7101 get_enabled_auth_plugins(true); // fix the list of enabled auths
7102 if (empty($CFG->auth)) {
7103 $authsenabled = array();
7104 } else {
7105 $authsenabled = explode(',', $CFG->auth);
7108 // construct the display array, with enabled auth plugins at the top, in order
7109 $displayauths = array();
7110 $registrationauths = array();
7111 $registrationauths[''] = $txt->disable;
7112 $authplugins = array();
7113 foreach ($authsenabled as $auth) {
7114 $authplugin = get_auth_plugin($auth);
7115 $authplugins[$auth] = $authplugin;
7116 /// Get the auth title (from core or own auth lang files)
7117 $authtitle = $authplugin->get_title();
7118 /// Apply titles
7119 $displayauths[$auth] = $authtitle;
7120 if ($authplugin->can_signup()) {
7121 $registrationauths[$auth] = $authtitle;
7125 foreach ($authsavailable as $auth => $dir) {
7126 if (array_key_exists($auth, $displayauths)) {
7127 continue; //already in the list
7129 $authplugin = get_auth_plugin($auth);
7130 $authplugins[$auth] = $authplugin;
7131 /// Get the auth title (from core or own auth lang files)
7132 $authtitle = $authplugin->get_title();
7133 /// Apply titles
7134 $displayauths[$auth] = $authtitle;
7135 if ($authplugin->can_signup()) {
7136 $registrationauths[$auth] = $authtitle;
7140 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7141 if (in_array('mnet', $authsenabled)) {
7142 $notify = new \core\output\notification(get_string('xmlrpcmnetauthenticationenabled', 'admin'),
7143 \core\output\notification::NOTIFY_WARNING);
7144 $return .= $OUTPUT->render($notify);
7146 $return .= $OUTPUT->box_start('generalbox authsui');
7148 $table = new html_table();
7149 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
7150 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7151 $table->data = array();
7152 $table->attributes['class'] = 'admintable generaltable';
7153 $table->id = 'manageauthtable';
7155 //add always enabled plugins first
7156 $displayname = $displayauths['manual'];
7157 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7158 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7159 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
7160 $displayname = $displayauths['nologin'];
7161 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7162 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
7165 // iterate through auth plugins and add to the display table
7166 $updowncount = 1;
7167 $authcount = count($authsenabled);
7168 $url = "auth.php?sesskey=" . sesskey();
7169 foreach ($displayauths as $auth => $name) {
7170 if ($auth == 'manual' or $auth == 'nologin') {
7171 continue;
7173 $class = '';
7174 // hide/show link
7175 if (in_array($auth, $authsenabled)) {
7176 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
7177 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7178 $enabled = true;
7179 $displayname = $name;
7181 else {
7182 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
7183 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7184 $enabled = false;
7185 $displayname = $name;
7186 $class = 'dimmed_text';
7189 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7191 // up/down link (only if auth is enabled)
7192 $updown = '';
7193 if ($enabled) {
7194 if ($updowncount > 1) {
7195 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
7196 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7198 else {
7199 $updown .= $OUTPUT->spacer() . '&nbsp;';
7201 if ($updowncount < $authcount) {
7202 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
7203 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7205 else {
7206 $updown .= $OUTPUT->spacer() . '&nbsp;';
7208 ++ $updowncount;
7211 // settings link
7212 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
7213 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7214 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
7215 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
7216 } else {
7217 $settings = '';
7220 // Uninstall link.
7221 $uninstall = '';
7222 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7223 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7226 $test = '';
7227 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7228 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
7229 $test = html_writer::link($testurl, $txt->testsettings);
7232 // Add a row to the table.
7233 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7234 if ($class) {
7235 $row->attributes['class'] = $class;
7237 $table->data[] = $row;
7239 $return .= html_writer::table($table);
7240 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7241 $return .= $OUTPUT->box_end();
7242 return highlight($query, $return);
7248 * Special class for authentication administration.
7250 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7252 class admin_setting_manageeditors extends admin_setting {
7254 * Calls parent::__construct with specific arguments
7256 public function __construct() {
7257 $this->nosave = true;
7258 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
7262 * Always returns true, does nothing
7264 * @return true
7266 public function get_setting() {
7267 return true;
7271 * Always returns true, does nothing
7273 * @return true
7275 public function get_defaultsetting() {
7276 return true;
7280 * Always returns '', does not write anything
7282 * @return string Always returns ''
7284 public function write_setting($data) {
7285 // do not write any setting
7286 return '';
7290 * Checks if $query is one of the available editors
7292 * @param string $query The string to search for
7293 * @return bool Returns true if found, false if not
7295 public function is_related($query) {
7296 if (parent::is_related($query)) {
7297 return true;
7300 $editors_available = editors_get_available();
7301 foreach ($editors_available as $editor=>$editorstr) {
7302 if (strpos($editor, $query) !== false) {
7303 return true;
7305 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
7306 return true;
7309 return false;
7313 * Builds the XHTML to display the control
7315 * @param string $data Unused
7316 * @param string $query
7317 * @return string
7319 public function output_html($data, $query='') {
7320 global $CFG, $OUTPUT;
7322 // display strings
7323 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7324 'up', 'down', 'none'));
7325 $struninstall = get_string('uninstallplugin', 'core_admin');
7327 $txt->updown = "$txt->up/$txt->down";
7329 $editors_available = editors_get_available();
7330 $active_editors = explode(',', $CFG->texteditors);
7332 $active_editors = array_reverse($active_editors);
7333 foreach ($active_editors as $key=>$editor) {
7334 if (empty($editors_available[$editor])) {
7335 unset($active_editors[$key]);
7336 } else {
7337 $name = $editors_available[$editor];
7338 unset($editors_available[$editor]);
7339 $editors_available[$editor] = $name;
7342 if (empty($active_editors)) {
7343 //$active_editors = array('textarea');
7345 $editors_available = array_reverse($editors_available, true);
7346 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
7347 $return .= $OUTPUT->box_start('generalbox editorsui');
7349 $table = new html_table();
7350 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7351 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7352 $table->id = 'editormanagement';
7353 $table->attributes['class'] = 'admintable generaltable';
7354 $table->data = array();
7356 // iterate through auth plugins and add to the display table
7357 $updowncount = 1;
7358 $editorcount = count($active_editors);
7359 $url = "editors.php?sesskey=" . sesskey();
7360 foreach ($editors_available as $editor => $name) {
7361 // hide/show link
7362 $class = '';
7363 if (in_array($editor, $active_editors)) {
7364 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
7365 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7366 $enabled = true;
7367 $displayname = $name;
7369 else {
7370 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
7371 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7372 $enabled = false;
7373 $displayname = $name;
7374 $class = 'dimmed_text';
7377 // up/down link (only if auth is enabled)
7378 $updown = '';
7379 if ($enabled) {
7380 if ($updowncount > 1) {
7381 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
7382 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7384 else {
7385 $updown .= $OUTPUT->spacer() . '&nbsp;';
7387 if ($updowncount < $editorcount) {
7388 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
7389 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7391 else {
7392 $updown .= $OUTPUT->spacer() . '&nbsp;';
7394 ++ $updowncount;
7397 // settings link
7398 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
7399 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7400 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7401 } else {
7402 $settings = '';
7405 $uninstall = '';
7406 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7407 $uninstall = html_writer::link($uninstallurl, $struninstall);
7410 // Add a row to the table.
7411 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7412 if ($class) {
7413 $row->attributes['class'] = $class;
7415 $table->data[] = $row;
7417 $return .= html_writer::table($table);
7418 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7419 $return .= $OUTPUT->box_end();
7420 return highlight($query, $return);
7425 * Special class for antiviruses administration.
7427 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7430 class admin_setting_manageantiviruses extends admin_setting {
7432 * Calls parent::__construct with specific arguments
7434 public function __construct() {
7435 $this->nosave = true;
7436 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7440 * Always returns true, does nothing
7442 * @return true
7444 public function get_setting() {
7445 return true;
7449 * Always returns true, does nothing
7451 * @return true
7453 public function get_defaultsetting() {
7454 return true;
7458 * Always returns '', does not write anything
7460 * @param string $data Unused
7461 * @return string Always returns ''
7463 public function write_setting($data) {
7464 // Do not write any setting.
7465 return '';
7469 * Checks if $query is one of the available editors
7471 * @param string $query The string to search for
7472 * @return bool Returns true if found, false if not
7474 public function is_related($query) {
7475 if (parent::is_related($query)) {
7476 return true;
7479 $antivirusesavailable = \core\antivirus\manager::get_available();
7480 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7481 if (strpos($antivirus, $query) !== false) {
7482 return true;
7484 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7485 return true;
7488 return false;
7492 * Builds the XHTML to display the control
7494 * @param string $data Unused
7495 * @param string $query
7496 * @return string
7498 public function output_html($data, $query='') {
7499 global $CFG, $OUTPUT;
7501 // Display strings.
7502 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7503 'up', 'down', 'none'));
7504 $struninstall = get_string('uninstallplugin', 'core_admin');
7506 $txt->updown = "$txt->up/$txt->down";
7508 $antivirusesavailable = \core\antivirus\manager::get_available();
7509 $activeantiviruses = explode(',', $CFG->antiviruses);
7511 $activeantiviruses = array_reverse($activeantiviruses);
7512 foreach ($activeantiviruses as $key => $antivirus) {
7513 if (empty($antivirusesavailable[$antivirus])) {
7514 unset($activeantiviruses[$key]);
7515 } else {
7516 $name = $antivirusesavailable[$antivirus];
7517 unset($antivirusesavailable[$antivirus]);
7518 $antivirusesavailable[$antivirus] = $name;
7521 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7522 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7523 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7525 $table = new html_table();
7526 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7527 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7528 $table->id = 'antivirusmanagement';
7529 $table->attributes['class'] = 'admintable generaltable';
7530 $table->data = array();
7532 // Iterate through auth plugins and add to the display table.
7533 $updowncount = 1;
7534 $antiviruscount = count($activeantiviruses);
7535 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7536 foreach ($antivirusesavailable as $antivirus => $name) {
7537 // Hide/show link.
7538 $class = '';
7539 if (in_array($antivirus, $activeantiviruses)) {
7540 $hideshowurl = $baseurl;
7541 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7542 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7543 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7544 $enabled = true;
7545 $displayname = $name;
7546 } else {
7547 $hideshowurl = $baseurl;
7548 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7549 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7550 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7551 $enabled = false;
7552 $displayname = $name;
7553 $class = 'dimmed_text';
7556 // Up/down link.
7557 $updown = '';
7558 if ($enabled) {
7559 if ($updowncount > 1) {
7560 $updownurl = $baseurl;
7561 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7562 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7563 $updown = html_writer::link($updownurl, $updownimg);
7564 } else {
7565 $updownimg = $OUTPUT->spacer();
7567 if ($updowncount < $antiviruscount) {
7568 $updownurl = $baseurl;
7569 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7570 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7571 $updown = html_writer::link($updownurl, $updownimg);
7572 } else {
7573 $updownimg = $OUTPUT->spacer();
7575 ++ $updowncount;
7578 // Settings link.
7579 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7580 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7581 $settings = html_writer::link($eurl, $txt->settings);
7582 } else {
7583 $settings = '';
7586 $uninstall = '';
7587 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7588 $uninstall = html_writer::link($uninstallurl, $struninstall);
7591 // Add a row to the table.
7592 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7593 if ($class) {
7594 $row->attributes['class'] = $class;
7596 $table->data[] = $row;
7598 $return .= html_writer::table($table);
7599 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7600 $return .= $OUTPUT->box_end();
7601 return highlight($query, $return);
7606 * Special class for license administration.
7608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7609 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7610 * @todo MDL-45184 This class will be deleted in Moodle 4.1.
7612 class admin_setting_managelicenses extends admin_setting {
7614 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7615 * @todo MDL-45184 This class will be deleted in Moodle 4.1
7617 public function __construct() {
7618 global $ADMIN;
7620 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7621 DEBUG_DEVELOPER);
7623 // Replace admin setting load with new external page load for tool_licensemanager, if not loaded already.
7624 if (!is_null($ADMIN->locate('licensemanager'))) {
7625 $temp = new admin_externalpage('licensemanager',
7626 get_string('licensemanager', 'tool_licensemanager'),
7627 \tool_licensemanager\helper::get_licensemanager_url());
7629 $ADMIN->add('license', $temp);
7634 * Always returns true, does nothing
7636 * @deprecated since Moodle 3.9 MDL-45184.
7637 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7639 * @return true
7641 public function get_setting() {
7642 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7643 DEBUG_DEVELOPER);
7645 return true;
7649 * Always returns true, does nothing
7651 * @deprecated since Moodle 3.9 MDL-45184.
7652 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7654 * @return true
7656 public function get_defaultsetting() {
7657 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7658 DEBUG_DEVELOPER);
7660 return true;
7664 * Always returns '', does not write anything
7666 * @deprecated since Moodle 3.9 MDL-45184.
7667 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7669 * @return string Always returns ''
7671 public function write_setting($data) {
7672 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7673 DEBUG_DEVELOPER);
7675 // do not write any setting
7676 return '';
7680 * Builds the XHTML to display the control
7682 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7683 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7685 * @param string $data Unused
7686 * @param string $query
7687 * @return string
7689 public function output_html($data, $query='') {
7690 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7691 DEBUG_DEVELOPER);
7693 redirect(\tool_licensemanager\helper::get_licensemanager_url());
7698 * Course formats manager. Allows to enable/disable formats and jump to settings
7700 class admin_setting_manageformats extends admin_setting {
7703 * Calls parent::__construct with specific arguments
7705 public function __construct() {
7706 $this->nosave = true;
7707 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7711 * Always returns true
7713 * @return true
7715 public function get_setting() {
7716 return true;
7720 * Always returns true
7722 * @return true
7724 public function get_defaultsetting() {
7725 return true;
7729 * Always returns '' and doesn't write anything
7731 * @param mixed $data string or array, must not be NULL
7732 * @return string Always returns ''
7734 public function write_setting($data) {
7735 // do not write any setting
7736 return '';
7740 * Search to find if Query is related to format plugin
7742 * @param string $query The string to search for
7743 * @return bool true for related false for not
7745 public function is_related($query) {
7746 if (parent::is_related($query)) {
7747 return true;
7749 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7750 foreach ($formats as $format) {
7751 if (strpos($format->component, $query) !== false ||
7752 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7753 return true;
7756 return false;
7760 * Return XHTML to display control
7762 * @param mixed $data Unused
7763 * @param string $query
7764 * @return string highlight
7766 public function output_html($data, $query='') {
7767 global $CFG, $OUTPUT;
7768 $return = '';
7769 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7770 $return .= $OUTPUT->box_start('generalbox formatsui');
7772 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7774 // display strings
7775 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7776 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7777 $txt->updown = "$txt->up/$txt->down";
7779 $table = new html_table();
7780 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7781 $table->align = array('left', 'center', 'center', 'center', 'center');
7782 $table->attributes['class'] = 'manageformattable generaltable admintable';
7783 $table->data = array();
7785 $cnt = 0;
7786 $defaultformat = get_config('moodlecourse', 'format');
7787 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7788 foreach ($formats as $format) {
7789 $url = new moodle_url('/admin/courseformats.php',
7790 array('sesskey' => sesskey(), 'format' => $format->name));
7791 $isdefault = '';
7792 $class = '';
7793 if ($format->is_enabled()) {
7794 $strformatname = $format->displayname;
7795 if ($defaultformat === $format->name) {
7796 $hideshow = $txt->default;
7797 } else {
7798 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7799 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7801 } else {
7802 $strformatname = $format->displayname;
7803 $class = 'dimmed_text';
7804 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7805 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7807 $updown = '';
7808 if ($cnt) {
7809 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7810 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7811 } else {
7812 $updown .= $spacer;
7814 if ($cnt < count($formats) - 1) {
7815 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7816 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7817 } else {
7818 $updown .= $spacer;
7820 $cnt++;
7821 $settings = '';
7822 if ($format->get_settings_url()) {
7823 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7825 $uninstall = '';
7826 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7827 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7829 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7830 if ($class) {
7831 $row->attributes['class'] = $class;
7833 $table->data[] = $row;
7835 $return .= html_writer::table($table);
7836 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7837 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7838 $return .= $OUTPUT->box_end();
7839 return highlight($query, $return);
7844 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7846 * @package core
7847 * @copyright 2018 Toni Barbera
7848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7850 class admin_setting_managecustomfields extends admin_setting {
7853 * Calls parent::__construct with specific arguments
7855 public function __construct() {
7856 $this->nosave = true;
7857 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7861 * Always returns true
7863 * @return true
7865 public function get_setting() {
7866 return true;
7870 * Always returns true
7872 * @return true
7874 public function get_defaultsetting() {
7875 return true;
7879 * Always returns '' and doesn't write anything
7881 * @param mixed $data string or array, must not be NULL
7882 * @return string Always returns ''
7884 public function write_setting($data) {
7885 // Do not write any setting.
7886 return '';
7890 * Search to find if Query is related to format plugin
7892 * @param string $query The string to search for
7893 * @return bool true for related false for not
7895 public function is_related($query) {
7896 if (parent::is_related($query)) {
7897 return true;
7899 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7900 foreach ($formats as $format) {
7901 if (strpos($format->component, $query) !== false ||
7902 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7903 return true;
7906 return false;
7910 * Return XHTML to display control
7912 * @param mixed $data Unused
7913 * @param string $query
7914 * @return string highlight
7916 public function output_html($data, $query='') {
7917 global $CFG, $OUTPUT;
7918 $return = '';
7919 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7920 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7922 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7924 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7925 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7926 $txt->updown = "$txt->up/$txt->down";
7928 $table = new html_table();
7929 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7930 $table->align = array('left', 'center', 'center', 'center');
7931 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7932 $table->data = array();
7934 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7935 foreach ($fields as $field) {
7936 $url = new moodle_url('/admin/customfields.php',
7937 array('sesskey' => sesskey(), 'field' => $field->name));
7939 if ($field->is_enabled()) {
7940 $strfieldname = $field->displayname;
7941 $class = '';
7942 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7943 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7944 } else {
7945 $strfieldname = $field->displayname;
7946 $class = 'dimmed_text';
7947 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7948 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7950 $settings = '';
7951 if ($field->get_settings_url()) {
7952 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7954 $uninstall = '';
7955 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7956 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7958 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7959 $row->attributes['class'] = $class;
7960 $table->data[] = $row;
7962 $return .= html_writer::table($table);
7963 $return .= $OUTPUT->box_end();
7964 return highlight($query, $return);
7969 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7971 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7974 class admin_setting_managedataformats extends admin_setting {
7977 * Calls parent::__construct with specific arguments
7979 public function __construct() {
7980 $this->nosave = true;
7981 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7985 * Always returns true
7987 * @return true
7989 public function get_setting() {
7990 return true;
7994 * Always returns true
7996 * @return true
7998 public function get_defaultsetting() {
7999 return true;
8003 * Always returns '' and doesn't write anything
8005 * @param mixed $data string or array, must not be NULL
8006 * @return string Always returns ''
8008 public function write_setting($data) {
8009 // Do not write any setting.
8010 return '';
8014 * Search to find if Query is related to format plugin
8016 * @param string $query The string to search for
8017 * @return bool true for related false for not
8019 public function is_related($query) {
8020 if (parent::is_related($query)) {
8021 return true;
8023 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
8024 foreach ($formats as $format) {
8025 if (strpos($format->component, $query) !== false ||
8026 strpos(core_text::strtolower($format->displayname), $query) !== false) {
8027 return true;
8030 return false;
8034 * Return XHTML to display control
8036 * @param mixed $data Unused
8037 * @param string $query
8038 * @return string highlight
8040 public function output_html($data, $query='') {
8041 global $CFG, $OUTPUT;
8042 $return = '';
8044 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
8046 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
8047 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8048 $txt->updown = "$txt->up/$txt->down";
8050 $table = new html_table();
8051 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
8052 $table->align = array('left', 'center', 'center', 'center', 'center');
8053 $table->attributes['class'] = 'manageformattable generaltable admintable';
8054 $table->data = array();
8056 $cnt = 0;
8057 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8058 $totalenabled = 0;
8059 foreach ($formats as $format) {
8060 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
8061 $totalenabled++;
8064 foreach ($formats as $format) {
8065 $status = $format->get_status();
8066 $url = new moodle_url('/admin/dataformats.php',
8067 array('sesskey' => sesskey(), 'name' => $format->name));
8069 $class = '';
8070 if ($format->is_enabled()) {
8071 $strformatname = $format->displayname;
8072 if ($totalenabled == 1&& $format->is_enabled()) {
8073 $hideshow = '';
8074 } else {
8075 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8076 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8078 } else {
8079 $class = 'dimmed_text';
8080 $strformatname = $format->displayname;
8081 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8082 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8085 $updown = '';
8086 if ($cnt) {
8087 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8088 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8089 } else {
8090 $updown .= $spacer;
8092 if ($cnt < count($formats) - 1) {
8093 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8094 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8095 } else {
8096 $updown .= $spacer;
8099 $uninstall = '';
8100 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8101 $uninstall = get_string('status_missing', 'core_plugin');
8102 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8103 $uninstall = get_string('status_new', 'core_plugin');
8104 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
8105 if ($totalenabled != 1 || !$format->is_enabled()) {
8106 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8110 $settings = '';
8111 if ($format->get_settings_url()) {
8112 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
8115 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
8116 if ($class) {
8117 $row->attributes['class'] = $class;
8119 $table->data[] = $row;
8120 $cnt++;
8122 $return .= html_writer::table($table);
8123 return highlight($query, $return);
8128 * Special class for filter administration.
8130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8132 class admin_page_managefilters extends admin_externalpage {
8134 * Calls parent::__construct with specific arguments
8136 public function __construct() {
8137 global $CFG;
8138 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
8142 * Searches all installed filters for specified filter
8144 * @param string $query The filter(string) to search for
8145 * @param string $query
8147 public function search($query) {
8148 global $CFG;
8149 if ($result = parent::search($query)) {
8150 return $result;
8153 $found = false;
8154 $filternames = filter_get_all_installed();
8155 foreach ($filternames as $path => $strfiltername) {
8156 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
8157 $found = true;
8158 break;
8160 if (strpos($path, $query) !== false) {
8161 $found = true;
8162 break;
8166 if ($found) {
8167 $result = new stdClass;
8168 $result->page = $this;
8169 $result->settings = array();
8170 return array($this->name => $result);
8171 } else {
8172 return array();
8178 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8179 * Requires a get_rank method on the plugininfo class for sorting.
8181 * @copyright 2017 Damyon Wiese
8182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8184 abstract class admin_setting_manage_plugins extends admin_setting {
8187 * Get the admin settings section name (just a unique string)
8189 * @return string
8191 public function get_section_name() {
8192 return 'manage' . $this->get_plugin_type() . 'plugins';
8196 * Get the admin settings section title (use get_string).
8198 * @return string
8200 abstract public function get_section_title();
8203 * Get the type of plugin to manage.
8205 * @return string
8207 abstract public function get_plugin_type();
8210 * Get the name of the second column.
8212 * @return string
8214 public function get_info_column_name() {
8215 return '';
8219 * Get the type of plugin to manage.
8221 * @param plugininfo The plugin info class.
8222 * @return string
8224 abstract public function get_info_column($plugininfo);
8227 * Calls parent::__construct with specific arguments
8229 public function __construct() {
8230 $this->nosave = true;
8231 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8235 * Always returns true, does nothing
8237 * @return true
8239 public function get_setting() {
8240 return true;
8244 * Always returns true, does nothing
8246 * @return true
8248 public function get_defaultsetting() {
8249 return true;
8253 * Always returns '', does not write anything
8255 * @param mixed $data
8256 * @return string Always returns ''
8258 public function write_setting($data) {
8259 // Do not write any setting.
8260 return '';
8264 * Checks if $query is one of the available plugins of this type
8266 * @param string $query The string to search for
8267 * @return bool Returns true if found, false if not
8269 public function is_related($query) {
8270 if (parent::is_related($query)) {
8271 return true;
8274 $query = core_text::strtolower($query);
8275 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
8276 foreach ($plugins as $name => $plugin) {
8277 $localised = $plugin->displayname;
8278 if (strpos(core_text::strtolower($name), $query) !== false) {
8279 return true;
8281 if (strpos(core_text::strtolower($localised), $query) !== false) {
8282 return true;
8285 return false;
8289 * The URL for the management page for this plugintype.
8291 * @return moodle_url
8293 protected function get_manage_url() {
8294 return new moodle_url('/admin/updatesetting.php');
8298 * Builds the HTML to display the control.
8300 * @param string $data Unused
8301 * @param string $query
8302 * @return string
8304 public function output_html($data, $query = '') {
8305 global $CFG, $OUTPUT, $DB, $PAGE;
8307 $context = (object) [
8308 'manageurl' => new moodle_url($this->get_manage_url(), [
8309 'type' => $this->get_plugin_type(),
8310 'sesskey' => sesskey(),
8312 'infocolumnname' => $this->get_info_column_name(),
8313 'plugins' => [],
8316 $pluginmanager = core_plugin_manager::instance();
8317 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8318 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8319 $plugins = array_merge($enabled, $allplugins);
8320 foreach ($plugins as $key => $plugin) {
8321 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
8323 $pluginkey = (object) [
8324 'plugin' => $plugin->displayname,
8325 'enabled' => $plugin->is_enabled(),
8326 'togglelink' => '',
8327 'moveuplink' => '',
8328 'movedownlink' => '',
8329 'settingslink' => $plugin->get_settings_url(),
8330 'uninstalllink' => '',
8331 'info' => '',
8334 // Enable/Disable link.
8335 $togglelink = new moodle_url($pluginlink);
8336 if ($plugin->is_enabled()) {
8337 $toggletarget = false;
8338 $togglelink->param('action', 'disable');
8340 if (count($context->plugins)) {
8341 // This is not the first plugin.
8342 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
8345 if (count($enabled) > count($context->plugins) + 1) {
8346 // This is not the last plugin.
8347 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
8350 $pluginkey->info = $this->get_info_column($plugin);
8351 } else {
8352 $toggletarget = true;
8353 $togglelink->param('action', 'enable');
8356 $pluginkey->toggletarget = $toggletarget;
8357 $pluginkey->togglelink = $togglelink;
8359 $frankenstyle = $plugin->type . '_' . $plugin->name;
8360 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8361 // This plugin supports uninstallation.
8362 $pluginkey->uninstalllink = $uninstalllink;
8365 if (!empty($this->get_info_column_name())) {
8366 // This plugintype has an info column.
8367 $pluginkey->info = $this->get_info_column($plugin);
8370 $context->plugins[] = $pluginkey;
8373 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8374 return highlight($query, $str);
8379 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8380 * Requires a get_rank method on the plugininfo class for sorting.
8382 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8385 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8386 public function get_section_title() {
8387 return get_string('type_fileconverter_plural', 'plugin');
8390 public function get_plugin_type() {
8391 return 'fileconverter';
8394 public function get_info_column_name() {
8395 return get_string('supportedconversions', 'plugin');
8398 public function get_info_column($plugininfo) {
8399 return $plugininfo->get_supported_conversions();
8404 * Special class for media player plugins management.
8406 * @copyright 2016 Marina Glancy
8407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8409 class admin_setting_managemediaplayers extends admin_setting {
8411 * Calls parent::__construct with specific arguments
8413 public function __construct() {
8414 $this->nosave = true;
8415 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8419 * Always returns true, does nothing
8421 * @return true
8423 public function get_setting() {
8424 return true;
8428 * Always returns true, does nothing
8430 * @return true
8432 public function get_defaultsetting() {
8433 return true;
8437 * Always returns '', does not write anything
8439 * @param mixed $data
8440 * @return string Always returns ''
8442 public function write_setting($data) {
8443 // Do not write any setting.
8444 return '';
8448 * Checks if $query is one of the available enrol plugins
8450 * @param string $query The string to search for
8451 * @return bool Returns true if found, false if not
8453 public function is_related($query) {
8454 if (parent::is_related($query)) {
8455 return true;
8458 $query = core_text::strtolower($query);
8459 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8460 foreach ($plugins as $name => $plugin) {
8461 $localised = $plugin->displayname;
8462 if (strpos(core_text::strtolower($name), $query) !== false) {
8463 return true;
8465 if (strpos(core_text::strtolower($localised), $query) !== false) {
8466 return true;
8469 return false;
8473 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8474 * @return \core\plugininfo\media[]
8476 protected function get_sorted_plugins() {
8477 $pluginmanager = core_plugin_manager::instance();
8479 $plugins = $pluginmanager->get_plugins_of_type('media');
8480 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8482 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8483 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8485 $order = array_values($enabledplugins);
8486 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8488 $sortedplugins = array();
8489 foreach ($order as $name) {
8490 $sortedplugins[$name] = $plugins[$name];
8493 return $sortedplugins;
8497 * Builds the XHTML to display the control
8499 * @param string $data Unused
8500 * @param string $query
8501 * @return string
8503 public function output_html($data, $query='') {
8504 global $CFG, $OUTPUT, $DB, $PAGE;
8506 // Display strings.
8507 $strup = get_string('up');
8508 $strdown = get_string('down');
8509 $strsettings = get_string('settings');
8510 $strenable = get_string('enable');
8511 $strdisable = get_string('disable');
8512 $struninstall = get_string('uninstallplugin', 'core_admin');
8513 $strversion = get_string('version');
8514 $strname = get_string('name');
8515 $strsupports = get_string('supports', 'core_media');
8517 $pluginmanager = core_plugin_manager::instance();
8519 $plugins = $this->get_sorted_plugins();
8520 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8522 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8524 $table = new html_table();
8525 $table->head = array($strname, $strsupports, $strversion,
8526 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8527 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8528 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8529 $table->id = 'mediaplayerplugins';
8530 $table->attributes['class'] = 'admintable generaltable';
8531 $table->data = array();
8533 // Iterate through media plugins and add to the display table.
8534 $updowncount = 1;
8535 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8536 $printed = array();
8537 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8539 $usedextensions = [];
8540 foreach ($plugins as $name => $plugin) {
8541 $url->param('media', $name);
8542 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8543 $version = $plugininfo->versiondb;
8544 $supports = $plugininfo->supports($usedextensions);
8546 // Hide/show links.
8547 $class = '';
8548 if (!$plugininfo->is_installed_and_upgraded()) {
8549 $hideshow = '';
8550 $enabled = false;
8551 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8552 } else {
8553 $enabled = $plugininfo->is_enabled();
8554 if ($enabled) {
8555 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8556 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8557 } else {
8558 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8559 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8560 $class = 'dimmed_text';
8562 $displayname = $plugin->displayname;
8563 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8564 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8567 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8568 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8569 } else {
8570 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8573 // Up/down link (only if enrol is enabled).
8574 $updown = '';
8575 if ($enabled) {
8576 if ($updowncount > 1) {
8577 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8578 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8579 } else {
8580 $updown = $spacer;
8582 if ($updowncount < count($enabledplugins)) {
8583 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8584 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8585 } else {
8586 $updown .= $spacer;
8588 ++$updowncount;
8591 $uninstall = '';
8592 $status = $plugininfo->get_status();
8593 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8594 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8596 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8597 $uninstall = get_string('status_new', 'core_plugin');
8598 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8599 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8602 $settings = '';
8603 if ($plugininfo->get_settings_url()) {
8604 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8607 // Add a row to the table.
8608 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8609 if ($class) {
8610 $row->attributes['class'] = $class;
8612 $table->data[] = $row;
8614 $printed[$name] = true;
8617 $return .= html_writer::table($table);
8618 $return .= $OUTPUT->box_end();
8619 return highlight($query, $return);
8625 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8627 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8630 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8633 * Calls parent::__construct with specific arguments
8635 public function __construct() {
8636 $this->nosave = true;
8637 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8641 * Always returns true
8643 * @return true
8645 public function get_setting() {
8646 return true;
8650 * Always returns true
8652 * @return true
8654 public function get_defaultsetting() {
8655 return true;
8659 * Always returns '' and doesn't write anything
8661 * @param mixed $data string or array, must not be NULL
8662 * @return string Always returns ''
8664 public function write_setting($data) {
8665 // Do not write any setting.
8666 return '';
8670 * Search to find if Query is related to content bank plugin
8672 * @param string $query The string to search for
8673 * @return bool true for related false for not
8675 public function is_related($query) {
8676 if (parent::is_related($query)) {
8677 return true;
8679 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8680 foreach ($types as $type) {
8681 if (strpos($type->component, $query) !== false ||
8682 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8683 return true;
8686 return false;
8690 * Return XHTML to display control
8692 * @param mixed $data Unused
8693 * @param string $query
8694 * @return string highlight
8696 public function output_html($data, $query='') {
8697 global $CFG, $OUTPUT;
8698 $return = '';
8700 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8701 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8702 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8704 $table = new html_table();
8705 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8706 $table->align = array('left', 'center', 'center', 'center', 'center');
8707 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8708 $table->data = array();
8709 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8711 $totalenabled = 0;
8712 $count = 0;
8713 foreach ($types as $type) {
8714 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8715 $totalenabled++;
8719 foreach ($types as $type) {
8720 $url = new moodle_url('/admin/contentbank.php',
8721 array('sesskey' => sesskey(), 'name' => $type->name));
8723 $class = '';
8724 $strtypename = $type->displayname;
8725 if ($type->is_enabled()) {
8726 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8727 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8728 } else {
8729 $class = 'dimmed_text';
8730 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8731 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8734 $updown = '';
8735 if ($count) {
8736 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8737 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8738 } else {
8739 $updown .= $spacer;
8741 if ($count < count($types) - 1) {
8742 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8743 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8744 } else {
8745 $updown .= $spacer;
8748 $settings = '';
8749 if ($type->get_settings_url()) {
8750 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8753 $uninstall = '';
8754 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8755 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8758 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8759 if ($class) {
8760 $row->attributes['class'] = $class;
8762 $table->data[] = $row;
8763 $count++;
8765 $return .= html_writer::table($table);
8766 return highlight($query, $return);
8771 * Initialise admin page - this function does require login and permission
8772 * checks specified in page definition.
8774 * This function must be called on each admin page before other code.
8776 * @global moodle_page $PAGE
8778 * @param string $section name of page
8779 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8780 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8781 * added to the turn blocks editing on/off form, so this page reloads correctly.
8782 * @param string $actualurl if the actual page being viewed is not the normal one for this
8783 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8784 * @param array $options Additional options that can be specified for page setup.
8785 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8787 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8788 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8790 $PAGE->set_context(null); // hack - set context to something, by default to system context
8792 $site = get_site();
8793 require_login(null, false);
8795 if (!empty($options['pagelayout'])) {
8796 // A specific page layout has been requested.
8797 $PAGE->set_pagelayout($options['pagelayout']);
8798 } else if ($section === 'upgradesettings') {
8799 $PAGE->set_pagelayout('maintenance');
8800 } else {
8801 $PAGE->set_pagelayout('admin');
8804 $adminroot = admin_get_root(false, false); // settings not required for external pages
8805 $extpage = $adminroot->locate($section, true);
8807 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8808 // The requested section isn't in the admin tree
8809 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8810 if (!has_capability('moodle/site:config', context_system::instance())) {
8811 // The requested section could depend on a different capability
8812 // but most likely the user has inadequate capabilities
8813 print_error('accessdenied', 'admin');
8814 } else {
8815 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8819 // this eliminates our need to authenticate on the actual pages
8820 if (!$extpage->check_access()) {
8821 print_error('accessdenied', 'admin');
8822 die;
8825 navigation_node::require_admin_tree();
8827 // $PAGE->set_extra_button($extrabutton); TODO
8829 if (!$actualurl) {
8830 $actualurl = $extpage->url;
8833 $PAGE->set_url($actualurl, $extraurlparams);
8834 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8835 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8838 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8839 // During initial install.
8840 $strinstallation = get_string('installation', 'install');
8841 $strsettings = get_string('settings');
8842 $PAGE->navbar->add($strsettings);
8843 $PAGE->set_title($strinstallation);
8844 $PAGE->set_heading($strinstallation);
8845 $PAGE->set_cacheable(false);
8846 return;
8849 // Locate the current item on the navigation and make it active when found.
8850 $path = $extpage->path;
8851 $node = $PAGE->settingsnav;
8852 while ($node && count($path) > 0) {
8853 $node = $node->get(array_pop($path));
8855 if ($node) {
8856 $node->make_active();
8859 // Normal case.
8860 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8861 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8862 $USER->editing = $adminediting;
8865 $visiblepathtosection = array_reverse($extpage->visiblepath);
8867 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8868 if ($PAGE->user_is_editing()) {
8869 $caption = get_string('blockseditoff');
8870 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8871 } else {
8872 $caption = get_string('blocksediton');
8873 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8875 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8878 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8879 $PAGE->set_heading($SITE->fullname);
8881 // prevent caching in nav block
8882 $PAGE->navigation->clear_cache();
8886 * Returns the reference to admin tree root
8888 * @return object admin_root object
8890 function admin_get_root($reload=false, $requirefulltree=true) {
8891 global $CFG, $DB, $OUTPUT, $ADMIN;
8893 if (is_null($ADMIN)) {
8894 // create the admin tree!
8895 $ADMIN = new admin_root($requirefulltree);
8898 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8899 $ADMIN->purge_children($requirefulltree);
8902 if (!$ADMIN->loaded) {
8903 // we process this file first to create categories first and in correct order
8904 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8906 // now we process all other files in admin/settings to build the admin tree
8907 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8908 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8909 continue;
8911 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8912 // plugins are loaded last - they may insert pages anywhere
8913 continue;
8915 require($file);
8917 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8919 $ADMIN->loaded = true;
8922 return $ADMIN;
8925 /// settings utility functions
8928 * This function applies default settings.
8929 * Because setting the defaults of some settings can enable other settings,
8930 * this function is called recursively until no more new settings are found.
8932 * @param object $node, NULL means complete tree, null by default
8933 * @param bool $unconditional if true overrides all values with defaults, true by default
8934 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8935 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8936 * @return array $settingsoutput The names and values of the changed settings
8938 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8939 $counter = 0;
8941 if (is_null($node)) {
8942 core_plugin_manager::reset_caches();
8943 $node = admin_get_root(true, true);
8944 $counter = count($settingsoutput);
8947 if ($node instanceof admin_category) {
8948 $entries = array_keys($node->children);
8949 foreach ($entries as $entry) {
8950 $settingsoutput = admin_apply_default_settings(
8951 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8955 } else if ($node instanceof admin_settingpage) {
8956 foreach ($node->settings as $setting) {
8957 if (!$unconditional && !is_null($setting->get_setting())) {
8958 // Do not override existing defaults.
8959 continue;
8961 $defaultsetting = $setting->get_defaultsetting();
8962 if (is_null($defaultsetting)) {
8963 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8964 continue;
8967 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8969 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8970 $admindefaultsettings[$settingname] = $settingname;
8971 $settingsoutput[$settingname] = $defaultsetting;
8973 // Set the default for this setting.
8974 $setting->write_setting($defaultsetting);
8975 $setting->write_setting_flags(null);
8976 } else {
8977 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8982 // Call this function recursively until all settings are processed.
8983 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8984 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8986 // Just in case somebody modifies the list of active plugins directly.
8987 core_plugin_manager::reset_caches();
8989 return $settingsoutput;
8993 * Store changed settings, this function updates the errors variable in $ADMIN
8995 * @param object $formdata from form
8996 * @return int number of changed settings
8998 function admin_write_settings($formdata) {
8999 global $CFG, $SITE, $DB;
9001 $olddbsessions = !empty($CFG->dbsessions);
9002 $formdata = (array)$formdata;
9004 $data = array();
9005 foreach ($formdata as $fullname=>$value) {
9006 if (strpos($fullname, 's_') !== 0) {
9007 continue; // not a config value
9009 $data[$fullname] = $value;
9012 $adminroot = admin_get_root();
9013 $settings = admin_find_write_settings($adminroot, $data);
9015 $count = 0;
9016 foreach ($settings as $fullname=>$setting) {
9017 /** @var $setting admin_setting */
9018 $original = $setting->get_setting();
9019 $error = $setting->write_setting($data[$fullname]);
9020 if ($error !== '') {
9021 $adminroot->errors[$fullname] = new stdClass();
9022 $adminroot->errors[$fullname]->data = $data[$fullname];
9023 $adminroot->errors[$fullname]->id = $setting->get_id();
9024 $adminroot->errors[$fullname]->error = $error;
9025 } else {
9026 $setting->write_setting_flags($data);
9028 if ($setting->post_write_settings($original)) {
9029 $count++;
9033 if ($olddbsessions != !empty($CFG->dbsessions)) {
9034 require_logout();
9037 // Now update $SITE - just update the fields, in case other people have a
9038 // a reference to it (e.g. $PAGE, $COURSE).
9039 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
9040 foreach (get_object_vars($newsite) as $field => $value) {
9041 $SITE->$field = $value;
9044 // now reload all settings - some of them might depend on the changed
9045 admin_get_root(true);
9046 return $count;
9050 * Internal recursive function - finds all settings from submitted form
9052 * @param object $node Instance of admin_category, or admin_settingpage
9053 * @param array $data
9054 * @return array
9056 function admin_find_write_settings($node, $data) {
9057 $return = array();
9059 if (empty($data)) {
9060 return $return;
9063 if ($node instanceof admin_category) {
9064 if ($node->check_access()) {
9065 $entries = array_keys($node->children);
9066 foreach ($entries as $entry) {
9067 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
9071 } else if ($node instanceof admin_settingpage) {
9072 if ($node->check_access()) {
9073 foreach ($node->settings as $setting) {
9074 $fullname = $setting->get_full_name();
9075 if (array_key_exists($fullname, $data)) {
9076 $return[$fullname] = $setting;
9083 return $return;
9087 * Internal function - prints the search results
9089 * @param string $query String to search for
9090 * @return string empty or XHTML
9092 function admin_search_settings_html($query) {
9093 global $CFG, $OUTPUT, $PAGE;
9095 if (core_text::strlen($query) < 2) {
9096 return '';
9098 $query = core_text::strtolower($query);
9100 $adminroot = admin_get_root();
9101 $findings = $adminroot->search($query);
9102 $savebutton = false;
9104 $tpldata = (object) [
9105 'actionurl' => $PAGE->url->out(false),
9106 'results' => [],
9107 'sesskey' => sesskey(),
9110 foreach ($findings as $found) {
9111 $page = $found->page;
9112 $settings = $found->settings;
9113 if ($page->is_hidden()) {
9114 // hidden pages are not displayed in search results
9115 continue;
9118 $heading = highlight($query, $page->visiblename);
9119 $headingurl = null;
9120 if ($page instanceof admin_externalpage) {
9121 $headingurl = new moodle_url($page->url);
9122 } else if ($page instanceof admin_settingpage) {
9123 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
9124 } else {
9125 continue;
9128 // Locate the page in the admin root and populate its visiblepath attribute.
9129 $path = array();
9130 $located = $adminroot->locate($page->name, true);
9131 if ($located) {
9132 foreach ($located->visiblepath as $pathitem) {
9133 array_unshift($path, (string) $pathitem);
9137 $sectionsettings = [];
9138 if (!empty($settings)) {
9139 foreach ($settings as $setting) {
9140 if (empty($setting->nosave)) {
9141 $savebutton = true;
9143 $fullname = $setting->get_full_name();
9144 if (array_key_exists($fullname, $adminroot->errors)) {
9145 $data = $adminroot->errors[$fullname]->data;
9146 } else {
9147 $data = $setting->get_setting();
9148 // do not use defaults if settings not available - upgradesettings handles the defaults!
9150 $sectionsettings[] = $setting->output_html($data, $query);
9154 $tpldata->results[] = (object) [
9155 'title' => $heading,
9156 'path' => $path,
9157 'url' => $headingurl->out(false),
9158 'settings' => $sectionsettings
9162 $tpldata->showsave = $savebutton;
9163 $tpldata->hasresults = !empty($tpldata->results);
9165 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
9169 * Internal function - returns arrays of html pages with uninitialised settings
9171 * @param object $node Instance of admin_category or admin_settingpage
9172 * @return array
9174 function admin_output_new_settings_by_page($node) {
9175 global $OUTPUT;
9176 $return = array();
9178 if ($node instanceof admin_category) {
9179 $entries = array_keys($node->children);
9180 foreach ($entries as $entry) {
9181 $return += admin_output_new_settings_by_page($node->children[$entry]);
9184 } else if ($node instanceof admin_settingpage) {
9185 $newsettings = array();
9186 foreach ($node->settings as $setting) {
9187 if (is_null($setting->get_setting())) {
9188 $newsettings[] = $setting;
9191 if (count($newsettings) > 0) {
9192 $adminroot = admin_get_root();
9193 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
9194 $page .= '<fieldset class="adminsettings">'."\n";
9195 foreach ($newsettings as $setting) {
9196 $fullname = $setting->get_full_name();
9197 if (array_key_exists($fullname, $adminroot->errors)) {
9198 $data = $adminroot->errors[$fullname]->data;
9199 } else {
9200 $data = $setting->get_setting();
9201 if (is_null($data)) {
9202 $data = $setting->get_defaultsetting();
9205 $page .= '<div class="clearer"><!-- --></div>'."\n";
9206 $page .= $setting->output_html($data);
9208 $page .= '</fieldset>';
9209 $return[$node->name] = $page;
9213 return $return;
9217 * Format admin settings
9219 * @param object $setting
9220 * @param string $title label element
9221 * @param string $form form fragment, html code - not highlighted automatically
9222 * @param string $description
9223 * @param mixed $label link label to id, true by default or string being the label to connect it to
9224 * @param string $warning warning text
9225 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9226 * @param string $query search query to be highlighted
9227 * @return string XHTML
9229 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9230 global $CFG, $OUTPUT;
9232 $context = (object) [
9233 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9234 'fullname' => $setting->get_full_name(),
9237 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9238 if ($label === true) {
9239 $context->labelfor = $setting->get_id();
9240 } else if ($label === false) {
9241 $context->labelfor = '';
9242 } else {
9243 $context->labelfor = $label;
9246 $form .= $setting->output_setting_flags();
9248 $context->warning = $warning;
9249 $context->override = '';
9250 if (empty($setting->plugin)) {
9251 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
9252 $context->override = get_string('configoverride', 'admin');
9254 } else {
9255 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9256 $context->override = get_string('configoverride', 'admin');
9260 $defaults = array();
9261 if (!is_null($defaultinfo)) {
9262 if ($defaultinfo === '') {
9263 $defaultinfo = get_string('emptysettingvalue', 'admin');
9265 $defaults[] = $defaultinfo;
9268 $context->default = null;
9269 $setting->get_setting_flag_defaults($defaults);
9270 if (!empty($defaults)) {
9271 $defaultinfo = implode(', ', $defaults);
9272 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9273 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9277 $context->error = '';
9278 $adminroot = admin_get_root();
9279 if (array_key_exists($context->fullname, $adminroot->errors)) {
9280 $context->error = $adminroot->errors[$context->fullname]->error;
9283 if ($dependenton = $setting->get_dependent_on()) {
9284 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9287 $context->id = 'admin-' . $setting->name;
9288 $context->title = highlightfast($query, $title);
9289 $context->name = highlightfast($query, $context->name);
9290 $context->description = highlight($query, markdown_to_html($description));
9291 $context->element = $form;
9292 $context->forceltr = $setting->get_force_ltr();
9293 $context->customcontrol = $setting->has_custom_form_control();
9295 return $OUTPUT->render_from_template('core_admin/setting', $context);
9299 * Based on find_new_settings{@link ()} in upgradesettings.php
9300 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9302 * @param object $node Instance of admin_category, or admin_settingpage
9303 * @return boolean true if any settings haven't been initialised, false if they all have
9305 function any_new_admin_settings($node) {
9307 if ($node instanceof admin_category) {
9308 $entries = array_keys($node->children);
9309 foreach ($entries as $entry) {
9310 if (any_new_admin_settings($node->children[$entry])) {
9311 return true;
9315 } else if ($node instanceof admin_settingpage) {
9316 foreach ($node->settings as $setting) {
9317 if ($setting->get_setting() === NULL) {
9318 return true;
9323 return false;
9327 * Given a table and optionally a column name should replaces be done?
9329 * @param string $table name
9330 * @param string $column name
9331 * @return bool success or fail
9333 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9335 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9336 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9337 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9339 // Additional skip tables.
9340 if (!empty($additionalskiptables)) {
9341 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9344 // Don't process these.
9345 if (in_array($table, $skiptables)) {
9346 return false;
9349 // To be safe never replace inside a table that looks related to logging.
9350 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9351 return false;
9354 // Do column based exclusions.
9355 if (!empty($column)) {
9356 // Don't touch anything that looks like a hash.
9357 if (preg_match('/hash$/', $column)) {
9358 return false;
9362 return true;
9366 * Moved from admin/replace.php so that we can use this in cron
9368 * @param string $search string to look for
9369 * @param string $replace string to replace
9370 * @return bool success or fail
9372 function db_replace($search, $replace, $additionalskiptables = '') {
9373 global $DB, $CFG, $OUTPUT;
9375 // Turn off time limits, sometimes upgrades can be slow.
9376 core_php_time_limit::raise();
9378 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9379 return false;
9381 foreach ($tables as $table) {
9383 if (!db_should_replace($table, '', $additionalskiptables)) {
9384 continue;
9387 if ($columns = $DB->get_columns($table)) {
9388 $DB->set_debug(true);
9389 foreach ($columns as $column) {
9390 if (!db_should_replace($table, $column->name)) {
9391 continue;
9393 $DB->replace_all_text($table, $column, $search, $replace);
9395 $DB->set_debug(false);
9399 // delete modinfo caches
9400 rebuild_course_cache(0, true);
9402 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9403 $blocks = core_component::get_plugin_list('block');
9404 foreach ($blocks as $blockname=>$fullblock) {
9405 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9406 continue;
9409 if (!is_readable($fullblock.'/lib.php')) {
9410 continue;
9413 $function = 'block_'.$blockname.'_global_db_replace';
9414 include_once($fullblock.'/lib.php');
9415 if (!function_exists($function)) {
9416 continue;
9419 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9420 $function($search, $replace);
9421 echo $OUTPUT->notification("...finished", 'notifysuccess');
9424 // Trigger an event.
9425 $eventargs = [
9426 'context' => context_system::instance(),
9427 'other' => [
9428 'search' => $search,
9429 'replace' => $replace
9432 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9433 $event->trigger();
9435 purge_all_caches();
9437 return true;
9441 * Manage repository settings
9443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9445 class admin_setting_managerepository extends admin_setting {
9446 /** @var string */
9447 private $baseurl;
9450 * calls parent::__construct with specific arguments
9452 public function __construct() {
9453 global $CFG;
9454 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9455 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9459 * Always returns true, does nothing
9461 * @return true
9463 public function get_setting() {
9464 return true;
9468 * Always returns true does nothing
9470 * @return true
9472 public function get_defaultsetting() {
9473 return true;
9477 * Always returns s_managerepository
9479 * @return string Always return 's_managerepository'
9481 public function get_full_name() {
9482 return 's_managerepository';
9486 * Always returns '' doesn't do anything
9488 public function write_setting($data) {
9489 $url = $this->baseurl . '&amp;new=' . $data;
9490 return '';
9491 // TODO
9492 // Should not use redirect and exit here
9493 // Find a better way to do this.
9494 // redirect($url);
9495 // exit;
9499 * Searches repository plugins for one that matches $query
9501 * @param string $query The string to search for
9502 * @return bool true if found, false if not
9504 public function is_related($query) {
9505 if (parent::is_related($query)) {
9506 return true;
9509 $repositories= core_component::get_plugin_list('repository');
9510 foreach ($repositories as $p => $dir) {
9511 if (strpos($p, $query) !== false) {
9512 return true;
9515 foreach (repository::get_types() as $instance) {
9516 $title = $instance->get_typename();
9517 if (strpos(core_text::strtolower($title), $query) !== false) {
9518 return true;
9521 return false;
9525 * Helper function that generates a moodle_url object
9526 * relevant to the repository
9529 function repository_action_url($repository) {
9530 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9534 * Builds XHTML to display the control
9536 * @param string $data Unused
9537 * @param string $query
9538 * @return string XHTML
9540 public function output_html($data, $query='') {
9541 global $CFG, $USER, $OUTPUT;
9543 // Get strings that are used
9544 $strshow = get_string('on', 'repository');
9545 $strhide = get_string('off', 'repository');
9546 $strdelete = get_string('disabled', 'repository');
9548 $actionchoicesforexisting = array(
9549 'show' => $strshow,
9550 'hide' => $strhide,
9551 'delete' => $strdelete
9554 $actionchoicesfornew = array(
9555 'newon' => $strshow,
9556 'newoff' => $strhide,
9557 'delete' => $strdelete
9560 $return = '';
9561 $return .= $OUTPUT->box_start('generalbox');
9563 // Set strings that are used multiple times
9564 $settingsstr = get_string('settings');
9565 $disablestr = get_string('disable');
9567 // Table to list plug-ins
9568 $table = new html_table();
9569 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9570 $table->align = array('left', 'center', 'center', 'center', 'center');
9571 $table->data = array();
9573 // Get list of used plug-ins
9574 $repositorytypes = repository::get_types();
9575 if (!empty($repositorytypes)) {
9576 // Array to store plugins being used
9577 $alreadyplugins = array();
9578 $totalrepositorytypes = count($repositorytypes);
9579 $updowncount = 1;
9580 foreach ($repositorytypes as $i) {
9581 $settings = '';
9582 $typename = $i->get_typename();
9583 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9584 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9585 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9587 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9588 // Calculate number of instances in order to display them for the Moodle administrator
9589 if (!empty($instanceoptionnames)) {
9590 $params = array();
9591 $params['context'] = array(context_system::instance());
9592 $params['onlyvisible'] = false;
9593 $params['type'] = $typename;
9594 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9595 // site instances
9596 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9597 $params['context'] = array();
9598 $instances = repository::static_function($typename, 'get_instances', $params);
9599 $courseinstances = array();
9600 $userinstances = array();
9602 foreach ($instances as $instance) {
9603 $repocontext = context::instance_by_id($instance->instance->contextid);
9604 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9605 $courseinstances[] = $instance;
9606 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9607 $userinstances[] = $instance;
9610 // course instances
9611 $instancenumber = count($courseinstances);
9612 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9614 // user private instances
9615 $instancenumber = count($userinstances);
9616 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9617 } else {
9618 $admininstancenumbertext = "";
9619 $courseinstancenumbertext = "";
9620 $userinstancenumbertext = "";
9623 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9625 $settings .= $OUTPUT->container_start('mdl-left');
9626 $settings .= '<br/>';
9627 $settings .= $admininstancenumbertext;
9628 $settings .= '<br/>';
9629 $settings .= $courseinstancenumbertext;
9630 $settings .= '<br/>';
9631 $settings .= $userinstancenumbertext;
9632 $settings .= $OUTPUT->container_end();
9634 // Get the current visibility
9635 if ($i->get_visible()) {
9636 $currentaction = 'show';
9637 } else {
9638 $currentaction = 'hide';
9641 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9643 // Display up/down link
9644 $updown = '';
9645 // Should be done with CSS instead.
9646 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9648 if ($updowncount > 1) {
9649 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9650 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9652 else {
9653 $updown .= $spacer;
9655 if ($updowncount < $totalrepositorytypes) {
9656 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9657 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9659 else {
9660 $updown .= $spacer;
9663 $updowncount++;
9665 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9667 if (!in_array($typename, $alreadyplugins)) {
9668 $alreadyplugins[] = $typename;
9673 // Get all the plugins that exist on disk
9674 $plugins = core_component::get_plugin_list('repository');
9675 if (!empty($plugins)) {
9676 foreach ($plugins as $plugin => $dir) {
9677 // Check that it has not already been listed
9678 if (!in_array($plugin, $alreadyplugins)) {
9679 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9680 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9685 $return .= html_writer::table($table);
9686 $return .= $OUTPUT->box_end();
9687 return highlight($query, $return);
9692 * Special checkbox for enable mobile web service
9693 * If enable then we store the service id of the mobile service into config table
9694 * If disable then we unstore the service id from the config table
9696 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9698 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9699 private $restuse;
9702 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9704 * @return boolean
9706 private function is_protocol_cap_allowed() {
9707 global $DB, $CFG;
9709 // If the $this->restuse variable is not set, it needs to be set.
9710 if (empty($this->restuse) and $this->restuse!==false) {
9711 $params = array();
9712 $params['permission'] = CAP_ALLOW;
9713 $params['roleid'] = $CFG->defaultuserroleid;
9714 $params['capability'] = 'webservice/rest:use';
9715 $this->restuse = $DB->record_exists('role_capabilities', $params);
9718 return $this->restuse;
9722 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9723 * @param type $status true to allow, false to not set
9725 private function set_protocol_cap($status) {
9726 global $CFG;
9727 if ($status and !$this->is_protocol_cap_allowed()) {
9728 //need to allow the cap
9729 $permission = CAP_ALLOW;
9730 $assign = true;
9731 } else if (!$status and $this->is_protocol_cap_allowed()){
9732 //need to disallow the cap
9733 $permission = CAP_INHERIT;
9734 $assign = true;
9736 if (!empty($assign)) {
9737 $systemcontext = context_system::instance();
9738 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9743 * Builds XHTML to display the control.
9744 * The main purpose of this overloading is to display a warning when https
9745 * is not supported by the server
9746 * @param string $data Unused
9747 * @param string $query
9748 * @return string XHTML
9750 public function output_html($data, $query='') {
9751 global $OUTPUT;
9752 $html = parent::output_html($data, $query);
9754 if ((string)$data === $this->yes) {
9755 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9756 foreach ($notifications as $notification) {
9757 $message = get_string($notification[0], $notification[1]);
9758 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9762 return $html;
9766 * Retrieves the current setting using the objects name
9768 * @return string
9770 public function get_setting() {
9771 global $CFG;
9773 // First check if is not set.
9774 $result = $this->config_read($this->name);
9775 if (is_null($result)) {
9776 return null;
9779 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9780 // Or if web services aren't enabled this can't be,
9781 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9782 return 0;
9785 require_once($CFG->dirroot . '/webservice/lib.php');
9786 $webservicemanager = new webservice();
9787 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9788 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9789 return $result;
9790 } else {
9791 return 0;
9796 * Save the selected setting
9798 * @param string $data The selected site
9799 * @return string empty string or error message
9801 public function write_setting($data) {
9802 global $DB, $CFG;
9804 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9805 if (empty($CFG->defaultuserroleid)) {
9806 return '';
9809 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9811 require_once($CFG->dirroot . '/webservice/lib.php');
9812 $webservicemanager = new webservice();
9814 $updateprotocol = false;
9815 if ((string)$data === $this->yes) {
9816 //code run when enable mobile web service
9817 //enable web service systeme if necessary
9818 set_config('enablewebservices', true);
9820 //enable mobile service
9821 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9822 $mobileservice->enabled = 1;
9823 $webservicemanager->update_external_service($mobileservice);
9825 // Enable REST server.
9826 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9828 if (!in_array('rest', $activeprotocols)) {
9829 $activeprotocols[] = 'rest';
9830 $updateprotocol = true;
9833 if ($updateprotocol) {
9834 set_config('webserviceprotocols', implode(',', $activeprotocols));
9837 // Allow rest:use capability for authenticated user.
9838 $this->set_protocol_cap(true);
9839 } else {
9840 // Disable the mobile service.
9841 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9842 $mobileservice->enabled = 0;
9843 $webservicemanager->update_external_service($mobileservice);
9846 return (parent::write_setting($data));
9851 * Special class for management of external services
9853 * @author Petr Skoda (skodak)
9855 class admin_setting_manageexternalservices extends admin_setting {
9857 * Calls parent::__construct with specific arguments
9859 public function __construct() {
9860 $this->nosave = true;
9861 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9865 * Always returns true, does nothing
9867 * @return true
9869 public function get_setting() {
9870 return true;
9874 * Always returns true, does nothing
9876 * @return true
9878 public function get_defaultsetting() {
9879 return true;
9883 * Always returns '', does not write anything
9885 * @return string Always returns ''
9887 public function write_setting($data) {
9888 // do not write any setting
9889 return '';
9893 * Checks if $query is one of the available external services
9895 * @param string $query The string to search for
9896 * @return bool Returns true if found, false if not
9898 public function is_related($query) {
9899 global $DB;
9901 if (parent::is_related($query)) {
9902 return true;
9905 $services = $DB->get_records('external_services', array(), 'id, name');
9906 foreach ($services as $service) {
9907 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9908 return true;
9911 return false;
9915 * Builds the XHTML to display the control
9917 * @param string $data Unused
9918 * @param string $query
9919 * @return string
9921 public function output_html($data, $query='') {
9922 global $CFG, $OUTPUT, $DB;
9924 // display strings
9925 $stradministration = get_string('administration');
9926 $stredit = get_string('edit');
9927 $strservice = get_string('externalservice', 'webservice');
9928 $strdelete = get_string('delete');
9929 $strplugin = get_string('plugin', 'admin');
9930 $stradd = get_string('add');
9931 $strfunctions = get_string('functions', 'webservice');
9932 $strusers = get_string('users');
9933 $strserviceusers = get_string('serviceusers', 'webservice');
9935 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9936 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9937 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9939 // built in services
9940 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9941 $return = "";
9942 if (!empty($services)) {
9943 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9947 $table = new html_table();
9948 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9949 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9950 $table->id = 'builtinservices';
9951 $table->attributes['class'] = 'admintable externalservices generaltable';
9952 $table->data = array();
9954 // iterate through auth plugins and add to the display table
9955 foreach ($services as $service) {
9956 $name = $service->name;
9958 // hide/show link
9959 if ($service->enabled) {
9960 $displayname = "<span>$name</span>";
9961 } else {
9962 $displayname = "<span class=\"dimmed_text\">$name</span>";
9965 $plugin = $service->component;
9967 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9969 if ($service->restrictedusers) {
9970 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9971 } else {
9972 $users = get_string('allusers', 'webservice');
9975 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9977 // add a row to the table
9978 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9980 $return .= html_writer::table($table);
9983 // Custom services
9984 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9985 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9987 $table = new html_table();
9988 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9989 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9990 $table->id = 'customservices';
9991 $table->attributes['class'] = 'admintable externalservices generaltable';
9992 $table->data = array();
9994 // iterate through auth plugins and add to the display table
9995 foreach ($services as $service) {
9996 $name = $service->name;
9998 // hide/show link
9999 if ($service->enabled) {
10000 $displayname = "<span>$name</span>";
10001 } else {
10002 $displayname = "<span class=\"dimmed_text\">$name</span>";
10005 // delete link
10006 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
10008 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
10010 if ($service->restrictedusers) {
10011 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
10012 } else {
10013 $users = get_string('allusers', 'webservice');
10016 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
10018 // add a row to the table
10019 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
10021 // add new custom service option
10022 $return .= html_writer::table($table);
10024 $return .= '<br />';
10025 // add a token to the table
10026 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
10028 return highlight($query, $return);
10033 * Special class for overview of external services
10035 * @author Jerome Mouneyrac
10037 class admin_setting_webservicesoverview extends admin_setting {
10040 * Calls parent::__construct with specific arguments
10042 public function __construct() {
10043 $this->nosave = true;
10044 parent::__construct('webservicesoverviewui',
10045 get_string('webservicesoverview', 'webservice'), '', '');
10049 * Always returns true, does nothing
10051 * @return true
10053 public function get_setting() {
10054 return true;
10058 * Always returns true, does nothing
10060 * @return true
10062 public function get_defaultsetting() {
10063 return true;
10067 * Always returns '', does not write anything
10069 * @return string Always returns ''
10071 public function write_setting($data) {
10072 // do not write any setting
10073 return '';
10077 * Builds the XHTML to display the control
10079 * @param string $data Unused
10080 * @param string $query
10081 * @return string
10083 public function output_html($data, $query='') {
10084 global $CFG, $OUTPUT;
10086 $return = "";
10087 $brtag = html_writer::empty_tag('br');
10089 /// One system controlling Moodle with Token
10090 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
10091 $table = new html_table();
10092 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10093 get_string('description'));
10094 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10095 $table->id = 'onesystemcontrol';
10096 $table->attributes['class'] = 'admintable wsoverview generaltable';
10097 $table->data = array();
10099 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
10100 . $brtag . $brtag;
10102 /// 1. Enable Web Services
10103 $row = array();
10104 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10105 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10106 array('href' => $url));
10107 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10108 if ($CFG->enablewebservices) {
10109 $status = get_string('yes');
10111 $row[1] = $status;
10112 $row[2] = get_string('enablewsdescription', 'webservice');
10113 $table->data[] = $row;
10115 /// 2. Enable protocols
10116 $row = array();
10117 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10118 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10119 array('href' => $url));
10120 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10121 //retrieve activated protocol
10122 $active_protocols = empty($CFG->webserviceprotocols) ?
10123 array() : explode(',', $CFG->webserviceprotocols);
10124 if (!empty($active_protocols)) {
10125 $status = "";
10126 foreach ($active_protocols as $protocol) {
10127 $status .= $protocol . $brtag;
10130 $row[1] = $status;
10131 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10132 $table->data[] = $row;
10134 /// 3. Create user account
10135 $row = array();
10136 $url = new moodle_url("/user/editadvanced.php?id=-1");
10137 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
10138 array('href' => $url));
10139 $row[1] = "";
10140 $row[2] = get_string('createuserdescription', 'webservice');
10141 $table->data[] = $row;
10143 /// 4. Add capability to users
10144 $row = array();
10145 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10146 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
10147 array('href' => $url));
10148 $row[1] = "";
10149 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
10150 $table->data[] = $row;
10152 /// 5. Select a web service
10153 $row = array();
10154 $url = new moodle_url("/admin/settings.php?section=externalservices");
10155 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10156 array('href' => $url));
10157 $row[1] = "";
10158 $row[2] = get_string('createservicedescription', 'webservice');
10159 $table->data[] = $row;
10161 /// 6. Add functions
10162 $row = array();
10163 $url = new moodle_url("/admin/settings.php?section=externalservices");
10164 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10165 array('href' => $url));
10166 $row[1] = "";
10167 $row[2] = get_string('addfunctionsdescription', 'webservice');
10168 $table->data[] = $row;
10170 /// 7. Add the specific user
10171 $row = array();
10172 $url = new moodle_url("/admin/settings.php?section=externalservices");
10173 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
10174 array('href' => $url));
10175 $row[1] = "";
10176 $row[2] = get_string('selectspecificuserdescription', 'webservice');
10177 $table->data[] = $row;
10179 /// 8. Create token for the specific user
10180 $row = array();
10181 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
10182 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
10183 array('href' => $url));
10184 $row[1] = "";
10185 $row[2] = get_string('createtokenforuserdescription', 'webservice');
10186 $table->data[] = $row;
10188 /// 9. Enable the documentation
10189 $row = array();
10190 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
10191 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
10192 array('href' => $url));
10193 $status = '<span class="warning">' . get_string('no') . '</span>';
10194 if ($CFG->enablewsdocumentation) {
10195 $status = get_string('yes');
10197 $row[1] = $status;
10198 $row[2] = get_string('enabledocumentationdescription', 'webservice');
10199 $table->data[] = $row;
10201 /// 10. Test the service
10202 $row = array();
10203 $url = new moodle_url("/admin/webservice/testclient.php");
10204 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10205 array('href' => $url));
10206 $row[1] = "";
10207 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10208 $table->data[] = $row;
10210 $return .= html_writer::table($table);
10212 /// Users as clients with token
10213 $return .= $brtag . $brtag . $brtag;
10214 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10215 $table = new html_table();
10216 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10217 get_string('description'));
10218 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10219 $table->id = 'userasclients';
10220 $table->attributes['class'] = 'admintable wsoverview generaltable';
10221 $table->data = array();
10223 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10224 $brtag . $brtag;
10226 /// 1. Enable Web Services
10227 $row = array();
10228 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10229 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10230 array('href' => $url));
10231 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10232 if ($CFG->enablewebservices) {
10233 $status = get_string('yes');
10235 $row[1] = $status;
10236 $row[2] = get_string('enablewsdescription', 'webservice');
10237 $table->data[] = $row;
10239 /// 2. Enable protocols
10240 $row = array();
10241 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10242 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10243 array('href' => $url));
10244 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10245 //retrieve activated protocol
10246 $active_protocols = empty($CFG->webserviceprotocols) ?
10247 array() : explode(',', $CFG->webserviceprotocols);
10248 if (!empty($active_protocols)) {
10249 $status = "";
10250 foreach ($active_protocols as $protocol) {
10251 $status .= $protocol . $brtag;
10254 $row[1] = $status;
10255 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10256 $table->data[] = $row;
10259 /// 3. Select a web service
10260 $row = array();
10261 $url = new moodle_url("/admin/settings.php?section=externalservices");
10262 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10263 array('href' => $url));
10264 $row[1] = "";
10265 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10266 $table->data[] = $row;
10268 /// 4. Add functions
10269 $row = array();
10270 $url = new moodle_url("/admin/settings.php?section=externalservices");
10271 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10272 array('href' => $url));
10273 $row[1] = "";
10274 $row[2] = get_string('addfunctionsdescription', 'webservice');
10275 $table->data[] = $row;
10277 /// 5. Add capability to users
10278 $row = array();
10279 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10280 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10281 array('href' => $url));
10282 $row[1] = "";
10283 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10284 $table->data[] = $row;
10286 /// 6. Test the service
10287 $row = array();
10288 $url = new moodle_url("/admin/webservice/testclient.php");
10289 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10290 array('href' => $url));
10291 $row[1] = "";
10292 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10293 $table->data[] = $row;
10295 $return .= html_writer::table($table);
10297 return highlight($query, $return);
10304 * Special class for web service protocol administration.
10306 * @author Petr Skoda (skodak)
10308 class admin_setting_managewebserviceprotocols extends admin_setting {
10311 * Calls parent::__construct with specific arguments
10313 public function __construct() {
10314 $this->nosave = true;
10315 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10319 * Always returns true, does nothing
10321 * @return true
10323 public function get_setting() {
10324 return true;
10328 * Always returns true, does nothing
10330 * @return true
10332 public function get_defaultsetting() {
10333 return true;
10337 * Always returns '', does not write anything
10339 * @return string Always returns ''
10341 public function write_setting($data) {
10342 // do not write any setting
10343 return '';
10347 * Checks if $query is one of the available webservices
10349 * @param string $query The string to search for
10350 * @return bool Returns true if found, false if not
10352 public function is_related($query) {
10353 if (parent::is_related($query)) {
10354 return true;
10357 $protocols = core_component::get_plugin_list('webservice');
10358 foreach ($protocols as $protocol=>$location) {
10359 if (strpos($protocol, $query) !== false) {
10360 return true;
10362 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10363 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10364 return true;
10367 return false;
10371 * Builds the XHTML to display the control
10373 * @param string $data Unused
10374 * @param string $query
10375 * @return string
10377 public function output_html($data, $query='') {
10378 global $CFG, $OUTPUT;
10380 // display strings
10381 $stradministration = get_string('administration');
10382 $strsettings = get_string('settings');
10383 $stredit = get_string('edit');
10384 $strprotocol = get_string('protocol', 'webservice');
10385 $strenable = get_string('enable');
10386 $strdisable = get_string('disable');
10387 $strversion = get_string('version');
10389 $protocols_available = core_component::get_plugin_list('webservice');
10390 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10391 ksort($protocols_available);
10393 foreach ($activeprotocols as $key => $protocol) {
10394 if (empty($protocols_available[$protocol])) {
10395 unset($activeprotocols[$key]);
10399 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10400 if (in_array('xmlrpc', $activeprotocols)) {
10401 $notify = new \core\output\notification(get_string('xmlrpcwebserviceenabled', 'admin'),
10402 \core\output\notification::NOTIFY_WARNING);
10403 $return .= $OUTPUT->render($notify);
10405 $return .= $OUTPUT->box_start('generalbox webservicesui');
10407 $table = new html_table();
10408 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10409 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10410 $table->id = 'webserviceprotocols';
10411 $table->attributes['class'] = 'admintable generaltable';
10412 $table->data = array();
10414 // iterate through auth plugins and add to the display table
10415 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10416 foreach ($protocols_available as $protocol => $location) {
10417 $name = get_string('pluginname', 'webservice_'.$protocol);
10419 $plugin = new stdClass();
10420 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10421 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10423 $version = isset($plugin->version) ? $plugin->version : '';
10425 // hide/show link
10426 if (in_array($protocol, $activeprotocols)) {
10427 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10428 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10429 $displayname = "<span>$name</span>";
10430 } else {
10431 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10432 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10433 $displayname = "<span class=\"dimmed_text\">$name</span>";
10436 // settings link
10437 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10438 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10439 } else {
10440 $settings = '';
10443 // add a row to the table
10444 $table->data[] = array($displayname, $version, $hideshow, $settings);
10446 $return .= html_writer::table($table);
10447 $return .= get_string('configwebserviceplugins', 'webservice');
10448 $return .= $OUTPUT->box_end();
10450 return highlight($query, $return);
10455 * Colour picker
10457 * @copyright 2010 Sam Hemelryk
10458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10460 class admin_setting_configcolourpicker extends admin_setting {
10463 * Information for previewing the colour
10465 * @var array|null
10467 protected $previewconfig = null;
10470 * Use default when empty.
10472 protected $usedefaultwhenempty = true;
10476 * @param string $name
10477 * @param string $visiblename
10478 * @param string $description
10479 * @param string $defaultsetting
10480 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10482 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10483 $usedefaultwhenempty = true) {
10484 $this->previewconfig = $previewconfig;
10485 $this->usedefaultwhenempty = $usedefaultwhenempty;
10486 parent::__construct($name, $visiblename, $description, $defaultsetting);
10487 $this->set_force_ltr(true);
10491 * Return the setting
10493 * @return mixed returns config if successful else null
10495 public function get_setting() {
10496 return $this->config_read($this->name);
10500 * Saves the setting
10502 * @param string $data
10503 * @return bool
10505 public function write_setting($data) {
10506 $data = $this->validate($data);
10507 if ($data === false) {
10508 return get_string('validateerror', 'admin');
10510 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10514 * Validates the colour that was entered by the user
10516 * @param string $data
10517 * @return string|false
10519 protected function validate($data) {
10521 * List of valid HTML colour names
10523 * @var array
10525 $colornames = array(
10526 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10527 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10528 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10529 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10530 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10531 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10532 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10533 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10534 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10535 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10536 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10537 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10538 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10539 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10540 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10541 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10542 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10543 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10544 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10545 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10546 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10547 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10548 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10549 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10550 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10551 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10552 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10553 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10554 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10555 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10556 'whitesmoke', 'yellow', 'yellowgreen'
10559 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10560 if (strpos($data, '#')!==0) {
10561 $data = '#'.$data;
10563 return $data;
10564 } else if (in_array(strtolower($data), $colornames)) {
10565 return $data;
10566 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10567 return $data;
10568 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10569 return $data;
10570 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10571 return $data;
10572 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10573 return $data;
10574 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10575 return $data;
10576 } else if (empty($data)) {
10577 if ($this->usedefaultwhenempty){
10578 return $this->defaultsetting;
10579 } else {
10580 return '';
10582 } else {
10583 return false;
10588 * Generates the HTML for the setting
10590 * @global moodle_page $PAGE
10591 * @global core_renderer $OUTPUT
10592 * @param string $data
10593 * @param string $query
10595 public function output_html($data, $query = '') {
10596 global $PAGE, $OUTPUT;
10598 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10599 $context = (object) [
10600 'id' => $this->get_id(),
10601 'name' => $this->get_full_name(),
10602 'value' => $data,
10603 'icon' => $icon->export_for_template($OUTPUT),
10604 'haspreviewconfig' => !empty($this->previewconfig),
10605 'forceltr' => $this->get_force_ltr(),
10606 'readonly' => $this->is_readonly(),
10609 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10610 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10612 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10613 $this->get_defaultsetting(), $query);
10620 * Class used for uploading of one file into file storage,
10621 * the file name is stored in config table.
10623 * Please note you need to implement your own '_pluginfile' callback function,
10624 * this setting only stores the file, it does not deal with file serving.
10626 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10629 class admin_setting_configstoredfile extends admin_setting {
10630 /** @var array file area options - should be one file only */
10631 protected $options;
10632 /** @var string name of the file area */
10633 protected $filearea;
10634 /** @var int intemid */
10635 protected $itemid;
10636 /** @var string used for detection of changes */
10637 protected $oldhashes;
10640 * Create new stored file setting.
10642 * @param string $name low level setting name
10643 * @param string $visiblename human readable setting name
10644 * @param string $description description of setting
10645 * @param mixed $filearea file area for file storage
10646 * @param int $itemid itemid for file storage
10647 * @param array $options file area options
10649 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10650 parent::__construct($name, $visiblename, $description, '');
10651 $this->filearea = $filearea;
10652 $this->itemid = $itemid;
10653 $this->options = (array)$options;
10654 $this->customcontrol = true;
10658 * Applies defaults and returns all options.
10659 * @return array
10661 protected function get_options() {
10662 global $CFG;
10664 require_once("$CFG->libdir/filelib.php");
10665 require_once("$CFG->dirroot/repository/lib.php");
10666 $defaults = array(
10667 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10668 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10669 'context' => context_system::instance());
10670 foreach($this->options as $k => $v) {
10671 $defaults[$k] = $v;
10674 return $defaults;
10677 public function get_setting() {
10678 return $this->config_read($this->name);
10681 public function write_setting($data) {
10682 global $USER;
10684 // Let's not deal with validation here, this is for admins only.
10685 $current = $this->get_setting();
10686 if (empty($data) && $current === null) {
10687 // This will be the case when applying default settings (installation).
10688 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10689 } else if (!is_number($data)) {
10690 // Draft item id is expected here!
10691 return get_string('errorsetting', 'admin');
10694 $options = $this->get_options();
10695 $fs = get_file_storage();
10696 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10698 $this->oldhashes = null;
10699 if ($current) {
10700 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10701 if ($file = $fs->get_file_by_hash($hash)) {
10702 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10704 unset($file);
10707 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10708 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10709 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10710 // with an error because the draft area does not exist, as he did not use it.
10711 $usercontext = context_user::instance($USER->id);
10712 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10713 return get_string('errorsetting', 'admin');
10717 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10718 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10720 $filepath = '';
10721 if ($files) {
10722 /** @var stored_file $file */
10723 $file = reset($files);
10724 $filepath = $file->get_filepath().$file->get_filename();
10727 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10730 public function post_write_settings($original) {
10731 $options = $this->get_options();
10732 $fs = get_file_storage();
10733 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10735 $current = $this->get_setting();
10736 $newhashes = null;
10737 if ($current) {
10738 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10739 if ($file = $fs->get_file_by_hash($hash)) {
10740 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10742 unset($file);
10745 if ($this->oldhashes === $newhashes) {
10746 $this->oldhashes = null;
10747 return false;
10749 $this->oldhashes = null;
10751 $callbackfunction = $this->updatedcallback;
10752 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10753 $callbackfunction($this->get_full_name());
10755 return true;
10758 public function output_html($data, $query = '') {
10759 global $PAGE, $CFG;
10761 $options = $this->get_options();
10762 $id = $this->get_id();
10763 $elname = $this->get_full_name();
10764 $draftitemid = file_get_submitted_draft_itemid($elname);
10765 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10766 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10768 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10769 require_once("$CFG->dirroot/lib/form/filemanager.php");
10771 $fmoptions = new stdClass();
10772 $fmoptions->mainfile = $options['mainfile'];
10773 $fmoptions->maxbytes = $options['maxbytes'];
10774 $fmoptions->maxfiles = $options['maxfiles'];
10775 $fmoptions->client_id = uniqid();
10776 $fmoptions->itemid = $draftitemid;
10777 $fmoptions->subdirs = $options['subdirs'];
10778 $fmoptions->target = $id;
10779 $fmoptions->accepted_types = $options['accepted_types'];
10780 $fmoptions->return_types = $options['return_types'];
10781 $fmoptions->context = $options['context'];
10782 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10784 $fm = new form_filemanager($fmoptions);
10785 $output = $PAGE->get_renderer('core', 'files');
10786 $html = $output->render($fm);
10788 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
10789 $html .= '<input value="" id="'.$id.'" type="hidden" />';
10791 return format_admin_setting($this, $this->visiblename,
10792 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
10793 $this->description, true, '', '', $query);
10799 * Administration interface for user specified regular expressions for device detection.
10801 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10803 class admin_setting_devicedetectregex extends admin_setting {
10806 * Calls parent::__construct with specific args
10808 * @param string $name
10809 * @param string $visiblename
10810 * @param string $description
10811 * @param mixed $defaultsetting
10813 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10814 global $CFG;
10815 parent::__construct($name, $visiblename, $description, $defaultsetting);
10819 * Return the current setting(s)
10821 * @return array Current settings array
10823 public function get_setting() {
10824 global $CFG;
10826 $config = $this->config_read($this->name);
10827 if (is_null($config)) {
10828 return null;
10831 return $this->prepare_form_data($config);
10835 * Save selected settings
10837 * @param array $data Array of settings to save
10838 * @return bool
10840 public function write_setting($data) {
10841 if (empty($data)) {
10842 $data = array();
10845 if ($this->config_write($this->name, $this->process_form_data($data))) {
10846 return ''; // success
10847 } else {
10848 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10853 * Return XHTML field(s) for regexes
10855 * @param array $data Array of options to set in HTML
10856 * @return string XHTML string for the fields and wrapping div(s)
10858 public function output_html($data, $query='') {
10859 global $OUTPUT;
10861 $context = (object) [
10862 'expressions' => [],
10863 'name' => $this->get_full_name()
10866 if (empty($data)) {
10867 $looplimit = 1;
10868 } else {
10869 $looplimit = (count($data)/2)+1;
10872 for ($i=0; $i<$looplimit; $i++) {
10874 $expressionname = 'expression'.$i;
10876 if (!empty($data[$expressionname])){
10877 $expression = $data[$expressionname];
10878 } else {
10879 $expression = '';
10882 $valuename = 'value'.$i;
10884 if (!empty($data[$valuename])){
10885 $value = $data[$valuename];
10886 } else {
10887 $value= '';
10890 $context->expressions[] = [
10891 'index' => $i,
10892 'expression' => $expression,
10893 'value' => $value
10897 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10899 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10903 * Converts the string of regexes
10905 * @see self::process_form_data()
10906 * @param $regexes string of regexes
10907 * @return array of form fields and their values
10909 protected function prepare_form_data($regexes) {
10911 $regexes = json_decode($regexes);
10913 $form = array();
10915 $i = 0;
10917 foreach ($regexes as $value => $regex) {
10918 $expressionname = 'expression'.$i;
10919 $valuename = 'value'.$i;
10921 $form[$expressionname] = $regex;
10922 $form[$valuename] = $value;
10923 $i++;
10926 return $form;
10930 * Converts the data from admin settings form into a string of regexes
10932 * @see self::prepare_form_data()
10933 * @param array $data array of admin form fields and values
10934 * @return false|string of regexes
10936 protected function process_form_data(array $form) {
10938 $count = count($form); // number of form field values
10940 if ($count % 2) {
10941 // we must get five fields per expression
10942 return false;
10945 $regexes = array();
10946 for ($i = 0; $i < $count / 2; $i++) {
10947 $expressionname = "expression".$i;
10948 $valuename = "value".$i;
10950 $expression = trim($form['expression'.$i]);
10951 $value = trim($form['value'.$i]);
10953 if (empty($expression)){
10954 continue;
10957 $regexes[$value] = $expression;
10960 $regexes = json_encode($regexes);
10962 return $regexes;
10968 * Multiselect for current modules
10970 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10972 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10973 private $excludesystem;
10976 * Calls parent::__construct - note array $choices is not required
10978 * @param string $name setting name
10979 * @param string $visiblename localised setting name
10980 * @param string $description setting description
10981 * @param array $defaultsetting a plain array of default module ids
10982 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10984 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10985 $excludesystem = true) {
10986 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10987 $this->excludesystem = $excludesystem;
10991 * Loads an array of current module choices
10993 * @return bool always return true
10995 public function load_choices() {
10996 if (is_array($this->choices)) {
10997 return true;
10999 $this->choices = array();
11001 global $CFG, $DB;
11002 $records = $DB->get_records('modules', array('visible'=>1), 'name');
11003 foreach ($records as $record) {
11004 // Exclude modules if the code doesn't exist
11005 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
11006 // Also exclude system modules (if specified)
11007 if (!($this->excludesystem &&
11008 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
11009 MOD_ARCHETYPE_SYSTEM)) {
11010 $this->choices[$record->id] = $record->name;
11014 return true;
11019 * Admin setting to show if a php extension is enabled or not.
11021 * @copyright 2013 Damyon Wiese
11022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11024 class admin_setting_php_extension_enabled extends admin_setting {
11026 /** @var string The name of the extension to check for */
11027 private $extension;
11030 * Calls parent::__construct with specific arguments
11032 public function __construct($name, $visiblename, $description, $extension) {
11033 $this->extension = $extension;
11034 $this->nosave = true;
11035 parent::__construct($name, $visiblename, $description, '');
11039 * Always returns true, does nothing
11041 * @return true
11043 public function get_setting() {
11044 return true;
11048 * Always returns true, does nothing
11050 * @return true
11052 public function get_defaultsetting() {
11053 return true;
11057 * Always returns '', does not write anything
11059 * @return string Always returns ''
11061 public function write_setting($data) {
11062 // Do not write any setting.
11063 return '';
11067 * Outputs the html for this setting.
11068 * @return string Returns an XHTML string
11070 public function output_html($data, $query='') {
11071 global $OUTPUT;
11073 $o = '';
11074 if (!extension_loaded($this->extension)) {
11075 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
11077 $o .= format_admin_setting($this, $this->visiblename, $warning);
11079 return $o;
11084 * Server timezone setting.
11086 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11088 * @author Petr Skoda <petr.skoda@totaralms.com>
11090 class admin_setting_servertimezone extends admin_setting_configselect {
11092 * Constructor.
11094 public function __construct() {
11095 $default = core_date::get_default_php_timezone();
11096 if ($default === 'UTC') {
11097 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
11098 $default = 'Europe/London';
11101 parent::__construct('timezone',
11102 new lang_string('timezone', 'core_admin'),
11103 new lang_string('configtimezone', 'core_admin'), $default, null);
11107 * Lazy load timezone options.
11108 * @return bool true if loaded, false if error
11110 public function load_choices() {
11111 global $CFG;
11112 if (is_array($this->choices)) {
11113 return true;
11116 $current = isset($CFG->timezone) ? $CFG->timezone : null;
11117 $this->choices = core_date::get_list_of_timezones($current, false);
11118 if ($current == 99) {
11119 // Do not show 99 unless it is current value, we want to get rid of it over time.
11120 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
11121 core_date::get_default_php_timezone());
11124 return true;
11129 * Forced user timezone setting.
11131 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11132 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11133 * @author Petr Skoda <petr.skoda@totaralms.com>
11135 class admin_setting_forcetimezone extends admin_setting_configselect {
11137 * Constructor.
11139 public function __construct() {
11140 parent::__construct('forcetimezone',
11141 new lang_string('forcetimezone', 'core_admin'),
11142 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
11146 * Lazy load timezone options.
11147 * @return bool true if loaded, false if error
11149 public function load_choices() {
11150 global $CFG;
11151 if (is_array($this->choices)) {
11152 return true;
11155 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
11156 $this->choices = core_date::get_list_of_timezones($current, true);
11157 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
11159 return true;
11165 * Search setup steps info.
11167 * @package core
11168 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
11169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11171 class admin_setting_searchsetupinfo extends admin_setting {
11174 * Calls parent::__construct with specific arguments
11176 public function __construct() {
11177 $this->nosave = true;
11178 parent::__construct('searchsetupinfo', '', '', '');
11182 * Always returns true, does nothing
11184 * @return true
11186 public function get_setting() {
11187 return true;
11191 * Always returns true, does nothing
11193 * @return true
11195 public function get_defaultsetting() {
11196 return true;
11200 * Always returns '', does not write anything
11202 * @param array $data
11203 * @return string Always returns ''
11205 public function write_setting($data) {
11206 // Do not write any setting.
11207 return '';
11211 * Builds the HTML to display the control
11213 * @param string $data Unused
11214 * @param string $query
11215 * @return string
11217 public function output_html($data, $query='') {
11218 global $CFG, $OUTPUT, $ADMIN;
11220 $return = '';
11221 $brtag = html_writer::empty_tag('br');
11223 $searchareas = \core_search\manager::get_search_areas_list();
11224 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11225 $anyindexed = false;
11226 foreach ($searchareas as $areaid => $searcharea) {
11227 list($componentname, $varname) = $searcharea->get_config_var_name();
11228 if (get_config($componentname, $varname . '_indexingstart')) {
11229 $anyindexed = true;
11230 break;
11234 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11236 $table = new html_table();
11237 $table->head = array(get_string('step', 'search'), get_string('status'));
11238 $table->colclasses = array('leftalign step', 'leftalign status');
11239 $table->id = 'searchsetup';
11240 $table->attributes['class'] = 'admintable generaltable';
11241 $table->data = array();
11243 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11245 // Select a search engine.
11246 $row = array();
11247 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11248 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11249 array('href' => $url));
11251 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11252 if (!empty($CFG->searchengine)) {
11253 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11254 array('class' => 'badge badge-success'));
11257 $row[1] = $status;
11258 $table->data[] = $row;
11260 // Available areas.
11261 $row = array();
11262 $url = new moodle_url('/admin/searchareas.php');
11263 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11264 array('href' => $url));
11266 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11267 if ($anyenabled) {
11268 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11271 $row[1] = $status;
11272 $table->data[] = $row;
11274 // Setup search engine.
11275 $row = array();
11276 if (empty($CFG->searchengine)) {
11277 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11278 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11279 } else {
11280 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11281 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11282 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11283 } else {
11284 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11287 // Check the engine status.
11288 $searchengine = \core_search\manager::search_engine_instance();
11289 try {
11290 $serverstatus = $searchengine->is_server_ready();
11291 } catch (\moodle_exception $e) {
11292 $serverstatus = $e->getMessage();
11294 if ($serverstatus === true) {
11295 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11296 } else {
11297 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11299 $row[1] = $status;
11301 $table->data[] = $row;
11303 // Indexed data.
11304 $row = array();
11305 $url = new moodle_url('/admin/searchareas.php');
11306 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11307 if ($anyindexed) {
11308 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11309 } else {
11310 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11312 $row[1] = $status;
11313 $table->data[] = $row;
11315 // Enable global search.
11316 $row = array();
11317 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11318 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11319 array('href' => $url));
11320 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11321 if (\core_search\manager::is_global_search_enabled()) {
11322 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11324 $row[1] = $status;
11325 $table->data[] = $row;
11327 // Replace front page search.
11328 $row = array();
11329 $url = new moodle_url("/admin/search.php?query=searchincludeallcourses");
11330 $row[0] = '6. ' . html_writer::tag('a', get_string('replacefrontsearch', 'admin'),
11331 array('href' => $url));
11332 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11333 if (\core_search\manager::can_replace_course_search()) {
11334 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11336 $row[1] = $status;
11337 $table->data[] = $row;
11339 $return .= html_writer::table($table);
11341 return highlight($query, $return);
11347 * Used to validate the contents of SCSS code and ensuring they are parsable.
11349 * It does not attempt to detect undefined SCSS variables because it is designed
11350 * to be used without knowledge of other config/scss included.
11352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11353 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11355 class admin_setting_scsscode extends admin_setting_configtextarea {
11358 * Validate the contents of the SCSS to ensure its parsable. Does not
11359 * attempt to detect undefined scss variables.
11361 * @param string $data The scss code from text field.
11362 * @return mixed bool true for success or string:error on failure.
11364 public function validate($data) {
11365 if (empty($data)) {
11366 return true;
11369 $scss = new core_scss();
11370 try {
11371 $scss->compile($data);
11372 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11373 return get_string('scssinvalid', 'admin', $e->getMessage());
11374 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11375 // Silently ignore this - it could be a scss variable defined from somewhere
11376 // else which we are not examining here.
11377 return true;
11380 return true;
11386 * Administration setting to define a list of file types.
11388 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11389 * @copyright 2017 David Mudrák <david@moodle.com>
11390 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11392 class admin_setting_filetypes extends admin_setting_configtext {
11394 /** @var array Allow selection from these file types only. */
11395 protected $onlytypes = [];
11397 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11398 protected $allowall = true;
11400 /** @var core_form\filetypes_util instance to use as a helper. */
11401 protected $util = null;
11404 * Constructor.
11406 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11407 * @param string $visiblename Localised label of the setting
11408 * @param string $description Localised description of the setting
11409 * @param string $defaultsetting Default setting value.
11410 * @param array $options Setting widget options, an array with optional keys:
11411 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11412 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11414 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11416 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11418 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11419 $this->onlytypes = $options['onlytypes'];
11422 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11423 $this->allowall = (bool)$options['allowall'];
11426 $this->util = new \core_form\filetypes_util();
11430 * Normalize the user's input and write it to the database as comma separated list.
11432 * Comma separated list as a text representation of the array was chosen to
11433 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11435 * @param string $data Value submitted by the admin.
11436 * @return string Epty string if all good, error message otherwise.
11438 public function write_setting($data) {
11439 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11443 * Validate data before storage
11445 * @param string $data The setting values provided by the admin
11446 * @return bool|string True if ok, the string if error found
11448 public function validate($data) {
11449 $parentcheck = parent::validate($data);
11450 if ($parentcheck !== true) {
11451 return $parentcheck;
11454 // Check for unknown file types.
11455 if ($unknown = $this->util->get_unknown_file_types($data)) {
11456 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11459 // Check for disallowed file types.
11460 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11461 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11464 return true;
11468 * Return an HTML string for the setting element.
11470 * @param string $data The current setting value
11471 * @param string $query Admin search query to be highlighted
11472 * @return string HTML to be displayed
11474 public function output_html($data, $query='') {
11475 global $OUTPUT, $PAGE;
11477 $default = $this->get_defaultsetting();
11478 $context = (object) [
11479 'id' => $this->get_id(),
11480 'name' => $this->get_full_name(),
11481 'value' => $data,
11482 'descriptions' => $this->util->describe_file_types($data),
11484 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11486 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11487 $this->get_id(),
11488 $this->visiblename->out(),
11489 $this->onlytypes,
11490 $this->allowall,
11493 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11497 * Should the values be always displayed in LTR mode?
11499 * We always return true here because these values are not RTL compatible.
11501 * @return bool True because these values are not RTL compatible.
11503 public function get_force_ltr() {
11504 return true;
11509 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11512 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11514 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11517 * Constructor.
11519 * @param string $name
11520 * @param string $visiblename
11521 * @param string $description
11522 * @param mixed $defaultsetting string or array
11523 * @param mixed $paramtype
11524 * @param string $cols
11525 * @param string $rows
11527 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11528 $cols = '60', $rows = '8') {
11529 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11530 // Pre-set force LTR to false.
11531 $this->set_force_ltr(false);
11535 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11537 * @param string $data The age of digital consent map from text field.
11538 * @return mixed bool true for success or string:error on failure.
11540 public function validate($data) {
11541 if (empty($data)) {
11542 return true;
11545 try {
11546 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11547 } catch (\moodle_exception $e) {
11548 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11551 return true;
11556 * Selection of plugins that can work as site policy handlers
11558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11559 * @copyright 2018 Marina Glancy
11561 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11564 * Constructor
11565 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11566 * for ones in config_plugins.
11567 * @param string $visiblename localised
11568 * @param string $description long localised info
11569 * @param string $defaultsetting
11571 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11572 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11576 * Lazy-load the available choices for the select box
11578 public function load_choices() {
11579 if (during_initial_install()) {
11580 return false;
11582 if (is_array($this->choices)) {
11583 return true;
11586 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11587 $manager = new \core_privacy\local\sitepolicy\manager();
11588 $plugins = $manager->get_all_handlers();
11589 foreach ($plugins as $pname => $unused) {
11590 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11591 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11594 return true;
11599 * Used to validate theme presets code and ensuring they compile well.
11601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11602 * @copyright 2019 Bas Brands <bas@moodle.com>
11604 class admin_setting_configthemepreset extends admin_setting_configselect {
11606 /** @var string The name of the theme to check for */
11607 private $themename;
11610 * Constructor
11611 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11612 * or 'myplugin/mysetting' for ones in config_plugins.
11613 * @param string $visiblename localised
11614 * @param string $description long localised info
11615 * @param string|int $defaultsetting
11616 * @param array $choices array of $value=>$label for each selection
11617 * @param string $themename name of theme to check presets for.
11619 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11620 $this->themename = $themename;
11621 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11625 * Write settings if validated
11627 * @param string $data
11628 * @return string
11630 public function write_setting($data) {
11631 $validated = $this->validate($data);
11632 if ($validated !== true) {
11633 return $validated;
11635 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11639 * Validate the preset file to ensure its parsable.
11641 * @param string $data The preset file chosen.
11642 * @return mixed bool true for success or string:error on failure.
11644 public function validate($data) {
11646 if (in_array($data, ['default.scss', 'plain.scss'])) {
11647 return true;
11650 $fs = get_file_storage();
11651 $theme = theme_config::load($this->themename);
11652 $context = context_system::instance();
11654 // If the preset has not changed there is no need to validate it.
11655 if ($theme->settings->preset == $data) {
11656 return true;
11659 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11660 // This operation uses a lot of resources.
11661 raise_memory_limit(MEMORY_EXTRA);
11662 core_php_time_limit::raise(300);
11664 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11665 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11667 $compiler = new core_scss();
11668 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11669 $compiler->append_raw_scss($presetfile->get_content());
11670 if ($scssproperties = $theme->get_scss_property()) {
11671 $compiler->setImportPaths($scssproperties[0]);
11673 $compiler->append_raw_scss($theme->get_extra_scss_code());
11675 try {
11676 $compiler->to_css();
11677 } catch (Exception $e) {
11678 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11681 // Try to save memory.
11682 $compiler = null;
11683 unset($compiler);
11686 return true;
11691 * Selection of plugins that can work as H5P libraries handlers
11693 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11694 * @copyright 2020 Sara Arjona <sara@moodle.com>
11696 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11699 * Constructor
11700 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11701 * for ones in config_plugins.
11702 * @param string $visiblename localised
11703 * @param string $description long localised info
11704 * @param string $defaultsetting
11706 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11707 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11711 * Lazy-load the available choices for the select box
11713 public function load_choices() {
11714 if (during_initial_install()) {
11715 return false;
11717 if (is_array($this->choices)) {
11718 return true;
11721 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11722 foreach ($this->choices as $name => $class) {
11723 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11724 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11727 return true;