MDL-65799 enrol: Final deprecations
[moodle.git] / lib / adminlib.php
blob9f13db277ca2c515a0f3d5a5037e91de9a838aa5
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.'/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 * Special text editor for site description.
4844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4846 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4849 * Calls parent::__construct with specific arguments
4851 public function __construct() {
4852 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4853 PARAM_RAW, 60, 15);
4857 * Return the current setting
4858 * @return string The current setting
4860 public function get_setting() {
4861 $site = course_get_format(get_site())->get_course();
4862 return $site->{$this->name};
4866 * Save the new setting
4868 * @param string $data The new value to save
4869 * @return string empty or error message
4871 public function write_setting($data) {
4872 global $DB, $SITE, $COURSE;
4873 $record = new stdClass();
4874 $record->id = $SITE->id;
4875 $record->{$this->name} = $data;
4876 $record->timemodified = time();
4878 course_get_format($SITE)->update_course_format_options($record);
4879 $DB->update_record('course', $record);
4881 // Reset caches.
4882 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4883 if ($SITE->id == $COURSE->id) {
4884 $COURSE = $SITE;
4886 core_courseformat\base::reset_course_cache($SITE->id);
4888 return '';
4894 * Administration interface for emoticon_manager settings.
4896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4898 class admin_setting_emoticons extends admin_setting {
4901 * Calls parent::__construct with specific args
4903 public function __construct() {
4904 global $CFG;
4906 $manager = get_emoticon_manager();
4907 $defaults = $this->prepare_form_data($manager->default_emoticons());
4908 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4912 * Return the current setting(s)
4914 * @return array Current settings array
4916 public function get_setting() {
4917 global $CFG;
4919 $manager = get_emoticon_manager();
4921 $config = $this->config_read($this->name);
4922 if (is_null($config)) {
4923 return null;
4926 $config = $manager->decode_stored_config($config);
4927 if (is_null($config)) {
4928 return null;
4931 return $this->prepare_form_data($config);
4935 * Save selected settings
4937 * @param array $data Array of settings to save
4938 * @return bool
4940 public function write_setting($data) {
4942 $manager = get_emoticon_manager();
4943 $emoticons = $this->process_form_data($data);
4945 if ($emoticons === false) {
4946 return false;
4949 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4950 return ''; // success
4951 } else {
4952 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4957 * Return XHTML field(s) for options
4959 * @param array $data Array of options to set in HTML
4960 * @return string XHTML string for the fields and wrapping div(s)
4962 public function output_html($data, $query='') {
4963 global $OUTPUT;
4965 $context = (object) [
4966 'name' => $this->get_full_name(),
4967 'emoticons' => [],
4968 'forceltr' => true,
4971 $i = 0;
4972 foreach ($data as $field => $value) {
4974 // When $i == 0: text.
4975 // When $i == 1: imagename.
4976 // When $i == 2: imagecomponent.
4977 // When $i == 3: altidentifier.
4978 // When $i == 4: altcomponent.
4979 $fields[$i] = (object) [
4980 'field' => $field,
4981 'value' => $value,
4982 'index' => $i
4984 $i++;
4986 if ($i > 4) {
4987 $icon = null;
4988 if (!empty($fields[1]->value)) {
4989 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4990 $alt = get_string($fields[3]->value, $fields[4]->value);
4991 } else {
4992 $alt = $fields[0]->value;
4994 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4996 $context->emoticons[] = [
4997 'fields' => $fields,
4998 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
5000 $fields = [];
5001 $i = 0;
5005 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
5006 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
5007 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5011 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
5013 * @see self::process_form_data()
5014 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
5015 * @return array of form fields and their values
5017 protected function prepare_form_data(array $emoticons) {
5019 $form = array();
5020 $i = 0;
5021 foreach ($emoticons as $emoticon) {
5022 $form['text'.$i] = $emoticon->text;
5023 $form['imagename'.$i] = $emoticon->imagename;
5024 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
5025 $form['altidentifier'.$i] = $emoticon->altidentifier;
5026 $form['altcomponent'.$i] = $emoticon->altcomponent;
5027 $i++;
5029 // add one more blank field set for new object
5030 $form['text'.$i] = '';
5031 $form['imagename'.$i] = '';
5032 $form['imagecomponent'.$i] = '';
5033 $form['altidentifier'.$i] = '';
5034 $form['altcomponent'.$i] = '';
5036 return $form;
5040 * Converts the data from admin settings form into an array of emoticon objects
5042 * @see self::prepare_form_data()
5043 * @param array $data array of admin form fields and values
5044 * @return false|array of emoticon objects
5046 protected function process_form_data(array $form) {
5048 $count = count($form); // number of form field values
5050 if ($count % 5) {
5051 // we must get five fields per emoticon object
5052 return false;
5055 $emoticons = array();
5056 for ($i = 0; $i < $count / 5; $i++) {
5057 $emoticon = new stdClass();
5058 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
5059 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
5060 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
5061 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
5062 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
5064 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
5065 // prevent from breaking http://url.addresses by accident
5066 $emoticon->text = '';
5069 if (strlen($emoticon->text) < 2) {
5070 // do not allow single character emoticons
5071 $emoticon->text = '';
5074 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
5075 // emoticon text must contain some non-alphanumeric character to prevent
5076 // breaking HTML tags
5077 $emoticon->text = '';
5080 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
5081 $emoticons[] = $emoticon;
5084 return $emoticons;
5091 * Special setting for limiting of the list of available languages.
5093 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5095 class admin_setting_langlist extends admin_setting_configtext {
5097 * Calls parent::__construct with specific arguments
5099 public function __construct() {
5100 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
5104 * Validate that each language identifier exists on the site
5106 * @param string $data
5107 * @return bool|string True if validation successful, otherwise error string
5109 public function validate($data) {
5110 $parentcheck = parent::validate($data);
5111 if ($parentcheck !== true) {
5112 return $parentcheck;
5115 if ($data === '') {
5116 return true;
5119 // Normalize language identifiers.
5120 $langcodes = array_map('trim', explode(',', $data));
5121 foreach ($langcodes as $langcode) {
5122 // If the langcode contains optional alias, split it out.
5123 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5125 if (!get_string_manager()->translation_exists($langcode)) {
5126 return get_string('invalidlanguagecode', 'error', $langcode);
5130 return true;
5134 * Save the new setting
5136 * @param string $data The new setting
5137 * @return bool
5139 public function write_setting($data) {
5140 $return = parent::write_setting($data);
5141 get_string_manager()->reset_caches();
5142 return $return;
5148 * Allows to specify comma separated list of known country codes.
5150 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5151 * known codes.
5153 * @package core
5154 * @category admin
5155 * @copyright 2020 David Mudrák <david@moodle.com>
5156 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5158 class admin_setting_countrycodes extends admin_setting_configtext {
5161 * Construct the instance of the setting.
5163 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5164 * @param lang_string|string $visiblename Language string with the field label text.
5165 * @param lang_string|string $description Language string with the field description text.
5166 * @param string $defaultsetting Default value of the setting.
5167 * @param int $size Input text field size.
5169 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5170 parent::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5174 * Validate the setting value before storing it.
5176 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5177 * a comma separated list of such words.
5179 * @param string $data Value inserted into the setting field.
5180 * @return bool|string True if the value is OK, error string otherwise.
5182 public function validate($data) {
5184 $parentcheck = parent::validate($data);
5186 if ($parentcheck !== true) {
5187 return $parentcheck;
5190 if ($data === '') {
5191 return true;
5194 $allcountries = get_string_manager()->get_list_of_countries(true);
5196 foreach (explode(',', $data) as $code) {
5197 if (!isset($allcountries[$code])) {
5198 return get_string('invalidcountrycode', 'core_error', $code);
5202 return true;
5208 * Selection of one of the recognised countries using the list
5209 * returned by {@link get_list_of_countries()}.
5211 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5213 class admin_settings_country_select extends admin_setting_configselect {
5214 protected $includeall;
5215 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5216 $this->includeall = $includeall;
5217 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
5221 * Lazy-load the available choices for the select box
5223 public function load_choices() {
5224 global $CFG;
5225 if (is_array($this->choices)) {
5226 return true;
5228 $this->choices = array_merge(
5229 array('0' => get_string('choosedots')),
5230 get_string_manager()->get_list_of_countries($this->includeall));
5231 return true;
5237 * admin_setting_configselect for the default number of sections in a course,
5238 * simply so we can lazy-load the choices.
5240 * @copyright 2011 The Open University
5241 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5243 class admin_settings_num_course_sections extends admin_setting_configselect {
5244 public function __construct($name, $visiblename, $description, $defaultsetting) {
5245 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
5248 /** Lazy-load the available choices for the select box */
5249 public function load_choices() {
5250 $max = get_config('moodlecourse', 'maxsections');
5251 if (!isset($max) || !is_numeric($max)) {
5252 $max = 52;
5254 for ($i = 0; $i <= $max; $i++) {
5255 $this->choices[$i] = "$i";
5257 return true;
5263 * Course category selection
5265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5267 class admin_settings_coursecat_select extends admin_setting_configselect_autocomplete {
5269 * Calls parent::__construct with specific arguments
5271 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5272 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5276 * Load the available choices for the select box
5278 * @return bool
5280 public function load_choices() {
5281 if (is_array($this->choices)) {
5282 return true;
5284 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
5285 return true;
5291 * Special control for selecting days to backup
5293 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5295 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
5297 * Calls parent::__construct with specific arguments
5299 public function __construct() {
5300 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5301 $this->plugin = 'backup';
5305 * Load the available choices for the select box
5307 * @return bool Always returns true
5309 public function load_choices() {
5310 if (is_array($this->choices)) {
5311 return true;
5313 $this->choices = array();
5314 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5315 foreach ($days as $day) {
5316 $this->choices[$day] = get_string($day, 'calendar');
5318 return true;
5323 * Special setting for backup auto destination.
5325 * @package core
5326 * @subpackage admin
5327 * @copyright 2014 Frédéric Massart - FMCorz.net
5328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5330 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5333 * Calls parent::__construct with specific arguments.
5335 public function __construct() {
5336 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5340 * Check if the directory must be set, depending on backup/backup_auto_storage.
5342 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5343 * there will be conflicts if this validation happens before the other one.
5345 * @param string $data Form data.
5346 * @return string Empty when no errors.
5348 public function write_setting($data) {
5349 $storage = (int) get_config('backup', 'backup_auto_storage');
5350 if ($storage !== 0) {
5351 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5352 // The directory must exist and be writable.
5353 return get_string('backuperrorinvaliddestination');
5356 return parent::write_setting($data);
5362 * Special debug setting
5364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5366 class admin_setting_special_debug extends admin_setting_configselect {
5368 * Calls parent::__construct with specific arguments
5370 public function __construct() {
5371 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5375 * Load the available choices for the select box
5377 * @return bool
5379 public function load_choices() {
5380 if (is_array($this->choices)) {
5381 return true;
5383 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5384 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5385 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5386 DEBUG_ALL => get_string('debugall', 'admin'),
5387 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5388 return true;
5394 * Special admin control
5396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5398 class admin_setting_special_calendar_weekend extends admin_setting {
5400 * Calls parent::__construct with specific arguments
5402 public function __construct() {
5403 $name = 'calendar_weekend';
5404 $visiblename = get_string('calendar_weekend', 'admin');
5405 $description = get_string('helpweekenddays', 'admin');
5406 $default = array ('0', '6'); // Saturdays and Sundays
5407 parent::__construct($name, $visiblename, $description, $default);
5411 * Gets the current settings as an array
5413 * @return mixed Null if none, else array of settings
5415 public function get_setting() {
5416 $result = $this->config_read($this->name);
5417 if (is_null($result)) {
5418 return NULL;
5420 if ($result === '') {
5421 return array();
5423 $settings = array();
5424 for ($i=0; $i<7; $i++) {
5425 if ($result & (1 << $i)) {
5426 $settings[] = $i;
5429 return $settings;
5433 * Save the new settings
5435 * @param array $data Array of new settings
5436 * @return bool
5438 public function write_setting($data) {
5439 if (!is_array($data)) {
5440 return '';
5442 unset($data['xxxxx']);
5443 $result = 0;
5444 foreach($data as $index) {
5445 $result |= 1 << $index;
5447 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5451 * Return XHTML to display the control
5453 * @param array $data array of selected days
5454 * @param string $query
5455 * @return string XHTML for display (field + wrapping div(s)
5457 public function output_html($data, $query='') {
5458 global $OUTPUT;
5460 // The order matters very much because of the implied numeric keys.
5461 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5462 $context = (object) [
5463 'name' => $this->get_full_name(),
5464 'id' => $this->get_id(),
5465 'days' => array_map(function($index) use ($days, $data) {
5466 return [
5467 'index' => $index,
5468 'label' => get_string($days[$index], 'calendar'),
5469 'checked' => in_array($index, $data)
5471 }, array_keys($days))
5474 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5476 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5483 * Admin setting that allows a user to pick a behaviour.
5485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5487 class admin_setting_question_behaviour extends admin_setting_configselect {
5489 * @param string $name name of config variable
5490 * @param string $visiblename display name
5491 * @param string $description description
5492 * @param string $default default.
5494 public function __construct($name, $visiblename, $description, $default) {
5495 parent::__construct($name, $visiblename, $description, $default, null);
5499 * Load list of behaviours as choices
5500 * @return bool true => success, false => error.
5502 public function load_choices() {
5503 global $CFG;
5504 require_once($CFG->dirroot . '/question/engine/lib.php');
5505 $this->choices = question_engine::get_behaviour_options('');
5506 return true;
5512 * Admin setting that allows a user to pick appropriate roles for something.
5514 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5516 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5517 /** @var array Array of capabilities which identify roles */
5518 private $types;
5521 * @param string $name Name of config variable
5522 * @param string $visiblename Display name
5523 * @param string $description Description
5524 * @param array $types Array of archetypes which identify
5525 * roles that will be enabled by default.
5527 public function __construct($name, $visiblename, $description, $types) {
5528 parent::__construct($name, $visiblename, $description, NULL, NULL);
5529 $this->types = $types;
5533 * Load roles as choices
5535 * @return bool true=>success, false=>error
5537 public function load_choices() {
5538 global $CFG, $DB;
5539 if (during_initial_install()) {
5540 return false;
5542 if (is_array($this->choices)) {
5543 return true;
5545 if ($roles = get_all_roles()) {
5546 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5547 return true;
5548 } else {
5549 return false;
5554 * Return the default setting for this control
5556 * @return array Array of default settings
5558 public function get_defaultsetting() {
5559 global $CFG;
5561 if (during_initial_install()) {
5562 return null;
5564 $result = array();
5565 foreach($this->types as $archetype) {
5566 if ($caproles = get_archetype_roles($archetype)) {
5567 foreach ($caproles as $caprole) {
5568 $result[$caprole->id] = 1;
5572 return $result;
5578 * Admin setting that is a list of installed filter plugins.
5580 * @copyright 2015 The Open University
5581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5583 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5586 * Constructor
5588 * @param string $name unique ascii name, either 'mysetting' for settings
5589 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5590 * @param string $visiblename localised name
5591 * @param string $description localised long description
5592 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5594 public function __construct($name, $visiblename, $description, $default) {
5595 if (empty($default)) {
5596 $default = array();
5598 $this->load_choices();
5599 foreach ($default as $plugin) {
5600 if (!isset($this->choices[$plugin])) {
5601 unset($default[$plugin]);
5604 parent::__construct($name, $visiblename, $description, $default, null);
5607 public function load_choices() {
5608 if (is_array($this->choices)) {
5609 return true;
5611 $this->choices = array();
5613 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5614 $this->choices[$plugin] = filter_get_name($plugin);
5616 return true;
5622 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5626 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5628 * Constructor
5629 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5630 * @param string $visiblename localised
5631 * @param string $description long localised info
5632 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5633 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5634 * @param int $size default field size
5636 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5637 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5638 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5644 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5646 * @copyright 2009 Petr Skoda (http://skodak.org)
5647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5649 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5652 * Constructor
5653 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5654 * @param string $visiblename localised
5655 * @param string $description long localised info
5656 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5657 * @param string $yes value used when checked
5658 * @param string $no value used when not checked
5660 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5661 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5662 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5669 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5671 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5673 * @copyright 2010 Sam Hemelryk
5674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5676 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5678 * Constructor
5679 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5680 * @param string $visiblename localised
5681 * @param string $description long localised info
5682 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5683 * @param string $yes value used when checked
5684 * @param string $no value used when not checked
5686 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5687 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5688 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5694 * Autocomplete as you type form element.
5696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5698 class admin_setting_configselect_autocomplete extends admin_setting_configselect {
5699 /** @var boolean $tags Should we allow typing new entries to the field? */
5700 protected $tags = false;
5701 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5702 protected $ajax = '';
5703 /** @var string $placeholder Placeholder text for an empty list. */
5704 protected $placeholder = '';
5705 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5706 protected $casesensitive = false;
5707 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5708 protected $showsuggestions = true;
5709 /** @var string $noselectionstring String that is shown when there are no selections. */
5710 protected $noselectionstring = '';
5713 * Returns XHTML select field and wrapping div(s)
5715 * @see output_select_html()
5717 * @param string $data the option to show as selected
5718 * @param string $query
5719 * @return string XHTML field and wrapping div
5721 public function output_html($data, $query='') {
5722 global $PAGE;
5724 $html = parent::output_html($data, $query);
5726 if ($html === '') {
5727 return $html;
5730 $this->placeholder = get_string('search');
5732 $params = array('#' . $this->get_id(), $this->tags, $this->ajax,
5733 $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring);
5735 // Load autocomplete wrapper for select2 library.
5736 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params);
5738 return $html;
5743 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5745 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5747 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5749 * Calls parent::__construct with specific arguments
5751 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5752 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5753 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5759 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5761 * @copyright 2017 Marina Glancy
5762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5764 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5766 * Constructor
5767 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5768 * or 'myplugin/mysetting' for ones in config_plugins.
5769 * @param string $visiblename localised
5770 * @param string $description long localised info
5771 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5772 * @param array $choices array of $value=>$label for each selection
5774 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5775 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5776 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5782 * Graded roles in gradebook
5784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5786 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5788 * Calls parent::__construct with specific arguments
5790 public function __construct() {
5791 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5792 get_string('configgradebookroles', 'admin'),
5793 array('student'));
5800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5802 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5804 * Saves the new settings passed in $data
5806 * @param string $data
5807 * @return mixed string or Array
5809 public function write_setting($data) {
5810 global $CFG, $DB;
5812 $oldvalue = $this->config_read($this->name);
5813 $return = parent::write_setting($data);
5814 $newvalue = $this->config_read($this->name);
5816 if ($oldvalue !== $newvalue) {
5817 // force full regrading
5818 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5821 return $return;
5827 * Which roles to show on course description page
5829 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5831 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5833 * Calls parent::__construct with specific arguments
5835 public function __construct() {
5836 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5837 get_string('coursecontact_desc', 'admin'),
5838 array('editingteacher'));
5839 $this->set_updatedcallback(function (){
5840 cache::make('core', 'coursecontacts')->purge();
5848 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5850 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5852 * Calls parent::__construct with specific arguments
5854 public function __construct() {
5855 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5856 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5860 * Old syntax of class constructor. Deprecated in PHP7.
5862 * @deprecated since Moodle 3.1
5864 public function admin_setting_special_gradelimiting() {
5865 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5866 self::__construct();
5870 * Force site regrading
5872 function regrade_all() {
5873 global $CFG;
5874 require_once("$CFG->libdir/gradelib.php");
5875 grade_force_site_regrading();
5879 * Saves the new settings
5881 * @param mixed $data
5882 * @return string empty string or error message
5884 function write_setting($data) {
5885 $previous = $this->get_setting();
5887 if ($previous === null) {
5888 if ($data) {
5889 $this->regrade_all();
5891 } else {
5892 if ($data != $previous) {
5893 $this->regrade_all();
5896 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5902 * Special setting for $CFG->grade_minmaxtouse.
5904 * @package core
5905 * @copyright 2015 Frédéric Massart - FMCorz.net
5906 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5908 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5911 * Constructor.
5913 public function __construct() {
5914 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5915 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5916 array(
5917 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5918 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5924 * Saves the new setting.
5926 * @param mixed $data
5927 * @return string empty string or error message
5929 function write_setting($data) {
5930 global $CFG;
5932 $previous = $this->get_setting();
5933 $result = parent::write_setting($data);
5935 // If saved and the value has changed.
5936 if (empty($result) && $previous != $data) {
5937 require_once($CFG->libdir . '/gradelib.php');
5938 grade_force_site_regrading();
5941 return $result;
5948 * Primary grade export plugin - has state tracking.
5950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5952 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5954 * Calls parent::__construct with specific arguments
5956 public function __construct() {
5957 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5958 get_string('configgradeexport', 'admin'), array(), NULL);
5962 * Load the available choices for the multicheckbox
5964 * @return bool always returns true
5966 public function load_choices() {
5967 if (is_array($this->choices)) {
5968 return true;
5970 $this->choices = array();
5972 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5973 foreach($plugins as $plugin => $unused) {
5974 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5977 return true;
5983 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5985 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5987 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5989 * Config gradepointmax constructor
5991 * @param string $name Overidden by "gradepointmax"
5992 * @param string $visiblename Overridden by "gradepointmax" language string.
5993 * @param string $description Overridden by "gradepointmax_help" language string.
5994 * @param string $defaultsetting Not used, overridden by 100.
5995 * @param mixed $paramtype Overridden by PARAM_INT.
5996 * @param int $size Overridden by 5.
5998 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5999 $name = 'gradepointdefault';
6000 $visiblename = get_string('gradepointdefault', 'grades');
6001 $description = get_string('gradepointdefault_help', 'grades');
6002 $defaultsetting = 100;
6003 $paramtype = PARAM_INT;
6004 $size = 5;
6005 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6009 * Validate data before storage
6010 * @param string $data The submitted data
6011 * @return bool|string true if ok, string if error found
6013 public function validate($data) {
6014 global $CFG;
6015 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
6016 return true;
6017 } else {
6018 return get_string('gradepointdefault_validateerror', 'grades');
6025 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
6027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6029 class admin_setting_special_gradepointmax extends admin_setting_configtext {
6032 * Config gradepointmax constructor
6034 * @param string $name Overidden by "gradepointmax"
6035 * @param string $visiblename Overridden by "gradepointmax" language string.
6036 * @param string $description Overridden by "gradepointmax_help" language string.
6037 * @param string $defaultsetting Not used, overridden by 100.
6038 * @param mixed $paramtype Overridden by PARAM_INT.
6039 * @param int $size Overridden by 5.
6041 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6042 $name = 'gradepointmax';
6043 $visiblename = get_string('gradepointmax', 'grades');
6044 $description = get_string('gradepointmax_help', 'grades');
6045 $defaultsetting = 100;
6046 $paramtype = PARAM_INT;
6047 $size = 5;
6048 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6052 * Save the selected setting
6054 * @param string $data The selected site
6055 * @return string empty string or error message
6057 public function write_setting($data) {
6058 if ($data === '') {
6059 $data = (int)$this->defaultsetting;
6060 } else {
6061 $data = $data;
6063 return parent::write_setting($data);
6067 * Validate data before storage
6068 * @param string $data The submitted data
6069 * @return bool|string true if ok, string if error found
6071 public function validate($data) {
6072 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6073 return true;
6074 } else {
6075 return get_string('gradepointmax_validateerror', 'grades');
6080 * Return an XHTML string for the setting
6081 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6082 * @param string $query search query to be highlighted
6083 * @return string XHTML to display control
6085 public function output_html($data, $query = '') {
6086 global $OUTPUT;
6088 $default = $this->get_defaultsetting();
6089 $context = (object) [
6090 'size' => $this->size,
6091 'id' => $this->get_id(),
6092 'name' => $this->get_full_name(),
6093 'value' => $data,
6094 'attributes' => [
6095 'maxlength' => 5
6097 'forceltr' => $this->get_force_ltr()
6099 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6101 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
6107 * Grade category settings
6109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6111 class admin_setting_gradecat_combo extends admin_setting {
6112 /** @var array Array of choices */
6113 public $choices;
6116 * Sets choices and calls parent::__construct with passed arguments
6117 * @param string $name
6118 * @param string $visiblename
6119 * @param string $description
6120 * @param mixed $defaultsetting string or array depending on implementation
6121 * @param array $choices An array of choices for the control
6123 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6124 $this->choices = $choices;
6125 parent::__construct($name, $visiblename, $description, $defaultsetting);
6129 * Return the current setting(s) array
6131 * @return array Array of value=>xx, forced=>xx, adv=>xx
6133 public function get_setting() {
6134 global $CFG;
6136 $value = $this->config_read($this->name);
6137 $flag = $this->config_read($this->name.'_flag');
6139 if (is_null($value) or is_null($flag)) {
6140 return NULL;
6143 $flag = (int)$flag;
6144 $forced = (boolean)(1 & $flag); // first bit
6145 $adv = (boolean)(2 & $flag); // second bit
6147 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6151 * Save the new settings passed in $data
6153 * @todo Add vartype handling to ensure $data is array
6154 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6155 * @return string empty or error message
6157 public function write_setting($data) {
6158 global $CFG;
6160 $value = $data['value'];
6161 $forced = empty($data['forced']) ? 0 : 1;
6162 $adv = empty($data['adv']) ? 0 : 2;
6163 $flag = ($forced | $adv); //bitwise or
6165 if (!in_array($value, array_keys($this->choices))) {
6166 return 'Error setting ';
6169 $oldvalue = $this->config_read($this->name);
6170 $oldflag = (int)$this->config_read($this->name.'_flag');
6171 $oldforced = (1 & $oldflag); // first bit
6173 $result1 = $this->config_write($this->name, $value);
6174 $result2 = $this->config_write($this->name.'_flag', $flag);
6176 // force regrade if needed
6177 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6178 require_once($CFG->libdir.'/gradelib.php');
6179 grade_category::updated_forced_settings();
6182 if ($result1 and $result2) {
6183 return '';
6184 } else {
6185 return get_string('errorsetting', 'admin');
6190 * Return XHTML to display the field and wrapping div
6192 * @todo Add vartype handling to ensure $data is array
6193 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6194 * @param string $query
6195 * @return string XHTML to display control
6197 public function output_html($data, $query='') {
6198 global $OUTPUT;
6200 $value = $data['value'];
6202 $default = $this->get_defaultsetting();
6203 if (!is_null($default)) {
6204 $defaultinfo = array();
6205 if (isset($this->choices[$default['value']])) {
6206 $defaultinfo[] = $this->choices[$default['value']];
6208 if (!empty($default['forced'])) {
6209 $defaultinfo[] = get_string('force');
6211 if (!empty($default['adv'])) {
6212 $defaultinfo[] = get_string('advanced');
6214 $defaultinfo = implode(', ', $defaultinfo);
6216 } else {
6217 $defaultinfo = NULL;
6220 $options = $this->choices;
6221 $context = (object) [
6222 'id' => $this->get_id(),
6223 'name' => $this->get_full_name(),
6224 'forced' => !empty($data['forced']),
6225 'advanced' => !empty($data['adv']),
6226 'options' => array_map(function($option) use ($options, $value) {
6227 return [
6228 'value' => $option,
6229 'name' => $options[$option],
6230 'selected' => $option == $value
6232 }, array_keys($options)),
6235 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6237 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
6243 * Selection of grade report in user profiles
6245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6247 class admin_setting_grade_profilereport extends admin_setting_configselect {
6249 * Calls parent::__construct with specific arguments
6251 public function __construct() {
6252 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6256 * Loads an array of choices for the configselect control
6258 * @return bool always return true
6260 public function load_choices() {
6261 if (is_array($this->choices)) {
6262 return true;
6264 $this->choices = array();
6266 global $CFG;
6267 require_once($CFG->libdir.'/gradelib.php');
6269 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6270 if (file_exists($plugindir.'/lib.php')) {
6271 require_once($plugindir.'/lib.php');
6272 $functionname = 'grade_report_'.$plugin.'_profilereport';
6273 if (function_exists($functionname)) {
6274 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6278 return true;
6283 * Provides a selection of grade reports to be used for "grades".
6285 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6288 class admin_setting_my_grades_report extends admin_setting_configselect {
6291 * Calls parent::__construct with specific arguments.
6293 public function __construct() {
6294 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6295 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6299 * Loads an array of choices for the configselect control.
6301 * @return bool always returns true.
6303 public function load_choices() {
6304 global $CFG; // Remove this line and behold the horror of behat test failures!
6305 $this->choices = array();
6306 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6307 if (file_exists($plugindir . '/lib.php')) {
6308 require_once($plugindir . '/lib.php');
6309 // Check to see if the class exists. Check the correct plugin convention first.
6310 if (class_exists('gradereport_' . $plugin)) {
6311 $classname = 'gradereport_' . $plugin;
6312 } else if (class_exists('grade_report_' . $plugin)) {
6313 // We are using the old plugin naming convention.
6314 $classname = 'grade_report_' . $plugin;
6315 } else {
6316 continue;
6318 if ($classname::supports_mygrades()) {
6319 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6323 // Add an option to specify an external url.
6324 $this->choices['external'] = get_string('externalurl', 'grades');
6325 return true;
6330 * Special class for register auth selection
6332 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6334 class admin_setting_special_registerauth extends admin_setting_configselect {
6336 * Calls parent::__construct with specific arguments
6338 public function __construct() {
6339 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6343 * Returns the default option
6345 * @return string empty or default option
6347 public function get_defaultsetting() {
6348 $this->load_choices();
6349 $defaultsetting = parent::get_defaultsetting();
6350 if (array_key_exists($defaultsetting, $this->choices)) {
6351 return $defaultsetting;
6352 } else {
6353 return '';
6358 * Loads the possible choices for the array
6360 * @return bool always returns true
6362 public function load_choices() {
6363 global $CFG;
6365 if (is_array($this->choices)) {
6366 return true;
6368 $this->choices = array();
6369 $this->choices[''] = get_string('disable');
6371 $authsenabled = get_enabled_auth_plugins();
6373 foreach ($authsenabled as $auth) {
6374 $authplugin = get_auth_plugin($auth);
6375 if (!$authplugin->can_signup()) {
6376 continue;
6378 // Get the auth title (from core or own auth lang files)
6379 $authtitle = $authplugin->get_title();
6380 $this->choices[$auth] = $authtitle;
6382 return true;
6388 * General plugins manager
6390 class admin_page_pluginsoverview extends admin_externalpage {
6393 * Sets basic information about the external page
6395 public function __construct() {
6396 global $CFG;
6397 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6398 "$CFG->wwwroot/$CFG->admin/plugins.php");
6403 * Module manage page
6405 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6407 class admin_page_managemods extends admin_externalpage {
6409 * Calls parent::__construct with specific arguments
6411 public function __construct() {
6412 global $CFG;
6413 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6417 * Try to find the specified module
6419 * @param string $query The module to search for
6420 * @return array
6422 public function search($query) {
6423 global $CFG, $DB;
6424 if ($result = parent::search($query)) {
6425 return $result;
6428 $found = false;
6429 if ($modules = $DB->get_records('modules')) {
6430 foreach ($modules as $module) {
6431 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6432 continue;
6434 if (strpos($module->name, $query) !== false) {
6435 $found = true;
6436 break;
6438 $strmodulename = get_string('modulename', $module->name);
6439 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6440 $found = true;
6441 break;
6445 if ($found) {
6446 $result = new stdClass();
6447 $result->page = $this;
6448 $result->settings = array();
6449 return array($this->name => $result);
6450 } else {
6451 return array();
6458 * Special class for enrol plugins management.
6460 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6461 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6463 class admin_setting_manageenrols extends admin_setting {
6465 * Calls parent::__construct with specific arguments
6467 public function __construct() {
6468 $this->nosave = true;
6469 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6473 * Always returns true, does nothing
6475 * @return true
6477 public function get_setting() {
6478 return true;
6482 * Always returns true, does nothing
6484 * @return true
6486 public function get_defaultsetting() {
6487 return true;
6491 * Always returns '', does not write anything
6493 * @return string Always returns ''
6495 public function write_setting($data) {
6496 // do not write any setting
6497 return '';
6501 * Checks if $query is one of the available enrol plugins
6503 * @param string $query The string to search for
6504 * @return bool Returns true if found, false if not
6506 public function is_related($query) {
6507 if (parent::is_related($query)) {
6508 return true;
6511 $query = core_text::strtolower($query);
6512 $enrols = enrol_get_plugins(false);
6513 foreach ($enrols as $name=>$enrol) {
6514 $localised = get_string('pluginname', 'enrol_'.$name);
6515 if (strpos(core_text::strtolower($name), $query) !== false) {
6516 return true;
6518 if (strpos(core_text::strtolower($localised), $query) !== false) {
6519 return true;
6522 return false;
6526 * Builds the XHTML to display the control
6528 * @param string $data Unused
6529 * @param string $query
6530 * @return string
6532 public function output_html($data, $query='') {
6533 global $CFG, $OUTPUT, $DB, $PAGE;
6535 // Display strings.
6536 $strup = get_string('up');
6537 $strdown = get_string('down');
6538 $strsettings = get_string('settings');
6539 $strenable = get_string('enable');
6540 $strdisable = get_string('disable');
6541 $struninstall = get_string('uninstallplugin', 'core_admin');
6542 $strusage = get_string('enrolusage', 'enrol');
6543 $strversion = get_string('version');
6544 $strtest = get_string('testsettings', 'core_enrol');
6546 $pluginmanager = core_plugin_manager::instance();
6548 $enrols_available = enrol_get_plugins(false);
6549 $active_enrols = enrol_get_plugins(true);
6551 $allenrols = array();
6552 foreach ($active_enrols as $key=>$enrol) {
6553 $allenrols[$key] = true;
6555 foreach ($enrols_available as $key=>$enrol) {
6556 $allenrols[$key] = true;
6558 // Now find all borked plugins and at least allow then to uninstall.
6559 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6560 foreach ($condidates as $candidate) {
6561 if (empty($allenrols[$candidate])) {
6562 $allenrols[$candidate] = true;
6566 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6567 $return .= $OUTPUT->box_start('generalbox enrolsui');
6569 $table = new html_table();
6570 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6571 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6572 $table->id = 'courseenrolmentplugins';
6573 $table->attributes['class'] = 'admintable generaltable';
6574 $table->data = array();
6576 // Iterate through enrol plugins and add to the display table.
6577 $updowncount = 1;
6578 $enrolcount = count($active_enrols);
6579 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6580 $printed = array();
6581 foreach($allenrols as $enrol => $unused) {
6582 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6583 $version = get_config('enrol_'.$enrol, 'version');
6584 if ($version === false) {
6585 $version = '';
6588 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6589 $name = get_string('pluginname', 'enrol_'.$enrol);
6590 } else {
6591 $name = $enrol;
6593 // Usage.
6594 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6595 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6596 $usage = "$ci / $cp";
6598 // Hide/show links.
6599 $class = '';
6600 if (isset($active_enrols[$enrol])) {
6601 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6602 $hideshow = "<a href=\"$aurl\">";
6603 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6604 $enabled = true;
6605 $displayname = $name;
6606 } else if (isset($enrols_available[$enrol])) {
6607 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6608 $hideshow = "<a href=\"$aurl\">";
6609 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6610 $enabled = false;
6611 $displayname = $name;
6612 $class = 'dimmed_text';
6613 } else {
6614 $hideshow = '';
6615 $enabled = false;
6616 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6618 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6619 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6620 } else {
6621 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6624 // Up/down link (only if enrol is enabled).
6625 $updown = '';
6626 if ($enabled) {
6627 if ($updowncount > 1) {
6628 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6629 $updown .= "<a href=\"$aurl\">";
6630 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6631 } else {
6632 $updown .= $OUTPUT->spacer() . '&nbsp;';
6634 if ($updowncount < $enrolcount) {
6635 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6636 $updown .= "<a href=\"$aurl\">";
6637 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6638 } else {
6639 $updown .= $OUTPUT->spacer() . '&nbsp;';
6641 ++$updowncount;
6644 // Add settings link.
6645 if (!$version) {
6646 $settings = '';
6647 } else if ($surl = $plugininfo->get_settings_url()) {
6648 $settings = html_writer::link($surl, $strsettings);
6649 } else {
6650 $settings = '';
6653 // Add uninstall info.
6654 $uninstall = '';
6655 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6656 $uninstall = html_writer::link($uninstallurl, $struninstall);
6659 $test = '';
6660 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6661 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6662 $test = html_writer::link($testsettingsurl, $strtest);
6665 // Add a row to the table.
6666 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6667 if ($class) {
6668 $row->attributes['class'] = $class;
6670 $table->data[] = $row;
6672 $printed[$enrol] = true;
6675 $return .= html_writer::table($table);
6676 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6677 $return .= $OUTPUT->box_end();
6678 return highlight($query, $return);
6684 * Blocks manage page
6686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6688 class admin_page_manageblocks extends admin_externalpage {
6690 * Calls parent::__construct with specific arguments
6692 public function __construct() {
6693 global $CFG;
6694 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6698 * Search for a specific block
6700 * @param string $query The string to search for
6701 * @return array
6703 public function search($query) {
6704 global $CFG, $DB;
6705 if ($result = parent::search($query)) {
6706 return $result;
6709 $found = false;
6710 if ($blocks = $DB->get_records('block')) {
6711 foreach ($blocks as $block) {
6712 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6713 continue;
6715 if (strpos($block->name, $query) !== false) {
6716 $found = true;
6717 break;
6719 $strblockname = get_string('pluginname', 'block_'.$block->name);
6720 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6721 $found = true;
6722 break;
6726 if ($found) {
6727 $result = new stdClass();
6728 $result->page = $this;
6729 $result->settings = array();
6730 return array($this->name => $result);
6731 } else {
6732 return array();
6738 * Message outputs configuration
6740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6742 class admin_page_managemessageoutputs extends admin_externalpage {
6744 * Calls parent::__construct with specific arguments
6746 public function __construct() {
6747 global $CFG;
6748 parent::__construct('managemessageoutputs',
6749 get_string('defaultmessageoutputs', 'message'),
6750 new moodle_url('/admin/message.php')
6755 * Search for a specific message processor
6757 * @param string $query The string to search for
6758 * @return array
6760 public function search($query) {
6761 global $CFG, $DB;
6762 if ($result = parent::search($query)) {
6763 return $result;
6766 $found = false;
6767 if ($processors = get_message_processors()) {
6768 foreach ($processors as $processor) {
6769 if (!$processor->available) {
6770 continue;
6772 if (strpos($processor->name, $query) !== false) {
6773 $found = true;
6774 break;
6776 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6777 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6778 $found = true;
6779 break;
6783 if ($found) {
6784 $result = new stdClass();
6785 $result->page = $this;
6786 $result->settings = array();
6787 return array($this->name => $result);
6788 } else {
6789 return array();
6795 * Manage question behaviours page
6797 * @copyright 2011 The Open University
6798 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6800 class admin_page_manageqbehaviours extends admin_externalpage {
6802 * Constructor
6804 public function __construct() {
6805 global $CFG;
6806 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6807 new moodle_url('/admin/qbehaviours.php'));
6811 * Search question behaviours for the specified string
6813 * @param string $query The string to search for in question behaviours
6814 * @return array
6816 public function search($query) {
6817 global $CFG;
6818 if ($result = parent::search($query)) {
6819 return $result;
6822 $found = false;
6823 require_once($CFG->dirroot . '/question/engine/lib.php');
6824 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6825 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6826 $query) !== false) {
6827 $found = true;
6828 break;
6831 if ($found) {
6832 $result = new stdClass();
6833 $result->page = $this;
6834 $result->settings = array();
6835 return array($this->name => $result);
6836 } else {
6837 return array();
6844 * Question type manage page
6846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6848 class admin_page_manageqtypes extends admin_externalpage {
6850 * Calls parent::__construct with specific arguments
6852 public function __construct() {
6853 global $CFG;
6854 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6855 new moodle_url('/admin/qtypes.php'));
6859 * Search question types for the specified string
6861 * @param string $query The string to search for in question types
6862 * @return array
6864 public function search($query) {
6865 global $CFG;
6866 if ($result = parent::search($query)) {
6867 return $result;
6870 $found = false;
6871 require_once($CFG->dirroot . '/question/engine/bank.php');
6872 foreach (question_bank::get_all_qtypes() as $qtype) {
6873 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6874 $found = true;
6875 break;
6878 if ($found) {
6879 $result = new stdClass();
6880 $result->page = $this;
6881 $result->settings = array();
6882 return array($this->name => $result);
6883 } else {
6884 return array();
6890 class admin_page_manageportfolios extends admin_externalpage {
6892 * Calls parent::__construct with specific arguments
6894 public function __construct() {
6895 global $CFG;
6896 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6897 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6901 * Searches page for the specified string.
6902 * @param string $query The string to search for
6903 * @return bool True if it is found on this page
6905 public function search($query) {
6906 global $CFG;
6907 if ($result = parent::search($query)) {
6908 return $result;
6911 $found = false;
6912 $portfolios = core_component::get_plugin_list('portfolio');
6913 foreach ($portfolios as $p => $dir) {
6914 if (strpos($p, $query) !== false) {
6915 $found = true;
6916 break;
6919 if (!$found) {
6920 foreach (portfolio_instances(false, false) as $instance) {
6921 $title = $instance->get('name');
6922 if (strpos(core_text::strtolower($title), $query) !== false) {
6923 $found = true;
6924 break;
6929 if ($found) {
6930 $result = new stdClass();
6931 $result->page = $this;
6932 $result->settings = array();
6933 return array($this->name => $result);
6934 } else {
6935 return array();
6941 class admin_page_managerepositories extends admin_externalpage {
6943 * Calls parent::__construct with specific arguments
6945 public function __construct() {
6946 global $CFG;
6947 parent::__construct('managerepositories', get_string('manage',
6948 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6952 * Searches page for the specified string.
6953 * @param string $query The string to search for
6954 * @return bool True if it is found on this page
6956 public function search($query) {
6957 global $CFG;
6958 if ($result = parent::search($query)) {
6959 return $result;
6962 $found = false;
6963 $repositories= core_component::get_plugin_list('repository');
6964 foreach ($repositories as $p => $dir) {
6965 if (strpos($p, $query) !== false) {
6966 $found = true;
6967 break;
6970 if (!$found) {
6971 foreach (repository::get_types() as $instance) {
6972 $title = $instance->get_typename();
6973 if (strpos(core_text::strtolower($title), $query) !== false) {
6974 $found = true;
6975 break;
6980 if ($found) {
6981 $result = new stdClass();
6982 $result->page = $this;
6983 $result->settings = array();
6984 return array($this->name => $result);
6985 } else {
6986 return array();
6993 * Special class for authentication administration.
6995 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6997 class admin_setting_manageauths extends admin_setting {
6999 * Calls parent::__construct with specific arguments
7001 public function __construct() {
7002 $this->nosave = true;
7003 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
7007 * Always returns true
7009 * @return true
7011 public function get_setting() {
7012 return true;
7016 * Always returns true
7018 * @return true
7020 public function get_defaultsetting() {
7021 return true;
7025 * Always returns '' and doesn't write anything
7027 * @return string Always returns ''
7029 public function write_setting($data) {
7030 // do not write any setting
7031 return '';
7035 * Search to find if Query is related to auth plugin
7037 * @param string $query The string to search for
7038 * @return bool true for related false for not
7040 public function is_related($query) {
7041 if (parent::is_related($query)) {
7042 return true;
7045 $authsavailable = core_component::get_plugin_list('auth');
7046 foreach ($authsavailable as $auth => $dir) {
7047 if (strpos($auth, $query) !== false) {
7048 return true;
7050 $authplugin = get_auth_plugin($auth);
7051 $authtitle = $authplugin->get_title();
7052 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
7053 return true;
7056 return false;
7060 * Return XHTML to display control
7062 * @param mixed $data Unused
7063 * @param string $query
7064 * @return string highlight
7066 public function output_html($data, $query='') {
7067 global $CFG, $OUTPUT, $DB;
7069 // display strings
7070 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7071 'settings', 'edit', 'name', 'enable', 'disable',
7072 'up', 'down', 'none', 'users'));
7073 $txt->updown = "$txt->up/$txt->down";
7074 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7075 $txt->testsettings = get_string('testsettings', 'core_auth');
7077 $authsavailable = core_component::get_plugin_list('auth');
7078 get_enabled_auth_plugins(true); // fix the list of enabled auths
7079 if (empty($CFG->auth)) {
7080 $authsenabled = array();
7081 } else {
7082 $authsenabled = explode(',', $CFG->auth);
7085 // construct the display array, with enabled auth plugins at the top, in order
7086 $displayauths = array();
7087 $registrationauths = array();
7088 $registrationauths[''] = $txt->disable;
7089 $authplugins = array();
7090 foreach ($authsenabled as $auth) {
7091 $authplugin = get_auth_plugin($auth);
7092 $authplugins[$auth] = $authplugin;
7093 /// Get the auth title (from core or own auth lang files)
7094 $authtitle = $authplugin->get_title();
7095 /// Apply titles
7096 $displayauths[$auth] = $authtitle;
7097 if ($authplugin->can_signup()) {
7098 $registrationauths[$auth] = $authtitle;
7102 foreach ($authsavailable as $auth => $dir) {
7103 if (array_key_exists($auth, $displayauths)) {
7104 continue; //already in the list
7106 $authplugin = get_auth_plugin($auth);
7107 $authplugins[$auth] = $authplugin;
7108 /// Get the auth title (from core or own auth lang files)
7109 $authtitle = $authplugin->get_title();
7110 /// Apply titles
7111 $displayauths[$auth] = $authtitle;
7112 if ($authplugin->can_signup()) {
7113 $registrationauths[$auth] = $authtitle;
7117 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7118 $return .= $OUTPUT->box_start('generalbox authsui');
7120 $table = new html_table();
7121 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
7122 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7123 $table->data = array();
7124 $table->attributes['class'] = 'admintable generaltable';
7125 $table->id = 'manageauthtable';
7127 //add always enabled plugins first
7128 $displayname = $displayauths['manual'];
7129 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7130 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7131 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
7132 $displayname = $displayauths['nologin'];
7133 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7134 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
7137 // iterate through auth plugins and add to the display table
7138 $updowncount = 1;
7139 $authcount = count($authsenabled);
7140 $url = "auth.php?sesskey=" . sesskey();
7141 foreach ($displayauths as $auth => $name) {
7142 if ($auth == 'manual' or $auth == 'nologin') {
7143 continue;
7145 $class = '';
7146 // hide/show link
7147 if (in_array($auth, $authsenabled)) {
7148 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
7149 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7150 $enabled = true;
7151 $displayname = $name;
7153 else {
7154 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
7155 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7156 $enabled = false;
7157 $displayname = $name;
7158 $class = 'dimmed_text';
7161 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7163 // up/down link (only if auth is enabled)
7164 $updown = '';
7165 if ($enabled) {
7166 if ($updowncount > 1) {
7167 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
7168 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7170 else {
7171 $updown .= $OUTPUT->spacer() . '&nbsp;';
7173 if ($updowncount < $authcount) {
7174 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
7175 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7177 else {
7178 $updown .= $OUTPUT->spacer() . '&nbsp;';
7180 ++ $updowncount;
7183 // settings link
7184 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
7185 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7186 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
7187 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
7188 } else {
7189 $settings = '';
7192 // Uninstall link.
7193 $uninstall = '';
7194 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7195 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7198 $test = '';
7199 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7200 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
7201 $test = html_writer::link($testurl, $txt->testsettings);
7204 // Add a row to the table.
7205 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7206 if ($class) {
7207 $row->attributes['class'] = $class;
7209 $table->data[] = $row;
7211 $return .= html_writer::table($table);
7212 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7213 $return .= $OUTPUT->box_end();
7214 return highlight($query, $return);
7220 * Special class for authentication administration.
7222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7224 class admin_setting_manageeditors extends admin_setting {
7226 * Calls parent::__construct with specific arguments
7228 public function __construct() {
7229 $this->nosave = true;
7230 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
7234 * Always returns true, does nothing
7236 * @return true
7238 public function get_setting() {
7239 return true;
7243 * Always returns true, does nothing
7245 * @return true
7247 public function get_defaultsetting() {
7248 return true;
7252 * Always returns '', does not write anything
7254 * @return string Always returns ''
7256 public function write_setting($data) {
7257 // do not write any setting
7258 return '';
7262 * Checks if $query is one of the available editors
7264 * @param string $query The string to search for
7265 * @return bool Returns true if found, false if not
7267 public function is_related($query) {
7268 if (parent::is_related($query)) {
7269 return true;
7272 $editors_available = editors_get_available();
7273 foreach ($editors_available as $editor=>$editorstr) {
7274 if (strpos($editor, $query) !== false) {
7275 return true;
7277 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
7278 return true;
7281 return false;
7285 * Builds the XHTML to display the control
7287 * @param string $data Unused
7288 * @param string $query
7289 * @return string
7291 public function output_html($data, $query='') {
7292 global $CFG, $OUTPUT;
7294 // display strings
7295 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7296 'up', 'down', 'none'));
7297 $struninstall = get_string('uninstallplugin', 'core_admin');
7299 $txt->updown = "$txt->up/$txt->down";
7301 $editors_available = editors_get_available();
7302 $active_editors = explode(',', $CFG->texteditors);
7304 $active_editors = array_reverse($active_editors);
7305 foreach ($active_editors as $key=>$editor) {
7306 if (empty($editors_available[$editor])) {
7307 unset($active_editors[$key]);
7308 } else {
7309 $name = $editors_available[$editor];
7310 unset($editors_available[$editor]);
7311 $editors_available[$editor] = $name;
7314 if (empty($active_editors)) {
7315 //$active_editors = array('textarea');
7317 $editors_available = array_reverse($editors_available, true);
7318 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
7319 $return .= $OUTPUT->box_start('generalbox editorsui');
7321 $table = new html_table();
7322 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7323 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7324 $table->id = 'editormanagement';
7325 $table->attributes['class'] = 'admintable generaltable';
7326 $table->data = array();
7328 // iterate through auth plugins and add to the display table
7329 $updowncount = 1;
7330 $editorcount = count($active_editors);
7331 $url = "editors.php?sesskey=" . sesskey();
7332 foreach ($editors_available as $editor => $name) {
7333 // hide/show link
7334 $class = '';
7335 if (in_array($editor, $active_editors)) {
7336 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
7337 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7338 $enabled = true;
7339 $displayname = $name;
7341 else {
7342 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
7343 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7344 $enabled = false;
7345 $displayname = $name;
7346 $class = 'dimmed_text';
7349 // up/down link (only if auth is enabled)
7350 $updown = '';
7351 if ($enabled) {
7352 if ($updowncount > 1) {
7353 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
7354 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7356 else {
7357 $updown .= $OUTPUT->spacer() . '&nbsp;';
7359 if ($updowncount < $editorcount) {
7360 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
7361 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7363 else {
7364 $updown .= $OUTPUT->spacer() . '&nbsp;';
7366 ++ $updowncount;
7369 // settings link
7370 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
7371 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7372 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7373 } else {
7374 $settings = '';
7377 $uninstall = '';
7378 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7379 $uninstall = html_writer::link($uninstallurl, $struninstall);
7382 // Add a row to the table.
7383 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7384 if ($class) {
7385 $row->attributes['class'] = $class;
7387 $table->data[] = $row;
7389 $return .= html_writer::table($table);
7390 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7391 $return .= $OUTPUT->box_end();
7392 return highlight($query, $return);
7397 * Special class for antiviruses administration.
7399 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7402 class admin_setting_manageantiviruses extends admin_setting {
7404 * Calls parent::__construct with specific arguments
7406 public function __construct() {
7407 $this->nosave = true;
7408 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7412 * Always returns true, does nothing
7414 * @return true
7416 public function get_setting() {
7417 return true;
7421 * Always returns true, does nothing
7423 * @return true
7425 public function get_defaultsetting() {
7426 return true;
7430 * Always returns '', does not write anything
7432 * @param string $data Unused
7433 * @return string Always returns ''
7435 public function write_setting($data) {
7436 // Do not write any setting.
7437 return '';
7441 * Checks if $query is one of the available editors
7443 * @param string $query The string to search for
7444 * @return bool Returns true if found, false if not
7446 public function is_related($query) {
7447 if (parent::is_related($query)) {
7448 return true;
7451 $antivirusesavailable = \core\antivirus\manager::get_available();
7452 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7453 if (strpos($antivirus, $query) !== false) {
7454 return true;
7456 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7457 return true;
7460 return false;
7464 * Builds the XHTML to display the control
7466 * @param string $data Unused
7467 * @param string $query
7468 * @return string
7470 public function output_html($data, $query='') {
7471 global $CFG, $OUTPUT;
7473 // Display strings.
7474 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7475 'up', 'down', 'none'));
7476 $struninstall = get_string('uninstallplugin', 'core_admin');
7478 $txt->updown = "$txt->up/$txt->down";
7480 $antivirusesavailable = \core\antivirus\manager::get_available();
7481 $activeantiviruses = explode(',', $CFG->antiviruses);
7483 $activeantiviruses = array_reverse($activeantiviruses);
7484 foreach ($activeantiviruses as $key => $antivirus) {
7485 if (empty($antivirusesavailable[$antivirus])) {
7486 unset($activeantiviruses[$key]);
7487 } else {
7488 $name = $antivirusesavailable[$antivirus];
7489 unset($antivirusesavailable[$antivirus]);
7490 $antivirusesavailable[$antivirus] = $name;
7493 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7494 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7495 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7497 $table = new html_table();
7498 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7499 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7500 $table->id = 'antivirusmanagement';
7501 $table->attributes['class'] = 'admintable generaltable';
7502 $table->data = array();
7504 // Iterate through auth plugins and add to the display table.
7505 $updowncount = 1;
7506 $antiviruscount = count($activeantiviruses);
7507 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7508 foreach ($antivirusesavailable as $antivirus => $name) {
7509 // Hide/show link.
7510 $class = '';
7511 if (in_array($antivirus, $activeantiviruses)) {
7512 $hideshowurl = $baseurl;
7513 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7514 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7515 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7516 $enabled = true;
7517 $displayname = $name;
7518 } else {
7519 $hideshowurl = $baseurl;
7520 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7521 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7522 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7523 $enabled = false;
7524 $displayname = $name;
7525 $class = 'dimmed_text';
7528 // Up/down link.
7529 $updown = '';
7530 if ($enabled) {
7531 if ($updowncount > 1) {
7532 $updownurl = $baseurl;
7533 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7534 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7535 $updown = html_writer::link($updownurl, $updownimg);
7536 } else {
7537 $updownimg = $OUTPUT->spacer();
7539 if ($updowncount < $antiviruscount) {
7540 $updownurl = $baseurl;
7541 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7542 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7543 $updown = html_writer::link($updownurl, $updownimg);
7544 } else {
7545 $updownimg = $OUTPUT->spacer();
7547 ++ $updowncount;
7550 // Settings link.
7551 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7552 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7553 $settings = html_writer::link($eurl, $txt->settings);
7554 } else {
7555 $settings = '';
7558 $uninstall = '';
7559 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7560 $uninstall = html_writer::link($uninstallurl, $struninstall);
7563 // Add a row to the table.
7564 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7565 if ($class) {
7566 $row->attributes['class'] = $class;
7568 $table->data[] = $row;
7570 $return .= html_writer::table($table);
7571 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7572 $return .= $OUTPUT->box_end();
7573 return highlight($query, $return);
7578 * Special class for license administration.
7580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7581 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7582 * @todo MDL-45184 This class will be deleted in Moodle 4.1.
7584 class admin_setting_managelicenses extends admin_setting {
7586 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7587 * @todo MDL-45184 This class will be deleted in Moodle 4.1
7589 public function __construct() {
7590 global $ADMIN;
7592 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7593 DEBUG_DEVELOPER);
7595 // Replace admin setting load with new external page load for tool_licensemanager, if not loaded already.
7596 if (!is_null($ADMIN->locate('licensemanager'))) {
7597 $temp = new admin_externalpage('licensemanager',
7598 get_string('licensemanager', 'tool_licensemanager'),
7599 \tool_licensemanager\helper::get_licensemanager_url());
7601 $ADMIN->add('license', $temp);
7606 * Always returns true, does nothing
7608 * @deprecated since Moodle 3.9 MDL-45184.
7609 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7611 * @return true
7613 public function get_setting() {
7614 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7615 DEBUG_DEVELOPER);
7617 return true;
7621 * Always returns true, does nothing
7623 * @deprecated since Moodle 3.9 MDL-45184.
7624 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7626 * @return true
7628 public function get_defaultsetting() {
7629 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7630 DEBUG_DEVELOPER);
7632 return true;
7636 * Always returns '', does not write anything
7638 * @deprecated since Moodle 3.9 MDL-45184.
7639 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7641 * @return string Always returns ''
7643 public function write_setting($data) {
7644 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7645 DEBUG_DEVELOPER);
7647 // do not write any setting
7648 return '';
7652 * Builds the XHTML to display the control
7654 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7655 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7657 * @param string $data Unused
7658 * @param string $query
7659 * @return string
7661 public function output_html($data, $query='') {
7662 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7663 DEBUG_DEVELOPER);
7665 redirect(\tool_licensemanager\helper::get_licensemanager_url());
7670 * Course formats manager. Allows to enable/disable formats and jump to settings
7672 class admin_setting_manageformats extends admin_setting {
7675 * Calls parent::__construct with specific arguments
7677 public function __construct() {
7678 $this->nosave = true;
7679 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7683 * Always returns true
7685 * @return true
7687 public function get_setting() {
7688 return true;
7692 * Always returns true
7694 * @return true
7696 public function get_defaultsetting() {
7697 return true;
7701 * Always returns '' and doesn't write anything
7703 * @param mixed $data string or array, must not be NULL
7704 * @return string Always returns ''
7706 public function write_setting($data) {
7707 // do not write any setting
7708 return '';
7712 * Search to find if Query is related to format plugin
7714 * @param string $query The string to search for
7715 * @return bool true for related false for not
7717 public function is_related($query) {
7718 if (parent::is_related($query)) {
7719 return true;
7721 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7722 foreach ($formats as $format) {
7723 if (strpos($format->component, $query) !== false ||
7724 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7725 return true;
7728 return false;
7732 * Return XHTML to display control
7734 * @param mixed $data Unused
7735 * @param string $query
7736 * @return string highlight
7738 public function output_html($data, $query='') {
7739 global $CFG, $OUTPUT;
7740 $return = '';
7741 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7742 $return .= $OUTPUT->box_start('generalbox formatsui');
7744 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7746 // display strings
7747 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7748 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7749 $txt->updown = "$txt->up/$txt->down";
7751 $table = new html_table();
7752 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7753 $table->align = array('left', 'center', 'center', 'center', 'center');
7754 $table->attributes['class'] = 'manageformattable generaltable admintable';
7755 $table->data = array();
7757 $cnt = 0;
7758 $defaultformat = get_config('moodlecourse', 'format');
7759 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7760 foreach ($formats as $format) {
7761 $url = new moodle_url('/admin/courseformats.php',
7762 array('sesskey' => sesskey(), 'format' => $format->name));
7763 $isdefault = '';
7764 $class = '';
7765 if ($format->is_enabled()) {
7766 $strformatname = $format->displayname;
7767 if ($defaultformat === $format->name) {
7768 $hideshow = $txt->default;
7769 } else {
7770 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7771 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7773 } else {
7774 $strformatname = $format->displayname;
7775 $class = 'dimmed_text';
7776 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7777 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7779 $updown = '';
7780 if ($cnt) {
7781 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7782 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7783 } else {
7784 $updown .= $spacer;
7786 if ($cnt < count($formats) - 1) {
7787 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7788 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7789 } else {
7790 $updown .= $spacer;
7792 $cnt++;
7793 $settings = '';
7794 if ($format->get_settings_url()) {
7795 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7797 $uninstall = '';
7798 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7799 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7801 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7802 if ($class) {
7803 $row->attributes['class'] = $class;
7805 $table->data[] = $row;
7807 $return .= html_writer::table($table);
7808 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7809 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7810 $return .= $OUTPUT->box_end();
7811 return highlight($query, $return);
7816 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7818 * @package core
7819 * @copyright 2018 Toni Barbera
7820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7822 class admin_setting_managecustomfields extends admin_setting {
7825 * Calls parent::__construct with specific arguments
7827 public function __construct() {
7828 $this->nosave = true;
7829 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7833 * Always returns true
7835 * @return true
7837 public function get_setting() {
7838 return true;
7842 * Always returns true
7844 * @return true
7846 public function get_defaultsetting() {
7847 return true;
7851 * Always returns '' and doesn't write anything
7853 * @param mixed $data string or array, must not be NULL
7854 * @return string Always returns ''
7856 public function write_setting($data) {
7857 // Do not write any setting.
7858 return '';
7862 * Search to find if Query is related to format plugin
7864 * @param string $query The string to search for
7865 * @return bool true for related false for not
7867 public function is_related($query) {
7868 if (parent::is_related($query)) {
7869 return true;
7871 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7872 foreach ($formats as $format) {
7873 if (strpos($format->component, $query) !== false ||
7874 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7875 return true;
7878 return false;
7882 * Return XHTML to display control
7884 * @param mixed $data Unused
7885 * @param string $query
7886 * @return string highlight
7888 public function output_html($data, $query='') {
7889 global $CFG, $OUTPUT;
7890 $return = '';
7891 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7892 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7894 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7896 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7897 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7898 $txt->updown = "$txt->up/$txt->down";
7900 $table = new html_table();
7901 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7902 $table->align = array('left', 'center', 'center', 'center');
7903 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7904 $table->data = array();
7906 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7907 foreach ($fields as $field) {
7908 $url = new moodle_url('/admin/customfields.php',
7909 array('sesskey' => sesskey(), 'field' => $field->name));
7911 if ($field->is_enabled()) {
7912 $strfieldname = $field->displayname;
7913 $class = '';
7914 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7915 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7916 } else {
7917 $strfieldname = $field->displayname;
7918 $class = 'dimmed_text';
7919 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7920 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7922 $settings = '';
7923 if ($field->get_settings_url()) {
7924 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7926 $uninstall = '';
7927 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7928 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7930 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7931 $row->attributes['class'] = $class;
7932 $table->data[] = $row;
7934 $return .= html_writer::table($table);
7935 $return .= $OUTPUT->box_end();
7936 return highlight($query, $return);
7941 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7943 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7946 class admin_setting_managedataformats extends admin_setting {
7949 * Calls parent::__construct with specific arguments
7951 public function __construct() {
7952 $this->nosave = true;
7953 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7957 * Always returns true
7959 * @return true
7961 public function get_setting() {
7962 return true;
7966 * Always returns true
7968 * @return true
7970 public function get_defaultsetting() {
7971 return true;
7975 * Always returns '' and doesn't write anything
7977 * @param mixed $data string or array, must not be NULL
7978 * @return string Always returns ''
7980 public function write_setting($data) {
7981 // Do not write any setting.
7982 return '';
7986 * Search to find if Query is related to format plugin
7988 * @param string $query The string to search for
7989 * @return bool true for related false for not
7991 public function is_related($query) {
7992 if (parent::is_related($query)) {
7993 return true;
7995 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7996 foreach ($formats as $format) {
7997 if (strpos($format->component, $query) !== false ||
7998 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7999 return true;
8002 return false;
8006 * Return XHTML to display control
8008 * @param mixed $data Unused
8009 * @param string $query
8010 * @return string highlight
8012 public function output_html($data, $query='') {
8013 global $CFG, $OUTPUT;
8014 $return = '';
8016 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
8018 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
8019 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8020 $txt->updown = "$txt->up/$txt->down";
8022 $table = new html_table();
8023 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
8024 $table->align = array('left', 'center', 'center', 'center', 'center');
8025 $table->attributes['class'] = 'manageformattable generaltable admintable';
8026 $table->data = array();
8028 $cnt = 0;
8029 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8030 $totalenabled = 0;
8031 foreach ($formats as $format) {
8032 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
8033 $totalenabled++;
8036 foreach ($formats as $format) {
8037 $status = $format->get_status();
8038 $url = new moodle_url('/admin/dataformats.php',
8039 array('sesskey' => sesskey(), 'name' => $format->name));
8041 $class = '';
8042 if ($format->is_enabled()) {
8043 $strformatname = $format->displayname;
8044 if ($totalenabled == 1&& $format->is_enabled()) {
8045 $hideshow = '';
8046 } else {
8047 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8048 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8050 } else {
8051 $class = 'dimmed_text';
8052 $strformatname = $format->displayname;
8053 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8054 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8057 $updown = '';
8058 if ($cnt) {
8059 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8060 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8061 } else {
8062 $updown .= $spacer;
8064 if ($cnt < count($formats) - 1) {
8065 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8066 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8067 } else {
8068 $updown .= $spacer;
8071 $uninstall = '';
8072 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8073 $uninstall = get_string('status_missing', 'core_plugin');
8074 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8075 $uninstall = get_string('status_new', 'core_plugin');
8076 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
8077 if ($totalenabled != 1 || !$format->is_enabled()) {
8078 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8082 $settings = '';
8083 if ($format->get_settings_url()) {
8084 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
8087 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
8088 if ($class) {
8089 $row->attributes['class'] = $class;
8091 $table->data[] = $row;
8092 $cnt++;
8094 $return .= html_writer::table($table);
8095 return highlight($query, $return);
8100 * Special class for filter administration.
8102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8104 class admin_page_managefilters extends admin_externalpage {
8106 * Calls parent::__construct with specific arguments
8108 public function __construct() {
8109 global $CFG;
8110 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
8114 * Searches all installed filters for specified filter
8116 * @param string $query The filter(string) to search for
8117 * @param string $query
8119 public function search($query) {
8120 global $CFG;
8121 if ($result = parent::search($query)) {
8122 return $result;
8125 $found = false;
8126 $filternames = filter_get_all_installed();
8127 foreach ($filternames as $path => $strfiltername) {
8128 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
8129 $found = true;
8130 break;
8132 if (strpos($path, $query) !== false) {
8133 $found = true;
8134 break;
8138 if ($found) {
8139 $result = new stdClass;
8140 $result->page = $this;
8141 $result->settings = array();
8142 return array($this->name => $result);
8143 } else {
8144 return array();
8150 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8151 * Requires a get_rank method on the plugininfo class for sorting.
8153 * @copyright 2017 Damyon Wiese
8154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8156 abstract class admin_setting_manage_plugins extends admin_setting {
8159 * Get the admin settings section name (just a unique string)
8161 * @return string
8163 public function get_section_name() {
8164 return 'manage' . $this->get_plugin_type() . 'plugins';
8168 * Get the admin settings section title (use get_string).
8170 * @return string
8172 abstract public function get_section_title();
8175 * Get the type of plugin to manage.
8177 * @return string
8179 abstract public function get_plugin_type();
8182 * Get the name of the second column.
8184 * @return string
8186 public function get_info_column_name() {
8187 return '';
8191 * Get the type of plugin to manage.
8193 * @param plugininfo The plugin info class.
8194 * @return string
8196 abstract public function get_info_column($plugininfo);
8199 * Calls parent::__construct with specific arguments
8201 public function __construct() {
8202 $this->nosave = true;
8203 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8207 * Always returns true, does nothing
8209 * @return true
8211 public function get_setting() {
8212 return true;
8216 * Always returns true, does nothing
8218 * @return true
8220 public function get_defaultsetting() {
8221 return true;
8225 * Always returns '', does not write anything
8227 * @param mixed $data
8228 * @return string Always returns ''
8230 public function write_setting($data) {
8231 // Do not write any setting.
8232 return '';
8236 * Checks if $query is one of the available plugins of this type
8238 * @param string $query The string to search for
8239 * @return bool Returns true if found, false if not
8241 public function is_related($query) {
8242 if (parent::is_related($query)) {
8243 return true;
8246 $query = core_text::strtolower($query);
8247 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
8248 foreach ($plugins as $name => $plugin) {
8249 $localised = $plugin->displayname;
8250 if (strpos(core_text::strtolower($name), $query) !== false) {
8251 return true;
8253 if (strpos(core_text::strtolower($localised), $query) !== false) {
8254 return true;
8257 return false;
8261 * The URL for the management page for this plugintype.
8263 * @return moodle_url
8265 protected function get_manage_url() {
8266 return new moodle_url('/admin/updatesetting.php');
8270 * Builds the HTML to display the control.
8272 * @param string $data Unused
8273 * @param string $query
8274 * @return string
8276 public function output_html($data, $query = '') {
8277 global $CFG, $OUTPUT, $DB, $PAGE;
8279 $context = (object) [
8280 'manageurl' => new moodle_url($this->get_manage_url(), [
8281 'type' => $this->get_plugin_type(),
8282 'sesskey' => sesskey(),
8284 'infocolumnname' => $this->get_info_column_name(),
8285 'plugins' => [],
8288 $pluginmanager = core_plugin_manager::instance();
8289 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8290 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8291 $plugins = array_merge($enabled, $allplugins);
8292 foreach ($plugins as $key => $plugin) {
8293 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
8295 $pluginkey = (object) [
8296 'plugin' => $plugin->displayname,
8297 'enabled' => $plugin->is_enabled(),
8298 'togglelink' => '',
8299 'moveuplink' => '',
8300 'movedownlink' => '',
8301 'settingslink' => $plugin->get_settings_url(),
8302 'uninstalllink' => '',
8303 'info' => '',
8306 // Enable/Disable link.
8307 $togglelink = new moodle_url($pluginlink);
8308 if ($plugin->is_enabled()) {
8309 $toggletarget = false;
8310 $togglelink->param('action', 'disable');
8312 if (count($context->plugins)) {
8313 // This is not the first plugin.
8314 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
8317 if (count($enabled) > count($context->plugins) + 1) {
8318 // This is not the last plugin.
8319 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
8322 $pluginkey->info = $this->get_info_column($plugin);
8323 } else {
8324 $toggletarget = true;
8325 $togglelink->param('action', 'enable');
8328 $pluginkey->toggletarget = $toggletarget;
8329 $pluginkey->togglelink = $togglelink;
8331 $frankenstyle = $plugin->type . '_' . $plugin->name;
8332 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8333 // This plugin supports uninstallation.
8334 $pluginkey->uninstalllink = $uninstalllink;
8337 if (!empty($this->get_info_column_name())) {
8338 // This plugintype has an info column.
8339 $pluginkey->info = $this->get_info_column($plugin);
8342 $context->plugins[] = $pluginkey;
8345 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8346 return highlight($query, $str);
8351 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8352 * Requires a get_rank method on the plugininfo class for sorting.
8354 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8355 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8357 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8358 public function get_section_title() {
8359 return get_string('type_fileconverter_plural', 'plugin');
8362 public function get_plugin_type() {
8363 return 'fileconverter';
8366 public function get_info_column_name() {
8367 return get_string('supportedconversions', 'plugin');
8370 public function get_info_column($plugininfo) {
8371 return $plugininfo->get_supported_conversions();
8376 * Special class for media player plugins management.
8378 * @copyright 2016 Marina Glancy
8379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8381 class admin_setting_managemediaplayers extends admin_setting {
8383 * Calls parent::__construct with specific arguments
8385 public function __construct() {
8386 $this->nosave = true;
8387 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8391 * Always returns true, does nothing
8393 * @return true
8395 public function get_setting() {
8396 return true;
8400 * Always returns true, does nothing
8402 * @return true
8404 public function get_defaultsetting() {
8405 return true;
8409 * Always returns '', does not write anything
8411 * @param mixed $data
8412 * @return string Always returns ''
8414 public function write_setting($data) {
8415 // Do not write any setting.
8416 return '';
8420 * Checks if $query is one of the available enrol plugins
8422 * @param string $query The string to search for
8423 * @return bool Returns true if found, false if not
8425 public function is_related($query) {
8426 if (parent::is_related($query)) {
8427 return true;
8430 $query = core_text::strtolower($query);
8431 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8432 foreach ($plugins as $name => $plugin) {
8433 $localised = $plugin->displayname;
8434 if (strpos(core_text::strtolower($name), $query) !== false) {
8435 return true;
8437 if (strpos(core_text::strtolower($localised), $query) !== false) {
8438 return true;
8441 return false;
8445 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8446 * @return \core\plugininfo\media[]
8448 protected function get_sorted_plugins() {
8449 $pluginmanager = core_plugin_manager::instance();
8451 $plugins = $pluginmanager->get_plugins_of_type('media');
8452 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8454 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8455 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8457 $order = array_values($enabledplugins);
8458 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8460 $sortedplugins = array();
8461 foreach ($order as $name) {
8462 $sortedplugins[$name] = $plugins[$name];
8465 return $sortedplugins;
8469 * Builds the XHTML to display the control
8471 * @param string $data Unused
8472 * @param string $query
8473 * @return string
8475 public function output_html($data, $query='') {
8476 global $CFG, $OUTPUT, $DB, $PAGE;
8478 // Display strings.
8479 $strup = get_string('up');
8480 $strdown = get_string('down');
8481 $strsettings = get_string('settings');
8482 $strenable = get_string('enable');
8483 $strdisable = get_string('disable');
8484 $struninstall = get_string('uninstallplugin', 'core_admin');
8485 $strversion = get_string('version');
8486 $strname = get_string('name');
8487 $strsupports = get_string('supports', 'core_media');
8489 $pluginmanager = core_plugin_manager::instance();
8491 $plugins = $this->get_sorted_plugins();
8492 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8494 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8496 $table = new html_table();
8497 $table->head = array($strname, $strsupports, $strversion,
8498 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8499 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8500 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8501 $table->id = 'mediaplayerplugins';
8502 $table->attributes['class'] = 'admintable generaltable';
8503 $table->data = array();
8505 // Iterate through media plugins and add to the display table.
8506 $updowncount = 1;
8507 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8508 $printed = array();
8509 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8511 $usedextensions = [];
8512 foreach ($plugins as $name => $plugin) {
8513 $url->param('media', $name);
8514 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8515 $version = $plugininfo->versiondb;
8516 $supports = $plugininfo->supports($usedextensions);
8518 // Hide/show links.
8519 $class = '';
8520 if (!$plugininfo->is_installed_and_upgraded()) {
8521 $hideshow = '';
8522 $enabled = false;
8523 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8524 } else {
8525 $enabled = $plugininfo->is_enabled();
8526 if ($enabled) {
8527 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8528 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8529 } else {
8530 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8531 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8532 $class = 'dimmed_text';
8534 $displayname = $plugin->displayname;
8535 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8536 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8539 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8540 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8541 } else {
8542 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8545 // Up/down link (only if enrol is enabled).
8546 $updown = '';
8547 if ($enabled) {
8548 if ($updowncount > 1) {
8549 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8550 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8551 } else {
8552 $updown = $spacer;
8554 if ($updowncount < count($enabledplugins)) {
8555 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8556 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8557 } else {
8558 $updown .= $spacer;
8560 ++$updowncount;
8563 $uninstall = '';
8564 $status = $plugininfo->get_status();
8565 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8566 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8568 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8569 $uninstall = get_string('status_new', 'core_plugin');
8570 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8571 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8574 $settings = '';
8575 if ($plugininfo->get_settings_url()) {
8576 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8579 // Add a row to the table.
8580 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8581 if ($class) {
8582 $row->attributes['class'] = $class;
8584 $table->data[] = $row;
8586 $printed[$name] = true;
8589 $return .= html_writer::table($table);
8590 $return .= $OUTPUT->box_end();
8591 return highlight($query, $return);
8597 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8599 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8602 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8605 * Calls parent::__construct with specific arguments
8607 public function __construct() {
8608 $this->nosave = true;
8609 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8613 * Always returns true
8615 * @return true
8617 public function get_setting() {
8618 return true;
8622 * Always returns true
8624 * @return true
8626 public function get_defaultsetting() {
8627 return true;
8631 * Always returns '' and doesn't write anything
8633 * @param mixed $data string or array, must not be NULL
8634 * @return string Always returns ''
8636 public function write_setting($data) {
8637 // Do not write any setting.
8638 return '';
8642 * Search to find if Query is related to content bank plugin
8644 * @param string $query The string to search for
8645 * @return bool true for related false for not
8647 public function is_related($query) {
8648 if (parent::is_related($query)) {
8649 return true;
8651 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8652 foreach ($types as $type) {
8653 if (strpos($type->component, $query) !== false ||
8654 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8655 return true;
8658 return false;
8662 * Return XHTML to display control
8664 * @param mixed $data Unused
8665 * @param string $query
8666 * @return string highlight
8668 public function output_html($data, $query='') {
8669 global $CFG, $OUTPUT;
8670 $return = '';
8672 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8673 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8674 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8676 $table = new html_table();
8677 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8678 $table->align = array('left', 'center', 'center', 'center', 'center');
8679 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8680 $table->data = array();
8681 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8683 $totalenabled = 0;
8684 $count = 0;
8685 foreach ($types as $type) {
8686 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8687 $totalenabled++;
8691 foreach ($types as $type) {
8692 $url = new moodle_url('/admin/contentbank.php',
8693 array('sesskey' => sesskey(), 'name' => $type->name));
8695 $class = '';
8696 $strtypename = $type->displayname;
8697 if ($type->is_enabled()) {
8698 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8699 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8700 } else {
8701 $class = 'dimmed_text';
8702 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8703 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8706 $updown = '';
8707 if ($count) {
8708 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8709 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8710 } else {
8711 $updown .= $spacer;
8713 if ($count < count($types) - 1) {
8714 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8715 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8716 } else {
8717 $updown .= $spacer;
8720 $settings = '';
8721 if ($type->get_settings_url()) {
8722 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8725 $uninstall = '';
8726 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8727 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8730 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8731 if ($class) {
8732 $row->attributes['class'] = $class;
8734 $table->data[] = $row;
8735 $count++;
8737 $return .= html_writer::table($table);
8738 return highlight($query, $return);
8743 * Initialise admin page - this function does require login and permission
8744 * checks specified in page definition.
8746 * This function must be called on each admin page before other code.
8748 * @global moodle_page $PAGE
8750 * @param string $section name of page
8751 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8752 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8753 * added to the turn blocks editing on/off form, so this page reloads correctly.
8754 * @param string $actualurl if the actual page being viewed is not the normal one for this
8755 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8756 * @param array $options Additional options that can be specified for page setup.
8757 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8759 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8760 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8762 $PAGE->set_context(null); // hack - set context to something, by default to system context
8764 $site = get_site();
8765 require_login(null, false);
8767 if (!empty($options['pagelayout'])) {
8768 // A specific page layout has been requested.
8769 $PAGE->set_pagelayout($options['pagelayout']);
8770 } else if ($section === 'upgradesettings') {
8771 $PAGE->set_pagelayout('maintenance');
8772 } else {
8773 $PAGE->set_pagelayout('admin');
8776 $adminroot = admin_get_root(false, false); // settings not required for external pages
8777 $extpage = $adminroot->locate($section, true);
8779 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8780 // The requested section isn't in the admin tree
8781 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8782 if (!has_capability('moodle/site:config', context_system::instance())) {
8783 // The requested section could depend on a different capability
8784 // but most likely the user has inadequate capabilities
8785 print_error('accessdenied', 'admin');
8786 } else {
8787 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8791 // this eliminates our need to authenticate on the actual pages
8792 if (!$extpage->check_access()) {
8793 print_error('accessdenied', 'admin');
8794 die;
8797 navigation_node::require_admin_tree();
8799 // $PAGE->set_extra_button($extrabutton); TODO
8801 if (!$actualurl) {
8802 $actualurl = $extpage->url;
8805 $PAGE->set_url($actualurl, $extraurlparams);
8806 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8807 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8810 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8811 // During initial install.
8812 $strinstallation = get_string('installation', 'install');
8813 $strsettings = get_string('settings');
8814 $PAGE->navbar->add($strsettings);
8815 $PAGE->set_title($strinstallation);
8816 $PAGE->set_heading($strinstallation);
8817 $PAGE->set_cacheable(false);
8818 return;
8821 // Locate the current item on the navigation and make it active when found.
8822 $path = $extpage->path;
8823 $node = $PAGE->settingsnav;
8824 while ($node && count($path) > 0) {
8825 $node = $node->get(array_pop($path));
8827 if ($node) {
8828 $node->make_active();
8831 // Normal case.
8832 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8833 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8834 $USER->editing = $adminediting;
8837 $visiblepathtosection = array_reverse($extpage->visiblepath);
8839 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8840 if ($PAGE->user_is_editing()) {
8841 $caption = get_string('blockseditoff');
8842 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8843 } else {
8844 $caption = get_string('blocksediton');
8845 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8847 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8850 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8851 $PAGE->set_heading($SITE->fullname);
8853 // prevent caching in nav block
8854 $PAGE->navigation->clear_cache();
8858 * Returns the reference to admin tree root
8860 * @return object admin_root object
8862 function admin_get_root($reload=false, $requirefulltree=true) {
8863 global $CFG, $DB, $OUTPUT, $ADMIN;
8865 if (is_null($ADMIN)) {
8866 // create the admin tree!
8867 $ADMIN = new admin_root($requirefulltree);
8870 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8871 $ADMIN->purge_children($requirefulltree);
8874 if (!$ADMIN->loaded) {
8875 // we process this file first to create categories first and in correct order
8876 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8878 // now we process all other files in admin/settings to build the admin tree
8879 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8880 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8881 continue;
8883 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8884 // plugins are loaded last - they may insert pages anywhere
8885 continue;
8887 require($file);
8889 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8891 $ADMIN->loaded = true;
8894 return $ADMIN;
8897 /// settings utility functions
8900 * This function applies default settings.
8901 * Because setting the defaults of some settings can enable other settings,
8902 * this function is called recursively until no more new settings are found.
8904 * @param object $node, NULL means complete tree, null by default
8905 * @param bool $unconditional if true overrides all values with defaults, true by default
8906 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8907 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8908 * @return array $settingsoutput The names and values of the changed settings
8910 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8911 $counter = 0;
8913 if (is_null($node)) {
8914 core_plugin_manager::reset_caches();
8915 $node = admin_get_root(true, true);
8916 $counter = count($settingsoutput);
8919 if ($node instanceof admin_category) {
8920 $entries = array_keys($node->children);
8921 foreach ($entries as $entry) {
8922 $settingsoutput = admin_apply_default_settings(
8923 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8927 } else if ($node instanceof admin_settingpage) {
8928 foreach ($node->settings as $setting) {
8929 if (!$unconditional && !is_null($setting->get_setting())) {
8930 // Do not override existing defaults.
8931 continue;
8933 $defaultsetting = $setting->get_defaultsetting();
8934 if (is_null($defaultsetting)) {
8935 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8936 continue;
8939 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8941 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8942 $admindefaultsettings[$settingname] = $settingname;
8943 $settingsoutput[$settingname] = $defaultsetting;
8945 // Set the default for this setting.
8946 $setting->write_setting($defaultsetting);
8947 $setting->write_setting_flags(null);
8948 } else {
8949 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8954 // Call this function recursively until all settings are processed.
8955 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8956 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8958 // Just in case somebody modifies the list of active plugins directly.
8959 core_plugin_manager::reset_caches();
8961 return $settingsoutput;
8965 * Store changed settings, this function updates the errors variable in $ADMIN
8967 * @param object $formdata from form
8968 * @return int number of changed settings
8970 function admin_write_settings($formdata) {
8971 global $CFG, $SITE, $DB;
8973 $olddbsessions = !empty($CFG->dbsessions);
8974 $formdata = (array)$formdata;
8976 $data = array();
8977 foreach ($formdata as $fullname=>$value) {
8978 if (strpos($fullname, 's_') !== 0) {
8979 continue; // not a config value
8981 $data[$fullname] = $value;
8984 $adminroot = admin_get_root();
8985 $settings = admin_find_write_settings($adminroot, $data);
8987 $count = 0;
8988 foreach ($settings as $fullname=>$setting) {
8989 /** @var $setting admin_setting */
8990 $original = $setting->get_setting();
8991 $error = $setting->write_setting($data[$fullname]);
8992 if ($error !== '') {
8993 $adminroot->errors[$fullname] = new stdClass();
8994 $adminroot->errors[$fullname]->data = $data[$fullname];
8995 $adminroot->errors[$fullname]->id = $setting->get_id();
8996 $adminroot->errors[$fullname]->error = $error;
8997 } else {
8998 $setting->write_setting_flags($data);
9000 if ($setting->post_write_settings($original)) {
9001 $count++;
9005 if ($olddbsessions != !empty($CFG->dbsessions)) {
9006 require_logout();
9009 // Now update $SITE - just update the fields, in case other people have a
9010 // a reference to it (e.g. $PAGE, $COURSE).
9011 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
9012 foreach (get_object_vars($newsite) as $field => $value) {
9013 $SITE->$field = $value;
9016 // now reload all settings - some of them might depend on the changed
9017 admin_get_root(true);
9018 return $count;
9022 * Internal recursive function - finds all settings from submitted form
9024 * @param object $node Instance of admin_category, or admin_settingpage
9025 * @param array $data
9026 * @return array
9028 function admin_find_write_settings($node, $data) {
9029 $return = array();
9031 if (empty($data)) {
9032 return $return;
9035 if ($node instanceof admin_category) {
9036 if ($node->check_access()) {
9037 $entries = array_keys($node->children);
9038 foreach ($entries as $entry) {
9039 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
9043 } else if ($node instanceof admin_settingpage) {
9044 if ($node->check_access()) {
9045 foreach ($node->settings as $setting) {
9046 $fullname = $setting->get_full_name();
9047 if (array_key_exists($fullname, $data)) {
9048 $return[$fullname] = $setting;
9055 return $return;
9059 * Internal function - prints the search results
9061 * @param string $query String to search for
9062 * @return string empty or XHTML
9064 function admin_search_settings_html($query) {
9065 global $CFG, $OUTPUT, $PAGE;
9067 if (core_text::strlen($query) < 2) {
9068 return '';
9070 $query = core_text::strtolower($query);
9072 $adminroot = admin_get_root();
9073 $findings = $adminroot->search($query);
9074 $savebutton = false;
9076 $tpldata = (object) [
9077 'actionurl' => $PAGE->url->out(false),
9078 'results' => [],
9079 'sesskey' => sesskey(),
9082 foreach ($findings as $found) {
9083 $page = $found->page;
9084 $settings = $found->settings;
9085 if ($page->is_hidden()) {
9086 // hidden pages are not displayed in search results
9087 continue;
9090 $heading = highlight($query, $page->visiblename);
9091 $headingurl = null;
9092 if ($page instanceof admin_externalpage) {
9093 $headingurl = new moodle_url($page->url);
9094 } else if ($page instanceof admin_settingpage) {
9095 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
9096 } else {
9097 continue;
9100 // Locate the page in the admin root and populate its visiblepath attribute.
9101 $path = array();
9102 $located = $adminroot->locate($page->name, true);
9103 if ($located) {
9104 foreach ($located->visiblepath as $pathitem) {
9105 array_unshift($path, (string) $pathitem);
9109 $sectionsettings = [];
9110 if (!empty($settings)) {
9111 foreach ($settings as $setting) {
9112 if (empty($setting->nosave)) {
9113 $savebutton = true;
9115 $fullname = $setting->get_full_name();
9116 if (array_key_exists($fullname, $adminroot->errors)) {
9117 $data = $adminroot->errors[$fullname]->data;
9118 } else {
9119 $data = $setting->get_setting();
9120 // do not use defaults if settings not available - upgradesettings handles the defaults!
9122 $sectionsettings[] = $setting->output_html($data, $query);
9126 $tpldata->results[] = (object) [
9127 'title' => $heading,
9128 'path' => $path,
9129 'url' => $headingurl->out(false),
9130 'settings' => $sectionsettings
9134 $tpldata->showsave = $savebutton;
9135 $tpldata->hasresults = !empty($tpldata->results);
9137 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
9141 * Internal function - returns arrays of html pages with uninitialised settings
9143 * @param object $node Instance of admin_category or admin_settingpage
9144 * @return array
9146 function admin_output_new_settings_by_page($node) {
9147 global $OUTPUT;
9148 $return = array();
9150 if ($node instanceof admin_category) {
9151 $entries = array_keys($node->children);
9152 foreach ($entries as $entry) {
9153 $return += admin_output_new_settings_by_page($node->children[$entry]);
9156 } else if ($node instanceof admin_settingpage) {
9157 $newsettings = array();
9158 foreach ($node->settings as $setting) {
9159 if (is_null($setting->get_setting())) {
9160 $newsettings[] = $setting;
9163 if (count($newsettings) > 0) {
9164 $adminroot = admin_get_root();
9165 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
9166 $page .= '<fieldset class="adminsettings">'."\n";
9167 foreach ($newsettings as $setting) {
9168 $fullname = $setting->get_full_name();
9169 if (array_key_exists($fullname, $adminroot->errors)) {
9170 $data = $adminroot->errors[$fullname]->data;
9171 } else {
9172 $data = $setting->get_setting();
9173 if (is_null($data)) {
9174 $data = $setting->get_defaultsetting();
9177 $page .= '<div class="clearer"><!-- --></div>'."\n";
9178 $page .= $setting->output_html($data);
9180 $page .= '</fieldset>';
9181 $return[$node->name] = $page;
9185 return $return;
9189 * Format admin settings
9191 * @param object $setting
9192 * @param string $title label element
9193 * @param string $form form fragment, html code - not highlighted automatically
9194 * @param string $description
9195 * @param mixed $label link label to id, true by default or string being the label to connect it to
9196 * @param string $warning warning text
9197 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9198 * @param string $query search query to be highlighted
9199 * @return string XHTML
9201 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9202 global $CFG, $OUTPUT;
9204 $context = (object) [
9205 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9206 'fullname' => $setting->get_full_name(),
9209 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9210 if ($label === true) {
9211 $context->labelfor = $setting->get_id();
9212 } else if ($label === false) {
9213 $context->labelfor = '';
9214 } else {
9215 $context->labelfor = $label;
9218 $form .= $setting->output_setting_flags();
9220 $context->warning = $warning;
9221 $context->override = '';
9222 if (empty($setting->plugin)) {
9223 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
9224 $context->override = get_string('configoverride', 'admin');
9226 } else {
9227 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9228 $context->override = get_string('configoverride', 'admin');
9232 $defaults = array();
9233 if (!is_null($defaultinfo)) {
9234 if ($defaultinfo === '') {
9235 $defaultinfo = get_string('emptysettingvalue', 'admin');
9237 $defaults[] = $defaultinfo;
9240 $context->default = null;
9241 $setting->get_setting_flag_defaults($defaults);
9242 if (!empty($defaults)) {
9243 $defaultinfo = implode(', ', $defaults);
9244 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9245 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9249 $context->error = '';
9250 $adminroot = admin_get_root();
9251 if (array_key_exists($context->fullname, $adminroot->errors)) {
9252 $context->error = $adminroot->errors[$context->fullname]->error;
9255 if ($dependenton = $setting->get_dependent_on()) {
9256 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9259 $context->id = 'admin-' . $setting->name;
9260 $context->title = highlightfast($query, $title);
9261 $context->name = highlightfast($query, $context->name);
9262 $context->description = highlight($query, markdown_to_html($description));
9263 $context->element = $form;
9264 $context->forceltr = $setting->get_force_ltr();
9265 $context->customcontrol = $setting->has_custom_form_control();
9267 return $OUTPUT->render_from_template('core_admin/setting', $context);
9271 * Based on find_new_settings{@link ()} in upgradesettings.php
9272 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9274 * @param object $node Instance of admin_category, or admin_settingpage
9275 * @return boolean true if any settings haven't been initialised, false if they all have
9277 function any_new_admin_settings($node) {
9279 if ($node instanceof admin_category) {
9280 $entries = array_keys($node->children);
9281 foreach ($entries as $entry) {
9282 if (any_new_admin_settings($node->children[$entry])) {
9283 return true;
9287 } else if ($node instanceof admin_settingpage) {
9288 foreach ($node->settings as $setting) {
9289 if ($setting->get_setting() === NULL) {
9290 return true;
9295 return false;
9299 * Given a table and optionally a column name should replaces be done?
9301 * @param string $table name
9302 * @param string $column name
9303 * @return bool success or fail
9305 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9307 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9308 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9309 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9311 // Additional skip tables.
9312 if (!empty($additionalskiptables)) {
9313 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9316 // Don't process these.
9317 if (in_array($table, $skiptables)) {
9318 return false;
9321 // To be safe never replace inside a table that looks related to logging.
9322 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9323 return false;
9326 // Do column based exclusions.
9327 if (!empty($column)) {
9328 // Don't touch anything that looks like a hash.
9329 if (preg_match('/hash$/', $column)) {
9330 return false;
9334 return true;
9338 * Moved from admin/replace.php so that we can use this in cron
9340 * @param string $search string to look for
9341 * @param string $replace string to replace
9342 * @return bool success or fail
9344 function db_replace($search, $replace, $additionalskiptables = '') {
9345 global $DB, $CFG, $OUTPUT;
9347 // Turn off time limits, sometimes upgrades can be slow.
9348 core_php_time_limit::raise();
9350 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9351 return false;
9353 foreach ($tables as $table) {
9355 if (!db_should_replace($table, '', $additionalskiptables)) {
9356 continue;
9359 if ($columns = $DB->get_columns($table)) {
9360 $DB->set_debug(true);
9361 foreach ($columns as $column) {
9362 if (!db_should_replace($table, $column->name)) {
9363 continue;
9365 $DB->replace_all_text($table, $column, $search, $replace);
9367 $DB->set_debug(false);
9371 // delete modinfo caches
9372 rebuild_course_cache(0, true);
9374 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9375 $blocks = core_component::get_plugin_list('block');
9376 foreach ($blocks as $blockname=>$fullblock) {
9377 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9378 continue;
9381 if (!is_readable($fullblock.'/lib.php')) {
9382 continue;
9385 $function = 'block_'.$blockname.'_global_db_replace';
9386 include_once($fullblock.'/lib.php');
9387 if (!function_exists($function)) {
9388 continue;
9391 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9392 $function($search, $replace);
9393 echo $OUTPUT->notification("...finished", 'notifysuccess');
9396 // Trigger an event.
9397 $eventargs = [
9398 'context' => context_system::instance(),
9399 'other' => [
9400 'search' => $search,
9401 'replace' => $replace
9404 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9405 $event->trigger();
9407 purge_all_caches();
9409 return true;
9413 * Manage repository settings
9415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9417 class admin_setting_managerepository extends admin_setting {
9418 /** @var string */
9419 private $baseurl;
9422 * calls parent::__construct with specific arguments
9424 public function __construct() {
9425 global $CFG;
9426 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9427 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9431 * Always returns true, does nothing
9433 * @return true
9435 public function get_setting() {
9436 return true;
9440 * Always returns true does nothing
9442 * @return true
9444 public function get_defaultsetting() {
9445 return true;
9449 * Always returns s_managerepository
9451 * @return string Always return 's_managerepository'
9453 public function get_full_name() {
9454 return 's_managerepository';
9458 * Always returns '' doesn't do anything
9460 public function write_setting($data) {
9461 $url = $this->baseurl . '&amp;new=' . $data;
9462 return '';
9463 // TODO
9464 // Should not use redirect and exit here
9465 // Find a better way to do this.
9466 // redirect($url);
9467 // exit;
9471 * Searches repository plugins for one that matches $query
9473 * @param string $query The string to search for
9474 * @return bool true if found, false if not
9476 public function is_related($query) {
9477 if (parent::is_related($query)) {
9478 return true;
9481 $repositories= core_component::get_plugin_list('repository');
9482 foreach ($repositories as $p => $dir) {
9483 if (strpos($p, $query) !== false) {
9484 return true;
9487 foreach (repository::get_types() as $instance) {
9488 $title = $instance->get_typename();
9489 if (strpos(core_text::strtolower($title), $query) !== false) {
9490 return true;
9493 return false;
9497 * Helper function that generates a moodle_url object
9498 * relevant to the repository
9501 function repository_action_url($repository) {
9502 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9506 * Builds XHTML to display the control
9508 * @param string $data Unused
9509 * @param string $query
9510 * @return string XHTML
9512 public function output_html($data, $query='') {
9513 global $CFG, $USER, $OUTPUT;
9515 // Get strings that are used
9516 $strshow = get_string('on', 'repository');
9517 $strhide = get_string('off', 'repository');
9518 $strdelete = get_string('disabled', 'repository');
9520 $actionchoicesforexisting = array(
9521 'show' => $strshow,
9522 'hide' => $strhide,
9523 'delete' => $strdelete
9526 $actionchoicesfornew = array(
9527 'newon' => $strshow,
9528 'newoff' => $strhide,
9529 'delete' => $strdelete
9532 $return = '';
9533 $return .= $OUTPUT->box_start('generalbox');
9535 // Set strings that are used multiple times
9536 $settingsstr = get_string('settings');
9537 $disablestr = get_string('disable');
9539 // Table to list plug-ins
9540 $table = new html_table();
9541 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9542 $table->align = array('left', 'center', 'center', 'center', 'center');
9543 $table->data = array();
9545 // Get list of used plug-ins
9546 $repositorytypes = repository::get_types();
9547 if (!empty($repositorytypes)) {
9548 // Array to store plugins being used
9549 $alreadyplugins = array();
9550 $totalrepositorytypes = count($repositorytypes);
9551 $updowncount = 1;
9552 foreach ($repositorytypes as $i) {
9553 $settings = '';
9554 $typename = $i->get_typename();
9555 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9556 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9557 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9559 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9560 // Calculate number of instances in order to display them for the Moodle administrator
9561 if (!empty($instanceoptionnames)) {
9562 $params = array();
9563 $params['context'] = array(context_system::instance());
9564 $params['onlyvisible'] = false;
9565 $params['type'] = $typename;
9566 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9567 // site instances
9568 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9569 $params['context'] = array();
9570 $instances = repository::static_function($typename, 'get_instances', $params);
9571 $courseinstances = array();
9572 $userinstances = array();
9574 foreach ($instances as $instance) {
9575 $repocontext = context::instance_by_id($instance->instance->contextid);
9576 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9577 $courseinstances[] = $instance;
9578 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9579 $userinstances[] = $instance;
9582 // course instances
9583 $instancenumber = count($courseinstances);
9584 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9586 // user private instances
9587 $instancenumber = count($userinstances);
9588 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9589 } else {
9590 $admininstancenumbertext = "";
9591 $courseinstancenumbertext = "";
9592 $userinstancenumbertext = "";
9595 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9597 $settings .= $OUTPUT->container_start('mdl-left');
9598 $settings .= '<br/>';
9599 $settings .= $admininstancenumbertext;
9600 $settings .= '<br/>';
9601 $settings .= $courseinstancenumbertext;
9602 $settings .= '<br/>';
9603 $settings .= $userinstancenumbertext;
9604 $settings .= $OUTPUT->container_end();
9606 // Get the current visibility
9607 if ($i->get_visible()) {
9608 $currentaction = 'show';
9609 } else {
9610 $currentaction = 'hide';
9613 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9615 // Display up/down link
9616 $updown = '';
9617 // Should be done with CSS instead.
9618 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9620 if ($updowncount > 1) {
9621 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9622 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9624 else {
9625 $updown .= $spacer;
9627 if ($updowncount < $totalrepositorytypes) {
9628 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9629 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9631 else {
9632 $updown .= $spacer;
9635 $updowncount++;
9637 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9639 if (!in_array($typename, $alreadyplugins)) {
9640 $alreadyplugins[] = $typename;
9645 // Get all the plugins that exist on disk
9646 $plugins = core_component::get_plugin_list('repository');
9647 if (!empty($plugins)) {
9648 foreach ($plugins as $plugin => $dir) {
9649 // Check that it has not already been listed
9650 if (!in_array($plugin, $alreadyplugins)) {
9651 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9652 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9657 $return .= html_writer::table($table);
9658 $return .= $OUTPUT->box_end();
9659 return highlight($query, $return);
9664 * Special checkbox for enable mobile web service
9665 * If enable then we store the service id of the mobile service into config table
9666 * If disable then we unstore the service id from the config table
9668 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9670 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9671 private $restuse;
9674 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9676 * @return boolean
9678 private function is_protocol_cap_allowed() {
9679 global $DB, $CFG;
9681 // If the $this->restuse variable is not set, it needs to be set.
9682 if (empty($this->restuse) and $this->restuse!==false) {
9683 $params = array();
9684 $params['permission'] = CAP_ALLOW;
9685 $params['roleid'] = $CFG->defaultuserroleid;
9686 $params['capability'] = 'webservice/rest:use';
9687 $this->restuse = $DB->record_exists('role_capabilities', $params);
9690 return $this->restuse;
9694 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9695 * @param type $status true to allow, false to not set
9697 private function set_protocol_cap($status) {
9698 global $CFG;
9699 if ($status and !$this->is_protocol_cap_allowed()) {
9700 //need to allow the cap
9701 $permission = CAP_ALLOW;
9702 $assign = true;
9703 } else if (!$status and $this->is_protocol_cap_allowed()){
9704 //need to disallow the cap
9705 $permission = CAP_INHERIT;
9706 $assign = true;
9708 if (!empty($assign)) {
9709 $systemcontext = context_system::instance();
9710 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9715 * Builds XHTML to display the control.
9716 * The main purpose of this overloading is to display a warning when https
9717 * is not supported by the server
9718 * @param string $data Unused
9719 * @param string $query
9720 * @return string XHTML
9722 public function output_html($data, $query='') {
9723 global $OUTPUT;
9724 $html = parent::output_html($data, $query);
9726 if ((string)$data === $this->yes) {
9727 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9728 foreach ($notifications as $notification) {
9729 $message = get_string($notification[0], $notification[1]);
9730 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9734 return $html;
9738 * Retrieves the current setting using the objects name
9740 * @return string
9742 public function get_setting() {
9743 global $CFG;
9745 // First check if is not set.
9746 $result = $this->config_read($this->name);
9747 if (is_null($result)) {
9748 return null;
9751 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9752 // Or if web services aren't enabled this can't be,
9753 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9754 return 0;
9757 require_once($CFG->dirroot . '/webservice/lib.php');
9758 $webservicemanager = new webservice();
9759 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9760 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9761 return $result;
9762 } else {
9763 return 0;
9768 * Save the selected setting
9770 * @param string $data The selected site
9771 * @return string empty string or error message
9773 public function write_setting($data) {
9774 global $DB, $CFG;
9776 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9777 if (empty($CFG->defaultuserroleid)) {
9778 return '';
9781 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9783 require_once($CFG->dirroot . '/webservice/lib.php');
9784 $webservicemanager = new webservice();
9786 $updateprotocol = false;
9787 if ((string)$data === $this->yes) {
9788 //code run when enable mobile web service
9789 //enable web service systeme if necessary
9790 set_config('enablewebservices', true);
9792 //enable mobile service
9793 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9794 $mobileservice->enabled = 1;
9795 $webservicemanager->update_external_service($mobileservice);
9797 // Enable REST server.
9798 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9800 if (!in_array('rest', $activeprotocols)) {
9801 $activeprotocols[] = 'rest';
9802 $updateprotocol = true;
9805 if ($updateprotocol) {
9806 set_config('webserviceprotocols', implode(',', $activeprotocols));
9809 // Allow rest:use capability for authenticated user.
9810 $this->set_protocol_cap(true);
9812 } else {
9813 //disable web service system if no other services are enabled
9814 $otherenabledservices = $DB->get_records_select('external_services',
9815 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
9816 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
9817 if (empty($otherenabledservices)) {
9818 set_config('enablewebservices', false);
9820 // Also disable REST server.
9821 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9823 $protocolkey = array_search('rest', $activeprotocols);
9824 if ($protocolkey !== false) {
9825 unset($activeprotocols[$protocolkey]);
9826 $updateprotocol = true;
9829 if ($updateprotocol) {
9830 set_config('webserviceprotocols', implode(',', $activeprotocols));
9833 // Disallow rest:use capability for authenticated user.
9834 $this->set_protocol_cap(false);
9837 //disable the mobile service
9838 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9839 $mobileservice->enabled = 0;
9840 $webservicemanager->update_external_service($mobileservice);
9843 return (parent::write_setting($data));
9848 * Special class for management of external services
9850 * @author Petr Skoda (skodak)
9852 class admin_setting_manageexternalservices extends admin_setting {
9854 * Calls parent::__construct with specific arguments
9856 public function __construct() {
9857 $this->nosave = true;
9858 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9862 * Always returns true, does nothing
9864 * @return true
9866 public function get_setting() {
9867 return true;
9871 * Always returns true, does nothing
9873 * @return true
9875 public function get_defaultsetting() {
9876 return true;
9880 * Always returns '', does not write anything
9882 * @return string Always returns ''
9884 public function write_setting($data) {
9885 // do not write any setting
9886 return '';
9890 * Checks if $query is one of the available external services
9892 * @param string $query The string to search for
9893 * @return bool Returns true if found, false if not
9895 public function is_related($query) {
9896 global $DB;
9898 if (parent::is_related($query)) {
9899 return true;
9902 $services = $DB->get_records('external_services', array(), 'id, name');
9903 foreach ($services as $service) {
9904 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9905 return true;
9908 return false;
9912 * Builds the XHTML to display the control
9914 * @param string $data Unused
9915 * @param string $query
9916 * @return string
9918 public function output_html($data, $query='') {
9919 global $CFG, $OUTPUT, $DB;
9921 // display strings
9922 $stradministration = get_string('administration');
9923 $stredit = get_string('edit');
9924 $strservice = get_string('externalservice', 'webservice');
9925 $strdelete = get_string('delete');
9926 $strplugin = get_string('plugin', 'admin');
9927 $stradd = get_string('add');
9928 $strfunctions = get_string('functions', 'webservice');
9929 $strusers = get_string('users');
9930 $strserviceusers = get_string('serviceusers', 'webservice');
9932 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9933 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9934 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9936 // built in services
9937 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9938 $return = "";
9939 if (!empty($services)) {
9940 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9944 $table = new html_table();
9945 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9946 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9947 $table->id = 'builtinservices';
9948 $table->attributes['class'] = 'admintable externalservices generaltable';
9949 $table->data = array();
9951 // iterate through auth plugins and add to the display table
9952 foreach ($services as $service) {
9953 $name = $service->name;
9955 // hide/show link
9956 if ($service->enabled) {
9957 $displayname = "<span>$name</span>";
9958 } else {
9959 $displayname = "<span class=\"dimmed_text\">$name</span>";
9962 $plugin = $service->component;
9964 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9966 if ($service->restrictedusers) {
9967 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9968 } else {
9969 $users = get_string('allusers', 'webservice');
9972 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9974 // add a row to the table
9975 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9977 $return .= html_writer::table($table);
9980 // Custom services
9981 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9982 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9984 $table = new html_table();
9985 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9986 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9987 $table->id = 'customservices';
9988 $table->attributes['class'] = 'admintable externalservices generaltable';
9989 $table->data = array();
9991 // iterate through auth plugins and add to the display table
9992 foreach ($services as $service) {
9993 $name = $service->name;
9995 // hide/show link
9996 if ($service->enabled) {
9997 $displayname = "<span>$name</span>";
9998 } else {
9999 $displayname = "<span class=\"dimmed_text\">$name</span>";
10002 // delete link
10003 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
10005 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
10007 if ($service->restrictedusers) {
10008 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
10009 } else {
10010 $users = get_string('allusers', 'webservice');
10013 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
10015 // add a row to the table
10016 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
10018 // add new custom service option
10019 $return .= html_writer::table($table);
10021 $return .= '<br />';
10022 // add a token to the table
10023 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
10025 return highlight($query, $return);
10030 * Special class for overview of external services
10032 * @author Jerome Mouneyrac
10034 class admin_setting_webservicesoverview extends admin_setting {
10037 * Calls parent::__construct with specific arguments
10039 public function __construct() {
10040 $this->nosave = true;
10041 parent::__construct('webservicesoverviewui',
10042 get_string('webservicesoverview', 'webservice'), '', '');
10046 * Always returns true, does nothing
10048 * @return true
10050 public function get_setting() {
10051 return true;
10055 * Always returns true, does nothing
10057 * @return true
10059 public function get_defaultsetting() {
10060 return true;
10064 * Always returns '', does not write anything
10066 * @return string Always returns ''
10068 public function write_setting($data) {
10069 // do not write any setting
10070 return '';
10074 * Builds the XHTML to display the control
10076 * @param string $data Unused
10077 * @param string $query
10078 * @return string
10080 public function output_html($data, $query='') {
10081 global $CFG, $OUTPUT;
10083 $return = "";
10084 $brtag = html_writer::empty_tag('br');
10086 /// One system controlling Moodle with Token
10087 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
10088 $table = new html_table();
10089 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10090 get_string('description'));
10091 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10092 $table->id = 'onesystemcontrol';
10093 $table->attributes['class'] = 'admintable wsoverview generaltable';
10094 $table->data = array();
10096 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
10097 . $brtag . $brtag;
10099 /// 1. Enable Web Services
10100 $row = array();
10101 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10102 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10103 array('href' => $url));
10104 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10105 if ($CFG->enablewebservices) {
10106 $status = get_string('yes');
10108 $row[1] = $status;
10109 $row[2] = get_string('enablewsdescription', 'webservice');
10110 $table->data[] = $row;
10112 /// 2. Enable protocols
10113 $row = array();
10114 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10115 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10116 array('href' => $url));
10117 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10118 //retrieve activated protocol
10119 $active_protocols = empty($CFG->webserviceprotocols) ?
10120 array() : explode(',', $CFG->webserviceprotocols);
10121 if (!empty($active_protocols)) {
10122 $status = "";
10123 foreach ($active_protocols as $protocol) {
10124 $status .= $protocol . $brtag;
10127 $row[1] = $status;
10128 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10129 $table->data[] = $row;
10131 /// 3. Create user account
10132 $row = array();
10133 $url = new moodle_url("/user/editadvanced.php?id=-1");
10134 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
10135 array('href' => $url));
10136 $row[1] = "";
10137 $row[2] = get_string('createuserdescription', 'webservice');
10138 $table->data[] = $row;
10140 /// 4. Add capability to users
10141 $row = array();
10142 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10143 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
10144 array('href' => $url));
10145 $row[1] = "";
10146 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
10147 $table->data[] = $row;
10149 /// 5. Select a web service
10150 $row = array();
10151 $url = new moodle_url("/admin/settings.php?section=externalservices");
10152 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10153 array('href' => $url));
10154 $row[1] = "";
10155 $row[2] = get_string('createservicedescription', 'webservice');
10156 $table->data[] = $row;
10158 /// 6. Add functions
10159 $row = array();
10160 $url = new moodle_url("/admin/settings.php?section=externalservices");
10161 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10162 array('href' => $url));
10163 $row[1] = "";
10164 $row[2] = get_string('addfunctionsdescription', 'webservice');
10165 $table->data[] = $row;
10167 /// 7. Add the specific user
10168 $row = array();
10169 $url = new moodle_url("/admin/settings.php?section=externalservices");
10170 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
10171 array('href' => $url));
10172 $row[1] = "";
10173 $row[2] = get_string('selectspecificuserdescription', 'webservice');
10174 $table->data[] = $row;
10176 /// 8. Create token for the specific user
10177 $row = array();
10178 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
10179 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
10180 array('href' => $url));
10181 $row[1] = "";
10182 $row[2] = get_string('createtokenforuserdescription', 'webservice');
10183 $table->data[] = $row;
10185 /// 9. Enable the documentation
10186 $row = array();
10187 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
10188 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
10189 array('href' => $url));
10190 $status = '<span class="warning">' . get_string('no') . '</span>';
10191 if ($CFG->enablewsdocumentation) {
10192 $status = get_string('yes');
10194 $row[1] = $status;
10195 $row[2] = get_string('enabledocumentationdescription', 'webservice');
10196 $table->data[] = $row;
10198 /// 10. Test the service
10199 $row = array();
10200 $url = new moodle_url("/admin/webservice/testclient.php");
10201 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10202 array('href' => $url));
10203 $row[1] = "";
10204 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10205 $table->data[] = $row;
10207 $return .= html_writer::table($table);
10209 /// Users as clients with token
10210 $return .= $brtag . $brtag . $brtag;
10211 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10212 $table = new html_table();
10213 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10214 get_string('description'));
10215 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10216 $table->id = 'userasclients';
10217 $table->attributes['class'] = 'admintable wsoverview generaltable';
10218 $table->data = array();
10220 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10221 $brtag . $brtag;
10223 /// 1. Enable Web Services
10224 $row = array();
10225 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10226 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10227 array('href' => $url));
10228 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10229 if ($CFG->enablewebservices) {
10230 $status = get_string('yes');
10232 $row[1] = $status;
10233 $row[2] = get_string('enablewsdescription', 'webservice');
10234 $table->data[] = $row;
10236 /// 2. Enable protocols
10237 $row = array();
10238 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10239 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10240 array('href' => $url));
10241 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10242 //retrieve activated protocol
10243 $active_protocols = empty($CFG->webserviceprotocols) ?
10244 array() : explode(',', $CFG->webserviceprotocols);
10245 if (!empty($active_protocols)) {
10246 $status = "";
10247 foreach ($active_protocols as $protocol) {
10248 $status .= $protocol . $brtag;
10251 $row[1] = $status;
10252 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10253 $table->data[] = $row;
10256 /// 3. Select a web service
10257 $row = array();
10258 $url = new moodle_url("/admin/settings.php?section=externalservices");
10259 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10260 array('href' => $url));
10261 $row[1] = "";
10262 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10263 $table->data[] = $row;
10265 /// 4. Add functions
10266 $row = array();
10267 $url = new moodle_url("/admin/settings.php?section=externalservices");
10268 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10269 array('href' => $url));
10270 $row[1] = "";
10271 $row[2] = get_string('addfunctionsdescription', 'webservice');
10272 $table->data[] = $row;
10274 /// 5. Add capability to users
10275 $row = array();
10276 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10277 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10278 array('href' => $url));
10279 $row[1] = "";
10280 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10281 $table->data[] = $row;
10283 /// 6. Test the service
10284 $row = array();
10285 $url = new moodle_url("/admin/webservice/testclient.php");
10286 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10287 array('href' => $url));
10288 $row[1] = "";
10289 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10290 $table->data[] = $row;
10292 $return .= html_writer::table($table);
10294 return highlight($query, $return);
10301 * Special class for web service protocol administration.
10303 * @author Petr Skoda (skodak)
10305 class admin_setting_managewebserviceprotocols extends admin_setting {
10308 * Calls parent::__construct with specific arguments
10310 public function __construct() {
10311 $this->nosave = true;
10312 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10316 * Always returns true, does nothing
10318 * @return true
10320 public function get_setting() {
10321 return true;
10325 * Always returns true, does nothing
10327 * @return true
10329 public function get_defaultsetting() {
10330 return true;
10334 * Always returns '', does not write anything
10336 * @return string Always returns ''
10338 public function write_setting($data) {
10339 // do not write any setting
10340 return '';
10344 * Checks if $query is one of the available webservices
10346 * @param string $query The string to search for
10347 * @return bool Returns true if found, false if not
10349 public function is_related($query) {
10350 if (parent::is_related($query)) {
10351 return true;
10354 $protocols = core_component::get_plugin_list('webservice');
10355 foreach ($protocols as $protocol=>$location) {
10356 if (strpos($protocol, $query) !== false) {
10357 return true;
10359 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10360 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10361 return true;
10364 return false;
10368 * Builds the XHTML to display the control
10370 * @param string $data Unused
10371 * @param string $query
10372 * @return string
10374 public function output_html($data, $query='') {
10375 global $CFG, $OUTPUT;
10377 // display strings
10378 $stradministration = get_string('administration');
10379 $strsettings = get_string('settings');
10380 $stredit = get_string('edit');
10381 $strprotocol = get_string('protocol', 'webservice');
10382 $strenable = get_string('enable');
10383 $strdisable = get_string('disable');
10384 $strversion = get_string('version');
10386 $protocols_available = core_component::get_plugin_list('webservice');
10387 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10388 ksort($protocols_available);
10390 foreach ($active_protocols as $key=>$protocol) {
10391 if (empty($protocols_available[$protocol])) {
10392 unset($active_protocols[$key]);
10396 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10397 $return .= $OUTPUT->box_start('generalbox webservicesui');
10399 $table = new html_table();
10400 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10401 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10402 $table->id = 'webserviceprotocols';
10403 $table->attributes['class'] = 'admintable generaltable';
10404 $table->data = array();
10406 // iterate through auth plugins and add to the display table
10407 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10408 foreach ($protocols_available as $protocol => $location) {
10409 $name = get_string('pluginname', 'webservice_'.$protocol);
10411 $plugin = new stdClass();
10412 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10413 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10415 $version = isset($plugin->version) ? $plugin->version : '';
10417 // hide/show link
10418 if (in_array($protocol, $active_protocols)) {
10419 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10420 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10421 $displayname = "<span>$name</span>";
10422 } else {
10423 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10424 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10425 $displayname = "<span class=\"dimmed_text\">$name</span>";
10428 // settings link
10429 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10430 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10431 } else {
10432 $settings = '';
10435 // add a row to the table
10436 $table->data[] = array($displayname, $version, $hideshow, $settings);
10438 $return .= html_writer::table($table);
10439 $return .= get_string('configwebserviceplugins', 'webservice');
10440 $return .= $OUTPUT->box_end();
10442 return highlight($query, $return);
10447 * Colour picker
10449 * @copyright 2010 Sam Hemelryk
10450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10452 class admin_setting_configcolourpicker extends admin_setting {
10455 * Information for previewing the colour
10457 * @var array|null
10459 protected $previewconfig = null;
10462 * Use default when empty.
10464 protected $usedefaultwhenempty = true;
10468 * @param string $name
10469 * @param string $visiblename
10470 * @param string $description
10471 * @param string $defaultsetting
10472 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10474 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10475 $usedefaultwhenempty = true) {
10476 $this->previewconfig = $previewconfig;
10477 $this->usedefaultwhenempty = $usedefaultwhenempty;
10478 parent::__construct($name, $visiblename, $description, $defaultsetting);
10479 $this->set_force_ltr(true);
10483 * Return the setting
10485 * @return mixed returns config if successful else null
10487 public function get_setting() {
10488 return $this->config_read($this->name);
10492 * Saves the setting
10494 * @param string $data
10495 * @return bool
10497 public function write_setting($data) {
10498 $data = $this->validate($data);
10499 if ($data === false) {
10500 return get_string('validateerror', 'admin');
10502 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10506 * Validates the colour that was entered by the user
10508 * @param string $data
10509 * @return string|false
10511 protected function validate($data) {
10513 * List of valid HTML colour names
10515 * @var array
10517 $colornames = array(
10518 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10519 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10520 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10521 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10522 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10523 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10524 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10525 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10526 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10527 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10528 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10529 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10530 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10531 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10532 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10533 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10534 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10535 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10536 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10537 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10538 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10539 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10540 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10541 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10542 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10543 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10544 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10545 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10546 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10547 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10548 'whitesmoke', 'yellow', 'yellowgreen'
10551 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10552 if (strpos($data, '#')!==0) {
10553 $data = '#'.$data;
10555 return $data;
10556 } else if (in_array(strtolower($data), $colornames)) {
10557 return $data;
10558 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10559 return $data;
10560 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10561 return $data;
10562 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10563 return $data;
10564 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10565 return $data;
10566 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10567 return $data;
10568 } else if (empty($data)) {
10569 if ($this->usedefaultwhenempty){
10570 return $this->defaultsetting;
10571 } else {
10572 return '';
10574 } else {
10575 return false;
10580 * Generates the HTML for the setting
10582 * @global moodle_page $PAGE
10583 * @global core_renderer $OUTPUT
10584 * @param string $data
10585 * @param string $query
10587 public function output_html($data, $query = '') {
10588 global $PAGE, $OUTPUT;
10590 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10591 $context = (object) [
10592 'id' => $this->get_id(),
10593 'name' => $this->get_full_name(),
10594 'value' => $data,
10595 'icon' => $icon->export_for_template($OUTPUT),
10596 'haspreviewconfig' => !empty($this->previewconfig),
10597 'forceltr' => $this->get_force_ltr(),
10598 'readonly' => $this->is_readonly(),
10601 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10602 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10604 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10605 $this->get_defaultsetting(), $query);
10612 * Class used for uploading of one file into file storage,
10613 * the file name is stored in config table.
10615 * Please note you need to implement your own '_pluginfile' callback function,
10616 * this setting only stores the file, it does not deal with file serving.
10618 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10621 class admin_setting_configstoredfile extends admin_setting {
10622 /** @var array file area options - should be one file only */
10623 protected $options;
10624 /** @var string name of the file area */
10625 protected $filearea;
10626 /** @var int intemid */
10627 protected $itemid;
10628 /** @var string used for detection of changes */
10629 protected $oldhashes;
10632 * Create new stored file setting.
10634 * @param string $name low level setting name
10635 * @param string $visiblename human readable setting name
10636 * @param string $description description of setting
10637 * @param mixed $filearea file area for file storage
10638 * @param int $itemid itemid for file storage
10639 * @param array $options file area options
10641 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10642 parent::__construct($name, $visiblename, $description, '');
10643 $this->filearea = $filearea;
10644 $this->itemid = $itemid;
10645 $this->options = (array)$options;
10646 $this->customcontrol = true;
10650 * Applies defaults and returns all options.
10651 * @return array
10653 protected function get_options() {
10654 global $CFG;
10656 require_once("$CFG->libdir/filelib.php");
10657 require_once("$CFG->dirroot/repository/lib.php");
10658 $defaults = array(
10659 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10660 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10661 'context' => context_system::instance());
10662 foreach($this->options as $k => $v) {
10663 $defaults[$k] = $v;
10666 return $defaults;
10669 public function get_setting() {
10670 return $this->config_read($this->name);
10673 public function write_setting($data) {
10674 global $USER;
10676 // Let's not deal with validation here, this is for admins only.
10677 $current = $this->get_setting();
10678 if (empty($data) && $current === null) {
10679 // This will be the case when applying default settings (installation).
10680 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10681 } else if (!is_number($data)) {
10682 // Draft item id is expected here!
10683 return get_string('errorsetting', 'admin');
10686 $options = $this->get_options();
10687 $fs = get_file_storage();
10688 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10690 $this->oldhashes = null;
10691 if ($current) {
10692 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10693 if ($file = $fs->get_file_by_hash($hash)) {
10694 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10696 unset($file);
10699 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10700 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10701 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10702 // with an error because the draft area does not exist, as he did not use it.
10703 $usercontext = context_user::instance($USER->id);
10704 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10705 return get_string('errorsetting', 'admin');
10709 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10710 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10712 $filepath = '';
10713 if ($files) {
10714 /** @var stored_file $file */
10715 $file = reset($files);
10716 $filepath = $file->get_filepath().$file->get_filename();
10719 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10722 public function post_write_settings($original) {
10723 $options = $this->get_options();
10724 $fs = get_file_storage();
10725 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10727 $current = $this->get_setting();
10728 $newhashes = null;
10729 if ($current) {
10730 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10731 if ($file = $fs->get_file_by_hash($hash)) {
10732 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10734 unset($file);
10737 if ($this->oldhashes === $newhashes) {
10738 $this->oldhashes = null;
10739 return false;
10741 $this->oldhashes = null;
10743 $callbackfunction = $this->updatedcallback;
10744 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10745 $callbackfunction($this->get_full_name());
10747 return true;
10750 public function output_html($data, $query = '') {
10751 global $PAGE, $CFG;
10753 $options = $this->get_options();
10754 $id = $this->get_id();
10755 $elname = $this->get_full_name();
10756 $draftitemid = file_get_submitted_draft_itemid($elname);
10757 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10758 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10760 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10761 require_once("$CFG->dirroot/lib/form/filemanager.php");
10763 $fmoptions = new stdClass();
10764 $fmoptions->mainfile = $options['mainfile'];
10765 $fmoptions->maxbytes = $options['maxbytes'];
10766 $fmoptions->maxfiles = $options['maxfiles'];
10767 $fmoptions->client_id = uniqid();
10768 $fmoptions->itemid = $draftitemid;
10769 $fmoptions->subdirs = $options['subdirs'];
10770 $fmoptions->target = $id;
10771 $fmoptions->accepted_types = $options['accepted_types'];
10772 $fmoptions->return_types = $options['return_types'];
10773 $fmoptions->context = $options['context'];
10774 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10776 $fm = new form_filemanager($fmoptions);
10777 $output = $PAGE->get_renderer('core', 'files');
10778 $html = $output->render($fm);
10780 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
10781 $html .= '<input value="" id="'.$id.'" type="hidden" />';
10783 return format_admin_setting($this, $this->visiblename,
10784 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
10785 $this->description, true, '', '', $query);
10791 * Administration interface for user specified regular expressions for device detection.
10793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10795 class admin_setting_devicedetectregex extends admin_setting {
10798 * Calls parent::__construct with specific args
10800 * @param string $name
10801 * @param string $visiblename
10802 * @param string $description
10803 * @param mixed $defaultsetting
10805 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10806 global $CFG;
10807 parent::__construct($name, $visiblename, $description, $defaultsetting);
10811 * Return the current setting(s)
10813 * @return array Current settings array
10815 public function get_setting() {
10816 global $CFG;
10818 $config = $this->config_read($this->name);
10819 if (is_null($config)) {
10820 return null;
10823 return $this->prepare_form_data($config);
10827 * Save selected settings
10829 * @param array $data Array of settings to save
10830 * @return bool
10832 public function write_setting($data) {
10833 if (empty($data)) {
10834 $data = array();
10837 if ($this->config_write($this->name, $this->process_form_data($data))) {
10838 return ''; // success
10839 } else {
10840 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10845 * Return XHTML field(s) for regexes
10847 * @param array $data Array of options to set in HTML
10848 * @return string XHTML string for the fields and wrapping div(s)
10850 public function output_html($data, $query='') {
10851 global $OUTPUT;
10853 $context = (object) [
10854 'expressions' => [],
10855 'name' => $this->get_full_name()
10858 if (empty($data)) {
10859 $looplimit = 1;
10860 } else {
10861 $looplimit = (count($data)/2)+1;
10864 for ($i=0; $i<$looplimit; $i++) {
10866 $expressionname = 'expression'.$i;
10868 if (!empty($data[$expressionname])){
10869 $expression = $data[$expressionname];
10870 } else {
10871 $expression = '';
10874 $valuename = 'value'.$i;
10876 if (!empty($data[$valuename])){
10877 $value = $data[$valuename];
10878 } else {
10879 $value= '';
10882 $context->expressions[] = [
10883 'index' => $i,
10884 'expression' => $expression,
10885 'value' => $value
10889 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10891 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10895 * Converts the string of regexes
10897 * @see self::process_form_data()
10898 * @param $regexes string of regexes
10899 * @return array of form fields and their values
10901 protected function prepare_form_data($regexes) {
10903 $regexes = json_decode($regexes);
10905 $form = array();
10907 $i = 0;
10909 foreach ($regexes as $value => $regex) {
10910 $expressionname = 'expression'.$i;
10911 $valuename = 'value'.$i;
10913 $form[$expressionname] = $regex;
10914 $form[$valuename] = $value;
10915 $i++;
10918 return $form;
10922 * Converts the data from admin settings form into a string of regexes
10924 * @see self::prepare_form_data()
10925 * @param array $data array of admin form fields and values
10926 * @return false|string of regexes
10928 protected function process_form_data(array $form) {
10930 $count = count($form); // number of form field values
10932 if ($count % 2) {
10933 // we must get five fields per expression
10934 return false;
10937 $regexes = array();
10938 for ($i = 0; $i < $count / 2; $i++) {
10939 $expressionname = "expression".$i;
10940 $valuename = "value".$i;
10942 $expression = trim($form['expression'.$i]);
10943 $value = trim($form['value'.$i]);
10945 if (empty($expression)){
10946 continue;
10949 $regexes[$value] = $expression;
10952 $regexes = json_encode($regexes);
10954 return $regexes;
10960 * Multiselect for current modules
10962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10964 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10965 private $excludesystem;
10968 * Calls parent::__construct - note array $choices is not required
10970 * @param string $name setting name
10971 * @param string $visiblename localised setting name
10972 * @param string $description setting description
10973 * @param array $defaultsetting a plain array of default module ids
10974 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10976 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10977 $excludesystem = true) {
10978 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10979 $this->excludesystem = $excludesystem;
10983 * Loads an array of current module choices
10985 * @return bool always return true
10987 public function load_choices() {
10988 if (is_array($this->choices)) {
10989 return true;
10991 $this->choices = array();
10993 global $CFG, $DB;
10994 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10995 foreach ($records as $record) {
10996 // Exclude modules if the code doesn't exist
10997 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10998 // Also exclude system modules (if specified)
10999 if (!($this->excludesystem &&
11000 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
11001 MOD_ARCHETYPE_SYSTEM)) {
11002 $this->choices[$record->id] = $record->name;
11006 return true;
11011 * Admin setting to show if a php extension is enabled or not.
11013 * @copyright 2013 Damyon Wiese
11014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11016 class admin_setting_php_extension_enabled extends admin_setting {
11018 /** @var string The name of the extension to check for */
11019 private $extension;
11022 * Calls parent::__construct with specific arguments
11024 public function __construct($name, $visiblename, $description, $extension) {
11025 $this->extension = $extension;
11026 $this->nosave = true;
11027 parent::__construct($name, $visiblename, $description, '');
11031 * Always returns true, does nothing
11033 * @return true
11035 public function get_setting() {
11036 return true;
11040 * Always returns true, does nothing
11042 * @return true
11044 public function get_defaultsetting() {
11045 return true;
11049 * Always returns '', does not write anything
11051 * @return string Always returns ''
11053 public function write_setting($data) {
11054 // Do not write any setting.
11055 return '';
11059 * Outputs the html for this setting.
11060 * @return string Returns an XHTML string
11062 public function output_html($data, $query='') {
11063 global $OUTPUT;
11065 $o = '';
11066 if (!extension_loaded($this->extension)) {
11067 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
11069 $o .= format_admin_setting($this, $this->visiblename, $warning);
11071 return $o;
11076 * Server timezone setting.
11078 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11080 * @author Petr Skoda <petr.skoda@totaralms.com>
11082 class admin_setting_servertimezone extends admin_setting_configselect {
11084 * Constructor.
11086 public function __construct() {
11087 $default = core_date::get_default_php_timezone();
11088 if ($default === 'UTC') {
11089 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
11090 $default = 'Europe/London';
11093 parent::__construct('timezone',
11094 new lang_string('timezone', 'core_admin'),
11095 new lang_string('configtimezone', 'core_admin'), $default, null);
11099 * Lazy load timezone options.
11100 * @return bool true if loaded, false if error
11102 public function load_choices() {
11103 global $CFG;
11104 if (is_array($this->choices)) {
11105 return true;
11108 $current = isset($CFG->timezone) ? $CFG->timezone : null;
11109 $this->choices = core_date::get_list_of_timezones($current, false);
11110 if ($current == 99) {
11111 // Do not show 99 unless it is current value, we want to get rid of it over time.
11112 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
11113 core_date::get_default_php_timezone());
11116 return true;
11121 * Forced user timezone setting.
11123 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11125 * @author Petr Skoda <petr.skoda@totaralms.com>
11127 class admin_setting_forcetimezone extends admin_setting_configselect {
11129 * Constructor.
11131 public function __construct() {
11132 parent::__construct('forcetimezone',
11133 new lang_string('forcetimezone', 'core_admin'),
11134 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
11138 * Lazy load timezone options.
11139 * @return bool true if loaded, false if error
11141 public function load_choices() {
11142 global $CFG;
11143 if (is_array($this->choices)) {
11144 return true;
11147 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
11148 $this->choices = core_date::get_list_of_timezones($current, true);
11149 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
11151 return true;
11157 * Search setup steps info.
11159 * @package core
11160 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
11161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11163 class admin_setting_searchsetupinfo extends admin_setting {
11166 * Calls parent::__construct with specific arguments
11168 public function __construct() {
11169 $this->nosave = true;
11170 parent::__construct('searchsetupinfo', '', '', '');
11174 * Always returns true, does nothing
11176 * @return true
11178 public function get_setting() {
11179 return true;
11183 * Always returns true, does nothing
11185 * @return true
11187 public function get_defaultsetting() {
11188 return true;
11192 * Always returns '', does not write anything
11194 * @param array $data
11195 * @return string Always returns ''
11197 public function write_setting($data) {
11198 // Do not write any setting.
11199 return '';
11203 * Builds the HTML to display the control
11205 * @param string $data Unused
11206 * @param string $query
11207 * @return string
11209 public function output_html($data, $query='') {
11210 global $CFG, $OUTPUT, $ADMIN;
11212 $return = '';
11213 $brtag = html_writer::empty_tag('br');
11215 $searchareas = \core_search\manager::get_search_areas_list();
11216 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11217 $anyindexed = false;
11218 foreach ($searchareas as $areaid => $searcharea) {
11219 list($componentname, $varname) = $searcharea->get_config_var_name();
11220 if (get_config($componentname, $varname . '_indexingstart')) {
11221 $anyindexed = true;
11222 break;
11226 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11228 $table = new html_table();
11229 $table->head = array(get_string('step', 'search'), get_string('status'));
11230 $table->colclasses = array('leftalign step', 'leftalign status');
11231 $table->id = 'searchsetup';
11232 $table->attributes['class'] = 'admintable generaltable';
11233 $table->data = array();
11235 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11237 // Select a search engine.
11238 $row = array();
11239 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11240 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11241 array('href' => $url));
11243 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11244 if (!empty($CFG->searchengine)) {
11245 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11246 array('class' => 'badge badge-success'));
11249 $row[1] = $status;
11250 $table->data[] = $row;
11252 // Available areas.
11253 $row = array();
11254 $url = new moodle_url('/admin/searchareas.php');
11255 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11256 array('href' => $url));
11258 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11259 if ($anyenabled) {
11260 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11263 $row[1] = $status;
11264 $table->data[] = $row;
11266 // Setup search engine.
11267 $row = array();
11268 if (empty($CFG->searchengine)) {
11269 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11270 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11271 } else {
11272 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11273 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11274 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11275 } else {
11276 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11279 // Check the engine status.
11280 $searchengine = \core_search\manager::search_engine_instance();
11281 try {
11282 $serverstatus = $searchengine->is_server_ready();
11283 } catch (\moodle_exception $e) {
11284 $serverstatus = $e->getMessage();
11286 if ($serverstatus === true) {
11287 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11288 } else {
11289 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11291 $row[1] = $status;
11293 $table->data[] = $row;
11295 // Indexed data.
11296 $row = array();
11297 $url = new moodle_url('/admin/searchareas.php');
11298 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11299 if ($anyindexed) {
11300 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11301 } else {
11302 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11304 $row[1] = $status;
11305 $table->data[] = $row;
11307 // Enable global search.
11308 $row = array();
11309 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11310 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11311 array('href' => $url));
11312 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11313 if (\core_search\manager::is_global_search_enabled()) {
11314 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11316 $row[1] = $status;
11317 $table->data[] = $row;
11319 $return .= html_writer::table($table);
11321 return highlight($query, $return);
11327 * Used to validate the contents of SCSS code and ensuring they are parsable.
11329 * It does not attempt to detect undefined SCSS variables because it is designed
11330 * to be used without knowledge of other config/scss included.
11332 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11333 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11335 class admin_setting_scsscode extends admin_setting_configtextarea {
11338 * Validate the contents of the SCSS to ensure its parsable. Does not
11339 * attempt to detect undefined scss variables.
11341 * @param string $data The scss code from text field.
11342 * @return mixed bool true for success or string:error on failure.
11344 public function validate($data) {
11345 if (empty($data)) {
11346 return true;
11349 $scss = new core_scss();
11350 try {
11351 $scss->compile($data);
11352 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11353 return get_string('scssinvalid', 'admin', $e->getMessage());
11354 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11355 // Silently ignore this - it could be a scss variable defined from somewhere
11356 // else which we are not examining here.
11357 return true;
11360 return true;
11366 * Administration setting to define a list of file types.
11368 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11369 * @copyright 2017 David Mudrák <david@moodle.com>
11370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11372 class admin_setting_filetypes extends admin_setting_configtext {
11374 /** @var array Allow selection from these file types only. */
11375 protected $onlytypes = [];
11377 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11378 protected $allowall = true;
11380 /** @var core_form\filetypes_util instance to use as a helper. */
11381 protected $util = null;
11384 * Constructor.
11386 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11387 * @param string $visiblename Localised label of the setting
11388 * @param string $description Localised description of the setting
11389 * @param string $defaultsetting Default setting value.
11390 * @param array $options Setting widget options, an array with optional keys:
11391 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11392 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11394 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11396 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11398 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11399 $this->onlytypes = $options['onlytypes'];
11402 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11403 $this->allowall = (bool)$options['allowall'];
11406 $this->util = new \core_form\filetypes_util();
11410 * Normalize the user's input and write it to the database as comma separated list.
11412 * Comma separated list as a text representation of the array was chosen to
11413 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11415 * @param string $data Value submitted by the admin.
11416 * @return string Epty string if all good, error message otherwise.
11418 public function write_setting($data) {
11419 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11423 * Validate data before storage
11425 * @param string $data The setting values provided by the admin
11426 * @return bool|string True if ok, the string if error found
11428 public function validate($data) {
11429 $parentcheck = parent::validate($data);
11430 if ($parentcheck !== true) {
11431 return $parentcheck;
11434 // Check for unknown file types.
11435 if ($unknown = $this->util->get_unknown_file_types($data)) {
11436 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11439 // Check for disallowed file types.
11440 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11441 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11444 return true;
11448 * Return an HTML string for the setting element.
11450 * @param string $data The current setting value
11451 * @param string $query Admin search query to be highlighted
11452 * @return string HTML to be displayed
11454 public function output_html($data, $query='') {
11455 global $OUTPUT, $PAGE;
11457 $default = $this->get_defaultsetting();
11458 $context = (object) [
11459 'id' => $this->get_id(),
11460 'name' => $this->get_full_name(),
11461 'value' => $data,
11462 'descriptions' => $this->util->describe_file_types($data),
11464 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11466 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11467 $this->get_id(),
11468 $this->visiblename->out(),
11469 $this->onlytypes,
11470 $this->allowall,
11473 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11477 * Should the values be always displayed in LTR mode?
11479 * We always return true here because these values are not RTL compatible.
11481 * @return bool True because these values are not RTL compatible.
11483 public function get_force_ltr() {
11484 return true;
11489 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11491 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11492 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11494 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11497 * Constructor.
11499 * @param string $name
11500 * @param string $visiblename
11501 * @param string $description
11502 * @param mixed $defaultsetting string or array
11503 * @param mixed $paramtype
11504 * @param string $cols
11505 * @param string $rows
11507 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11508 $cols = '60', $rows = '8') {
11509 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11510 // Pre-set force LTR to false.
11511 $this->set_force_ltr(false);
11515 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11517 * @param string $data The age of digital consent map from text field.
11518 * @return mixed bool true for success or string:error on failure.
11520 public function validate($data) {
11521 if (empty($data)) {
11522 return true;
11525 try {
11526 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11527 } catch (\moodle_exception $e) {
11528 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11531 return true;
11536 * Selection of plugins that can work as site policy handlers
11538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11539 * @copyright 2018 Marina Glancy
11541 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11544 * Constructor
11545 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11546 * for ones in config_plugins.
11547 * @param string $visiblename localised
11548 * @param string $description long localised info
11549 * @param string $defaultsetting
11551 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11552 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11556 * Lazy-load the available choices for the select box
11558 public function load_choices() {
11559 if (during_initial_install()) {
11560 return false;
11562 if (is_array($this->choices)) {
11563 return true;
11566 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11567 $manager = new \core_privacy\local\sitepolicy\manager();
11568 $plugins = $manager->get_all_handlers();
11569 foreach ($plugins as $pname => $unused) {
11570 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11571 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11574 return true;
11579 * Used to validate theme presets code and ensuring they compile well.
11581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11582 * @copyright 2019 Bas Brands <bas@moodle.com>
11584 class admin_setting_configthemepreset extends admin_setting_configselect {
11586 /** @var string The name of the theme to check for */
11587 private $themename;
11590 * Constructor
11591 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11592 * or 'myplugin/mysetting' for ones in config_plugins.
11593 * @param string $visiblename localised
11594 * @param string $description long localised info
11595 * @param string|int $defaultsetting
11596 * @param array $choices array of $value=>$label for each selection
11597 * @param string $themename name of theme to check presets for.
11599 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11600 $this->themename = $themename;
11601 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11605 * Write settings if validated
11607 * @param string $data
11608 * @return string
11610 public function write_setting($data) {
11611 $validated = $this->validate($data);
11612 if ($validated !== true) {
11613 return $validated;
11615 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11619 * Validate the preset file to ensure its parsable.
11621 * @param string $data The preset file chosen.
11622 * @return mixed bool true for success or string:error on failure.
11624 public function validate($data) {
11626 if (in_array($data, ['default.scss', 'plain.scss'])) {
11627 return true;
11630 $fs = get_file_storage();
11631 $theme = theme_config::load($this->themename);
11632 $context = context_system::instance();
11634 // If the preset has not changed there is no need to validate it.
11635 if ($theme->settings->preset == $data) {
11636 return true;
11639 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11640 // This operation uses a lot of resources.
11641 raise_memory_limit(MEMORY_EXTRA);
11642 core_php_time_limit::raise(300);
11644 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11645 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11647 $compiler = new core_scss();
11648 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11649 $compiler->append_raw_scss($presetfile->get_content());
11650 if ($scssproperties = $theme->get_scss_property()) {
11651 $compiler->setImportPaths($scssproperties[0]);
11653 $compiler->append_raw_scss($theme->get_extra_scss_code());
11655 try {
11656 $compiler->to_css();
11657 } catch (Exception $e) {
11658 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11661 // Try to save memory.
11662 $compiler = null;
11663 unset($compiler);
11666 return true;
11671 * Selection of plugins that can work as H5P libraries handlers
11673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11674 * @copyright 2020 Sara Arjona <sara@moodle.com>
11676 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11679 * Constructor
11680 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11681 * for ones in config_plugins.
11682 * @param string $visiblename localised
11683 * @param string $description long localised info
11684 * @param string $defaultsetting
11686 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11687 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11691 * Lazy-load the available choices for the select box
11693 public function load_choices() {
11694 if (during_initial_install()) {
11695 return false;
11697 if (is_array($this->choices)) {
11698 return true;
11701 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11702 foreach ($this->choices as $name => $class) {
11703 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11704 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11707 return true;