MDL-78165 mod_bigbluebuttonbn: Fetch cron status using API
[moodle.git] / lib / adminlib.php
blob0cabc17744ac33f705de43c473c62d10b877a1eb
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(__DIR__.'/../../config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 use core_admin\local\settings\linkable_settings_page;
107 defined('MOODLE_INTERNAL') || die();
109 /// Add libraries
110 require_once($CFG->libdir.'/ddllib.php');
111 require_once($CFG->libdir.'/xmlize.php');
112 require_once($CFG->libdir.'/messagelib.php');
114 // Add classes, traits, and interfaces which should be autoloaded.
115 // The autoloader is configured late in setup.php, after ABORT_AFTER_CONFIG.
116 // This is also required where the setup system is not included at all.
117 require_once($CFG->dirroot.'/'.$CFG->admin.'/classes/local/settings/linkable_settings_page.php');
119 define('INSECURE_DATAROOT_WARNING', 1);
120 define('INSECURE_DATAROOT_ERROR', 2);
123 * Automatically clean-up all plugin data and remove the plugin DB tables
125 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
127 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
128 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
129 * @uses global $OUTPUT to produce notices and other messages
130 * @return void
132 function uninstall_plugin($type, $name) {
133 global $CFG, $DB, $OUTPUT;
135 // This may take a long time.
136 core_php_time_limit::raise();
138 // Recursively uninstall all subplugins first.
139 $subplugintypes = core_component::get_plugin_types_with_subplugins();
140 if (isset($subplugintypes[$type])) {
141 $base = core_component::get_plugin_directory($type, $name);
143 $subpluginsfile = "{$base}/db/subplugins.json";
144 if (file_exists($subpluginsfile)) {
145 $subplugins = (array) json_decode(file_get_contents($subpluginsfile))->plugintypes;
146 } else if (file_exists("{$base}/db/subplugins.php")) {
147 debugging('Use of subplugins.php has been deprecated. ' .
148 'Please update your plugin to provide a subplugins.json file instead.',
149 DEBUG_DEVELOPER);
150 $subplugins = [];
151 include("{$base}/db/subplugins.php");
154 if (!empty($subplugins)) {
155 foreach (array_keys($subplugins) as $subplugintype) {
156 $instances = core_component::get_plugin_list($subplugintype);
157 foreach ($instances as $subpluginname => $notusedpluginpath) {
158 uninstall_plugin($subplugintype, $subpluginname);
164 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
166 if ($type === 'mod') {
167 $pluginname = $name; // eg. 'forum'
168 if (get_string_manager()->string_exists('modulename', $component)) {
169 $strpluginname = get_string('modulename', $component);
170 } else {
171 $strpluginname = $component;
174 } else {
175 $pluginname = $component;
176 if (get_string_manager()->string_exists('pluginname', $component)) {
177 $strpluginname = get_string('pluginname', $component);
178 } else {
179 $strpluginname = $component;
183 echo $OUTPUT->heading($pluginname);
185 // Delete all tag areas, collections and instances associated with this plugin.
186 core_tag_area::uninstall($component);
188 // Custom plugin uninstall.
189 $plugindirectory = core_component::get_plugin_directory($type, $name);
190 $uninstalllib = $plugindirectory . '/db/uninstall.php';
191 if (file_exists($uninstalllib)) {
192 require_once($uninstalllib);
193 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
194 if (function_exists($uninstallfunction)) {
195 // Do not verify result, let plugin complain if necessary.
196 $uninstallfunction();
200 // Specific plugin type cleanup.
201 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
202 if ($plugininfo) {
203 $plugininfo->uninstall_cleanup();
204 core_plugin_manager::reset_caches();
206 $plugininfo = null;
208 // Perform clean-up task common for all the plugin/subplugin types.
210 // Delete the web service functions and pre-built services.
211 \core_external\util::delete_service_descriptions($component);
213 // delete calendar events
214 $DB->delete_records('event', array('modulename' => $pluginname));
215 $DB->delete_records('event', ['component' => $component]);
217 // Delete scheduled tasks.
218 $DB->delete_records('task_adhoc', ['component' => $component]);
219 $DB->delete_records('task_scheduled', array('component' => $component));
221 // Delete Inbound Message datakeys.
222 $DB->delete_records_select('messageinbound_datakeys',
223 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
225 // Delete Inbound Message handlers.
226 $DB->delete_records('messageinbound_handlers', array('component' => $component));
228 // delete all the logs
229 $DB->delete_records('log', array('module' => $pluginname));
231 // delete log_display information
232 $DB->delete_records('log_display', array('component' => $component));
234 // delete the module configuration records
235 unset_all_config_for_plugin($component);
236 if ($type === 'mod') {
237 unset_all_config_for_plugin($pluginname);
240 // Wipe any xAPI state information.
241 if (core_xapi\handler::supports_xapi($component)) {
242 core_xapi\api::remove_states_from_component($component);
245 // delete message provider
246 message_provider_uninstall($component);
248 // delete the plugin tables
249 $xmldbfilepath = $plugindirectory . '/db/install.xml';
250 drop_plugin_tables($component, $xmldbfilepath, false);
251 if ($type === 'mod' or $type === 'block') {
252 // non-frankenstyle table prefixes
253 drop_plugin_tables($name, $xmldbfilepath, false);
256 // delete the capabilities that were defined by this module
257 capabilities_cleanup($component);
259 // Delete all remaining files in the filepool owned by the component.
260 $fs = get_file_storage();
261 $fs->delete_component_files($component);
263 // Finally purge all caches.
264 purge_all_caches();
266 // Invalidate the hash used for upgrade detections.
267 set_config('allversionshash', '');
269 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
273 * Returns the version of installed component
275 * @param string $component component name
276 * @param string $source either 'disk' or 'installed' - where to get the version information from
277 * @return string|bool version number or false if the component is not found
279 function get_component_version($component, $source='installed') {
280 global $CFG, $DB;
282 list($type, $name) = core_component::normalize_component($component);
284 // moodle core or a core subsystem
285 if ($type === 'core') {
286 if ($source === 'installed') {
287 if (empty($CFG->version)) {
288 return false;
289 } else {
290 return $CFG->version;
292 } else {
293 if (!is_readable($CFG->dirroot.'/version.php')) {
294 return false;
295 } else {
296 $version = null; //initialize variable for IDEs
297 include($CFG->dirroot.'/version.php');
298 return $version;
303 // activity module
304 if ($type === 'mod') {
305 if ($source === 'installed') {
306 if ($CFG->version < 2013092001.02) {
307 return $DB->get_field('modules', 'version', array('name'=>$name));
308 } else {
309 return get_config('mod_'.$name, 'version');
312 } else {
313 $mods = core_component::get_plugin_list('mod');
314 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
315 return false;
316 } else {
317 $plugin = new stdClass();
318 $plugin->version = null;
319 $module = $plugin;
320 include($mods[$name].'/version.php');
321 return $plugin->version;
326 // block
327 if ($type === 'block') {
328 if ($source === 'installed') {
329 if ($CFG->version < 2013092001.02) {
330 return $DB->get_field('block', 'version', array('name'=>$name));
331 } else {
332 return get_config('block_'.$name, 'version');
334 } else {
335 $blocks = core_component::get_plugin_list('block');
336 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
337 return false;
338 } else {
339 $plugin = new stdclass();
340 include($blocks[$name].'/version.php');
341 return $plugin->version;
346 // all other plugin types
347 if ($source === 'installed') {
348 return get_config($type.'_'.$name, 'version');
349 } else {
350 $plugins = core_component::get_plugin_list($type);
351 if (empty($plugins[$name])) {
352 return false;
353 } else {
354 $plugin = new stdclass();
355 include($plugins[$name].'/version.php');
356 return $plugin->version;
362 * Delete all plugin tables
364 * @param string $name Name of plugin, used as table prefix
365 * @param string $file Path to install.xml file
366 * @param bool $feedback defaults to true
367 * @return bool Always returns true
369 function drop_plugin_tables($name, $file, $feedback=true) {
370 global $CFG, $DB;
372 // first try normal delete
373 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
374 return true;
377 // then try to find all tables that start with name and are not in any xml file
378 $used_tables = get_used_table_names();
380 $tables = $DB->get_tables();
382 /// Iterate over, fixing id fields as necessary
383 foreach ($tables as $table) {
384 if (in_array($table, $used_tables)) {
385 continue;
388 if (strpos($table, $name) !== 0) {
389 continue;
392 // found orphan table --> delete it
393 if ($DB->get_manager()->table_exists($table)) {
394 $xmldb_table = new xmldb_table($table);
395 $DB->get_manager()->drop_table($xmldb_table);
399 return true;
403 * Returns names of all known tables == tables that moodle knows about.
405 * @return array Array of lowercase table names
407 function get_used_table_names() {
408 $table_names = array();
409 $dbdirs = get_db_directories();
411 foreach ($dbdirs as $dbdir) {
412 $file = $dbdir.'/install.xml';
414 $xmldb_file = new xmldb_file($file);
416 if (!$xmldb_file->fileExists()) {
417 continue;
420 $loaded = $xmldb_file->loadXMLStructure();
421 $structure = $xmldb_file->getStructure();
423 if ($loaded and $tables = $structure->getTables()) {
424 foreach($tables as $table) {
425 $table_names[] = strtolower($table->getName());
430 return $table_names;
434 * Returns list of all directories where we expect install.xml files
435 * @return array Array of paths
437 function get_db_directories() {
438 global $CFG;
440 $dbdirs = array();
442 /// First, the main one (lib/db)
443 $dbdirs[] = $CFG->libdir.'/db';
445 /// Then, all the ones defined by core_component::get_plugin_types()
446 $plugintypes = core_component::get_plugin_types();
447 foreach ($plugintypes as $plugintype => $pluginbasedir) {
448 if ($plugins = core_component::get_plugin_list($plugintype)) {
449 foreach ($plugins as $plugin => $plugindir) {
450 $dbdirs[] = $plugindir.'/db';
455 return $dbdirs;
459 * Try to obtain or release the cron lock.
460 * @param string $name name of lock
461 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
462 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
463 * @return bool true if lock obtained
465 function set_cron_lock($name, $until, $ignorecurrent=false) {
466 global $DB;
467 if (empty($name)) {
468 debugging("Tried to get a cron lock for a null fieldname");
469 return false;
472 // remove lock by force == remove from config table
473 if (is_null($until)) {
474 set_config($name, null);
475 return true;
478 if (!$ignorecurrent) {
479 // read value from db - other processes might have changed it
480 $value = $DB->get_field('config', 'value', array('name'=>$name));
482 if ($value and $value > time()) {
483 //lock active
484 return false;
488 set_config($name, $until);
489 return true;
493 * Test if and critical warnings are present
494 * @return bool
496 function admin_critical_warnings_present() {
497 global $SESSION;
499 if (!has_capability('moodle/site:config', context_system::instance())) {
500 return 0;
503 if (!isset($SESSION->admin_critical_warning)) {
504 $SESSION->admin_critical_warning = 0;
505 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
506 $SESSION->admin_critical_warning = 1;
510 return $SESSION->admin_critical_warning;
514 * Detects if float supports at least 10 decimal digits
516 * Detects if float supports at least 10 decimal digits
517 * and also if float-->string conversion works as expected.
519 * @return bool true if problem found
521 function is_float_problem() {
522 $num1 = 2009010200.01;
523 $num2 = 2009010200.02;
525 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
529 * Try to verify that dataroot is not accessible from web.
531 * Try to verify that dataroot is not accessible from web.
532 * It is not 100% correct but might help to reduce number of vulnerable sites.
533 * Protection from httpd.conf and .htaccess is not detected properly.
535 * @uses INSECURE_DATAROOT_WARNING
536 * @uses INSECURE_DATAROOT_ERROR
537 * @param bool $fetchtest try to test public access by fetching file, default false
538 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
540 function is_dataroot_insecure($fetchtest=false) {
541 global $CFG;
543 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
545 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
546 $rp = strrev(trim($rp, '/'));
547 $rp = explode('/', $rp);
548 foreach($rp as $r) {
549 if (strpos($siteroot, '/'.$r.'/') === 0) {
550 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
551 } else {
552 break; // probably alias root
556 $siteroot = strrev($siteroot);
557 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
559 if (strpos($dataroot, $siteroot) !== 0) {
560 return false;
563 if (!$fetchtest) {
564 return INSECURE_DATAROOT_WARNING;
567 // now try all methods to fetch a test file using http protocol
569 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
570 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
571 $httpdocroot = $matches[1];
572 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
573 make_upload_directory('diag');
574 $testfile = $CFG->dataroot.'/diag/public.txt';
575 if (!file_exists($testfile)) {
576 file_put_contents($testfile, 'test file, do not delete');
577 @chmod($testfile, $CFG->filepermissions);
579 $teststr = trim(file_get_contents($testfile));
580 if (empty($teststr)) {
581 // hmm, strange
582 return INSECURE_DATAROOT_WARNING;
585 $testurl = $datarooturl.'/diag/public.txt';
586 if (extension_loaded('curl') and
587 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
588 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
589 ($ch = @curl_init($testurl)) !== false) {
590 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
591 curl_setopt($ch, CURLOPT_HEADER, false);
592 $data = curl_exec($ch);
593 if (!curl_errno($ch)) {
594 $data = trim($data);
595 if ($data === $teststr) {
596 curl_close($ch);
597 return INSECURE_DATAROOT_ERROR;
600 curl_close($ch);
603 if ($data = @file_get_contents($testurl)) {
604 $data = trim($data);
605 if ($data === $teststr) {
606 return INSECURE_DATAROOT_ERROR;
610 preg_match('|https?://([^/]+)|i', $testurl, $matches);
611 $sitename = $matches[1];
612 $error = 0;
613 if ($fp = @fsockopen($sitename, 80, $error)) {
614 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
615 $localurl = $matches[1];
616 $out = "GET $localurl HTTP/1.1\r\n";
617 $out .= "Host: $sitename\r\n";
618 $out .= "Connection: Close\r\n\r\n";
619 fwrite($fp, $out);
620 $data = '';
621 $incoming = false;
622 while (!feof($fp)) {
623 if ($incoming) {
624 $data .= fgets($fp, 1024);
625 } else if (@fgets($fp, 1024) === "\r\n") {
626 $incoming = true;
629 fclose($fp);
630 $data = trim($data);
631 if ($data === $teststr) {
632 return INSECURE_DATAROOT_ERROR;
636 return INSECURE_DATAROOT_WARNING;
640 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
642 function enable_cli_maintenance_mode() {
643 global $CFG, $SITE;
645 if (file_exists("$CFG->dataroot/climaintenance.html")) {
646 unlink("$CFG->dataroot/climaintenance.html");
649 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
650 $data = $CFG->maintenance_message;
651 $data = bootstrap_renderer::early_error_content($data, null, null, null);
652 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
654 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
655 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
657 } else {
658 $data = get_string('sitemaintenance', 'admin');
659 $data = bootstrap_renderer::early_error_content($data, null, null, null);
660 $data = bootstrap_renderer::plain_page(get_string('sitemaintenancetitle', 'admin',
661 format_string($SITE->fullname, true, ['context' => context_system::instance()])), $data);
664 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
665 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
668 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
672 * Interface for anything appearing in the admin tree
674 * The interface that is implemented by anything that appears in the admin tree
675 * block. It forces inheriting classes to define a method for checking user permissions
676 * and methods for finding something in the admin tree.
678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
680 interface part_of_admin_tree {
683 * Finds a named part_of_admin_tree.
685 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
686 * and not parentable_part_of_admin_tree, then this function should only check if
687 * $this->name matches $name. If it does, it should return a reference to $this,
688 * otherwise, it should return a reference to NULL.
690 * If a class inherits parentable_part_of_admin_tree, this method should be called
691 * recursively on all child objects (assuming, of course, the parent object's name
692 * doesn't match the search criterion).
694 * @param string $name The internal name of the part_of_admin_tree we're searching for.
695 * @return mixed An object reference or a NULL reference.
697 public function locate($name);
700 * Removes named part_of_admin_tree.
702 * @param string $name The internal name of the part_of_admin_tree we want to remove.
703 * @return bool success.
705 public function prune($name);
708 * Search using query
709 * @param string $query
710 * @return mixed array-object structure of found settings and pages
712 public function search($query);
715 * Verifies current user's access to this part_of_admin_tree.
717 * Used to check if the current user has access to this part of the admin tree or
718 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
719 * then this method is usually just a call to has_capability() in the site context.
721 * If a class inherits parentable_part_of_admin_tree, this method should return the
722 * logical OR of the return of check_access() on all child objects.
724 * @return bool True if the user has access, false if she doesn't.
726 public function check_access();
729 * Mostly useful for removing of some parts of the tree in admin tree block.
731 * @return True is hidden from normal list view
733 public function is_hidden();
736 * Show we display Save button at the page bottom?
737 * @return bool
739 public function show_save();
744 * Interface implemented by any part_of_admin_tree that has children.
746 * The interface implemented by any part_of_admin_tree that can be a parent
747 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
748 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
749 * include an add method for adding other part_of_admin_tree objects as children.
751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
753 interface parentable_part_of_admin_tree extends part_of_admin_tree {
756 * Adds a part_of_admin_tree object to the admin tree.
758 * Used to add a part_of_admin_tree object to this object or a child of this
759 * object. $something should only be added if $destinationname matches
760 * $this->name. If it doesn't, add should be called on child objects that are
761 * also parentable_part_of_admin_tree's.
763 * $something should be appended as the last child in the $destinationname. If the
764 * $beforesibling is specified, $something should be prepended to it. If the given
765 * sibling is not found, $something should be appended to the end of $destinationname
766 * and a developer debugging message should be displayed.
768 * @param string $destinationname The internal name of the new parent for $something.
769 * @param part_of_admin_tree $something The object to be added.
770 * @return bool True on success, false on failure.
772 public function add($destinationname, $something, $beforesibling = null);
778 * The object used to represent folders (a.k.a. categories) in the admin tree block.
780 * Each admin_category object contains a number of part_of_admin_tree objects.
782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
784 class admin_category implements parentable_part_of_admin_tree, linkable_settings_page {
786 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
787 protected $children;
788 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
789 public $name;
790 /** @var string The displayed name for this category. Usually obtained through get_string() */
791 public $visiblename;
792 /** @var bool Should this category be hidden in admin tree block? */
793 public $hidden;
794 /** @var mixed Either a string or an array or strings */
795 public $path;
796 /** @var mixed Either a string or an array or strings */
797 public $visiblepath;
799 /** @var array fast lookup category cache, all categories of one tree point to one cache */
800 protected $category_cache;
802 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
803 protected $sort = false;
804 /** @var bool If set to true children will be sorted in ascending order. */
805 protected $sortasc = true;
806 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
807 protected $sortsplit = true;
808 /** @var bool $sorted True if the children have been sorted and don't need resorting */
809 protected $sorted = false;
812 * Constructor for an empty admin category
814 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
815 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
816 * @param bool $hidden hide category in admin tree block, defaults to false
818 public function __construct($name, $visiblename, $hidden=false) {
819 $this->children = array();
820 $this->name = $name;
821 $this->visiblename = $visiblename;
822 $this->hidden = $hidden;
826 * Get the URL to view this settings page.
828 * @return moodle_url
830 public function get_settings_page_url(): moodle_url {
831 return new moodle_url(
832 '/admin/category.php',
834 'category' => $this->name,
840 * Returns a reference to the part_of_admin_tree object with internal name $name.
842 * @param string $name The internal name of the object we want.
843 * @param bool $findpath initialize path and visiblepath arrays
844 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
845 * defaults to false
847 public function locate($name, $findpath=false) {
848 if (!isset($this->category_cache[$this->name])) {
849 // somebody much have purged the cache
850 $this->category_cache[$this->name] = $this;
853 if ($this->name == $name) {
854 if ($findpath) {
855 $this->visiblepath[] = $this->visiblename;
856 $this->path[] = $this->name;
858 return $this;
861 // quick category lookup
862 if (!$findpath and isset($this->category_cache[$name])) {
863 return $this->category_cache[$name];
866 $return = NULL;
867 foreach($this->children as $childid=>$unused) {
868 if ($return = $this->children[$childid]->locate($name, $findpath)) {
869 break;
873 if (!is_null($return) and $findpath) {
874 $return->visiblepath[] = $this->visiblename;
875 $return->path[] = $this->name;
878 return $return;
882 * Search using query
884 * @param string query
885 * @return mixed array-object structure of found settings and pages
887 public function search($query) {
888 $result = array();
889 foreach ($this->get_children() as $child) {
890 $subsearch = $child->search($query);
891 if (!is_array($subsearch)) {
892 debugging('Incorrect search result from '.$child->name);
893 continue;
895 $result = array_merge($result, $subsearch);
897 return $result;
901 * Removes part_of_admin_tree object with internal name $name.
903 * @param string $name The internal name of the object we want to remove.
904 * @return bool success
906 public function prune($name) {
908 if ($this->name == $name) {
909 return false; //can not remove itself
912 foreach($this->children as $precedence => $child) {
913 if ($child->name == $name) {
914 // clear cache and delete self
915 while($this->category_cache) {
916 // delete the cache, but keep the original array address
917 array_pop($this->category_cache);
919 unset($this->children[$precedence]);
920 return true;
921 } else if ($this->children[$precedence]->prune($name)) {
922 return true;
925 return false;
929 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
931 * By default the new part of the tree is appended as the last child of the parent. You
932 * can specify a sibling node that the new part should be prepended to. If the given
933 * sibling is not found, the part is appended to the end (as it would be by default) and
934 * a developer debugging message is displayed.
936 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
937 * @param string $destinationame The internal name of the immediate parent that we want for $something.
938 * @param mixed $something A part_of_admin_tree or setting instance to be added.
939 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
940 * @return bool True if successfully added, false if $something can not be added.
942 public function add($parentname, $something, $beforesibling = null) {
943 global $CFG;
945 $parent = $this->locate($parentname);
946 if (is_null($parent)) {
947 debugging('parent does not exist!');
948 return false;
951 if ($something instanceof part_of_admin_tree) {
952 if (!($parent instanceof parentable_part_of_admin_tree)) {
953 debugging('error - parts of tree can be inserted only into parentable parts');
954 return false;
956 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
957 // The name of the node is already used, simply warn the developer that this should not happen.
958 // It is intentional to check for the debug level before performing the check.
959 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
961 if (is_null($beforesibling)) {
962 // Append $something as the parent's last child.
963 $parent->children[] = $something;
964 } else {
965 if (!is_string($beforesibling) or trim($beforesibling) === '') {
966 throw new coding_exception('Unexpected value of the beforesibling parameter');
968 // Try to find the position of the sibling.
969 $siblingposition = null;
970 foreach ($parent->children as $childposition => $child) {
971 if ($child->name === $beforesibling) {
972 $siblingposition = $childposition;
973 break;
976 if (is_null($siblingposition)) {
977 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
978 $parent->children[] = $something;
979 } else {
980 $parent->children = array_merge(
981 array_slice($parent->children, 0, $siblingposition),
982 array($something),
983 array_slice($parent->children, $siblingposition)
987 if ($something instanceof admin_category) {
988 if (isset($this->category_cache[$something->name])) {
989 debugging('Duplicate admin category name: '.$something->name);
990 } else {
991 $this->category_cache[$something->name] = $something;
992 $something->category_cache =& $this->category_cache;
993 foreach ($something->children as $child) {
994 // just in case somebody already added subcategories
995 if ($child instanceof admin_category) {
996 if (isset($this->category_cache[$child->name])) {
997 debugging('Duplicate admin category name: '.$child->name);
998 } else {
999 $this->category_cache[$child->name] = $child;
1000 $child->category_cache =& $this->category_cache;
1006 return true;
1008 } else {
1009 debugging('error - can not add this element');
1010 return false;
1016 * Checks if the user has access to anything in this category.
1018 * @return bool True if the user has access to at least one child in this category, false otherwise.
1020 public function check_access() {
1021 foreach ($this->children as $child) {
1022 if ($child->check_access()) {
1023 return true;
1026 return false;
1030 * Is this category hidden in admin tree block?
1032 * @return bool True if hidden
1034 public function is_hidden() {
1035 return $this->hidden;
1039 * Show we display Save button at the page bottom?
1040 * @return bool
1042 public function show_save() {
1043 foreach ($this->children as $child) {
1044 if ($child->show_save()) {
1045 return true;
1048 return false;
1052 * Sets sorting on this category.
1054 * Please note this function doesn't actually do the sorting.
1055 * It can be called anytime.
1056 * Sorting occurs when the user calls get_children.
1057 * Code using the children array directly won't see the sorted results.
1059 * @param bool $sort If set to true children will be sorted, if false they won't be.
1060 * @param bool $asc If true sorting will be ascending, otherwise descending.
1061 * @param bool $split If true we sort pages and sub categories separately.
1063 public function set_sorting($sort, $asc = true, $split = true) {
1064 $this->sort = (bool)$sort;
1065 $this->sortasc = (bool)$asc;
1066 $this->sortsplit = (bool)$split;
1070 * Returns the children associated with this category.
1072 * @return part_of_admin_tree[]
1074 public function get_children() {
1075 // If we should sort and it hasn't already been sorted.
1076 if ($this->sort && !$this->sorted) {
1077 if ($this->sortsplit) {
1078 $categories = array();
1079 $pages = array();
1080 foreach ($this->children as $child) {
1081 if ($child instanceof admin_category) {
1082 $categories[] = $child;
1083 } else {
1084 $pages[] = $child;
1087 core_collator::asort_objects_by_property($categories, 'visiblename');
1088 core_collator::asort_objects_by_property($pages, 'visiblename');
1089 if (!$this->sortasc) {
1090 $categories = array_reverse($categories);
1091 $pages = array_reverse($pages);
1093 $this->children = array_merge($pages, $categories);
1094 } else {
1095 core_collator::asort_objects_by_property($this->children, 'visiblename');
1096 if (!$this->sortasc) {
1097 $this->children = array_reverse($this->children);
1100 $this->sorted = true;
1102 return $this->children;
1106 * Magically gets a property from this object.
1108 * @param $property
1109 * @return part_of_admin_tree[]
1110 * @throws coding_exception
1112 public function __get($property) {
1113 if ($property === 'children') {
1114 return $this->get_children();
1116 throw new coding_exception('Invalid property requested.');
1120 * Magically sets a property against this object.
1122 * @param string $property
1123 * @param mixed $value
1124 * @throws coding_exception
1126 public function __set($property, $value) {
1127 if ($property === 'children') {
1128 $this->sorted = false;
1129 $this->children = $value;
1130 } else {
1131 throw new coding_exception('Invalid property requested.');
1136 * Checks if an inaccessible property is set.
1138 * @param string $property
1139 * @return bool
1140 * @throws coding_exception
1142 public function __isset($property) {
1143 if ($property === 'children') {
1144 return isset($this->children);
1146 throw new coding_exception('Invalid property requested.');
1152 * Root of admin settings tree, does not have any parent.
1154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1156 class admin_root extends admin_category {
1157 /** @var array List of errors */
1158 public $errors;
1159 /** @var string search query */
1160 public $search;
1161 /** @var bool full tree flag - true means all settings required, false only pages required */
1162 public $fulltree;
1163 /** @var bool flag indicating loaded tree */
1164 public $loaded;
1165 /** @var mixed site custom defaults overriding defaults in settings files*/
1166 public $custom_defaults;
1169 * @param bool $fulltree true means all settings required,
1170 * false only pages required
1172 public function __construct($fulltree) {
1173 global $CFG;
1175 parent::__construct('root', get_string('administration'), false);
1176 $this->errors = array();
1177 $this->search = '';
1178 $this->fulltree = $fulltree;
1179 $this->loaded = false;
1181 $this->category_cache = array();
1183 // load custom defaults if found
1184 $this->custom_defaults = null;
1185 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1186 if (is_readable($defaultsfile)) {
1187 $defaults = array();
1188 include($defaultsfile);
1189 if (is_array($defaults) and count($defaults)) {
1190 $this->custom_defaults = $defaults;
1196 * Empties children array, and sets loaded to false
1198 * @param bool $requirefulltree
1200 public function purge_children($requirefulltree) {
1201 $this->children = array();
1202 $this->fulltree = ($requirefulltree || $this->fulltree);
1203 $this->loaded = false;
1204 //break circular dependencies - this helps PHP 5.2
1205 while($this->category_cache) {
1206 array_pop($this->category_cache);
1208 $this->category_cache = array();
1214 * Links external PHP pages into the admin tree.
1216 * See detailed usage example at the top of this document (adminlib.php)
1218 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1220 class admin_externalpage implements part_of_admin_tree, linkable_settings_page {
1222 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1223 public $name;
1225 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1226 public $visiblename;
1228 /** @var string The external URL that we should link to when someone requests this external page. */
1229 public $url;
1231 /** @var array The role capability/permission a user must have to access this external page. */
1232 public $req_capability;
1234 /** @var object The context in which capability/permission should be checked, default is site context. */
1235 public $context;
1237 /** @var bool hidden in admin tree block. */
1238 public $hidden;
1240 /** @var mixed either string or array of string */
1241 public $path;
1243 /** @var array list of visible names of page parents */
1244 public $visiblepath;
1247 * Constructor for adding an external page into the admin tree.
1249 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1250 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1251 * @param string $url The external URL that we should link to when someone requests this external page.
1252 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1253 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1254 * @param stdClass $context The context the page relates to. Not sure what happens
1255 * if you specify something other than system or front page. Defaults to system.
1257 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1258 $this->name = $name;
1259 $this->visiblename = $visiblename;
1260 $this->url = $url;
1261 if (is_array($req_capability)) {
1262 $this->req_capability = $req_capability;
1263 } else {
1264 $this->req_capability = array($req_capability);
1266 $this->hidden = $hidden;
1267 $this->context = $context;
1271 * Get the URL to view this settings page.
1273 * @return moodle_url
1275 public function get_settings_page_url(): moodle_url {
1276 return new moodle_url($this->url);
1280 * Returns a reference to the part_of_admin_tree object with internal name $name.
1282 * @param string $name The internal name of the object we want.
1283 * @param bool $findpath defaults to false
1284 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1286 public function locate($name, $findpath=false) {
1287 if ($this->name == $name) {
1288 if ($findpath) {
1289 $this->visiblepath = array($this->visiblename);
1290 $this->path = array($this->name);
1292 return $this;
1293 } else {
1294 $return = NULL;
1295 return $return;
1300 * This function always returns false, required function by interface
1302 * @param string $name
1303 * @return false
1305 public function prune($name) {
1306 return false;
1310 * Search using query
1312 * @param string $query
1313 * @return mixed array-object structure of found settings and pages
1315 public function search($query) {
1316 $found = false;
1317 if (strpos(strtolower($this->name), $query) !== false) {
1318 $found = true;
1319 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1320 $found = true;
1322 if ($found) {
1323 $result = new stdClass();
1324 $result->page = $this;
1325 $result->settings = array();
1326 return array($this->name => $result);
1327 } else {
1328 return array();
1333 * Determines if the current user has access to this external page based on $this->req_capability.
1335 * @return bool True if user has access, false otherwise.
1337 public function check_access() {
1338 global $CFG;
1339 $context = empty($this->context) ? context_system::instance() : $this->context;
1340 foreach($this->req_capability as $cap) {
1341 if (has_capability($cap, $context)) {
1342 return true;
1345 return false;
1349 * Is this external page hidden in admin tree block?
1351 * @return bool True if hidden
1353 public function is_hidden() {
1354 return $this->hidden;
1358 * Show we display Save button at the page bottom?
1359 * @return bool
1361 public function show_save() {
1362 return false;
1367 * Used to store details of the dependency between two settings elements.
1369 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1370 * @copyright 2017 Davo Smith, Synergy Learning
1372 class admin_settingdependency {
1373 /** @var string the name of the setting to be shown/hidden */
1374 public $settingname;
1375 /** @var string the setting this is dependent on */
1376 public $dependenton;
1377 /** @var string the condition to show/hide the element */
1378 public $condition;
1379 /** @var string the value to compare against */
1380 public $value;
1382 /** @var string[] list of valid conditions */
1383 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1386 * admin_settingdependency constructor.
1387 * @param string $settingname
1388 * @param string $dependenton
1389 * @param string $condition
1390 * @param string $value
1391 * @throws \coding_exception
1393 public function __construct($settingname, $dependenton, $condition, $value) {
1394 $this->settingname = $this->parse_name($settingname);
1395 $this->dependenton = $this->parse_name($dependenton);
1396 $this->condition = $condition;
1397 $this->value = $value;
1399 if (!in_array($this->condition, self::$validconditions)) {
1400 throw new coding_exception("Invalid condition '$condition'");
1405 * Convert the setting name into the form field name.
1406 * @param string $name
1407 * @return string
1409 private function parse_name($name) {
1410 $bits = explode('/', $name);
1411 $name = array_pop($bits);
1412 $plugin = '';
1413 if ($bits) {
1414 $plugin = array_pop($bits);
1415 if ($plugin === 'moodle') {
1416 $plugin = '';
1419 return 's_'.$plugin.'_'.$name;
1423 * Gather together all the dependencies in a format suitable for initialising javascript
1424 * @param admin_settingdependency[] $dependencies
1425 * @return array
1427 public static function prepare_for_javascript($dependencies) {
1428 $result = [];
1429 foreach ($dependencies as $d) {
1430 if (!isset($result[$d->dependenton])) {
1431 $result[$d->dependenton] = [];
1433 if (!isset($result[$d->dependenton][$d->condition])) {
1434 $result[$d->dependenton][$d->condition] = [];
1436 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1437 $result[$d->dependenton][$d->condition][$d->value] = [];
1439 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1441 return $result;
1446 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1450 class admin_settingpage implements part_of_admin_tree, linkable_settings_page {
1452 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1453 public $name;
1455 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1456 public $visiblename;
1458 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1459 public $settings;
1461 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1462 protected $dependencies = [];
1464 /** @var array The role capability/permission a user must have to access this external page. */
1465 public $req_capability;
1467 /** @var object The context in which capability/permission should be checked, default is site context. */
1468 public $context;
1470 /** @var bool hidden in admin tree block. */
1471 public $hidden;
1473 /** @var mixed string of paths or array of strings of paths */
1474 public $path;
1476 /** @var array list of visible names of page parents */
1477 public $visiblepath;
1480 * see admin_settingpage for details of this function
1482 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1483 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1484 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1485 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1486 * @param stdClass $context The context the page relates to. Not sure what happens
1487 * if you specify something other than system or front page. Defaults to system.
1489 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1490 $this->settings = new stdClass();
1491 $this->name = $name;
1492 $this->visiblename = $visiblename;
1493 if (is_array($req_capability)) {
1494 $this->req_capability = $req_capability;
1495 } else {
1496 $this->req_capability = array($req_capability);
1498 $this->hidden = $hidden;
1499 $this->context = $context;
1503 * Get the URL to view this page.
1505 * @return moodle_url
1507 public function get_settings_page_url(): moodle_url {
1508 return new moodle_url(
1509 '/admin/settings.php',
1511 'section' => $this->name,
1517 * see admin_category
1519 * @param string $name
1520 * @param bool $findpath
1521 * @return mixed Object (this) if name == this->name, else returns null
1523 public function locate($name, $findpath=false) {
1524 if ($this->name == $name) {
1525 if ($findpath) {
1526 $this->visiblepath = array($this->visiblename);
1527 $this->path = array($this->name);
1529 return $this;
1530 } else {
1531 $return = NULL;
1532 return $return;
1537 * Search string in settings page.
1539 * @param string $query
1540 * @return array
1542 public function search($query) {
1543 $found = array();
1545 foreach ($this->settings as $setting) {
1546 if ($setting->is_related($query)) {
1547 $found[] = $setting;
1551 if ($found) {
1552 $result = new stdClass();
1553 $result->page = $this;
1554 $result->settings = $found;
1555 return array($this->name => $result);
1558 $found = false;
1559 if (strpos(strtolower($this->name), $query) !== false) {
1560 $found = true;
1561 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1562 $found = true;
1564 if ($found) {
1565 $result = new stdClass();
1566 $result->page = $this;
1567 $result->settings = array();
1568 return array($this->name => $result);
1569 } else {
1570 return array();
1575 * This function always returns false, required by interface
1577 * @param string $name
1578 * @return bool Always false
1580 public function prune($name) {
1581 return false;
1585 * adds an admin_setting to this admin_settingpage
1587 * 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
1588 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1590 * @param object $setting is the admin_setting object you want to add
1591 * @return bool true if successful, false if not
1593 public function add($setting) {
1594 if (!($setting instanceof admin_setting)) {
1595 debugging('error - not a setting instance');
1596 return false;
1599 $name = $setting->name;
1600 if ($setting->plugin) {
1601 $name = $setting->plugin . $name;
1603 $this->settings->{$name} = $setting;
1604 return true;
1608 * Hide the named setting if the specified condition is matched.
1610 * @param string $settingname
1611 * @param string $dependenton
1612 * @param string $condition
1613 * @param string $value
1615 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1616 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1618 // Reformat the dependency name to the plugin | name format used in the display.
1619 $dependenton = str_replace('/', ' | ', $dependenton);
1621 // Let the setting know, so it can be displayed underneath.
1622 $findname = str_replace('/', '', $settingname);
1623 foreach ($this->settings as $name => $setting) {
1624 if ($name === $findname) {
1625 $setting->add_dependent_on($dependenton);
1631 * see admin_externalpage
1633 * @return bool Returns true for yes false for no
1635 public function check_access() {
1636 global $CFG;
1637 $context = empty($this->context) ? context_system::instance() : $this->context;
1638 foreach($this->req_capability as $cap) {
1639 if (has_capability($cap, $context)) {
1640 return true;
1643 return false;
1647 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1648 * @return string Returns an XHTML string
1650 public function output_html() {
1651 $adminroot = admin_get_root();
1652 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1653 foreach($this->settings as $setting) {
1654 $fullname = $setting->get_full_name();
1655 if (array_key_exists($fullname, $adminroot->errors)) {
1656 $data = $adminroot->errors[$fullname]->data;
1657 } else {
1658 $data = $setting->get_setting();
1659 // do not use defaults if settings not available - upgrade settings handles the defaults!
1661 $return .= $setting->output_html($data);
1663 $return .= '</fieldset>';
1664 return $return;
1668 * Is this settings page hidden in admin tree block?
1670 * @return bool True if hidden
1672 public function is_hidden() {
1673 return $this->hidden;
1677 * Show we display Save button at the page bottom?
1678 * @return bool
1680 public function show_save() {
1681 foreach($this->settings as $setting) {
1682 if (empty($setting->nosave)) {
1683 return true;
1686 return false;
1690 * Should any of the settings on this page be shown / hidden based on conditions?
1691 * @return bool
1693 public function has_dependencies() {
1694 return (bool)$this->dependencies;
1698 * Format the setting show/hide conditions ready to initialise the page javascript
1699 * @return array
1701 public function get_dependencies_for_javascript() {
1702 if (!$this->has_dependencies()) {
1703 return [];
1705 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1711 * Admin settings class. Only exists on setting pages.
1712 * Read & write happens at this level; no authentication.
1714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1716 abstract class admin_setting {
1717 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1718 public $name;
1719 /** @var lang_string|string localised name */
1720 public $visiblename;
1721 /** @var string localised long description in Markdown format */
1722 public $description;
1723 /** @var mixed Can be string or array of string */
1724 public $defaultsetting;
1725 /** @var string */
1726 public $updatedcallback;
1727 /** @var mixed can be String or Null. Null means main config table */
1728 public $plugin; // null means main config table
1729 /** @var bool true indicates this setting does not actually save anything, just information */
1730 public $nosave = false;
1731 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1732 public $affectsmodinfo = false;
1733 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1734 private $flags = array();
1735 /** @var bool Whether this field must be forced LTR. */
1736 private $forceltr = null;
1737 /** @var array list of other settings that may cause this setting to be hidden */
1738 private $dependenton = [];
1739 /** @var bool Whether this setting uses a custom form control */
1740 protected $customcontrol = false;
1743 * Constructor
1744 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1745 * or 'myplugin/mysetting' for ones in config_plugins.
1746 * @param string $visiblename localised name
1747 * @param string $description localised long description
1748 * @param mixed $defaultsetting string or array depending on implementation
1750 public function __construct($name, $visiblename, $description, $defaultsetting) {
1751 $this->parse_setting_name($name);
1752 $this->visiblename = $visiblename;
1753 $this->description = $description;
1754 $this->defaultsetting = $defaultsetting;
1758 * Generic function to add a flag to this admin setting.
1760 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1761 * @param bool $default - The default for the flag
1762 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1763 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1765 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1766 if (empty($this->flags[$shortname])) {
1767 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1768 } else {
1769 $this->flags[$shortname]->set_options($enabled, $default);
1774 * Set the enabled options flag on this admin setting.
1776 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1777 * @param bool $default - The default for the flag
1779 public function set_enabled_flag_options($enabled, $default) {
1780 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1784 * Set the advanced options flag on this admin setting.
1786 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1787 * @param bool $default - The default for the flag
1789 public function set_advanced_flag_options($enabled, $default) {
1790 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1795 * Set the locked options flag on this admin setting.
1797 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1798 * @param bool $default - The default for the flag
1800 public function set_locked_flag_options($enabled, $default) {
1801 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1805 * Set the required options flag on this admin setting.
1807 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1808 * @param bool $default - The default for the flag.
1810 public function set_required_flag_options($enabled, $default) {
1811 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1815 * Is this option forced in config.php?
1817 * @return bool
1819 public function is_readonly(): bool {
1820 global $CFG;
1822 if (empty($this->plugin)) {
1823 if (array_key_exists($this->name, $CFG->config_php_settings)) {
1824 return true;
1826 } else {
1827 if (array_key_exists($this->plugin, $CFG->forced_plugin_settings)
1828 and array_key_exists($this->name, $CFG->forced_plugin_settings[$this->plugin])) {
1829 return true;
1832 return false;
1836 * Get the currently saved value for a setting flag
1838 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1839 * @return bool
1841 public function get_setting_flag_value(admin_setting_flag $flag) {
1842 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1843 if (!isset($value)) {
1844 $value = $flag->get_default();
1847 return !empty($value);
1851 * Get the list of defaults for the flags on this setting.
1853 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1855 public function get_setting_flag_defaults(& $defaults) {
1856 foreach ($this->flags as $flag) {
1857 if ($flag->is_enabled() && $flag->get_default()) {
1858 $defaults[] = $flag->get_displayname();
1864 * Output the input fields for the advanced and locked flags on this setting.
1866 * @param bool $adv - The current value of the advanced flag.
1867 * @param bool $locked - The current value of the locked flag.
1868 * @return string $output - The html for the flags.
1870 public function output_setting_flags() {
1871 $output = '';
1873 foreach ($this->flags as $flag) {
1874 if ($flag->is_enabled()) {
1875 $output .= $flag->output_setting_flag($this);
1879 if (!empty($output)) {
1880 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1882 return $output;
1886 * Write the values of the flags for this admin setting.
1888 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1889 * @return bool - true if successful.
1891 public function write_setting_flags($data) {
1892 $result = true;
1893 foreach ($this->flags as $flag) {
1894 $result = $result && $flag->write_setting_flag($this, $data);
1896 return $result;
1900 * Set up $this->name and potentially $this->plugin
1902 * Set up $this->name and possibly $this->plugin based on whether $name looks
1903 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1904 * on the names, that is, output a developer debug warning if the name
1905 * contains anything other than [a-zA-Z0-9_]+.
1907 * @param string $name the setting name passed in to the constructor.
1909 private function parse_setting_name($name) {
1910 $bits = explode('/', $name);
1911 if (count($bits) > 2) {
1912 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1914 $this->name = array_pop($bits);
1915 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1916 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1918 if (!empty($bits)) {
1919 $this->plugin = array_pop($bits);
1920 if ($this->plugin === 'moodle') {
1921 $this->plugin = null;
1922 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1923 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1929 * Returns the fullname prefixed by the plugin
1930 * @return string
1932 public function get_full_name() {
1933 return 's_'.$this->plugin.'_'.$this->name;
1937 * Returns the ID string based on plugin and name
1938 * @return string
1940 public function get_id() {
1941 return 'id_s_'.$this->plugin.'_'.$this->name;
1945 * @param bool $affectsmodinfo If true, changes to this setting will
1946 * cause the course cache to be rebuilt
1948 public function set_affects_modinfo($affectsmodinfo) {
1949 $this->affectsmodinfo = $affectsmodinfo;
1953 * Returns the config if possible
1955 * @return mixed returns config if successful else null
1957 public function config_read($name) {
1958 global $CFG;
1959 if (!empty($this->plugin)) {
1960 $value = get_config($this->plugin, $name);
1961 return $value === false ? NULL : $value;
1963 } else {
1964 if (isset($CFG->$name)) {
1965 return $CFG->$name;
1966 } else {
1967 return NULL;
1973 * Used to set a config pair and log change
1975 * @param string $name
1976 * @param mixed $value Gets converted to string if not null
1977 * @return bool Write setting to config table
1979 public function config_write($name, $value) {
1980 global $DB, $USER, $CFG;
1982 if ($this->nosave) {
1983 return true;
1986 // make sure it is a real change
1987 $oldvalue = get_config($this->plugin, $name);
1988 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1989 $value = is_null($value) ? null : (string)$value;
1991 if ($oldvalue === $value) {
1992 return true;
1995 // store change
1996 set_config($name, $value, $this->plugin);
1998 // Some admin settings affect course modinfo
1999 if ($this->affectsmodinfo) {
2000 // Clear course cache for all courses
2001 rebuild_course_cache(0, true);
2004 $this->add_to_config_log($name, $oldvalue, $value);
2006 return true; // BC only
2010 * Log config changes if necessary.
2011 * @param string $name
2012 * @param string $oldvalue
2013 * @param string $value
2015 protected function add_to_config_log($name, $oldvalue, $value) {
2016 add_to_config_log($name, $oldvalue, $value, $this->plugin);
2020 * Returns current value of this setting
2021 * @return mixed array or string depending on instance, NULL means not set yet
2023 public abstract function get_setting();
2026 * Returns default setting if exists
2027 * @return mixed array or string depending on instance; NULL means no default, user must supply
2029 public function get_defaultsetting() {
2030 $adminroot = admin_get_root(false, false);
2031 if (!empty($adminroot->custom_defaults)) {
2032 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
2033 if (isset($adminroot->custom_defaults[$plugin])) {
2034 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
2035 return $adminroot->custom_defaults[$plugin][$this->name];
2039 return $this->defaultsetting;
2043 * Store new setting
2045 * @param mixed $data string or array, must not be NULL
2046 * @return string empty string if ok, string error message otherwise
2048 public abstract function write_setting($data);
2051 * Return part of form with setting
2052 * This function should always be overwritten
2054 * @param mixed $data array or string depending on setting
2055 * @param string $query
2056 * @return string
2058 public function output_html($data, $query='') {
2059 // should be overridden
2060 return;
2064 * Function called if setting updated - cleanup, cache reset, etc.
2065 * @param string $functionname Sets the function name
2066 * @return void
2068 public function set_updatedcallback($functionname) {
2069 $this->updatedcallback = $functionname;
2073 * Execute postupdatecallback if necessary.
2074 * @param mixed $original original value before write_setting()
2075 * @return bool true if changed, false if not.
2077 public function post_write_settings($original) {
2078 // Comparison must work for arrays too.
2079 if (serialize($original) === serialize($this->get_setting())) {
2080 return false;
2083 $callbackfunction = $this->updatedcallback;
2084 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2085 $callbackfunction($this->get_full_name());
2087 return true;
2091 * Is setting related to query text - used when searching
2092 * @param string $query
2093 * @return bool
2095 public function is_related($query) {
2096 if (strpos(strtolower($this->name), $query) !== false) {
2097 return true;
2099 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2100 return true;
2102 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2103 return true;
2105 $current = $this->get_setting();
2106 if (!is_null($current)) {
2107 if (is_string($current)) {
2108 if (strpos(core_text::strtolower($current), $query) !== false) {
2109 return true;
2113 $default = $this->get_defaultsetting();
2114 if (!is_null($default)) {
2115 if (is_string($default)) {
2116 if (strpos(core_text::strtolower($default), $query) !== false) {
2117 return true;
2121 return false;
2125 * Get whether this should be displayed in LTR mode.
2127 * @return bool|null
2129 public function get_force_ltr() {
2130 return $this->forceltr;
2134 * Set whether to force LTR or not.
2136 * @param bool $value True when forced, false when not force, null when unknown.
2138 public function set_force_ltr($value) {
2139 $this->forceltr = $value;
2143 * Add a setting to the list of those that could cause this one to be hidden
2144 * @param string $dependenton
2146 public function add_dependent_on($dependenton) {
2147 $this->dependenton[] = $dependenton;
2151 * Get a list of the settings that could cause this one to be hidden.
2152 * @return array
2154 public function get_dependent_on() {
2155 return $this->dependenton;
2159 * Whether this setting uses a custom form control.
2160 * This function is especially useful to decide if we should render a label element for this setting or not.
2162 * @return bool
2164 public function has_custom_form_control(): bool {
2165 return $this->customcontrol;
2170 * An additional option that can be applied to an admin setting.
2171 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2173 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2175 class admin_setting_flag {
2176 /** @var bool Flag to indicate if this option can be toggled for this setting */
2177 private $enabled = false;
2178 /** @var bool Flag to indicate if this option defaults to true or false */
2179 private $default = false;
2180 /** @var string Short string used to create setting name - e.g. 'adv' */
2181 private $shortname = '';
2182 /** @var string String used as the label for this flag */
2183 private $displayname = '';
2184 /** @const Checkbox for this flag is displayed in admin page */
2185 const ENABLED = true;
2186 /** @const Checkbox for this flag is not displayed in admin page */
2187 const DISABLED = false;
2190 * Constructor
2192 * @param bool $enabled Can this option can be toggled.
2193 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2194 * @param bool $default The default checked state for this setting option.
2195 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2196 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2198 public function __construct($enabled, $default, $shortname, $displayname) {
2199 $this->shortname = $shortname;
2200 $this->displayname = $displayname;
2201 $this->set_options($enabled, $default);
2205 * Update the values of this setting options class
2207 * @param bool $enabled Can this option can be toggled.
2208 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2209 * @param bool $default The default checked state for this setting option.
2211 public function set_options($enabled, $default) {
2212 $this->enabled = $enabled;
2213 $this->default = $default;
2217 * Should this option appear in the interface and be toggleable?
2219 * @return bool Is it enabled?
2221 public function is_enabled() {
2222 return $this->enabled;
2226 * Should this option be checked by default?
2228 * @return bool Is it on by default?
2230 public function get_default() {
2231 return $this->default;
2235 * Return the short name for this flag. e.g. 'adv' or 'locked'
2237 * @return string
2239 public function get_shortname() {
2240 return $this->shortname;
2244 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2246 * @return string
2248 public function get_displayname() {
2249 return $this->displayname;
2253 * Save the submitted data for this flag - or set it to the default if $data is null.
2255 * @param admin_setting $setting - The admin setting for this flag
2256 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2257 * @return bool
2259 public function write_setting_flag(admin_setting $setting, $data) {
2260 $result = true;
2261 if ($this->is_enabled()) {
2262 if (!isset($data)) {
2263 $value = $this->get_default();
2264 } else {
2265 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2267 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2270 return $result;
2275 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2277 * @param admin_setting $setting - The admin setting for this flag
2278 * @return string - The html for the checkbox.
2280 public function output_setting_flag(admin_setting $setting) {
2281 global $OUTPUT;
2283 $value = $setting->get_setting_flag_value($this);
2285 $context = new stdClass();
2286 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2287 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2288 $context->value = 1;
2289 $context->checked = $value ? true : false;
2290 $context->label = $this->get_displayname();
2292 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2298 * No setting - just heading and text.
2300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2302 class admin_setting_heading extends admin_setting {
2305 * not a setting, just text
2306 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2307 * @param string $heading heading
2308 * @param string $information text in box
2310 public function __construct($name, $heading, $information) {
2311 $this->nosave = true;
2312 parent::__construct($name, $heading, $information, '');
2316 * Always returns true
2317 * @return bool Always returns true
2319 public function get_setting() {
2320 return true;
2324 * Always returns true
2325 * @return bool Always returns true
2327 public function get_defaultsetting() {
2328 return true;
2332 * Never write settings
2333 * @return string Always returns an empty string
2335 public function write_setting($data) {
2336 // do not write any setting
2337 return '';
2341 * Returns an HTML string
2342 * @return string Returns an HTML string
2344 public function output_html($data, $query='') {
2345 global $OUTPUT;
2346 $context = new stdClass();
2347 $context->title = $this->visiblename;
2348 $context->description = $this->description;
2349 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2350 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2355 * No setting - just name and description in same row.
2357 * @copyright 2018 onwards Amaia Anabitarte
2358 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2360 class admin_setting_description extends admin_setting {
2363 * Not a setting, just text
2365 * @param string $name
2366 * @param string $visiblename
2367 * @param string $description
2369 public function __construct($name, $visiblename, $description) {
2370 $this->nosave = true;
2371 parent::__construct($name, $visiblename, $description, '');
2375 * Always returns true
2377 * @return bool Always returns true
2379 public function get_setting() {
2380 return true;
2384 * Always returns true
2386 * @return bool Always returns true
2388 public function get_defaultsetting() {
2389 return true;
2393 * Never write settings
2395 * @param mixed $data Gets converted to str for comparison against yes value
2396 * @return string Always returns an empty string
2398 public function write_setting($data) {
2399 // Do not write any setting.
2400 return '';
2404 * Returns an HTML string
2406 * @param string $data
2407 * @param string $query
2408 * @return string Returns an HTML string
2410 public function output_html($data, $query='') {
2411 global $OUTPUT;
2413 $context = new stdClass();
2414 $context->title = $this->visiblename;
2415 $context->description = $this->description;
2417 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2424 * The most flexible setting, the user enters text.
2426 * This type of field should be used for config settings which are using
2427 * English words and are not localised (passwords, database name, list of values, ...).
2429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2431 class admin_setting_configtext extends admin_setting {
2433 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2434 public $paramtype;
2435 /** @var int default field size */
2436 public $size;
2439 * Config text constructor
2441 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2442 * @param string $visiblename localised
2443 * @param string $description long localised info
2444 * @param string $defaultsetting
2445 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2446 * @param int $size default field size
2448 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2449 $this->paramtype = $paramtype;
2450 if (!is_null($size)) {
2451 $this->size = $size;
2452 } else {
2453 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2455 parent::__construct($name, $visiblename, $description, $defaultsetting);
2459 * Get whether this should be displayed in LTR mode.
2461 * Try to guess from the PARAM type unless specifically set.
2463 public function get_force_ltr() {
2464 $forceltr = parent::get_force_ltr();
2465 if ($forceltr === null) {
2466 return !is_rtl_compatible($this->paramtype);
2468 return $forceltr;
2472 * Return the setting
2474 * @return mixed returns config if successful else null
2476 public function get_setting() {
2477 return $this->config_read($this->name);
2480 public function write_setting($data) {
2481 if ($this->paramtype === PARAM_INT and $data === '') {
2482 // do not complain if '' used instead of 0
2483 $data = 0;
2485 // $data is a string
2486 $validated = $this->validate($data);
2487 if ($validated !== true) {
2488 return $validated;
2490 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2494 * Validate data before storage
2495 * @param string data
2496 * @return mixed true if ok string if error found
2498 public function validate($data) {
2499 // allow paramtype to be a custom regex if it is the form of /pattern/
2500 if (preg_match('#^/.*/$#', $this->paramtype)) {
2501 if (preg_match($this->paramtype, $data)) {
2502 return true;
2503 } else {
2504 return get_string('validateerror', 'admin');
2507 } else if ($this->paramtype === PARAM_RAW) {
2508 return true;
2510 } else {
2511 $cleaned = clean_param($data, $this->paramtype);
2512 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2513 return true;
2514 } else {
2515 return get_string('validateerror', 'admin');
2521 * Return an XHTML string for the setting
2522 * @return string Returns an XHTML string
2524 public function output_html($data, $query='') {
2525 global $OUTPUT;
2527 $default = $this->get_defaultsetting();
2528 $context = (object) [
2529 'size' => $this->size,
2530 'id' => $this->get_id(),
2531 'name' => $this->get_full_name(),
2532 'value' => $data,
2533 'forceltr' => $this->get_force_ltr(),
2534 'readonly' => $this->is_readonly(),
2536 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2538 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2543 * Text input with a maximum length constraint.
2545 * @copyright 2015 onwards Ankit Agarwal
2546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2548 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2550 /** @var int maximum number of chars allowed. */
2551 protected $maxlength;
2554 * Config text constructor
2556 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2557 * or 'myplugin/mysetting' for ones in config_plugins.
2558 * @param string $visiblename localised
2559 * @param string $description long localised info
2560 * @param string $defaultsetting
2561 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2562 * @param int $size default field size
2563 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2565 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2566 $size=null, $maxlength = 0) {
2567 $this->maxlength = $maxlength;
2568 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2572 * Validate data before storage
2574 * @param string $data data
2575 * @return mixed true if ok string if error found
2577 public function validate($data) {
2578 $parentvalidation = parent::validate($data);
2579 if ($parentvalidation === true) {
2580 if ($this->maxlength > 0) {
2581 // Max length check.
2582 $length = core_text::strlen($data);
2583 if ($length > $this->maxlength) {
2584 return get_string('maximumchars', 'moodle', $this->maxlength);
2586 return true;
2587 } else {
2588 return true; // No max length check needed.
2590 } else {
2591 return $parentvalidation;
2597 * General text area without html editor.
2599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2601 class admin_setting_configtextarea extends admin_setting_configtext {
2602 private $rows;
2603 private $cols;
2606 * @param string $name
2607 * @param string $visiblename
2608 * @param string $description
2609 * @param mixed $defaultsetting string or array
2610 * @param mixed $paramtype
2611 * @param string $cols The number of columns to make the editor
2612 * @param string $rows The number of rows to make the editor
2614 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2615 $this->rows = $rows;
2616 $this->cols = $cols;
2617 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2621 * Returns an XHTML string for the editor
2623 * @param string $data
2624 * @param string $query
2625 * @return string XHTML string for the editor
2627 public function output_html($data, $query='') {
2628 global $OUTPUT;
2630 $default = $this->get_defaultsetting();
2631 $defaultinfo = $default;
2632 if (!is_null($default) and $default !== '') {
2633 $defaultinfo = "\n".$default;
2636 $context = (object) [
2637 'cols' => $this->cols,
2638 'rows' => $this->rows,
2639 'id' => $this->get_id(),
2640 'name' => $this->get_full_name(),
2641 'value' => $data,
2642 'forceltr' => $this->get_force_ltr(),
2643 'readonly' => $this->is_readonly(),
2645 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2647 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2652 * General text area with html editor.
2654 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2657 * @param string $name
2658 * @param string $visiblename
2659 * @param string $description
2660 * @param mixed $defaultsetting string or array
2661 * @param mixed $paramtype
2663 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2664 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2665 $this->set_force_ltr(false);
2666 editors_head_setup();
2670 * Returns an XHTML string for the editor
2672 * @param string $data
2673 * @param string $query
2674 * @return string XHTML string for the editor
2676 public function output_html($data, $query='') {
2677 $editor = editors_get_preferred_editor(FORMAT_HTML);
2678 $editor->set_text($data);
2679 $editor->use_editor($this->get_id(), array('noclean'=>true));
2680 return parent::output_html($data, $query);
2684 * Checks if data has empty html.
2686 * @param string $data
2687 * @return string Empty when no errors.
2689 public function write_setting($data) {
2690 if (trim(html_to_text($data)) === '') {
2691 $data = '';
2693 return parent::write_setting($data);
2699 * Password field, allows unmasking of password
2701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2703 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2706 * Constructor
2707 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2708 * @param string $visiblename localised
2709 * @param string $description long localised info
2710 * @param string $defaultsetting default password
2712 public function __construct($name, $visiblename, $description, $defaultsetting) {
2713 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2717 * Log config changes if necessary.
2718 * @param string $name
2719 * @param string $oldvalue
2720 * @param string $value
2722 protected function add_to_config_log($name, $oldvalue, $value) {
2723 if ($value !== '') {
2724 $value = '********';
2726 if ($oldvalue !== '' and $oldvalue !== null) {
2727 $oldvalue = '********';
2729 parent::add_to_config_log($name, $oldvalue, $value);
2733 * Returns HTML for the field.
2735 * @param string $data Value for the field
2736 * @param string $query Passed as final argument for format_admin_setting
2737 * @return string Rendered HTML
2739 public function output_html($data, $query='') {
2740 global $OUTPUT;
2742 $context = (object) [
2743 'id' => $this->get_id(),
2744 'name' => $this->get_full_name(),
2745 'size' => $this->size,
2746 'value' => $this->is_readonly() ? null : $data,
2747 'forceltr' => $this->get_force_ltr(),
2748 'readonly' => $this->is_readonly(),
2750 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2751 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2756 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2759 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2761 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2764 * Constructor
2766 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2767 * @param string $visiblename localised
2768 * @param string $description long localised info
2769 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2771 public function __construct($name, $visiblename, $description, $defaultsetting) {
2772 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2773 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2778 * Admin setting class for encrypted values using secure encryption.
2780 * @copyright 2019 The Open University
2781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2783 class admin_setting_encryptedpassword extends admin_setting {
2786 * Constructor. Same as parent except that the default value is always an empty string.
2788 * @param string $name Internal name used in config table
2789 * @param string $visiblename Name shown on form
2790 * @param string $description Description that appears below field
2792 public function __construct(string $name, string $visiblename, string $description) {
2793 parent::__construct($name, $visiblename, $description, '');
2796 public function get_setting() {
2797 return $this->config_read($this->name);
2800 public function write_setting($data) {
2801 $data = trim($data);
2802 if ($data === '') {
2803 // Value can really be set to nothing.
2804 $savedata = '';
2805 } else {
2806 // Encrypt value before saving it.
2807 $savedata = \core\encryption::encrypt($data);
2809 return ($this->config_write($this->name, $savedata) ? '' : get_string('errorsetting', 'admin'));
2812 public function output_html($data, $query='') {
2813 global $OUTPUT;
2815 $default = $this->get_defaultsetting();
2816 $context = (object) [
2817 'id' => $this->get_id(),
2818 'name' => $this->get_full_name(),
2819 'set' => $data !== '',
2820 'novalue' => $this->get_setting() === null
2822 $element = $OUTPUT->render_from_template('core_admin/setting_encryptedpassword', $context);
2824 return format_admin_setting($this, $this->visiblename, $element, $this->description,
2825 true, '', $default, $query);
2830 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2831 * Note: Only advanced makes sense right now - locked does not.
2833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2835 class admin_setting_configempty extends admin_setting_configtext {
2838 * @param string $name
2839 * @param string $visiblename
2840 * @param string $description
2842 public function __construct($name, $visiblename, $description) {
2843 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2847 * Returns an XHTML string for the hidden field
2849 * @param string $data
2850 * @param string $query
2851 * @return string XHTML string for the editor
2853 public function output_html($data, $query='') {
2854 global $OUTPUT;
2856 $context = (object) [
2857 'id' => $this->get_id(),
2858 'name' => $this->get_full_name()
2860 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2862 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2868 * Path to directory
2870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2872 class admin_setting_configfile extends admin_setting_configtext {
2874 * Constructor
2875 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2876 * @param string $visiblename localised
2877 * @param string $description long localised info
2878 * @param string $defaultdirectory default directory location
2880 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2881 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2885 * Returns XHTML for the field
2887 * Returns XHTML for the field and also checks whether the file
2888 * specified in $data exists using file_exists()
2890 * @param string $data File name and path to use in value attr
2891 * @param string $query
2892 * @return string XHTML field
2894 public function output_html($data, $query='') {
2895 global $CFG, $OUTPUT;
2897 $default = $this->get_defaultsetting();
2898 $context = (object) [
2899 'id' => $this->get_id(),
2900 'name' => $this->get_full_name(),
2901 'size' => $this->size,
2902 'value' => $data,
2903 'showvalidity' => !empty($data),
2904 'valid' => $data && file_exists($data),
2905 'readonly' => !empty($CFG->preventexecpath) || $this->is_readonly(),
2906 'forceltr' => $this->get_force_ltr(),
2909 if ($context->readonly) {
2910 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2913 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2915 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2919 * Checks if execpatch has been disabled in config.php
2921 public function write_setting($data) {
2922 global $CFG;
2923 if (!empty($CFG->preventexecpath)) {
2924 if ($this->get_setting() === null) {
2925 // Use default during installation.
2926 $data = $this->get_defaultsetting();
2927 if ($data === null) {
2928 $data = '';
2930 } else {
2931 return '';
2934 return parent::write_setting($data);
2941 * Path to executable file
2943 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2945 class admin_setting_configexecutable extends admin_setting_configfile {
2948 * Returns an XHTML field
2950 * @param string $data This is the value for the field
2951 * @param string $query
2952 * @return string XHTML field
2954 public function output_html($data, $query='') {
2955 global $CFG, $OUTPUT;
2956 $default = $this->get_defaultsetting();
2957 require_once("$CFG->libdir/filelib.php");
2959 $context = (object) [
2960 'id' => $this->get_id(),
2961 'name' => $this->get_full_name(),
2962 'size' => $this->size,
2963 'value' => $data,
2964 'showvalidity' => !empty($data),
2965 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2966 'readonly' => !empty($CFG->preventexecpath),
2967 'forceltr' => $this->get_force_ltr()
2970 if (!empty($CFG->preventexecpath)) {
2971 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2974 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2976 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2982 * Path to directory
2984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2986 class admin_setting_configdirectory extends admin_setting_configfile {
2989 * Returns an XHTML field
2991 * @param string $data This is the value for the field
2992 * @param string $query
2993 * @return string XHTML
2995 public function output_html($data, $query='') {
2996 global $CFG, $OUTPUT;
2997 $default = $this->get_defaultsetting();
2999 $context = (object) [
3000 'id' => $this->get_id(),
3001 'name' => $this->get_full_name(),
3002 'size' => $this->size,
3003 'value' => $data,
3004 'showvalidity' => !empty($data),
3005 'valid' => $data && file_exists($data) && is_dir($data),
3006 'readonly' => !empty($CFG->preventexecpath),
3007 'forceltr' => $this->get_force_ltr()
3010 if (!empty($CFG->preventexecpath)) {
3011 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
3014 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
3016 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
3022 * Checkbox
3024 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3026 class admin_setting_configcheckbox extends admin_setting {
3027 /** @var string Value used when checked */
3028 public $yes;
3029 /** @var string Value used when not checked */
3030 public $no;
3033 * Constructor
3034 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3035 * @param string $visiblename localised
3036 * @param string $description long localised info
3037 * @param string $defaultsetting
3038 * @param string $yes value used when checked
3039 * @param string $no value used when not checked
3041 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3042 parent::__construct($name, $visiblename, $description, $defaultsetting);
3043 $this->yes = (string)$yes;
3044 $this->no = (string)$no;
3048 * Retrieves the current setting using the objects name
3050 * @return string
3052 public function get_setting() {
3053 return $this->config_read($this->name);
3057 * Sets the value for the setting
3059 * Sets the value for the setting to either the yes or no values
3060 * of the object by comparing $data to yes
3062 * @param mixed $data Gets converted to str for comparison against yes value
3063 * @return string empty string or error
3065 public function write_setting($data) {
3066 if ((string)$data === $this->yes) { // convert to strings before comparison
3067 $data = $this->yes;
3068 } else {
3069 $data = $this->no;
3071 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3075 * Returns an XHTML checkbox field
3077 * @param string $data If $data matches yes then checkbox is checked
3078 * @param string $query
3079 * @return string XHTML field
3081 public function output_html($data, $query='') {
3082 global $OUTPUT;
3084 $context = (object) [
3085 'id' => $this->get_id(),
3086 'name' => $this->get_full_name(),
3087 'no' => $this->no,
3088 'value' => $this->yes,
3089 'checked' => (string) $data === $this->yes,
3090 'readonly' => $this->is_readonly(),
3093 $default = $this->get_defaultsetting();
3094 if (!is_null($default)) {
3095 if ((string)$default === $this->yes) {
3096 $defaultinfo = get_string('checkboxyes', 'admin');
3097 } else {
3098 $defaultinfo = get_string('checkboxno', 'admin');
3100 } else {
3101 $defaultinfo = NULL;
3104 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
3106 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3112 * Multiple checkboxes, each represents different value, stored in csv format
3114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3116 class admin_setting_configmulticheckbox extends admin_setting {
3117 /** @var array Array of choices value=>label */
3118 public $choices;
3119 /** @var callable|null Loader function for choices */
3120 protected $choiceloader = null;
3123 * Constructor: uses parent::__construct
3125 * The $choices parameter may be either an array of $value => $label format,
3126 * e.g. [1 => get_string('yes')], or a callback function which takes no parameters and
3127 * returns an array in that format.
3129 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3130 * @param string $visiblename localised
3131 * @param string $description long localised info
3132 * @param array $defaultsetting array of selected
3133 * @param array|callable $choices array of $value => $label for each checkbox, or a callback
3135 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3136 if (is_array($choices)) {
3137 $this->choices = $choices;
3139 if (is_callable($choices)) {
3140 $this->choiceloader = $choices;
3142 parent::__construct($name, $visiblename, $description, $defaultsetting);
3146 * This function may be used in ancestors for lazy loading of choices
3148 * Override this method if loading of choices is expensive, such
3149 * as when it requires multiple db requests.
3151 * @return bool true if loaded, false if error
3153 public function load_choices() {
3154 if ($this->choiceloader) {
3155 if (!is_array($this->choices)) {
3156 $this->choices = call_user_func($this->choiceloader);
3159 return true;
3163 * Is setting related to query text - used when searching
3165 * @param string $query
3166 * @return bool true on related, false on not or failure
3168 public function is_related($query) {
3169 if (!$this->load_choices() or empty($this->choices)) {
3170 return false;
3172 if (parent::is_related($query)) {
3173 return true;
3176 foreach ($this->choices as $desc) {
3177 if (strpos(core_text::strtolower($desc), $query) !== false) {
3178 return true;
3181 return false;
3185 * Returns the current setting if it is set
3187 * @return mixed null if null, else an array
3189 public function get_setting() {
3190 $result = $this->config_read($this->name);
3192 if (is_null($result)) {
3193 return NULL;
3195 if ($result === '') {
3196 return array();
3198 $enabled = explode(',', $result);
3199 $setting = array();
3200 foreach ($enabled as $option) {
3201 $setting[$option] = 1;
3203 return $setting;
3207 * Saves the setting(s) provided in $data
3209 * @param array $data An array of data, if not array returns empty str
3210 * @return mixed empty string on useless data or bool true=success, false=failed
3212 public function write_setting($data) {
3213 if (!is_array($data)) {
3214 return ''; // ignore it
3216 if (!$this->load_choices() or empty($this->choices)) {
3217 return '';
3219 unset($data['xxxxx']);
3220 $result = array();
3221 foreach ($data as $key => $value) {
3222 if ($value and array_key_exists($key, $this->choices)) {
3223 $result[] = $key;
3226 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3230 * Returns XHTML field(s) as required by choices
3232 * Relies on data being an array should data ever be another valid vartype with
3233 * acceptable value this may cause a warning/error
3234 * if (!is_array($data)) would fix the problem
3236 * @todo Add vartype handling to ensure $data is an array
3238 * @param array $data An array of checked values
3239 * @param string $query
3240 * @return string XHTML field
3242 public function output_html($data, $query='') {
3243 global $OUTPUT;
3245 if (!$this->load_choices() or empty($this->choices)) {
3246 return '';
3249 $default = $this->get_defaultsetting();
3250 if (is_null($default)) {
3251 $default = array();
3253 if (is_null($data)) {
3254 $data = array();
3257 $context = (object) [
3258 'id' => $this->get_id(),
3259 'name' => $this->get_full_name(),
3262 $options = array();
3263 $defaults = array();
3264 foreach ($this->choices as $key => $description) {
3265 if (!empty($default[$key])) {
3266 $defaults[] = $description;
3269 $options[] = [
3270 'key' => $key,
3271 'checked' => !empty($data[$key]),
3272 'label' => highlightfast($query, $description)
3276 if (is_null($default)) {
3277 $defaultinfo = null;
3278 } else if (!empty($defaults)) {
3279 $defaultinfo = implode(', ', $defaults);
3280 } else {
3281 $defaultinfo = get_string('none');
3284 $context->options = $options;
3285 $context->hasoptions = !empty($options);
3287 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3289 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3296 * Multiple checkboxes 2, value stored as string 00101011
3298 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3300 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3303 * Returns the setting if set
3305 * @return mixed null if not set, else an array of set settings
3307 public function get_setting() {
3308 $result = $this->config_read($this->name);
3309 if (is_null($result)) {
3310 return NULL;
3312 if (!$this->load_choices()) {
3313 return NULL;
3315 $result = str_pad($result, count($this->choices), '0');
3316 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3317 $setting = array();
3318 foreach ($this->choices as $key=>$unused) {
3319 $value = array_shift($result);
3320 if ($value) {
3321 $setting[$key] = 1;
3324 return $setting;
3328 * Save setting(s) provided in $data param
3330 * @param array $data An array of settings to save
3331 * @return mixed empty string for bad data or bool true=>success, false=>error
3333 public function write_setting($data) {
3334 if (!is_array($data)) {
3335 return ''; // ignore it
3337 if (!$this->load_choices() or empty($this->choices)) {
3338 return '';
3340 $result = '';
3341 foreach ($this->choices as $key=>$unused) {
3342 if (!empty($data[$key])) {
3343 $result .= '1';
3344 } else {
3345 $result .= '0';
3348 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3354 * Select one value from list
3356 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3358 class admin_setting_configselect extends admin_setting {
3359 /** @var array Array of choices value=>label */
3360 public $choices;
3361 /** @var array Array of choices grouped using optgroups */
3362 public $optgroups;
3363 /** @var callable|null Loader function for choices */
3364 protected $choiceloader = null;
3365 /** @var callable|null Validation function */
3366 protected $validatefunction = null;
3369 * Constructor.
3371 * If you want to lazy-load the choices, pass a callback function that returns a choice
3372 * array for the $choices parameter.
3374 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3375 * @param string $visiblename localised
3376 * @param string $description long localised info
3377 * @param string|int $defaultsetting
3378 * @param array|callable|null $choices array of $value=>$label for each selection, or callback
3380 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3381 // Look for optgroup and single options.
3382 if (is_array($choices)) {
3383 $this->choices = [];
3384 foreach ($choices as $key => $val) {
3385 if (is_array($val)) {
3386 $this->optgroups[$key] = $val;
3387 $this->choices = array_merge($this->choices, $val);
3388 } else {
3389 $this->choices[$key] = $val;
3393 if (is_callable($choices)) {
3394 $this->choiceloader = $choices;
3397 parent::__construct($name, $visiblename, $description, $defaultsetting);
3401 * Sets a validate function.
3403 * The callback will be passed one parameter, the new setting value, and should return either
3404 * an empty string '' if the value is OK, or an error message if not.
3406 * @param callable|null $validatefunction Validate function or null to clear
3407 * @since Moodle 3.10
3409 public function set_validate_function(?callable $validatefunction = null) {
3410 $this->validatefunction = $validatefunction;
3414 * This function may be used in ancestors for lazy loading of choices
3416 * Override this method if loading of choices is expensive, such
3417 * as when it requires multiple db requests.
3419 * @return bool true if loaded, false if error
3421 public function load_choices() {
3422 if ($this->choiceloader) {
3423 if (!is_array($this->choices)) {
3424 $this->choices = call_user_func($this->choiceloader);
3426 return true;
3428 return true;
3432 * Check if this is $query is related to a choice
3434 * @param string $query
3435 * @return bool true if related, false if not
3437 public function is_related($query) {
3438 if (parent::is_related($query)) {
3439 return true;
3441 if (!$this->load_choices()) {
3442 return false;
3444 foreach ($this->choices as $key=>$value) {
3445 if (strpos(core_text::strtolower($key), $query) !== false) {
3446 return true;
3448 if (strpos(core_text::strtolower($value), $query) !== false) {
3449 return true;
3452 return false;
3456 * Return the setting
3458 * @return mixed returns config if successful else null
3460 public function get_setting() {
3461 return $this->config_read($this->name);
3465 * Save a setting
3467 * @param string $data
3468 * @return string empty of error string
3470 public function write_setting($data) {
3471 if (!$this->load_choices() or empty($this->choices)) {
3472 return '';
3474 if (!array_key_exists($data, $this->choices)) {
3475 return ''; // ignore it
3478 // Validate the new setting.
3479 $error = $this->validate_setting($data);
3480 if ($error) {
3481 return $error;
3484 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3488 * Validate the setting. This uses the callback function if provided; subclasses could override
3489 * to carry out validation directly in the class.
3491 * @param string $data New value being set
3492 * @return string Empty string if valid, or error message text
3493 * @since Moodle 3.10
3495 protected function validate_setting(string $data): string {
3496 // If validation function is specified, call it now.
3497 if ($this->validatefunction) {
3498 return call_user_func($this->validatefunction, $data);
3499 } else {
3500 return '';
3505 * Returns XHTML select field
3507 * Ensure the options are loaded, and generate the XHTML for the select
3508 * element and any warning message. Separating this out from output_html
3509 * makes it easier to subclass this class.
3511 * @param string $data the option to show as selected.
3512 * @param string $current the currently selected option in the database, null if none.
3513 * @param string $default the default selected option.
3514 * @return array the HTML for the select element, and a warning message.
3515 * @deprecated since Moodle 3.2
3517 public function output_select_html($data, $current, $default, $extraname = '') {
3518 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3522 * Returns XHTML select field and wrapping div(s)
3524 * @see output_select_html()
3526 * @param string $data the option to show as selected
3527 * @param string $query
3528 * @return string XHTML field and wrapping div
3530 public function output_html($data, $query='') {
3531 global $OUTPUT;
3533 $default = $this->get_defaultsetting();
3534 $current = $this->get_setting();
3536 if (!$this->load_choices() || empty($this->choices)) {
3537 return '';
3540 $context = (object) [
3541 'id' => $this->get_id(),
3542 'name' => $this->get_full_name(),
3545 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3546 $defaultinfo = $this->choices[$default];
3547 } else {
3548 $defaultinfo = NULL;
3551 // Warnings.
3552 $warning = '';
3553 if ($current === null) {
3554 // First run.
3555 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3556 // No warning.
3557 } else if (!array_key_exists($current, $this->choices)) {
3558 $warning = get_string('warningcurrentsetting', 'admin', $current);
3559 if (!is_null($default) && $data == $current) {
3560 $data = $default; // Use default instead of first value when showing the form.
3564 $options = [];
3565 $template = 'core_admin/setting_configselect';
3567 if (!empty($this->optgroups)) {
3568 $optgroups = [];
3569 foreach ($this->optgroups as $label => $choices) {
3570 $optgroup = array('label' => $label, 'options' => []);
3571 foreach ($choices as $value => $name) {
3572 $optgroup['options'][] = [
3573 'value' => $value,
3574 'name' => $name,
3575 'selected' => (string) $value == $data
3577 unset($this->choices[$value]);
3579 $optgroups[] = $optgroup;
3581 $context->options = $options;
3582 $context->optgroups = $optgroups;
3583 $template = 'core_admin/setting_configselect_optgroup';
3586 foreach ($this->choices as $value => $name) {
3587 $options[] = [
3588 'value' => $value,
3589 'name' => $name,
3590 'selected' => (string) $value == $data
3593 $context->options = $options;
3594 $context->readonly = $this->is_readonly();
3596 $element = $OUTPUT->render_from_template($template, $context);
3598 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3603 * Select multiple items from list
3605 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3607 class admin_setting_configmultiselect extends admin_setting_configselect {
3609 * Constructor
3610 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3611 * @param string $visiblename localised
3612 * @param string $description long localised info
3613 * @param array $defaultsetting array of selected items
3614 * @param array $choices array of $value=>$label for each list item
3616 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3617 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3621 * Returns the select setting(s)
3623 * @return mixed null or array. Null if no settings else array of setting(s)
3625 public function get_setting() {
3626 $result = $this->config_read($this->name);
3627 if (is_null($result)) {
3628 return NULL;
3630 if ($result === '') {
3631 return array();
3633 return explode(',', $result);
3637 * Saves setting(s) provided through $data
3639 * Potential bug in the works should anyone call with this function
3640 * using a vartype that is not an array
3642 * @param array $data
3644 public function write_setting($data) {
3645 if (!is_array($data)) {
3646 return ''; //ignore it
3648 if (!$this->load_choices() or empty($this->choices)) {
3649 return '';
3652 unset($data['xxxxx']);
3654 $save = array();
3655 foreach ($data as $value) {
3656 if (!array_key_exists($value, $this->choices)) {
3657 continue; // ignore it
3659 $save[] = $value;
3662 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3666 * Is setting related to query text - used when searching
3668 * @param string $query
3669 * @return bool true if related, false if not
3671 public function is_related($query) {
3672 if (!$this->load_choices() or empty($this->choices)) {
3673 return false;
3675 if (parent::is_related($query)) {
3676 return true;
3679 foreach ($this->choices as $desc) {
3680 if (strpos(core_text::strtolower($desc), $query) !== false) {
3681 return true;
3684 return false;
3688 * Returns XHTML multi-select field
3690 * @todo Add vartype handling to ensure $data is an array
3691 * @param array $data Array of values to select by default
3692 * @param string $query
3693 * @return string XHTML multi-select field
3695 public function output_html($data, $query='') {
3696 global $OUTPUT;
3698 if (!$this->load_choices() or empty($this->choices)) {
3699 return '';
3702 $default = $this->get_defaultsetting();
3703 if (is_null($default)) {
3704 $default = array();
3706 if (is_null($data)) {
3707 $data = array();
3710 $context = (object) [
3711 'id' => $this->get_id(),
3712 'name' => $this->get_full_name(),
3713 'size' => min(10, count($this->choices))
3716 $defaults = [];
3717 $options = [];
3718 $template = 'core_admin/setting_configmultiselect';
3720 if (!empty($this->optgroups)) {
3721 $optgroups = [];
3722 foreach ($this->optgroups as $label => $choices) {
3723 $optgroup = array('label' => $label, 'options' => []);
3724 foreach ($choices as $value => $name) {
3725 if (in_array($value, $default)) {
3726 $defaults[] = $name;
3728 $optgroup['options'][] = [
3729 'value' => $value,
3730 'name' => $name,
3731 'selected' => in_array($value, $data)
3733 unset($this->choices[$value]);
3735 $optgroups[] = $optgroup;
3737 $context->optgroups = $optgroups;
3738 $template = 'core_admin/setting_configmultiselect_optgroup';
3741 foreach ($this->choices as $value => $name) {
3742 if (in_array($value, $default)) {
3743 $defaults[] = $name;
3745 $options[] = [
3746 'value' => $value,
3747 'name' => $name,
3748 'selected' => in_array($value, $data)
3751 $context->options = $options;
3752 $context->readonly = $this->is_readonly();
3754 if (is_null($default)) {
3755 $defaultinfo = NULL;
3756 } if (!empty($defaults)) {
3757 $defaultinfo = implode(', ', $defaults);
3758 } else {
3759 $defaultinfo = get_string('none');
3762 $element = $OUTPUT->render_from_template($template, $context);
3764 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3769 * Time selector
3771 * This is a liiitle bit messy. we're using two selects, but we're returning
3772 * them as an array named after $name (so we only use $name2 internally for the setting)
3774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3776 class admin_setting_configtime extends admin_setting {
3777 /** @var string Used for setting second select (minutes) */
3778 public $name2;
3781 * Constructor
3782 * @param string $hoursname setting for hours
3783 * @param string $minutesname setting for hours
3784 * @param string $visiblename localised
3785 * @param string $description long localised info
3786 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3788 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3789 $this->name2 = $minutesname;
3790 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3794 * Get the selected time
3796 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3798 public function get_setting() {
3799 $result1 = $this->config_read($this->name);
3800 $result2 = $this->config_read($this->name2);
3801 if (is_null($result1) or is_null($result2)) {
3802 return NULL;
3805 return array('h' => $result1, 'm' => $result2);
3809 * Store the time (hours and minutes)
3811 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3812 * @return bool true if success, false if not
3814 public function write_setting($data) {
3815 if (!is_array($data)) {
3816 return '';
3819 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3820 return ($result ? '' : get_string('errorsetting', 'admin'));
3824 * Returns XHTML time select fields
3826 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3827 * @param string $query
3828 * @return string XHTML time select fields and wrapping div(s)
3830 public function output_html($data, $query='') {
3831 global $OUTPUT;
3833 $default = $this->get_defaultsetting();
3834 if (is_array($default)) {
3835 $defaultinfo = $default['h'].':'.$default['m'];
3836 } else {
3837 $defaultinfo = NULL;
3840 $context = (object) [
3841 'id' => $this->get_id(),
3842 'name' => $this->get_full_name(),
3843 'readonly' => $this->is_readonly(),
3844 'hours' => array_map(function($i) use ($data) {
3845 return [
3846 'value' => $i,
3847 'name' => $i,
3848 'selected' => $i == $data['h']
3850 }, range(0, 23)),
3851 'minutes' => array_map(function($i) use ($data) {
3852 return [
3853 'value' => $i,
3854 'name' => $i,
3855 'selected' => $i == $data['m']
3857 }, range(0, 59, 5))
3860 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3862 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3863 $this->get_id() . 'h', '', $defaultinfo, $query);
3870 * Seconds duration setting.
3872 * @copyright 2012 Petr Skoda (http://skodak.org)
3873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3875 class admin_setting_configduration extends admin_setting {
3877 /** @var int default duration unit */
3878 protected $defaultunit;
3879 /** @var callable|null Validation function */
3880 protected $validatefunction = null;
3882 /** @var int The minimum allowed value */
3883 protected int $minduration = 0;
3885 /** @var null|int The maximum allowed value */
3886 protected null|int $maxduration = null;
3889 * Constructor
3890 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3891 * or 'myplugin/mysetting' for ones in config_plugins.
3892 * @param string $visiblename localised name
3893 * @param string $description localised long description
3894 * @param mixed $defaultsetting string or array depending on implementation
3895 * @param int $defaultunit - day, week, etc. (in seconds)
3897 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3898 if (is_number($defaultsetting)) {
3899 $defaultsetting = self::parse_seconds($defaultsetting);
3901 $units = self::get_units();
3902 if (isset($units[$defaultunit])) {
3903 $this->defaultunit = $defaultunit;
3904 } else {
3905 $this->defaultunit = 86400;
3907 parent::__construct($name, $visiblename, $description, $defaultsetting);
3911 * Set the minimum allowed value.
3912 * This must be at least 0.
3914 * @param int $duration
3916 public function set_min_duration(int $duration): void {
3917 if ($duration < 0) {
3918 throw new coding_exception('The minimum duration must be at least 0.');
3921 $this->minduration = $duration;
3925 * Set the maximum allowed value.
3927 * A value of null will disable the maximum duration value.
3929 * @param int|null $duration
3931 public function set_max_duration(?int $duration): void {
3932 $this->maxduration = $duration;
3936 * Sets a validate function.
3938 * The callback will be passed one parameter, the new setting value, and should return either
3939 * an empty string '' if the value is OK, or an error message if not.
3941 * @param callable|null $validatefunction Validate function or null to clear
3942 * @since Moodle 3.10
3944 public function set_validate_function(?callable $validatefunction = null) {
3945 $this->validatefunction = $validatefunction;
3949 * Validate the setting. This uses the callback function if provided; subclasses could override
3950 * to carry out validation directly in the class.
3952 * @param int $data New value being set
3953 * @return string Empty string if valid, or error message text
3954 * @since Moodle 3.10
3956 protected function validate_setting(int $data): string {
3957 if ($data < $this->minduration) {
3958 return get_string(
3959 'configduration_low',
3960 'admin',
3961 self::get_duration_text($this->minduration, get_string('numseconds', 'core', 0))
3965 if ($this->maxduration && $data > $this->maxduration) {
3966 return get_string('configduration_high', 'admin', self::get_duration_text($this->maxduration));
3969 // If validation function is specified, call it now.
3970 if ($this->validatefunction) {
3971 return call_user_func($this->validatefunction, $data);
3973 return '';
3977 * Returns selectable units.
3978 * @static
3979 * @return array
3981 protected static function get_units() {
3982 return array(
3983 604800 => get_string('weeks'),
3984 86400 => get_string('days'),
3985 3600 => get_string('hours'),
3986 60 => get_string('minutes'),
3987 1 => get_string('seconds'),
3992 * Converts seconds to some more user friendly string.
3993 * @static
3994 * @param int $seconds
3995 * @param null|string The value to use when the duration is empty. If not specified, a "None" value is used.
3996 * @return string
3998 protected static function get_duration_text(int $seconds, ?string $emptyvalue = null): string {
3999 if (empty($seconds)) {
4000 if ($emptyvalue !== null) {
4001 return $emptyvalue;
4003 return get_string('none');
4005 $data = self::parse_seconds($seconds);
4006 switch ($data['u']) {
4007 case (60*60*24*7):
4008 return get_string('numweeks', '', $data['v']);
4009 case (60*60*24):
4010 return get_string('numdays', '', $data['v']);
4011 case (60*60):
4012 return get_string('numhours', '', $data['v']);
4013 case (60):
4014 return get_string('numminutes', '', $data['v']);
4015 default:
4016 return get_string('numseconds', '', $data['v']*$data['u']);
4021 * Finds suitable units for given duration.
4022 * @static
4023 * @param int $seconds
4024 * @return array
4026 protected static function parse_seconds($seconds) {
4027 foreach (self::get_units() as $unit => $unused) {
4028 if ($seconds % $unit === 0) {
4029 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
4032 return array('v'=>(int)$seconds, 'u'=>1);
4036 * Get the selected duration as array.
4038 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
4040 public function get_setting() {
4041 $seconds = $this->config_read($this->name);
4042 if (is_null($seconds)) {
4043 return null;
4046 return self::parse_seconds($seconds);
4050 * Store the duration as seconds.
4052 * @param array $data Must be form 'h'=>xx, 'm'=>xx
4053 * @return bool true if success, false if not
4055 public function write_setting($data) {
4056 if (!is_array($data)) {
4057 return '';
4060 $unit = (int)$data['u'];
4061 $value = (int)$data['v'];
4062 $seconds = $value * $unit;
4064 // Validate the new setting.
4065 $error = $this->validate_setting($seconds);
4066 if ($error) {
4067 return $error;
4070 $result = $this->config_write($this->name, $seconds);
4071 return ($result ? '' : get_string('errorsetting', 'admin'));
4075 * Returns duration text+select fields.
4077 * @param array $data Must be form 'v'=>xx, 'u'=>xx
4078 * @param string $query
4079 * @return string duration text+select fields and wrapping div(s)
4081 public function output_html($data, $query='') {
4082 global $OUTPUT;
4084 $default = $this->get_defaultsetting();
4085 if (is_number($default)) {
4086 $defaultinfo = self::get_duration_text($default);
4087 } else if (is_array($default)) {
4088 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
4089 } else {
4090 $defaultinfo = null;
4093 $inputid = $this->get_id() . 'v';
4094 $units = array_filter(self::get_units(), function($unit): bool {
4095 if (!$this->maxduration) {
4096 // No duration limit. All units are valid.
4097 return true;
4100 return $unit <= $this->maxduration;
4101 }, ARRAY_FILTER_USE_KEY);
4103 $defaultunit = $this->defaultunit;
4105 $context = (object) [
4106 'id' => $this->get_id(),
4107 'name' => $this->get_full_name(),
4108 'value' => $data['v'] ?? '',
4109 'readonly' => $this->is_readonly(),
4110 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
4111 return [
4112 'value' => $unit,
4113 'name' => $units[$unit],
4114 'selected' => isset($data) && (($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u'])
4116 }, array_keys($units))
4119 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
4121 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
4127 * Seconds duration setting with an advanced checkbox, that controls a additional
4128 * $name.'_adv' setting.
4130 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4131 * @copyright 2014 The Open University
4133 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
4135 * Constructor
4136 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
4137 * or 'myplugin/mysetting' for ones in config_plugins.
4138 * @param string $visiblename localised name
4139 * @param string $description localised long description
4140 * @param array $defaultsetting array of int value, and bool whether it is
4141 * is advanced by default.
4142 * @param int $defaultunit - day, week, etc. (in seconds)
4144 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
4145 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
4146 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4152 * Used to validate a textarea used for ip addresses
4154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4155 * @copyright 2011 Petr Skoda (http://skodak.org)
4157 class admin_setting_configiplist extends admin_setting_configtextarea {
4160 * Validate the contents of the textarea as IP addresses
4162 * Used to validate a new line separated list of IP addresses collected from
4163 * a textarea control
4165 * @param string $data A list of IP Addresses separated by new lines
4166 * @return mixed bool true for success or string:error on failure
4168 public function validate($data) {
4169 if(!empty($data)) {
4170 $lines = explode("\n", $data);
4171 } else {
4172 return true;
4174 $result = true;
4175 $badips = array();
4176 foreach ($lines as $line) {
4177 $tokens = explode('#', $line);
4178 $ip = trim($tokens[0]);
4179 if (empty($ip)) {
4180 continue;
4182 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
4183 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
4184 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4185 } else {
4186 $result = false;
4187 $badips[] = $ip;
4190 if($result) {
4191 return true;
4192 } else {
4193 return get_string('validateiperror', 'admin', join(', ', $badips));
4199 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
4201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4202 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4204 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
4207 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
4208 * Used to validate a new line separated list of entries collected from a textarea control.
4210 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
4211 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
4212 * via the get_setting() method, which has been overriden.
4214 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
4215 * @return mixed bool true for success or string:error on failure
4217 public function validate($data) {
4218 if (empty($data)) {
4219 return true;
4221 $entries = explode("\n", $data);
4222 $badentries = [];
4224 foreach ($entries as $key => $entry) {
4225 $entry = trim($entry);
4226 if (empty($entry)) {
4227 return get_string('validateemptylineerror', 'admin');
4230 // Validate each string entry against the supported formats.
4231 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
4232 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
4233 || \core\ip_utils::is_domain_matching_pattern($entry)) {
4234 continue;
4237 // Otherwise, the entry is invalid.
4238 $badentries[] = $entry;
4241 if ($badentries) {
4242 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
4244 return true;
4248 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
4250 * @param string $data the setting data, as sent from the web form.
4251 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
4253 protected function ace_encode($data) {
4254 if (empty($data)) {
4255 return $data;
4257 $entries = explode("\n", $data);
4258 foreach ($entries as $key => $entry) {
4259 $entry = trim($entry);
4260 // This regex matches any string that has non-ascii character.
4261 if (preg_match('/[^\x00-\x7f]/', $entry)) {
4262 // If we can convert the unicode string to an idn, do so.
4263 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
4264 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4265 $entries[$key] = $val ? $val : $entry;
4268 return implode("\n", $entries);
4272 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4274 * @param string $data the setting data, as found in the database.
4275 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4277 protected function ace_decode($data) {
4278 $entries = explode("\n", $data);
4279 foreach ($entries as $key => $entry) {
4280 $entry = trim($entry);
4281 if (strpos($entry, 'xn--') !== false) {
4282 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4285 return implode("\n", $entries);
4289 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4291 * @return mixed returns punycode-converted setting string if successful, else null.
4293 public function get_setting() {
4294 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4295 $data = $this->config_read($this->name);
4296 if (function_exists('idn_to_utf8') && !is_null($data)) {
4297 $data = $this->ace_decode($data);
4299 return $data;
4303 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4305 * @param string $data
4306 * @return string
4308 public function write_setting($data) {
4309 if ($this->paramtype === PARAM_INT and $data === '') {
4310 // Do not complain if '' used instead of 0.
4311 $data = 0;
4314 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4315 if (function_exists('idn_to_ascii')) {
4316 $data = $this->ace_encode($data);
4319 $validated = $this->validate($data);
4320 if ($validated !== true) {
4321 return $validated;
4323 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4328 * Used to validate a textarea used for port numbers.
4330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4331 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4333 class admin_setting_configportlist extends admin_setting_configtextarea {
4336 * Validate the contents of the textarea as port numbers.
4337 * Used to validate a new line separated list of ports collected from a textarea control.
4339 * @param string $data A list of ports separated by new lines
4340 * @return mixed bool true for success or string:error on failure
4342 public function validate($data) {
4343 if (empty($data)) {
4344 return true;
4346 $ports = explode("\n", $data);
4347 $badentries = [];
4348 foreach ($ports as $port) {
4349 $port = trim($port);
4350 if (empty($port)) {
4351 return get_string('validateemptylineerror', 'admin');
4354 // Is the string a valid integer number?
4355 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4356 $badentries[] = $port;
4359 if ($badentries) {
4360 return get_string('validateerrorlist', 'admin', $badentries);
4362 return true;
4368 * An admin setting for selecting one or more users who have a capability
4369 * in the system context
4371 * An admin setting for selecting one or more users, who have a particular capability
4372 * in the system context. Warning, make sure the list will never be too long. There is
4373 * no paging or searching of this list.
4375 * To correctly get a list of users from this config setting, you need to call the
4376 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4378 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4380 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4381 /** @var string The capabilities name */
4382 protected $capability;
4383 /** @var int include admin users too */
4384 protected $includeadmins;
4387 * Constructor.
4389 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4390 * @param string $visiblename localised name
4391 * @param string $description localised long description
4392 * @param array $defaultsetting array of usernames
4393 * @param string $capability string capability name.
4394 * @param bool $includeadmins include administrators
4396 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4397 $this->capability = $capability;
4398 $this->includeadmins = $includeadmins;
4399 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4403 * Load all of the uses who have the capability into choice array
4405 * @return bool Always returns true
4407 function load_choices() {
4408 if (is_array($this->choices)) {
4409 return true;
4411 list($sort, $sortparams) = users_order_by_sql('u');
4412 if (!empty($sortparams)) {
4413 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4414 'This is unexpected, and a problem because there is no way to pass these ' .
4415 'parameters to get_users_by_capability. See MDL-34657.');
4417 $userfieldsapi = \core_user\fields::for_name();
4418 $userfields = 'u.id, u.username, ' . $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4419 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4420 $this->choices = array(
4421 '$@NONE@$' => get_string('nobody'),
4422 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4424 if ($this->includeadmins) {
4425 $admins = get_admins();
4426 foreach ($admins as $user) {
4427 $this->choices[$user->id] = fullname($user);
4430 if (is_array($users)) {
4431 foreach ($users as $user) {
4432 $this->choices[$user->id] = fullname($user);
4435 return true;
4439 * Returns the default setting for class
4441 * @return mixed Array, or string. Empty string if no default
4443 public function get_defaultsetting() {
4444 $this->load_choices();
4445 $defaultsetting = parent::get_defaultsetting();
4446 if (empty($defaultsetting)) {
4447 return array('$@NONE@$');
4448 } else if (array_key_exists($defaultsetting, $this->choices)) {
4449 return $defaultsetting;
4450 } else {
4451 return '';
4456 * Returns the current setting
4458 * @return mixed array or string
4460 public function get_setting() {
4461 $result = parent::get_setting();
4462 if ($result === null) {
4463 // this is necessary for settings upgrade
4464 return null;
4466 if (empty($result)) {
4467 $result = array('$@NONE@$');
4469 return $result;
4473 * Save the chosen setting provided as $data
4475 * @param array $data
4476 * @return mixed string or array
4478 public function write_setting($data) {
4479 // If all is selected, remove any explicit options.
4480 if (in_array('$@ALL@$', $data)) {
4481 $data = array('$@ALL@$');
4483 // None never needs to be written to the DB.
4484 if (in_array('$@NONE@$', $data)) {
4485 unset($data[array_search('$@NONE@$', $data)]);
4487 return parent::write_setting($data);
4493 * Special checkbox for calendar - resets SESSION vars.
4495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4497 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4499 * Calls the parent::__construct with default values
4501 * name => calendar_adminseesall
4502 * visiblename => get_string('adminseesall', 'admin')
4503 * description => get_string('helpadminseesall', 'admin')
4504 * defaultsetting => 0
4506 public function __construct() {
4507 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4508 get_string('helpadminseesall', 'admin'), '0');
4512 * Stores the setting passed in $data
4514 * @param mixed gets converted to string for comparison
4515 * @return string empty string or error message
4517 public function write_setting($data) {
4518 global $SESSION;
4519 return parent::write_setting($data);
4524 * Special select for settings that are altered in setup.php and can not be altered on the fly
4526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4528 class admin_setting_special_selectsetup extends admin_setting_configselect {
4530 * Reads the setting directly from the database
4532 * @return mixed
4534 public function get_setting() {
4535 // read directly from db!
4536 return get_config(NULL, $this->name);
4540 * Save the setting passed in $data
4542 * @param string $data The setting to save
4543 * @return string empty or error message
4545 public function write_setting($data) {
4546 global $CFG;
4547 // do not change active CFG setting!
4548 $current = $CFG->{$this->name};
4549 $result = parent::write_setting($data);
4550 $CFG->{$this->name} = $current;
4551 return $result;
4557 * Special select for frontpage - stores data in course table
4559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4561 class admin_setting_sitesetselect extends admin_setting_configselect {
4563 * Returns the site name for the selected site
4565 * @see get_site()
4566 * @return string The site name of the selected site
4568 public function get_setting() {
4569 $site = course_get_format(get_site())->get_course();
4570 return $site->{$this->name};
4574 * Updates the database and save the setting
4576 * @param string data
4577 * @return string empty or error message
4579 public function write_setting($data) {
4580 global $DB, $SITE, $COURSE;
4581 if (!in_array($data, array_keys($this->choices))) {
4582 return get_string('errorsetting', 'admin');
4584 $record = new stdClass();
4585 $record->id = SITEID;
4586 $temp = $this->name;
4587 $record->$temp = $data;
4588 $record->timemodified = time();
4590 course_get_format($SITE)->update_course_format_options($record);
4591 $DB->update_record('course', $record);
4593 // Reset caches.
4594 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4595 if ($SITE->id == $COURSE->id) {
4596 $COURSE = $SITE;
4598 core_courseformat\base::reset_course_cache($SITE->id);
4600 return '';
4607 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4608 * block to hidden.
4610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4612 class admin_setting_bloglevel extends admin_setting_configselect {
4614 * Updates the database and save the setting
4616 * @param string data
4617 * @return string empty or error message
4619 public function write_setting($data) {
4620 global $DB, $CFG;
4621 if ($data == 0) {
4622 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4623 foreach ($blogblocks as $block) {
4624 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4626 } else {
4627 // reenable all blocks only when switching from disabled blogs
4628 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4629 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4630 foreach ($blogblocks as $block) {
4631 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4635 return parent::write_setting($data);
4641 * Special select - lists on the frontpage - hacky
4643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4645 class admin_setting_courselist_frontpage extends admin_setting {
4646 /** @var array Array of choices value=>label */
4647 public $choices;
4650 * Construct override, requires one param
4652 * @param bool $loggedin Is the user logged in
4654 public function __construct($loggedin) {
4655 global $CFG;
4656 require_once($CFG->dirroot.'/course/lib.php');
4657 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4658 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4659 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4660 $defaults = array(FRONTPAGEALLCOURSELIST);
4661 parent::__construct($name, $visiblename, $description, $defaults);
4665 * Loads the choices available
4667 * @return bool always returns true
4669 public function load_choices() {
4670 if (is_array($this->choices)) {
4671 return true;
4673 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4674 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4675 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4676 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4677 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4678 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4679 'none' => get_string('none'));
4680 if ($this->name === 'frontpage') {
4681 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4683 return true;
4687 * Returns the selected settings
4689 * @param mixed array or setting or null
4691 public function get_setting() {
4692 $result = $this->config_read($this->name);
4693 if (is_null($result)) {
4694 return NULL;
4696 if ($result === '') {
4697 return array();
4699 return explode(',', $result);
4703 * Save the selected options
4705 * @param array $data
4706 * @return mixed empty string (data is not an array) or bool true=success false=failure
4708 public function write_setting($data) {
4709 if (!is_array($data)) {
4710 return '';
4712 $this->load_choices();
4713 $save = array();
4714 foreach($data as $datum) {
4715 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4716 continue;
4718 $save[$datum] = $datum; // no duplicates
4720 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4724 * Return XHTML select field and wrapping div
4726 * @todo Add vartype handling to make sure $data is an array
4727 * @param array $data Array of elements to select by default
4728 * @return string XHTML select field and wrapping div
4730 public function output_html($data, $query='') {
4731 global $OUTPUT;
4733 $this->load_choices();
4734 $currentsetting = array();
4735 foreach ($data as $key) {
4736 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4737 $currentsetting[] = $key; // already selected first
4741 $context = (object) [
4742 'id' => $this->get_id(),
4743 'name' => $this->get_full_name(),
4746 $options = $this->choices;
4747 $selects = [];
4748 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4749 if (!array_key_exists($i, $currentsetting)) {
4750 $currentsetting[$i] = 'none';
4752 $selects[] = [
4753 'key' => $i,
4754 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4755 return [
4756 'name' => $options[$option],
4757 'value' => $option,
4758 'selected' => $currentsetting[$i] == $option
4760 }, array_keys($options))
4763 $context->selects = $selects;
4765 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4767 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4773 * Special checkbox for frontpage - stores data in course table
4775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4777 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4779 * Returns the current sites name
4781 * @return string
4783 public function get_setting() {
4784 $site = course_get_format(get_site())->get_course();
4785 return $site->{$this->name};
4789 * Save the selected setting
4791 * @param string $data The selected site
4792 * @return string empty string or error message
4794 public function write_setting($data) {
4795 global $DB, $SITE, $COURSE;
4796 $record = new stdClass();
4797 $record->id = $SITE->id;
4798 $record->{$this->name} = ($data == '1' ? 1 : 0);
4799 $record->timemodified = time();
4801 course_get_format($SITE)->update_course_format_options($record);
4802 $DB->update_record('course', $record);
4804 // Reset caches.
4805 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4806 if ($SITE->id == $COURSE->id) {
4807 $COURSE = $SITE;
4809 core_courseformat\base::reset_course_cache($SITE->id);
4811 return '';
4816 * Special text for frontpage - stores data in course table.
4817 * Empty string means not set here. Manual setting is required.
4819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4821 class admin_setting_sitesettext extends admin_setting_configtext {
4824 * Constructor.
4826 public function __construct() {
4827 call_user_func_array([parent::class, '__construct'], func_get_args());
4828 $this->set_force_ltr(false);
4832 * Return the current setting
4834 * @return mixed string or null
4836 public function get_setting() {
4837 $site = course_get_format(get_site())->get_course();
4838 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4842 * Validate the selected data
4844 * @param string $data The selected value to validate
4845 * @return mixed true or message string
4847 public function validate($data) {
4848 global $DB, $SITE;
4849 $cleaned = clean_param($data, PARAM_TEXT);
4850 if ($cleaned === '') {
4851 return get_string('required');
4853 if ($this->name ==='shortname' &&
4854 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4855 return get_string('shortnametaken', 'error', $data);
4857 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4858 return true;
4859 } else {
4860 return get_string('validateerror', 'admin');
4865 * Save the selected setting
4867 * @param string $data The selected value
4868 * @return string empty or error message
4870 public function write_setting($data) {
4871 global $DB, $SITE, $COURSE;
4872 $data = trim($data);
4873 $validated = $this->validate($data);
4874 if ($validated !== true) {
4875 return $validated;
4878 $record = new stdClass();
4879 $record->id = $SITE->id;
4880 $record->{$this->name} = $data;
4881 $record->timemodified = time();
4883 course_get_format($SITE)->update_course_format_options($record);
4884 $DB->update_record('course', $record);
4886 // Reset caches.
4887 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4888 if ($SITE->id == $COURSE->id) {
4889 $COURSE = $SITE;
4891 core_courseformat\base::reset_course_cache($SITE->id);
4893 return '';
4899 * This type of field should be used for mandatory config settings.
4901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4903 class admin_setting_requiredtext extends admin_setting_configtext {
4906 * Validate data before storage.
4908 * @param string $data The string to be validated.
4909 * @return bool|string true for success or error string if invalid.
4911 public function validate($data) {
4912 $cleaned = clean_param($data, PARAM_TEXT);
4913 if ($cleaned === '') {
4914 return get_string('required');
4917 return parent::validate($data);
4922 * Special text editor for site description.
4924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4926 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4929 * Calls parent::__construct with specific arguments
4931 public function __construct() {
4932 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4933 PARAM_RAW, 60, 15);
4937 * Return the current setting
4938 * @return string The current setting
4940 public function get_setting() {
4941 $site = course_get_format(get_site())->get_course();
4942 return $site->{$this->name};
4946 * Save the new setting
4948 * @param string $data The new value to save
4949 * @return string empty or error message
4951 public function write_setting($data) {
4952 global $DB, $SITE, $COURSE;
4953 $record = new stdClass();
4954 $record->id = $SITE->id;
4955 $record->{$this->name} = $data;
4956 $record->timemodified = time();
4958 course_get_format($SITE)->update_course_format_options($record);
4959 $DB->update_record('course', $record);
4961 // Reset caches.
4962 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4963 if ($SITE->id == $COURSE->id) {
4964 $COURSE = $SITE;
4966 core_courseformat\base::reset_course_cache($SITE->id);
4968 return '';
4974 * Administration interface for emoticon_manager settings.
4976 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4978 class admin_setting_emoticons extends admin_setting {
4981 * Calls parent::__construct with specific args
4983 public function __construct() {
4984 global $CFG;
4986 $manager = get_emoticon_manager();
4987 $defaults = $this->prepare_form_data($manager->default_emoticons());
4988 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4992 * Return the current setting(s)
4994 * @return array Current settings array
4996 public function get_setting() {
4997 global $CFG;
4999 $manager = get_emoticon_manager();
5001 $config = $this->config_read($this->name);
5002 if (is_null($config)) {
5003 return null;
5006 $config = $manager->decode_stored_config($config);
5007 if (is_null($config)) {
5008 return null;
5011 return $this->prepare_form_data($config);
5015 * Save selected settings
5017 * @param array $data Array of settings to save
5018 * @return bool
5020 public function write_setting($data) {
5022 $manager = get_emoticon_manager();
5023 $emoticons = $this->process_form_data($data);
5025 if ($emoticons === false) {
5026 return false;
5029 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
5030 return ''; // success
5031 } else {
5032 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
5037 * Return XHTML field(s) for options
5039 * @param array $data Array of options to set in HTML
5040 * @return string XHTML string for the fields and wrapping div(s)
5042 public function output_html($data, $query='') {
5043 global $OUTPUT;
5045 $context = (object) [
5046 'name' => $this->get_full_name(),
5047 'emoticons' => [],
5048 'forceltr' => true,
5051 $i = 0;
5052 foreach ($data as $field => $value) {
5054 // When $i == 0: text.
5055 // When $i == 1: imagename.
5056 // When $i == 2: imagecomponent.
5057 // When $i == 3: altidentifier.
5058 // When $i == 4: altcomponent.
5059 $fields[$i] = (object) [
5060 'field' => $field,
5061 'value' => $value,
5062 'index' => $i
5064 $i++;
5066 if ($i > 4) {
5067 $icon = null;
5068 if (!empty($fields[1]->value)) {
5069 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
5070 $alt = get_string($fields[3]->value, $fields[4]->value);
5071 } else {
5072 $alt = $fields[0]->value;
5074 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
5076 $context->emoticons[] = [
5077 'fields' => $fields,
5078 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
5080 $fields = [];
5081 $i = 0;
5085 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
5086 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
5087 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5091 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
5093 * @see self::process_form_data()
5094 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
5095 * @return array of form fields and their values
5097 protected function prepare_form_data(array $emoticons) {
5099 $form = array();
5100 $i = 0;
5101 foreach ($emoticons as $emoticon) {
5102 $form['text'.$i] = $emoticon->text;
5103 $form['imagename'.$i] = $emoticon->imagename;
5104 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
5105 $form['altidentifier'.$i] = $emoticon->altidentifier;
5106 $form['altcomponent'.$i] = $emoticon->altcomponent;
5107 $i++;
5109 // add one more blank field set for new object
5110 $form['text'.$i] = '';
5111 $form['imagename'.$i] = '';
5112 $form['imagecomponent'.$i] = '';
5113 $form['altidentifier'.$i] = '';
5114 $form['altcomponent'.$i] = '';
5116 return $form;
5120 * Converts the data from admin settings form into an array of emoticon objects
5122 * @see self::prepare_form_data()
5123 * @param array $data array of admin form fields and values
5124 * @return false|array of emoticon objects
5126 protected function process_form_data(array $form) {
5128 $count = count($form); // number of form field values
5130 if ($count % 5) {
5131 // we must get five fields per emoticon object
5132 return false;
5135 $emoticons = array();
5136 for ($i = 0; $i < $count / 5; $i++) {
5137 $emoticon = new stdClass();
5138 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
5139 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
5140 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
5141 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
5142 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
5144 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
5145 // prevent from breaking http://url.addresses by accident
5146 $emoticon->text = '';
5149 if (strlen($emoticon->text) < 2) {
5150 // do not allow single character emoticons
5151 $emoticon->text = '';
5154 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
5155 // emoticon text must contain some non-alphanumeric character to prevent
5156 // breaking HTML tags
5157 $emoticon->text = '';
5160 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
5161 $emoticons[] = $emoticon;
5164 return $emoticons;
5171 * Special setting for limiting of the list of available languages.
5173 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5175 class admin_setting_langlist extends admin_setting_configtext {
5177 * Calls parent::__construct with specific arguments
5179 public function __construct() {
5180 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
5184 * Validate that each language identifier exists on the site
5186 * @param string $data
5187 * @return bool|string True if validation successful, otherwise error string
5189 public function validate($data) {
5190 $parentcheck = parent::validate($data);
5191 if ($parentcheck !== true) {
5192 return $parentcheck;
5195 if ($data === '') {
5196 return true;
5199 // Normalize language identifiers.
5200 $langcodes = array_map('trim', explode(',', $data));
5201 foreach ($langcodes as $langcode) {
5202 // If the langcode contains optional alias, split it out.
5203 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5205 if (!get_string_manager()->translation_exists($langcode)) {
5206 return get_string('invalidlanguagecode', 'error', $langcode);
5210 return true;
5214 * Save the new setting
5216 * @param string $data The new setting
5217 * @return bool
5219 public function write_setting($data) {
5220 $return = parent::write_setting($data);
5221 get_string_manager()->reset_caches();
5222 return $return;
5228 * Allows to specify comma separated list of known country codes.
5230 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5231 * known codes.
5233 * @package core
5234 * @category admin
5235 * @copyright 2020 David Mudrák <david@moodle.com>
5236 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5238 class admin_setting_countrycodes extends admin_setting_configtext {
5241 * Construct the instance of the setting.
5243 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5244 * @param lang_string|string $visiblename Language string with the field label text.
5245 * @param lang_string|string $description Language string with the field description text.
5246 * @param string $defaultsetting Default value of the setting.
5247 * @param int $size Input text field size.
5249 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5250 parent::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5254 * Validate the setting value before storing it.
5256 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5257 * a comma separated list of such words.
5259 * @param string $data Value inserted into the setting field.
5260 * @return bool|string True if the value is OK, error string otherwise.
5262 public function validate($data) {
5264 $parentcheck = parent::validate($data);
5266 if ($parentcheck !== true) {
5267 return $parentcheck;
5270 if ($data === '') {
5271 return true;
5274 $allcountries = get_string_manager()->get_list_of_countries(true);
5276 foreach (explode(',', $data) as $code) {
5277 if (!isset($allcountries[$code])) {
5278 return get_string('invalidcountrycode', 'core_error', $code);
5282 return true;
5288 * Selection of one of the recognised countries using the list
5289 * returned by {@link get_list_of_countries()}.
5291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5293 class admin_settings_country_select extends admin_setting_configselect {
5294 protected $includeall;
5295 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5296 $this->includeall = $includeall;
5297 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
5301 * Lazy-load the available choices for the select box
5303 public function load_choices() {
5304 global $CFG;
5305 if (is_array($this->choices)) {
5306 return true;
5308 $this->choices = array_merge(
5309 array('0' => get_string('choosedots')),
5310 get_string_manager()->get_list_of_countries($this->includeall));
5311 return true;
5317 * admin_setting_configselect for the default number of sections in a course,
5318 * simply so we can lazy-load the choices.
5320 * @copyright 2011 The Open University
5321 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5323 class admin_settings_num_course_sections extends admin_setting_configselect {
5324 public function __construct($name, $visiblename, $description, $defaultsetting) {
5325 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
5328 /** Lazy-load the available choices for the select box */
5329 public function load_choices() {
5330 $max = get_config('moodlecourse', 'maxsections');
5331 if (!isset($max) || !is_numeric($max)) {
5332 $max = 52;
5334 for ($i = 0; $i <= $max; $i++) {
5335 $this->choices[$i] = "$i";
5337 return true;
5343 * Course category selection
5345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5347 class admin_settings_coursecat_select extends admin_setting_configselect_autocomplete {
5349 * Calls parent::__construct with specific arguments
5351 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5352 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5356 * Load the available choices for the select box
5358 * @return bool
5360 public function load_choices() {
5361 if (is_array($this->choices)) {
5362 return true;
5364 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
5365 return true;
5371 * Special control for selecting days to backup
5373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5375 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
5377 * Calls parent::__construct with specific arguments
5379 public function __construct() {
5380 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5381 $this->plugin = 'backup';
5385 * Load the available choices for the select box
5387 * @return bool Always returns true
5389 public function load_choices() {
5390 if (is_array($this->choices)) {
5391 return true;
5393 $this->choices = array();
5394 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5395 foreach ($days as $day) {
5396 $this->choices[$day] = get_string($day, 'calendar');
5398 return true;
5403 * Special setting for backup auto destination.
5405 * @package core
5406 * @subpackage admin
5407 * @copyright 2014 Frédéric Massart - FMCorz.net
5408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5410 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5413 * Calls parent::__construct with specific arguments.
5415 public function __construct() {
5416 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5420 * Check if the directory must be set, depending on backup/backup_auto_storage.
5422 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5423 * there will be conflicts if this validation happens before the other one.
5425 * @param string $data Form data.
5426 * @return string Empty when no errors.
5428 public function write_setting($data) {
5429 $storage = (int) get_config('backup', 'backup_auto_storage');
5430 if ($storage !== 0) {
5431 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5432 // The directory must exist and be writable.
5433 return get_string('backuperrorinvaliddestination');
5436 return parent::write_setting($data);
5442 * Special debug setting
5444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5446 class admin_setting_special_debug extends admin_setting_configselect {
5448 * Calls parent::__construct with specific arguments
5450 public function __construct() {
5451 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5455 * Load the available choices for the select box
5457 * @return bool
5459 public function load_choices() {
5460 if (is_array($this->choices)) {
5461 return true;
5463 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5464 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5465 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5466 DEBUG_ALL => get_string('debugall', 'admin'),
5467 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5468 return true;
5474 * Special admin control
5476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5478 class admin_setting_special_calendar_weekend extends admin_setting {
5480 * Calls parent::__construct with specific arguments
5482 public function __construct() {
5483 $name = 'calendar_weekend';
5484 $visiblename = get_string('calendar_weekend', 'admin');
5485 $description = get_string('helpweekenddays', 'admin');
5486 $default = array ('0', '6'); // Saturdays and Sundays
5487 parent::__construct($name, $visiblename, $description, $default);
5491 * Gets the current settings as an array
5493 * @return mixed Null if none, else array of settings
5495 public function get_setting() {
5496 $result = $this->config_read($this->name);
5497 if (is_null($result)) {
5498 return NULL;
5500 if ($result === '') {
5501 return array();
5503 $settings = array();
5504 for ($i=0; $i<7; $i++) {
5505 if ($result & (1 << $i)) {
5506 $settings[] = $i;
5509 return $settings;
5513 * Save the new settings
5515 * @param array $data Array of new settings
5516 * @return bool
5518 public function write_setting($data) {
5519 if (!is_array($data)) {
5520 return '';
5522 unset($data['xxxxx']);
5523 $result = 0;
5524 foreach($data as $index) {
5525 $result |= 1 << $index;
5527 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5531 * Return XHTML to display the control
5533 * @param array $data array of selected days
5534 * @param string $query
5535 * @return string XHTML for display (field + wrapping div(s)
5537 public function output_html($data, $query='') {
5538 global $OUTPUT;
5540 // The order matters very much because of the implied numeric keys.
5541 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5542 $context = (object) [
5543 'name' => $this->get_full_name(),
5544 'id' => $this->get_id(),
5545 'days' => array_map(function($index) use ($days, $data) {
5546 return [
5547 'index' => $index,
5548 'label' => get_string($days[$index], 'calendar'),
5549 'checked' => in_array($index, $data)
5551 }, array_keys($days))
5554 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5556 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5563 * Admin setting that allows a user to pick a behaviour.
5565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5567 class admin_setting_question_behaviour extends admin_setting_configselect {
5569 * @param string $name name of config variable
5570 * @param string $visiblename display name
5571 * @param string $description description
5572 * @param string $default default.
5574 public function __construct($name, $visiblename, $description, $default) {
5575 parent::__construct($name, $visiblename, $description, $default, null);
5579 * Load list of behaviours as choices
5580 * @return bool true => success, false => error.
5582 public function load_choices() {
5583 global $CFG;
5584 require_once($CFG->dirroot . '/question/engine/lib.php');
5585 $this->choices = question_engine::get_behaviour_options('');
5586 return true;
5592 * Admin setting that allows a user to pick appropriate roles for something.
5594 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5596 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5597 /** @var array Array of capabilities which identify roles */
5598 private $types;
5601 * @param string $name Name of config variable
5602 * @param string $visiblename Display name
5603 * @param string $description Description
5604 * @param array $types Array of archetypes which identify
5605 * roles that will be enabled by default.
5607 public function __construct($name, $visiblename, $description, $types) {
5608 parent::__construct($name, $visiblename, $description, NULL, NULL);
5609 $this->types = $types;
5613 * Load roles as choices
5615 * @return bool true=>success, false=>error
5617 public function load_choices() {
5618 global $CFG, $DB;
5619 if (during_initial_install()) {
5620 return false;
5622 if (is_array($this->choices)) {
5623 return true;
5625 if ($roles = get_all_roles()) {
5626 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5627 return true;
5628 } else {
5629 return false;
5634 * Return the default setting for this control
5636 * @return array Array of default settings
5638 public function get_defaultsetting() {
5639 global $CFG;
5641 if (during_initial_install()) {
5642 return null;
5644 $result = array();
5645 foreach($this->types as $archetype) {
5646 if ($caproles = get_archetype_roles($archetype)) {
5647 foreach ($caproles as $caprole) {
5648 $result[$caprole->id] = 1;
5652 return $result;
5658 * Admin setting that is a list of installed filter plugins.
5660 * @copyright 2015 The Open University
5661 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5663 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5666 * Constructor
5668 * @param string $name unique ascii name, either 'mysetting' for settings
5669 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5670 * @param string $visiblename localised name
5671 * @param string $description localised long description
5672 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5674 public function __construct($name, $visiblename, $description, $default) {
5675 if (empty($default)) {
5676 $default = array();
5678 $this->load_choices();
5679 foreach ($default as $plugin) {
5680 if (!isset($this->choices[$plugin])) {
5681 unset($default[$plugin]);
5684 parent::__construct($name, $visiblename, $description, $default, null);
5687 public function load_choices() {
5688 if (is_array($this->choices)) {
5689 return true;
5691 $this->choices = array();
5693 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5694 $this->choices[$plugin] = filter_get_name($plugin);
5696 return true;
5702 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5706 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5708 * Constructor
5709 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5710 * @param string $visiblename localised
5711 * @param string $description long localised info
5712 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5713 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5714 * @param int $size default field size
5716 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5717 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5718 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5724 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5726 * @copyright 2009 Petr Skoda (http://skodak.org)
5727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5729 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5732 * Constructor
5733 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5734 * @param string $visiblename localised
5735 * @param string $description long localised info
5736 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5737 * @param string $yes value used when checked
5738 * @param string $no value used when not checked
5740 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5741 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5742 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5749 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5751 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5753 * @copyright 2010 Sam Hemelryk
5754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5756 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5758 * Constructor
5759 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5760 * @param string $visiblename localised
5761 * @param string $description long localised info
5762 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5763 * @param string $yes value used when checked
5764 * @param string $no value used when not checked
5766 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5767 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5768 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5774 * Autocomplete as you type form element.
5776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5778 class admin_setting_configselect_autocomplete extends admin_setting_configselect {
5779 /** @var boolean $tags Should we allow typing new entries to the field? */
5780 protected $tags = false;
5781 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5782 protected $ajax = '';
5783 /** @var string $placeholder Placeholder text for an empty list. */
5784 protected $placeholder = '';
5785 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5786 protected $casesensitive = false;
5787 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5788 protected $showsuggestions = true;
5789 /** @var string $noselectionstring String that is shown when there are no selections. */
5790 protected $noselectionstring = '';
5793 * Returns XHTML select field and wrapping div(s)
5795 * @see output_select_html()
5797 * @param string $data the option to show as selected
5798 * @param string $query
5799 * @return string XHTML field and wrapping div
5801 public function output_html($data, $query='') {
5802 global $PAGE;
5804 $html = parent::output_html($data, $query);
5806 if ($html === '') {
5807 return $html;
5810 $this->placeholder = get_string('search');
5812 $params = array('#' . $this->get_id(), $this->tags, $this->ajax,
5813 $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring);
5815 // Load autocomplete wrapper for select2 library.
5816 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params);
5818 return $html;
5823 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5827 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5829 * Calls parent::__construct with specific arguments
5831 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5832 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5833 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5839 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5841 * @copyright 2017 Marina Glancy
5842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5844 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5846 * Constructor
5847 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5848 * or 'myplugin/mysetting' for ones in config_plugins.
5849 * @param string $visiblename localised
5850 * @param string $description long localised info
5851 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5852 * @param array $choices array of $value=>$label for each selection
5854 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5855 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5856 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5862 * Graded roles in gradebook
5864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5866 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5868 * Calls parent::__construct with specific arguments
5870 public function __construct() {
5871 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5872 get_string('configgradebookroles', 'admin'),
5873 array('student'));
5880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5882 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5884 * Saves the new settings passed in $data
5886 * @param string $data
5887 * @return mixed string or Array
5889 public function write_setting($data) {
5890 global $CFG, $DB;
5892 $oldvalue = $this->config_read($this->name);
5893 $return = parent::write_setting($data);
5894 $newvalue = $this->config_read($this->name);
5896 if ($oldvalue !== $newvalue) {
5897 // force full regrading
5898 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5901 return $return;
5907 * Which roles to show on course description page
5909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5911 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5913 * Calls parent::__construct with specific arguments
5915 public function __construct() {
5916 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5917 get_string('coursecontact_desc', 'admin'),
5918 array('editingteacher'));
5919 $this->set_updatedcallback(function (){
5920 cache::make('core', 'coursecontacts')->purge();
5928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5930 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5932 * Calls parent::__construct with specific arguments
5934 public function __construct() {
5935 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5936 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5940 * Old syntax of class constructor. Deprecated in PHP7.
5942 * @deprecated since Moodle 3.1
5944 public function admin_setting_special_gradelimiting() {
5945 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5946 self::__construct();
5950 * Force site regrading
5952 function regrade_all() {
5953 global $CFG;
5954 require_once("$CFG->libdir/gradelib.php");
5955 grade_force_site_regrading();
5959 * Saves the new settings
5961 * @param mixed $data
5962 * @return string empty string or error message
5964 function write_setting($data) {
5965 $previous = $this->get_setting();
5967 if ($previous === null) {
5968 if ($data) {
5969 $this->regrade_all();
5971 } else {
5972 if ($data != $previous) {
5973 $this->regrade_all();
5976 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5982 * Special setting for $CFG->grade_minmaxtouse.
5984 * @package core
5985 * @copyright 2015 Frédéric Massart - FMCorz.net
5986 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5988 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5991 * Constructor.
5993 public function __construct() {
5994 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5995 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5996 array(
5997 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5998 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
6004 * Saves the new setting.
6006 * @param mixed $data
6007 * @return string empty string or error message
6009 function write_setting($data) {
6010 global $CFG;
6012 $previous = $this->get_setting();
6013 $result = parent::write_setting($data);
6015 // If saved and the value has changed.
6016 if (empty($result) && $previous != $data) {
6017 require_once($CFG->libdir . '/gradelib.php');
6018 grade_force_site_regrading();
6021 return $result;
6028 * Primary grade export plugin - has state tracking.
6030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6032 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
6034 * Calls parent::__construct with specific arguments
6036 public function __construct() {
6037 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
6038 get_string('configgradeexport', 'admin'), array(), NULL);
6042 * Load the available choices for the multicheckbox
6044 * @return bool always returns true
6046 public function load_choices() {
6047 if (is_array($this->choices)) {
6048 return true;
6050 $this->choices = array();
6052 if ($plugins = core_component::get_plugin_list('gradeexport')) {
6053 foreach($plugins as $plugin => $unused) {
6054 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
6057 return true;
6063 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
6065 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6067 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
6069 * Config gradepointmax constructor
6071 * @param string $name Overidden by "gradepointmax"
6072 * @param string $visiblename Overridden by "gradepointmax" language string.
6073 * @param string $description Overridden by "gradepointmax_help" language string.
6074 * @param string $defaultsetting Not used, overridden by 100.
6075 * @param mixed $paramtype Overridden by PARAM_INT.
6076 * @param int $size Overridden by 5.
6078 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6079 $name = 'gradepointdefault';
6080 $visiblename = get_string('gradepointdefault', 'grades');
6081 $description = get_string('gradepointdefault_help', 'grades');
6082 $defaultsetting = 100;
6083 $paramtype = PARAM_INT;
6084 $size = 5;
6085 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6089 * Validate data before storage
6090 * @param string $data The submitted data
6091 * @return bool|string true if ok, string if error found
6093 public function validate($data) {
6094 global $CFG;
6095 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
6096 return true;
6097 } else {
6098 return get_string('gradepointdefault_validateerror', 'grades');
6105 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
6107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6109 class admin_setting_special_gradepointmax extends admin_setting_configtext {
6112 * Config gradepointmax constructor
6114 * @param string $name Overidden by "gradepointmax"
6115 * @param string $visiblename Overridden by "gradepointmax" language string.
6116 * @param string $description Overridden by "gradepointmax_help" language string.
6117 * @param string $defaultsetting Not used, overridden by 100.
6118 * @param mixed $paramtype Overridden by PARAM_INT.
6119 * @param int $size Overridden by 5.
6121 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6122 $name = 'gradepointmax';
6123 $visiblename = get_string('gradepointmax', 'grades');
6124 $description = get_string('gradepointmax_help', 'grades');
6125 $defaultsetting = 100;
6126 $paramtype = PARAM_INT;
6127 $size = 5;
6128 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6132 * Save the selected setting
6134 * @param string $data The selected site
6135 * @return string empty string or error message
6137 public function write_setting($data) {
6138 if ($data === '') {
6139 $data = (int)$this->defaultsetting;
6140 } else {
6141 $data = $data;
6143 return parent::write_setting($data);
6147 * Validate data before storage
6148 * @param string $data The submitted data
6149 * @return bool|string true if ok, string if error found
6151 public function validate($data) {
6152 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6153 return true;
6154 } else {
6155 return get_string('gradepointmax_validateerror', 'grades');
6160 * Return an XHTML string for the setting
6161 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6162 * @param string $query search query to be highlighted
6163 * @return string XHTML to display control
6165 public function output_html($data, $query = '') {
6166 global $OUTPUT;
6168 $default = $this->get_defaultsetting();
6169 $context = (object) [
6170 'size' => $this->size,
6171 'id' => $this->get_id(),
6172 'name' => $this->get_full_name(),
6173 'value' => $data,
6174 'attributes' => [
6175 'maxlength' => 5
6177 'forceltr' => $this->get_force_ltr()
6179 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6181 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
6187 * Grade category settings
6189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6191 class admin_setting_gradecat_combo extends admin_setting {
6192 /** @var array Array of choices */
6193 public $choices;
6196 * Sets choices and calls parent::__construct with passed arguments
6197 * @param string $name
6198 * @param string $visiblename
6199 * @param string $description
6200 * @param mixed $defaultsetting string or array depending on implementation
6201 * @param array $choices An array of choices for the control
6203 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6204 $this->choices = $choices;
6205 parent::__construct($name, $visiblename, $description, $defaultsetting);
6209 * Return the current setting(s) array
6211 * @return array Array of value=>xx, forced=>xx, adv=>xx
6213 public function get_setting() {
6214 global $CFG;
6216 $value = $this->config_read($this->name);
6217 $flag = $this->config_read($this->name.'_flag');
6219 if (is_null($value) or is_null($flag)) {
6220 return NULL;
6223 $flag = (int)$flag;
6224 $forced = (boolean)(1 & $flag); // first bit
6225 $adv = (boolean)(2 & $flag); // second bit
6227 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6231 * Save the new settings passed in $data
6233 * @todo Add vartype handling to ensure $data is array
6234 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6235 * @return string empty or error message
6237 public function write_setting($data) {
6238 global $CFG;
6240 $value = $data['value'];
6241 $forced = empty($data['forced']) ? 0 : 1;
6242 $adv = empty($data['adv']) ? 0 : 2;
6243 $flag = ($forced | $adv); //bitwise or
6245 if (!in_array($value, array_keys($this->choices))) {
6246 return 'Error setting ';
6249 $oldvalue = $this->config_read($this->name);
6250 $oldflag = (int)$this->config_read($this->name.'_flag');
6251 $oldforced = (1 & $oldflag); // first bit
6253 $result1 = $this->config_write($this->name, $value);
6254 $result2 = $this->config_write($this->name.'_flag', $flag);
6256 // force regrade if needed
6257 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6258 require_once($CFG->libdir.'/gradelib.php');
6259 grade_category::updated_forced_settings();
6262 if ($result1 and $result2) {
6263 return '';
6264 } else {
6265 return get_string('errorsetting', 'admin');
6270 * Return XHTML to display the field and wrapping div
6272 * @todo Add vartype handling to ensure $data is array
6273 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6274 * @param string $query
6275 * @return string XHTML to display control
6277 public function output_html($data, $query='') {
6278 global $OUTPUT;
6280 $value = $data['value'];
6282 $default = $this->get_defaultsetting();
6283 if (!is_null($default)) {
6284 $defaultinfo = array();
6285 if (isset($this->choices[$default['value']])) {
6286 $defaultinfo[] = $this->choices[$default['value']];
6288 if (!empty($default['forced'])) {
6289 $defaultinfo[] = get_string('force');
6291 if (!empty($default['adv'])) {
6292 $defaultinfo[] = get_string('advanced');
6294 $defaultinfo = implode(', ', $defaultinfo);
6296 } else {
6297 $defaultinfo = NULL;
6300 $options = $this->choices;
6301 $context = (object) [
6302 'id' => $this->get_id(),
6303 'name' => $this->get_full_name(),
6304 'forced' => !empty($data['forced']),
6305 'advanced' => !empty($data['adv']),
6306 'options' => array_map(function($option) use ($options, $value) {
6307 return [
6308 'value' => $option,
6309 'name' => $options[$option],
6310 'selected' => $option == $value
6312 }, array_keys($options)),
6315 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6317 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
6323 * Selection of grade report in user profiles
6325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6327 class admin_setting_grade_profilereport extends admin_setting_configselect {
6329 * Calls parent::__construct with specific arguments
6331 public function __construct() {
6332 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6336 * Loads an array of choices for the configselect control
6338 * @return bool always return true
6340 public function load_choices() {
6341 if (is_array($this->choices)) {
6342 return true;
6344 $this->choices = array();
6346 global $CFG;
6347 require_once($CFG->libdir.'/gradelib.php');
6349 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6350 if (file_exists($plugindir.'/lib.php')) {
6351 require_once($plugindir.'/lib.php');
6352 $functionname = 'grade_report_'.$plugin.'_profilereport';
6353 if (function_exists($functionname)) {
6354 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6358 return true;
6363 * Provides a selection of grade reports to be used for "grades".
6365 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6366 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6368 class admin_setting_my_grades_report extends admin_setting_configselect {
6371 * Calls parent::__construct with specific arguments.
6373 public function __construct() {
6374 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6375 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6379 * Loads an array of choices for the configselect control.
6381 * @return bool always returns true.
6383 public function load_choices() {
6384 global $CFG; // Remove this line and behold the horror of behat test failures!
6385 $this->choices = array();
6386 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6387 if (file_exists($plugindir . '/lib.php')) {
6388 require_once($plugindir . '/lib.php');
6389 // Check to see if the class exists. Check the correct plugin convention first.
6390 if (class_exists('gradereport_' . $plugin)) {
6391 $classname = 'gradereport_' . $plugin;
6392 } else if (class_exists('grade_report_' . $plugin)) {
6393 // We are using the old plugin naming convention.
6394 $classname = 'grade_report_' . $plugin;
6395 } else {
6396 continue;
6398 if ($classname::supports_mygrades()) {
6399 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6403 // Add an option to specify an external url.
6404 $this->choices['external'] = get_string('externalurl', 'grades');
6405 return true;
6410 * Special class for register auth selection
6412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6414 class admin_setting_special_registerauth extends admin_setting_configselect {
6416 * Calls parent::__construct with specific arguments
6418 public function __construct() {
6419 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6423 * Returns the default option
6425 * @return string empty or default option
6427 public function get_defaultsetting() {
6428 $this->load_choices();
6429 $defaultsetting = parent::get_defaultsetting();
6430 if (array_key_exists($defaultsetting, $this->choices)) {
6431 return $defaultsetting;
6432 } else {
6433 return '';
6438 * Loads the possible choices for the array
6440 * @return bool always returns true
6442 public function load_choices() {
6443 global $CFG;
6445 if (is_array($this->choices)) {
6446 return true;
6448 $this->choices = array();
6449 $this->choices[''] = get_string('disable');
6451 $authsenabled = get_enabled_auth_plugins();
6453 foreach ($authsenabled as $auth) {
6454 $authplugin = get_auth_plugin($auth);
6455 if (!$authplugin->can_signup()) {
6456 continue;
6458 // Get the auth title (from core or own auth lang files)
6459 $authtitle = $authplugin->get_title();
6460 $this->choices[$auth] = $authtitle;
6462 return true;
6468 * General plugins manager
6470 class admin_page_pluginsoverview extends admin_externalpage {
6473 * Sets basic information about the external page
6475 public function __construct() {
6476 global $CFG;
6477 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6478 "$CFG->wwwroot/$CFG->admin/plugins.php");
6483 * Module manage page
6485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6487 class admin_page_managemods extends admin_externalpage {
6489 * Calls parent::__construct with specific arguments
6491 public function __construct() {
6492 global $CFG;
6493 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6497 * Try to find the specified module
6499 * @param string $query The module to search for
6500 * @return array
6502 public function search($query) {
6503 global $CFG, $DB;
6504 if ($result = parent::search($query)) {
6505 return $result;
6508 $found = false;
6509 if ($modules = $DB->get_records('modules')) {
6510 foreach ($modules as $module) {
6511 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6512 continue;
6514 if (strpos($module->name, $query) !== false) {
6515 $found = true;
6516 break;
6518 $strmodulename = get_string('modulename', $module->name);
6519 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6520 $found = true;
6521 break;
6525 if ($found) {
6526 $result = new stdClass();
6527 $result->page = $this;
6528 $result->settings = array();
6529 return array($this->name => $result);
6530 } else {
6531 return array();
6538 * Special class for enrol plugins management.
6540 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6543 class admin_setting_manageenrols extends admin_setting {
6545 * Calls parent::__construct with specific arguments
6547 public function __construct() {
6548 $this->nosave = true;
6549 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6553 * Always returns true, does nothing
6555 * @return true
6557 public function get_setting() {
6558 return true;
6562 * Always returns true, does nothing
6564 * @return true
6566 public function get_defaultsetting() {
6567 return true;
6571 * Always returns '', does not write anything
6573 * @return string Always returns ''
6575 public function write_setting($data) {
6576 // do not write any setting
6577 return '';
6581 * Checks if $query is one of the available enrol plugins
6583 * @param string $query The string to search for
6584 * @return bool Returns true if found, false if not
6586 public function is_related($query) {
6587 if (parent::is_related($query)) {
6588 return true;
6591 $query = core_text::strtolower($query);
6592 $enrols = enrol_get_plugins(false);
6593 foreach ($enrols as $name=>$enrol) {
6594 $localised = get_string('pluginname', 'enrol_'.$name);
6595 if (strpos(core_text::strtolower($name), $query) !== false) {
6596 return true;
6598 if (strpos(core_text::strtolower($localised), $query) !== false) {
6599 return true;
6602 return false;
6606 * Builds the XHTML to display the control
6608 * @param string $data Unused
6609 * @param string $query
6610 * @return string
6612 public function output_html($data, $query='') {
6613 global $CFG, $OUTPUT, $DB, $PAGE;
6615 // Display strings.
6616 $strup = get_string('up');
6617 $strdown = get_string('down');
6618 $strsettings = get_string('settings');
6619 $strenable = get_string('enable');
6620 $strdisable = get_string('disable');
6621 $struninstall = get_string('uninstallplugin', 'core_admin');
6622 $strusage = get_string('enrolusage', 'enrol');
6623 $strversion = get_string('version');
6624 $strtest = get_string('testsettings', 'core_enrol');
6626 $pluginmanager = core_plugin_manager::instance();
6628 $enrols_available = enrol_get_plugins(false);
6629 $active_enrols = enrol_get_plugins(true);
6631 $allenrols = array();
6632 foreach ($active_enrols as $key=>$enrol) {
6633 $allenrols[$key] = true;
6635 foreach ($enrols_available as $key=>$enrol) {
6636 $allenrols[$key] = true;
6638 // Now find all borked plugins and at least allow then to uninstall.
6639 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6640 foreach ($condidates as $candidate) {
6641 if (empty($allenrols[$candidate])) {
6642 $allenrols[$candidate] = true;
6646 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6647 $return .= $OUTPUT->box_start('generalbox enrolsui');
6649 $table = new html_table();
6650 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6651 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6652 $table->id = 'courseenrolmentplugins';
6653 $table->attributes['class'] = 'admintable generaltable';
6654 $table->data = array();
6656 // Iterate through enrol plugins and add to the display table.
6657 $updowncount = 1;
6658 $enrolcount = count($active_enrols);
6659 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6660 $printed = array();
6661 foreach($allenrols as $enrol => $unused) {
6662 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6663 $version = get_config('enrol_'.$enrol, 'version');
6664 if ($version === false) {
6665 $version = '';
6668 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6669 $name = get_string('pluginname', 'enrol_'.$enrol);
6670 } else {
6671 $name = $enrol;
6673 // Usage.
6674 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6675 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6676 $usage = "$ci / $cp";
6678 // Hide/show links.
6679 $class = '';
6680 if (isset($active_enrols[$enrol])) {
6681 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6682 $hideshow = "<a href=\"$aurl\">";
6683 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6684 $enabled = true;
6685 $displayname = $name;
6686 } else if (isset($enrols_available[$enrol])) {
6687 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6688 $hideshow = "<a href=\"$aurl\">";
6689 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6690 $enabled = false;
6691 $displayname = $name;
6692 $class = 'dimmed_text';
6693 } else {
6694 $hideshow = '';
6695 $enabled = false;
6696 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6698 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6699 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6700 } else {
6701 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6704 // Up/down link (only if enrol is enabled).
6705 $updown = '';
6706 if ($enabled) {
6707 if ($updowncount > 1) {
6708 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6709 $updown .= "<a href=\"$aurl\">";
6710 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6711 } else {
6712 $updown .= $OUTPUT->spacer() . '&nbsp;';
6714 if ($updowncount < $enrolcount) {
6715 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6716 $updown .= "<a href=\"$aurl\">";
6717 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6718 } else {
6719 $updown .= $OUTPUT->spacer() . '&nbsp;';
6721 ++$updowncount;
6724 // Add settings link.
6725 if (!$version) {
6726 $settings = '';
6727 } else if ($surl = $plugininfo->get_settings_url()) {
6728 $settings = html_writer::link($surl, $strsettings);
6729 } else {
6730 $settings = '';
6733 // Add uninstall info.
6734 $uninstall = '';
6735 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6736 $uninstall = html_writer::link($uninstallurl, $struninstall);
6739 $test = '';
6740 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6741 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6742 $test = html_writer::link($testsettingsurl, $strtest);
6745 // Add a row to the table.
6746 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6747 if ($class) {
6748 $row->attributes['class'] = $class;
6750 $table->data[] = $row;
6752 $printed[$enrol] = true;
6755 $return .= html_writer::table($table);
6756 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6757 $return .= $OUTPUT->box_end();
6758 return highlight($query, $return);
6764 * Blocks manage page
6766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6768 class admin_page_manageblocks extends admin_externalpage {
6770 * Calls parent::__construct with specific arguments
6772 public function __construct() {
6773 global $CFG;
6774 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6778 * Search for a specific block
6780 * @param string $query The string to search for
6781 * @return array
6783 public function search($query) {
6784 global $CFG, $DB;
6785 if ($result = parent::search($query)) {
6786 return $result;
6789 $found = false;
6790 if ($blocks = $DB->get_records('block')) {
6791 foreach ($blocks as $block) {
6792 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6793 continue;
6795 if (strpos($block->name, $query) !== false) {
6796 $found = true;
6797 break;
6799 $strblockname = get_string('pluginname', 'block_'.$block->name);
6800 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6801 $found = true;
6802 break;
6806 if ($found) {
6807 $result = new stdClass();
6808 $result->page = $this;
6809 $result->settings = array();
6810 return array($this->name => $result);
6811 } else {
6812 return array();
6818 * Message outputs configuration
6820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6822 class admin_page_managemessageoutputs extends admin_externalpage {
6824 * Calls parent::__construct with specific arguments
6826 public function __construct() {
6827 global $CFG;
6828 parent::__construct('managemessageoutputs',
6829 get_string('defaultmessageoutputs', 'message'),
6830 new moodle_url('/admin/message.php')
6835 * Search for a specific message processor
6837 * @param string $query The string to search for
6838 * @return array
6840 public function search($query) {
6841 global $CFG, $DB;
6842 if ($result = parent::search($query)) {
6843 return $result;
6846 $found = false;
6847 if ($processors = get_message_processors()) {
6848 foreach ($processors as $processor) {
6849 if (!$processor->available) {
6850 continue;
6852 if (strpos($processor->name, $query) !== false) {
6853 $found = true;
6854 break;
6856 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6857 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6858 $found = true;
6859 break;
6863 if ($found) {
6864 $result = new stdClass();
6865 $result->page = $this;
6866 $result->settings = array();
6867 return array($this->name => $result);
6868 } else {
6869 return array();
6875 * Manage question behaviours page
6877 * @copyright 2011 The Open University
6878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6880 class admin_page_manageqbehaviours extends admin_externalpage {
6882 * Constructor
6884 public function __construct() {
6885 global $CFG;
6886 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6887 new moodle_url('/admin/qbehaviours.php'));
6891 * Search question behaviours for the specified string
6893 * @param string $query The string to search for in question behaviours
6894 * @return array
6896 public function search($query) {
6897 global $CFG;
6898 if ($result = parent::search($query)) {
6899 return $result;
6902 $found = false;
6903 require_once($CFG->dirroot . '/question/engine/lib.php');
6904 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6905 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6906 $query) !== false) {
6907 $found = true;
6908 break;
6911 if ($found) {
6912 $result = new stdClass();
6913 $result->page = $this;
6914 $result->settings = array();
6915 return array($this->name => $result);
6916 } else {
6917 return array();
6924 * Question type manage page
6926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6928 class admin_page_manageqtypes extends admin_externalpage {
6930 * Calls parent::__construct with specific arguments
6932 public function __construct() {
6933 global $CFG;
6934 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6935 new moodle_url('/admin/qtypes.php'));
6939 * Search question types for the specified string
6941 * @param string $query The string to search for in question types
6942 * @return array
6944 public function search($query) {
6945 global $CFG;
6946 if ($result = parent::search($query)) {
6947 return $result;
6950 $found = false;
6951 require_once($CFG->dirroot . '/question/engine/bank.php');
6952 foreach (question_bank::get_all_qtypes() as $qtype) {
6953 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6954 $found = true;
6955 break;
6958 if ($found) {
6959 $result = new stdClass();
6960 $result->page = $this;
6961 $result->settings = array();
6962 return array($this->name => $result);
6963 } else {
6964 return array();
6970 class admin_page_manageportfolios extends admin_externalpage {
6972 * Calls parent::__construct with specific arguments
6974 public function __construct() {
6975 global $CFG;
6976 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6977 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6981 * Searches page for the specified string.
6982 * @param string $query The string to search for
6983 * @return bool True if it is found on this page
6985 public function search($query) {
6986 global $CFG;
6987 if ($result = parent::search($query)) {
6988 return $result;
6991 $found = false;
6992 $portfolios = core_component::get_plugin_list('portfolio');
6993 foreach ($portfolios as $p => $dir) {
6994 if (strpos($p, $query) !== false) {
6995 $found = true;
6996 break;
6999 if (!$found) {
7000 foreach (portfolio_instances(false, false) as $instance) {
7001 $title = $instance->get('name');
7002 if (strpos(core_text::strtolower($title), $query) !== false) {
7003 $found = true;
7004 break;
7009 if ($found) {
7010 $result = new stdClass();
7011 $result->page = $this;
7012 $result->settings = array();
7013 return array($this->name => $result);
7014 } else {
7015 return array();
7021 class admin_page_managerepositories extends admin_externalpage {
7023 * Calls parent::__construct with specific arguments
7025 public function __construct() {
7026 global $CFG;
7027 parent::__construct('managerepositories', get_string('manage',
7028 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
7032 * Searches page for the specified string.
7033 * @param string $query The string to search for
7034 * @return bool True if it is found on this page
7036 public function search($query) {
7037 global $CFG;
7038 if ($result = parent::search($query)) {
7039 return $result;
7042 $found = false;
7043 $repositories= core_component::get_plugin_list('repository');
7044 foreach ($repositories as $p => $dir) {
7045 if (strpos($p, $query) !== false) {
7046 $found = true;
7047 break;
7050 if (!$found) {
7051 foreach (repository::get_types() as $instance) {
7052 $title = $instance->get_typename();
7053 if (strpos(core_text::strtolower($title), $query) !== false) {
7054 $found = true;
7055 break;
7060 if ($found) {
7061 $result = new stdClass();
7062 $result->page = $this;
7063 $result->settings = array();
7064 return array($this->name => $result);
7065 } else {
7066 return array();
7073 * Special class for authentication administration.
7075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7077 class admin_setting_manageauths extends admin_setting {
7079 * Calls parent::__construct with specific arguments
7081 public function __construct() {
7082 $this->nosave = true;
7083 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
7087 * Always returns true
7089 * @return true
7091 public function get_setting() {
7092 return true;
7096 * Always returns true
7098 * @return true
7100 public function get_defaultsetting() {
7101 return true;
7105 * Always returns '' and doesn't write anything
7107 * @return string Always returns ''
7109 public function write_setting($data) {
7110 // do not write any setting
7111 return '';
7115 * Search to find if Query is related to auth plugin
7117 * @param string $query The string to search for
7118 * @return bool true for related false for not
7120 public function is_related($query) {
7121 if (parent::is_related($query)) {
7122 return true;
7125 $authsavailable = core_component::get_plugin_list('auth');
7126 foreach ($authsavailable as $auth => $dir) {
7127 if (strpos($auth, $query) !== false) {
7128 return true;
7130 $authplugin = get_auth_plugin($auth);
7131 $authtitle = $authplugin->get_title();
7132 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
7133 return true;
7136 return false;
7140 * Return XHTML to display control
7142 * @param mixed $data Unused
7143 * @param string $query
7144 * @return string highlight
7146 public function output_html($data, $query='') {
7147 global $CFG, $OUTPUT, $DB;
7149 // display strings
7150 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7151 'settings', 'edit', 'name', 'enable', 'disable',
7152 'up', 'down', 'none', 'users'));
7153 $txt->updown = "$txt->up/$txt->down";
7154 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7155 $txt->testsettings = get_string('testsettings', 'core_auth');
7157 $authsavailable = core_component::get_plugin_list('auth');
7158 get_enabled_auth_plugins(true); // fix the list of enabled auths
7159 if (empty($CFG->auth)) {
7160 $authsenabled = array();
7161 } else {
7162 $authsenabled = explode(',', $CFG->auth);
7165 // construct the display array, with enabled auth plugins at the top, in order
7166 $displayauths = array();
7167 $registrationauths = array();
7168 $registrationauths[''] = $txt->disable;
7169 $authplugins = array();
7170 foreach ($authsenabled as $auth) {
7171 $authplugin = get_auth_plugin($auth);
7172 $authplugins[$auth] = $authplugin;
7173 /// Get the auth title (from core or own auth lang files)
7174 $authtitle = $authplugin->get_title();
7175 /// Apply titles
7176 $displayauths[$auth] = $authtitle;
7177 if ($authplugin->can_signup()) {
7178 $registrationauths[$auth] = $authtitle;
7182 foreach ($authsavailable as $auth => $dir) {
7183 if (array_key_exists($auth, $displayauths)) {
7184 continue; //already in the list
7186 $authplugin = get_auth_plugin($auth);
7187 $authplugins[$auth] = $authplugin;
7188 /// Get the auth title (from core or own auth lang files)
7189 $authtitle = $authplugin->get_title();
7190 /// Apply titles
7191 $displayauths[$auth] = $authtitle;
7192 if ($authplugin->can_signup()) {
7193 $registrationauths[$auth] = $authtitle;
7197 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7198 $return .= $OUTPUT->box_start('generalbox authsui');
7200 $table = new html_table();
7201 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
7202 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7203 $table->data = array();
7204 $table->attributes['class'] = 'admintable generaltable';
7205 $table->id = 'manageauthtable';
7207 //add always enabled plugins first
7208 $displayname = $displayauths['manual'];
7209 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7210 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7211 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
7212 $displayname = $displayauths['nologin'];
7213 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7214 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
7217 // iterate through auth plugins and add to the display table
7218 $updowncount = 1;
7219 $authcount = count($authsenabled);
7220 $url = "auth.php?sesskey=" . sesskey();
7221 foreach ($displayauths as $auth => $name) {
7222 if ($auth == 'manual' or $auth == 'nologin') {
7223 continue;
7225 $class = '';
7226 // hide/show link
7227 if (in_array($auth, $authsenabled)) {
7228 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
7229 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7230 $enabled = true;
7231 $displayname = $name;
7233 else {
7234 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
7235 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7236 $enabled = false;
7237 $displayname = $name;
7238 $class = 'dimmed_text';
7241 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7243 // up/down link (only if auth is enabled)
7244 $updown = '';
7245 if ($enabled) {
7246 if ($updowncount > 1) {
7247 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
7248 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7250 else {
7251 $updown .= $OUTPUT->spacer() . '&nbsp;';
7253 if ($updowncount < $authcount) {
7254 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
7255 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7257 else {
7258 $updown .= $OUTPUT->spacer() . '&nbsp;';
7260 ++ $updowncount;
7263 // settings link
7264 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
7265 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7266 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
7267 throw new \coding_exception('config.html is no longer supported, please use settings.php instead.');
7268 } else {
7269 $settings = '';
7272 // Uninstall link.
7273 $uninstall = '';
7274 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7275 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7278 $test = '';
7279 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7280 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
7281 $test = html_writer::link($testurl, $txt->testsettings);
7284 // Add a row to the table.
7285 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7286 if ($class) {
7287 $row->attributes['class'] = $class;
7289 $table->data[] = $row;
7291 $return .= html_writer::table($table);
7292 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7293 $return .= $OUTPUT->box_end();
7294 return highlight($query, $return);
7299 * Special class for antiviruses administration.
7301 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7304 class admin_setting_manageantiviruses extends admin_setting {
7306 * Calls parent::__construct with specific arguments
7308 public function __construct() {
7309 $this->nosave = true;
7310 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7314 * Always returns true, does nothing
7316 * @return true
7318 public function get_setting() {
7319 return true;
7323 * Always returns true, does nothing
7325 * @return true
7327 public function get_defaultsetting() {
7328 return true;
7332 * Always returns '', does not write anything
7334 * @param string $data Unused
7335 * @return string Always returns ''
7337 public function write_setting($data) {
7338 // Do not write any setting.
7339 return '';
7343 * Checks if $query is one of the available editors
7345 * @param string $query The string to search for
7346 * @return bool Returns true if found, false if not
7348 public function is_related($query) {
7349 if (parent::is_related($query)) {
7350 return true;
7353 $antivirusesavailable = \core\antivirus\manager::get_available();
7354 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7355 if (strpos($antivirus, $query) !== false) {
7356 return true;
7358 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7359 return true;
7362 return false;
7366 * Builds the XHTML to display the control
7368 * @param string $data Unused
7369 * @param string $query
7370 * @return string
7372 public function output_html($data, $query='') {
7373 global $CFG, $OUTPUT;
7375 // Display strings.
7376 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7377 'up', 'down', 'none'));
7378 $struninstall = get_string('uninstallplugin', 'core_admin');
7380 $txt->updown = "$txt->up/$txt->down";
7382 $antivirusesavailable = \core\antivirus\manager::get_available();
7383 $activeantiviruses = explode(',', $CFG->antiviruses);
7385 $activeantiviruses = array_reverse($activeantiviruses);
7386 foreach ($activeantiviruses as $key => $antivirus) {
7387 if (empty($antivirusesavailable[$antivirus])) {
7388 unset($activeantiviruses[$key]);
7389 } else {
7390 $name = $antivirusesavailable[$antivirus];
7391 unset($antivirusesavailable[$antivirus]);
7392 $antivirusesavailable[$antivirus] = $name;
7395 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7396 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7397 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7399 $table = new html_table();
7400 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7401 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7402 $table->id = 'antivirusmanagement';
7403 $table->attributes['class'] = 'admintable generaltable';
7404 $table->data = array();
7406 // Iterate through auth plugins and add to the display table.
7407 $updowncount = 1;
7408 $antiviruscount = count($activeantiviruses);
7409 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7410 foreach ($antivirusesavailable as $antivirus => $name) {
7411 // Hide/show link.
7412 $class = '';
7413 if (in_array($antivirus, $activeantiviruses)) {
7414 $hideshowurl = $baseurl;
7415 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7416 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7417 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7418 $enabled = true;
7419 $displayname = $name;
7420 } else {
7421 $hideshowurl = $baseurl;
7422 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7423 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7424 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7425 $enabled = false;
7426 $displayname = $name;
7427 $class = 'dimmed_text';
7430 // Up/down link.
7431 $updown = '';
7432 if ($enabled) {
7433 if ($updowncount > 1) {
7434 $updownurl = $baseurl;
7435 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7436 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7437 $updown = html_writer::link($updownurl, $updownimg);
7438 } else {
7439 $updownimg = $OUTPUT->spacer();
7441 if ($updowncount < $antiviruscount) {
7442 $updownurl = $baseurl;
7443 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7444 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7445 $updown = html_writer::link($updownurl, $updownimg);
7446 } else {
7447 $updownimg = $OUTPUT->spacer();
7449 ++ $updowncount;
7452 // Settings link.
7453 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7454 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7455 $settings = html_writer::link($eurl, $txt->settings);
7456 } else {
7457 $settings = '';
7460 $uninstall = '';
7461 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7462 $uninstall = html_writer::link($uninstallurl, $struninstall);
7465 // Add a row to the table.
7466 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7467 if ($class) {
7468 $row->attributes['class'] = $class;
7470 $table->data[] = $row;
7472 $return .= html_writer::table($table);
7473 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7474 $return .= $OUTPUT->box_end();
7475 return highlight($query, $return);
7480 * Course formats manager. Allows to enable/disable formats and jump to settings
7482 class admin_setting_manageformats extends admin_setting {
7485 * Calls parent::__construct with specific arguments
7487 public function __construct() {
7488 $this->nosave = true;
7489 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7493 * Always returns true
7495 * @return true
7497 public function get_setting() {
7498 return true;
7502 * Always returns true
7504 * @return true
7506 public function get_defaultsetting() {
7507 return true;
7511 * Always returns '' and doesn't write anything
7513 * @param mixed $data string or array, must not be NULL
7514 * @return string Always returns ''
7516 public function write_setting($data) {
7517 // do not write any setting
7518 return '';
7522 * Search to find if Query is related to format plugin
7524 * @param string $query The string to search for
7525 * @return bool true for related false for not
7527 public function is_related($query) {
7528 if (parent::is_related($query)) {
7529 return true;
7531 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7532 foreach ($formats as $format) {
7533 if (strpos($format->component, $query) !== false ||
7534 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7535 return true;
7538 return false;
7542 * Return XHTML to display control
7544 * @param mixed $data Unused
7545 * @param string $query
7546 * @return string highlight
7548 public function output_html($data, $query='') {
7549 global $CFG, $OUTPUT;
7550 $return = '';
7551 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7552 $return .= $OUTPUT->box_start('generalbox formatsui');
7554 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7556 // display strings
7557 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7558 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7559 $txt->updown = "$txt->up/$txt->down";
7561 $table = new html_table();
7562 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7563 $table->align = array('left', 'center', 'center', 'center', 'center');
7564 $table->attributes['class'] = 'manageformattable generaltable admintable';
7565 $table->data = array();
7567 $cnt = 0;
7568 $defaultformat = get_config('moodlecourse', 'format');
7569 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7570 foreach ($formats as $format) {
7571 $url = new moodle_url('/admin/courseformats.php',
7572 array('sesskey' => sesskey(), 'format' => $format->name));
7573 $isdefault = '';
7574 $class = '';
7575 if ($format->is_enabled()) {
7576 $strformatname = $format->displayname;
7577 if ($defaultformat === $format->name) {
7578 $hideshow = $txt->default;
7579 } else {
7580 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7581 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7583 } else {
7584 $strformatname = $format->displayname;
7585 $class = 'dimmed_text';
7586 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7587 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7589 $updown = '';
7590 if ($cnt) {
7591 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7592 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7593 } else {
7594 $updown .= $spacer;
7596 if ($cnt < count($formats) - 1) {
7597 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7598 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7599 } else {
7600 $updown .= $spacer;
7602 $cnt++;
7603 $settings = '';
7604 if ($format->get_settings_url()) {
7605 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7607 $uninstall = '';
7608 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7609 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7611 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7612 if ($class) {
7613 $row->attributes['class'] = $class;
7615 $table->data[] = $row;
7617 $return .= html_writer::table($table);
7618 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7619 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7620 $return .= $OUTPUT->box_end();
7621 return highlight($query, $return);
7626 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7628 * @package core
7629 * @copyright 2018 Toni Barbera
7630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7632 class admin_setting_managecustomfields extends admin_setting {
7635 * Calls parent::__construct with specific arguments
7637 public function __construct() {
7638 $this->nosave = true;
7639 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7643 * Always returns true
7645 * @return true
7647 public function get_setting() {
7648 return true;
7652 * Always returns true
7654 * @return true
7656 public function get_defaultsetting() {
7657 return true;
7661 * Always returns '' and doesn't write anything
7663 * @param mixed $data string or array, must not be NULL
7664 * @return string Always returns ''
7666 public function write_setting($data) {
7667 // Do not write any setting.
7668 return '';
7672 * Search to find if Query is related to format plugin
7674 * @param string $query The string to search for
7675 * @return bool true for related false for not
7677 public function is_related($query) {
7678 if (parent::is_related($query)) {
7679 return true;
7681 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7682 foreach ($formats as $format) {
7683 if (strpos($format->component, $query) !== false ||
7684 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7685 return true;
7688 return false;
7692 * Return XHTML to display control
7694 * @param mixed $data Unused
7695 * @param string $query
7696 * @return string highlight
7698 public function output_html($data, $query='') {
7699 global $CFG, $OUTPUT;
7700 $return = '';
7701 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7702 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7704 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7706 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7707 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7708 $txt->updown = "$txt->up/$txt->down";
7710 $table = new html_table();
7711 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7712 $table->align = array('left', 'center', 'center', 'center');
7713 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7714 $table->data = array();
7716 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7717 foreach ($fields as $field) {
7718 $url = new moodle_url('/admin/customfields.php',
7719 array('sesskey' => sesskey(), 'field' => $field->name));
7721 if ($field->is_enabled()) {
7722 $strfieldname = $field->displayname;
7723 $class = '';
7724 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7725 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7726 } else {
7727 $strfieldname = $field->displayname;
7728 $class = 'dimmed_text';
7729 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7730 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7732 $settings = '';
7733 if ($field->get_settings_url()) {
7734 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7736 $uninstall = '';
7737 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7738 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7740 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7741 $row->attributes['class'] = $class;
7742 $table->data[] = $row;
7744 $return .= html_writer::table($table);
7745 $return .= $OUTPUT->box_end();
7746 return highlight($query, $return);
7751 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7753 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7756 class admin_setting_managedataformats extends admin_setting {
7759 * Calls parent::__construct with specific arguments
7761 public function __construct() {
7762 $this->nosave = true;
7763 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7767 * Always returns true
7769 * @return true
7771 public function get_setting() {
7772 return true;
7776 * Always returns true
7778 * @return true
7780 public function get_defaultsetting() {
7781 return true;
7785 * Always returns '' and doesn't write anything
7787 * @param mixed $data string or array, must not be NULL
7788 * @return string Always returns ''
7790 public function write_setting($data) {
7791 // Do not write any setting.
7792 return '';
7796 * Search to find if Query is related to format plugin
7798 * @param string $query The string to search for
7799 * @return bool true for related false for not
7801 public function is_related($query) {
7802 if (parent::is_related($query)) {
7803 return true;
7805 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7806 foreach ($formats as $format) {
7807 if (strpos($format->component, $query) !== false ||
7808 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7809 return true;
7812 return false;
7816 * Return XHTML to display control
7818 * @param mixed $data Unused
7819 * @param string $query
7820 * @return string highlight
7822 public function output_html($data, $query='') {
7823 global $CFG, $OUTPUT;
7824 $return = '';
7826 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7828 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7829 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7830 $txt->updown = "$txt->up/$txt->down";
7832 $table = new html_table();
7833 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7834 $table->align = array('left', 'center', 'center', 'center', 'center');
7835 $table->attributes['class'] = 'manageformattable generaltable admintable';
7836 $table->data = array();
7838 $cnt = 0;
7839 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7840 $totalenabled = 0;
7841 foreach ($formats as $format) {
7842 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7843 $totalenabled++;
7846 foreach ($formats as $format) {
7847 $status = $format->get_status();
7848 $url = new moodle_url('/admin/dataformats.php',
7849 array('sesskey' => sesskey(), 'name' => $format->name));
7851 $class = '';
7852 if ($format->is_enabled()) {
7853 $strformatname = $format->displayname;
7854 if ($totalenabled == 1&& $format->is_enabled()) {
7855 $hideshow = '';
7856 } else {
7857 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7858 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7860 } else {
7861 $class = 'dimmed_text';
7862 $strformatname = $format->displayname;
7863 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7864 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7867 $updown = '';
7868 if ($cnt) {
7869 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7870 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7871 } else {
7872 $updown .= $spacer;
7874 if ($cnt < count($formats) - 1) {
7875 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7876 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7877 } else {
7878 $updown .= $spacer;
7881 $uninstall = '';
7882 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7883 $uninstall = get_string('status_missing', 'core_plugin');
7884 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7885 $uninstall = get_string('status_new', 'core_plugin');
7886 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7887 if ($totalenabled != 1 || !$format->is_enabled()) {
7888 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7892 $settings = '';
7893 if ($format->get_settings_url()) {
7894 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7897 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7898 if ($class) {
7899 $row->attributes['class'] = $class;
7901 $table->data[] = $row;
7902 $cnt++;
7904 $return .= html_writer::table($table);
7905 return highlight($query, $return);
7910 * Special class for filter administration.
7912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7914 class admin_page_managefilters extends admin_externalpage {
7916 * Calls parent::__construct with specific arguments
7918 public function __construct() {
7919 global $CFG;
7920 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7924 * Searches all installed filters for specified filter
7926 * @param string $query The filter(string) to search for
7927 * @param string $query
7929 public function search($query) {
7930 global $CFG;
7931 if ($result = parent::search($query)) {
7932 return $result;
7935 $found = false;
7936 $filternames = filter_get_all_installed();
7937 foreach ($filternames as $path => $strfiltername) {
7938 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7939 $found = true;
7940 break;
7942 if (strpos($path, $query) !== false) {
7943 $found = true;
7944 break;
7948 if ($found) {
7949 $result = new stdClass;
7950 $result->page = $this;
7951 $result->settings = array();
7952 return array($this->name => $result);
7953 } else {
7954 return array();
7960 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7961 * Requires a get_rank method on the plugininfo class for sorting.
7963 * @copyright 2017 Damyon Wiese
7964 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7966 abstract class admin_setting_manage_plugins extends admin_setting {
7969 * Get the admin settings section name (just a unique string)
7971 * @return string
7973 public function get_section_name() {
7974 return 'manage' . $this->get_plugin_type() . 'plugins';
7978 * Get the admin settings section title (use get_string).
7980 * @return string
7982 abstract public function get_section_title();
7985 * Get the type of plugin to manage.
7987 * @return string
7989 abstract public function get_plugin_type();
7992 * Get the name of the second column.
7994 * @return string
7996 public function get_info_column_name() {
7997 return '';
8001 * Get the type of plugin to manage.
8003 * @param plugininfo The plugin info class.
8004 * @return string
8006 abstract public function get_info_column($plugininfo);
8009 * Calls parent::__construct with specific arguments
8011 public function __construct() {
8012 $this->nosave = true;
8013 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8017 * Always returns true, does nothing
8019 * @return true
8021 public function get_setting() {
8022 return true;
8026 * Always returns true, does nothing
8028 * @return true
8030 public function get_defaultsetting() {
8031 return true;
8035 * Always returns '', does not write anything
8037 * @param mixed $data
8038 * @return string Always returns ''
8040 public function write_setting($data) {
8041 // Do not write any setting.
8042 return '';
8046 * Checks if $query is one of the available plugins of this type
8048 * @param string $query The string to search for
8049 * @return bool Returns true if found, false if not
8051 public function is_related($query) {
8052 if (parent::is_related($query)) {
8053 return true;
8056 $query = core_text::strtolower($query);
8057 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
8058 foreach ($plugins as $name => $plugin) {
8059 $localised = $plugin->displayname;
8060 if (strpos(core_text::strtolower($name), $query) !== false) {
8061 return true;
8063 if (strpos(core_text::strtolower($localised), $query) !== false) {
8064 return true;
8067 return false;
8071 * The URL for the management page for this plugintype.
8073 * @return moodle_url
8075 protected function get_manage_url() {
8076 return new moodle_url('/admin/updatesetting.php');
8080 * Builds the HTML to display the control.
8082 * @param string $data Unused
8083 * @param string $query
8084 * @return string
8086 public function output_html($data, $query = '') {
8087 global $CFG, $OUTPUT, $DB, $PAGE;
8089 $context = (object) [
8090 'manageurl' => new moodle_url($this->get_manage_url(), [
8091 'type' => $this->get_plugin_type(),
8092 'sesskey' => sesskey(),
8094 'infocolumnname' => $this->get_info_column_name(),
8095 'plugins' => [],
8098 $pluginmanager = core_plugin_manager::instance();
8099 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8100 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8101 $plugins = array_merge($enabled, $allplugins);
8102 foreach ($plugins as $key => $plugin) {
8103 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
8105 $pluginkey = (object) [
8106 'plugin' => $plugin->displayname,
8107 'enabled' => $plugin->is_enabled(),
8108 'togglelink' => '',
8109 'moveuplink' => '',
8110 'movedownlink' => '',
8111 'settingslink' => $plugin->get_settings_url(),
8112 'uninstalllink' => '',
8113 'info' => '',
8116 // Enable/Disable link.
8117 $togglelink = new moodle_url($pluginlink);
8118 if ($plugin->is_enabled()) {
8119 $toggletarget = false;
8120 $togglelink->param('action', 'disable');
8122 if (count($context->plugins)) {
8123 // This is not the first plugin.
8124 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
8127 if (count($enabled) > count($context->plugins) + 1) {
8128 // This is not the last plugin.
8129 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
8132 $pluginkey->info = $this->get_info_column($plugin);
8133 } else {
8134 $toggletarget = true;
8135 $togglelink->param('action', 'enable');
8138 $pluginkey->toggletarget = $toggletarget;
8139 $pluginkey->togglelink = $togglelink;
8141 $frankenstyle = $plugin->type . '_' . $plugin->name;
8142 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8143 // This plugin supports uninstallation.
8144 $pluginkey->uninstalllink = $uninstalllink;
8147 if (!empty($this->get_info_column_name())) {
8148 // This plugintype has an info column.
8149 $pluginkey->info = $this->get_info_column($plugin);
8152 $context->plugins[] = $pluginkey;
8155 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8156 return highlight($query, $str);
8161 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8162 * Requires a get_rank method on the plugininfo class for sorting.
8164 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8165 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8167 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8168 public function get_section_title() {
8169 return get_string('type_fileconverter_plural', 'plugin');
8172 public function get_plugin_type() {
8173 return 'fileconverter';
8176 public function get_info_column_name() {
8177 return get_string('supportedconversions', 'plugin');
8180 public function get_info_column($plugininfo) {
8181 return $plugininfo->get_supported_conversions();
8186 * Special class for media player plugins management.
8188 * @copyright 2016 Marina Glancy
8189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8191 class admin_setting_managemediaplayers extends admin_setting {
8193 * Calls parent::__construct with specific arguments
8195 public function __construct() {
8196 $this->nosave = true;
8197 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8201 * Always returns true, does nothing
8203 * @return true
8205 public function get_setting() {
8206 return true;
8210 * Always returns true, does nothing
8212 * @return true
8214 public function get_defaultsetting() {
8215 return true;
8219 * Always returns '', does not write anything
8221 * @param mixed $data
8222 * @return string Always returns ''
8224 public function write_setting($data) {
8225 // Do not write any setting.
8226 return '';
8230 * Checks if $query is one of the available enrol plugins
8232 * @param string $query The string to search for
8233 * @return bool Returns true if found, false if not
8235 public function is_related($query) {
8236 if (parent::is_related($query)) {
8237 return true;
8240 $query = core_text::strtolower($query);
8241 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8242 foreach ($plugins as $name => $plugin) {
8243 $localised = $plugin->displayname;
8244 if (strpos(core_text::strtolower($name), $query) !== false) {
8245 return true;
8247 if (strpos(core_text::strtolower($localised), $query) !== false) {
8248 return true;
8251 return false;
8255 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8256 * @return \core\plugininfo\media[]
8258 protected function get_sorted_plugins() {
8259 $pluginmanager = core_plugin_manager::instance();
8261 $plugins = $pluginmanager->get_plugins_of_type('media');
8262 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8264 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8265 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8267 $order = array_values($enabledplugins);
8268 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8270 $sortedplugins = array();
8271 foreach ($order as $name) {
8272 $sortedplugins[$name] = $plugins[$name];
8275 return $sortedplugins;
8279 * Builds the XHTML to display the control
8281 * @param string $data Unused
8282 * @param string $query
8283 * @return string
8285 public function output_html($data, $query='') {
8286 global $CFG, $OUTPUT, $DB, $PAGE;
8288 // Display strings.
8289 $strup = get_string('up');
8290 $strdown = get_string('down');
8291 $strsettings = get_string('settings');
8292 $strenable = get_string('enable');
8293 $strdisable = get_string('disable');
8294 $struninstall = get_string('uninstallplugin', 'core_admin');
8295 $strversion = get_string('version');
8296 $strname = get_string('name');
8297 $strsupports = get_string('supports', 'core_media');
8299 $pluginmanager = core_plugin_manager::instance();
8301 $plugins = $this->get_sorted_plugins();
8302 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8304 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8306 $table = new html_table();
8307 $table->head = array($strname, $strsupports, $strversion,
8308 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8309 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8310 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8311 $table->id = 'mediaplayerplugins';
8312 $table->attributes['class'] = 'admintable generaltable';
8313 $table->data = array();
8315 // Iterate through media plugins and add to the display table.
8316 $updowncount = 1;
8317 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8318 $printed = array();
8319 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8321 $usedextensions = [];
8322 foreach ($plugins as $name => $plugin) {
8323 $url->param('media', $name);
8324 /** @var \core\plugininfo\media $plugininfo */
8325 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8326 $version = $plugininfo->versiondb;
8327 $supports = $plugininfo->supports($usedextensions);
8329 // Hide/show links.
8330 $class = '';
8331 if (!$plugininfo->is_installed_and_upgraded()) {
8332 $hideshow = '';
8333 $enabled = false;
8334 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8335 } else {
8336 $enabled = $plugininfo->is_enabled();
8337 if ($enabled) {
8338 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8339 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8340 } else {
8341 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8342 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8343 $class = 'dimmed_text';
8345 $displayname = $plugin->displayname;
8346 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8347 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8350 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8351 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8352 } else {
8353 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8356 // Up/down link (only if enrol is enabled).
8357 $updown = '';
8358 if ($enabled) {
8359 if ($updowncount > 1) {
8360 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8361 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8362 } else {
8363 $updown = $spacer;
8365 if ($updowncount < count($enabledplugins)) {
8366 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8367 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8368 } else {
8369 $updown .= $spacer;
8371 ++$updowncount;
8374 $uninstall = '';
8375 $status = $plugininfo->get_status();
8376 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8377 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8379 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8380 $uninstall = get_string('status_new', 'core_plugin');
8381 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8382 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8385 $settings = '';
8386 if ($plugininfo->get_settings_url()) {
8387 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8390 // Add a row to the table.
8391 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8392 if ($class) {
8393 $row->attributes['class'] = $class;
8395 $table->data[] = $row;
8397 $printed[$name] = true;
8400 $return .= html_writer::table($table);
8401 $return .= $OUTPUT->box_end();
8402 return highlight($query, $return);
8408 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8410 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8413 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8416 * Calls parent::__construct with specific arguments
8418 public function __construct() {
8419 $this->nosave = true;
8420 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8424 * Always returns true
8426 * @return true
8428 public function get_setting() {
8429 return true;
8433 * Always returns true
8435 * @return true
8437 public function get_defaultsetting() {
8438 return true;
8442 * Always returns '' and doesn't write anything
8444 * @param mixed $data string or array, must not be NULL
8445 * @return string Always returns ''
8447 public function write_setting($data) {
8448 // Do not write any setting.
8449 return '';
8453 * Search to find if Query is related to content bank plugin
8455 * @param string $query The string to search for
8456 * @return bool true for related false for not
8458 public function is_related($query) {
8459 if (parent::is_related($query)) {
8460 return true;
8462 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8463 foreach ($types as $type) {
8464 if (strpos($type->component, $query) !== false ||
8465 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8466 return true;
8469 return false;
8473 * Return XHTML to display control
8475 * @param mixed $data Unused
8476 * @param string $query
8477 * @return string highlight
8479 public function output_html($data, $query='') {
8480 global $CFG, $OUTPUT;
8481 $return = '';
8483 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8484 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8485 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8487 $table = new html_table();
8488 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8489 $table->align = array('left', 'center', 'center', 'center', 'center');
8490 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8491 $table->data = array();
8492 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8494 $totalenabled = 0;
8495 $count = 0;
8496 foreach ($types as $type) {
8497 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8498 $totalenabled++;
8502 foreach ($types as $type) {
8503 $url = new moodle_url('/admin/contentbank.php',
8504 array('sesskey' => sesskey(), 'name' => $type->name));
8506 $class = '';
8507 $strtypename = $type->displayname;
8508 if ($type->is_enabled()) {
8509 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8510 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8511 } else {
8512 $class = 'dimmed_text';
8513 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8514 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8517 $updown = '';
8518 if ($count) {
8519 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8520 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8521 } else {
8522 $updown .= $spacer;
8524 if ($count < count($types) - 1) {
8525 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8526 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8527 } else {
8528 $updown .= $spacer;
8531 $settings = '';
8532 if ($type->get_settings_url()) {
8533 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8536 $uninstall = '';
8537 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8538 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8541 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8542 if ($class) {
8543 $row->attributes['class'] = $class;
8545 $table->data[] = $row;
8546 $count++;
8548 $return .= html_writer::table($table);
8549 return highlight($query, $return);
8554 * Initialise admin page - this function does require login and permission
8555 * checks specified in page definition.
8557 * This function must be called on each admin page before other code.
8559 * @global moodle_page $PAGE
8561 * @param string $section name of page
8562 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8563 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8564 * added to the turn blocks editing on/off form, so this page reloads correctly.
8565 * @param string $actualurl if the actual page being viewed is not the normal one for this
8566 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8567 * @param array $options Additional options that can be specified for page setup.
8568 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8569 * nosearch - Do not display search bar
8571 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8572 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8574 $PAGE->set_context(null); // hack - set context to something, by default to system context
8576 $site = get_site();
8577 require_login(null, false);
8579 if (!empty($options['pagelayout'])) {
8580 // A specific page layout has been requested.
8581 $PAGE->set_pagelayout($options['pagelayout']);
8582 } else if ($section === 'upgradesettings') {
8583 $PAGE->set_pagelayout('maintenance');
8584 } else {
8585 $PAGE->set_pagelayout('admin');
8588 $adminroot = admin_get_root(false, false); // settings not required for external pages
8589 $extpage = $adminroot->locate($section, true);
8591 $hassiteconfig = has_capability('moodle/site:config', context_system::instance());
8592 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8593 // The requested section isn't in the admin tree
8594 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8595 if (!$hassiteconfig) {
8596 // The requested section could depend on a different capability
8597 // but most likely the user has inadequate capabilities
8598 throw new \moodle_exception('accessdenied', 'admin');
8599 } else {
8600 throw new \moodle_exception('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8604 // this eliminates our need to authenticate on the actual pages
8605 if (!$extpage->check_access()) {
8606 throw new \moodle_exception('accessdenied', 'admin');
8607 die;
8610 navigation_node::require_admin_tree();
8612 // $PAGE->set_extra_button($extrabutton); TODO
8614 if (!$actualurl) {
8615 $actualurl = $extpage->url;
8618 $PAGE->set_url($actualurl, $extraurlparams);
8619 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8620 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8623 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8624 // During initial install.
8625 $strinstallation = get_string('installation', 'install');
8626 $strsettings = get_string('settings');
8627 $PAGE->navbar->add($strsettings);
8628 $PAGE->set_title($strinstallation);
8629 $PAGE->set_heading($strinstallation);
8630 $PAGE->set_cacheable(false);
8631 return;
8634 // Locate the current item on the navigation and make it active when found.
8635 $path = $extpage->path;
8636 $node = $PAGE->settingsnav;
8637 while ($node && count($path) > 0) {
8638 $node = $node->get(array_pop($path));
8640 if ($node) {
8641 $node->make_active();
8644 // Normal case.
8645 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8646 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8647 $USER->editing = $adminediting;
8650 $visiblepathtosection = array_reverse($extpage->visiblepath);
8652 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8653 if ($PAGE->user_is_editing()) {
8654 $caption = get_string('blockseditoff');
8655 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8656 } else {
8657 $caption = get_string('blocksediton');
8658 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8660 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8663 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8664 $PAGE->set_heading($SITE->fullname);
8666 if ($hassiteconfig && empty($options['nosearch'])) {
8667 $PAGE->add_header_action($OUTPUT->render_from_template('core_admin/header_search_input', [
8668 'action' => new moodle_url('/admin/search.php'),
8669 'query' => $PAGE->url->get_param('query'),
8670 ]));
8673 // prevent caching in nav block
8674 $PAGE->navigation->clear_cache();
8678 * Returns the reference to admin tree root
8680 * @return object admin_root object
8682 function admin_get_root($reload=false, $requirefulltree=true) {
8683 global $CFG, $DB, $OUTPUT, $ADMIN;
8685 if (is_null($ADMIN)) {
8686 // create the admin tree!
8687 $ADMIN = new admin_root($requirefulltree);
8690 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8691 $ADMIN->purge_children($requirefulltree);
8694 if (!$ADMIN->loaded) {
8695 // we process this file first to create categories first and in correct order
8696 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8698 // now we process all other files in admin/settings to build the admin tree
8699 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8700 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8701 continue;
8703 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8704 // plugins are loaded last - they may insert pages anywhere
8705 continue;
8707 require($file);
8709 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8711 $ADMIN->loaded = true;
8714 return $ADMIN;
8717 /// settings utility functions
8720 * This function applies default settings.
8721 * Because setting the defaults of some settings can enable other settings,
8722 * this function is called recursively until no more new settings are found.
8724 * @param object $node, NULL means complete tree, null by default
8725 * @param bool $unconditional if true overrides all values with defaults, true by default
8726 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8727 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8728 * @return array $settingsoutput The names and values of the changed settings
8730 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8731 $counter = 0;
8733 // This function relies heavily on config cache, so we need to enable in-memory caches if it
8734 // is used during install when normal caching is disabled.
8735 $token = new \core_cache\allow_temporary_caches();
8737 if (is_null($node)) {
8738 core_plugin_manager::reset_caches();
8739 $node = admin_get_root(true, true);
8740 $counter = count($settingsoutput);
8743 if ($node instanceof admin_category) {
8744 $entries = array_keys($node->children);
8745 foreach ($entries as $entry) {
8746 $settingsoutput = admin_apply_default_settings(
8747 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8751 } else if ($node instanceof admin_settingpage) {
8752 foreach ($node->settings as $setting) {
8753 if (!$unconditional && !is_null($setting->get_setting())) {
8754 // Do not override existing defaults.
8755 continue;
8757 $defaultsetting = $setting->get_defaultsetting();
8758 if (is_null($defaultsetting)) {
8759 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8760 continue;
8763 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8765 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8766 $admindefaultsettings[$settingname] = $settingname;
8767 $settingsoutput[$settingname] = $defaultsetting;
8769 // Set the default for this setting.
8770 $setting->write_setting($defaultsetting);
8771 $setting->write_setting_flags(null);
8772 } else {
8773 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8778 // Call this function recursively until all settings are processed.
8779 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8780 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8782 // Just in case somebody modifies the list of active plugins directly.
8783 core_plugin_manager::reset_caches();
8785 return $settingsoutput;
8789 * Store changed settings, this function updates the errors variable in $ADMIN
8791 * @param object $formdata from form
8792 * @return int number of changed settings
8794 function admin_write_settings($formdata) {
8795 global $CFG, $SITE, $DB;
8797 $olddbsessions = !empty($CFG->dbsessions);
8798 $formdata = (array)$formdata;
8800 $data = array();
8801 foreach ($formdata as $fullname=>$value) {
8802 if (strpos($fullname, 's_') !== 0) {
8803 continue; // not a config value
8805 $data[$fullname] = $value;
8808 $adminroot = admin_get_root();
8809 $settings = admin_find_write_settings($adminroot, $data);
8811 $count = 0;
8812 foreach ($settings as $fullname=>$setting) {
8813 /** @var $setting admin_setting */
8814 $original = $setting->get_setting();
8815 $error = $setting->write_setting($data[$fullname]);
8816 if ($error !== '') {
8817 $adminroot->errors[$fullname] = new stdClass();
8818 $adminroot->errors[$fullname]->data = $data[$fullname];
8819 $adminroot->errors[$fullname]->id = $setting->get_id();
8820 $adminroot->errors[$fullname]->error = $error;
8821 } else {
8822 $setting->write_setting_flags($data);
8824 if ($setting->post_write_settings($original)) {
8825 $count++;
8829 if ($olddbsessions != !empty($CFG->dbsessions)) {
8830 require_logout();
8833 // Now update $SITE - just update the fields, in case other people have a
8834 // a reference to it (e.g. $PAGE, $COURSE).
8835 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8836 foreach (get_object_vars($newsite) as $field => $value) {
8837 $SITE->$field = $value;
8840 // now reload all settings - some of them might depend on the changed
8841 admin_get_root(true);
8842 return $count;
8846 * Internal recursive function - finds all settings from submitted form
8848 * @param object $node Instance of admin_category, or admin_settingpage
8849 * @param array $data
8850 * @return array
8852 function admin_find_write_settings($node, $data) {
8853 $return = array();
8855 if (empty($data)) {
8856 return $return;
8859 if ($node instanceof admin_category) {
8860 if ($node->check_access()) {
8861 $entries = array_keys($node->children);
8862 foreach ($entries as $entry) {
8863 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8867 } else if ($node instanceof admin_settingpage) {
8868 if ($node->check_access()) {
8869 foreach ($node->settings as $setting) {
8870 $fullname = $setting->get_full_name();
8871 if (array_key_exists($fullname, $data)) {
8872 $return[$fullname] = $setting;
8879 return $return;
8883 * Internal function - prints the search results
8885 * @param string $query String to search for
8886 * @return string empty or XHTML
8888 function admin_search_settings_html($query) {
8889 global $CFG, $OUTPUT, $PAGE;
8891 if (core_text::strlen($query) < 2) {
8892 return '';
8894 $query = core_text::strtolower($query);
8896 $adminroot = admin_get_root();
8897 $findings = $adminroot->search($query);
8898 $savebutton = false;
8900 $tpldata = (object) [
8901 'actionurl' => $PAGE->url->out(false),
8902 'results' => [],
8903 'sesskey' => sesskey(),
8906 foreach ($findings as $found) {
8907 $page = $found->page;
8908 $settings = $found->settings;
8909 if ($page->is_hidden()) {
8910 // hidden pages are not displayed in search results
8911 continue;
8914 $heading = highlight($query, $page->visiblename);
8915 $headingurl = null;
8916 if ($page instanceof admin_externalpage) {
8917 $headingurl = new moodle_url($page->url);
8918 } else if ($page instanceof admin_settingpage) {
8919 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8920 } else {
8921 continue;
8924 // Locate the page in the admin root and populate its visiblepath attribute.
8925 $path = array();
8926 $located = $adminroot->locate($page->name, true);
8927 if ($located) {
8928 foreach ($located->visiblepath as $pathitem) {
8929 array_unshift($path, (string) $pathitem);
8933 $sectionsettings = [];
8934 if (!empty($settings)) {
8935 foreach ($settings as $setting) {
8936 if (empty($setting->nosave)) {
8937 $savebutton = true;
8939 $fullname = $setting->get_full_name();
8940 if (array_key_exists($fullname, $adminroot->errors)) {
8941 $data = $adminroot->errors[$fullname]->data;
8942 } else {
8943 $data = $setting->get_setting();
8944 // do not use defaults if settings not available - upgradesettings handles the defaults!
8946 $sectionsettings[] = $setting->output_html($data, $query);
8950 $tpldata->results[] = (object) [
8951 'title' => $heading,
8952 'path' => $path,
8953 'url' => $headingurl->out(false),
8954 'settings' => $sectionsettings
8958 $tpldata->showsave = $savebutton;
8959 $tpldata->hasresults = !empty($tpldata->results);
8961 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8965 * Internal function - returns arrays of html pages with uninitialised settings
8967 * @param object $node Instance of admin_category or admin_settingpage
8968 * @return array
8970 function admin_output_new_settings_by_page($node) {
8971 global $OUTPUT;
8972 $return = array();
8974 if ($node instanceof admin_category) {
8975 $entries = array_keys($node->children);
8976 foreach ($entries as $entry) {
8977 $return += admin_output_new_settings_by_page($node->children[$entry]);
8980 } else if ($node instanceof admin_settingpage) {
8981 $newsettings = array();
8982 foreach ($node->settings as $setting) {
8983 if (is_null($setting->get_setting())) {
8984 $newsettings[] = $setting;
8987 if (count($newsettings) > 0) {
8988 $adminroot = admin_get_root();
8989 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8990 $page .= '<fieldset class="adminsettings">'."\n";
8991 foreach ($newsettings as $setting) {
8992 $fullname = $setting->get_full_name();
8993 if (array_key_exists($fullname, $adminroot->errors)) {
8994 $data = $adminroot->errors[$fullname]->data;
8995 } else {
8996 $data = $setting->get_setting();
8997 if (is_null($data)) {
8998 $data = $setting->get_defaultsetting();
9001 $page .= '<div class="clearer"><!-- --></div>'."\n";
9002 $page .= $setting->output_html($data);
9004 $page .= '</fieldset>';
9005 $return[$node->name] = $page;
9009 return $return;
9013 * Format admin settings
9015 * @param object $setting
9016 * @param string $title label element
9017 * @param string $form form fragment, html code - not highlighted automatically
9018 * @param string $description
9019 * @param mixed $label link label to id, true by default or string being the label to connect it to
9020 * @param string $warning warning text
9021 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9022 * @param string $query search query to be highlighted
9023 * @return string XHTML
9025 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9026 global $CFG, $OUTPUT;
9028 $context = (object) [
9029 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9030 'fullname' => $setting->get_full_name(),
9033 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9034 if ($label === true) {
9035 $context->labelfor = $setting->get_id();
9036 } else if ($label === false) {
9037 $context->labelfor = '';
9038 } else {
9039 $context->labelfor = $label;
9042 $form .= $setting->output_setting_flags();
9044 $context->warning = $warning;
9045 $context->override = '';
9046 if (empty($setting->plugin)) {
9047 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
9048 $context->override = get_string('configoverride', 'admin');
9050 } else {
9051 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9052 $context->override = get_string('configoverride', 'admin');
9056 $defaults = array();
9057 if (!is_null($defaultinfo)) {
9058 if ($defaultinfo === '') {
9059 $defaultinfo = get_string('emptysettingvalue', 'admin');
9061 $defaults[] = $defaultinfo;
9064 $context->default = null;
9065 $setting->get_setting_flag_defaults($defaults);
9066 if (!empty($defaults)) {
9067 $defaultinfo = implode(', ', $defaults);
9068 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9069 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9073 $context->error = '';
9074 $adminroot = admin_get_root();
9075 if (array_key_exists($context->fullname, $adminroot->errors)) {
9076 $context->error = $adminroot->errors[$context->fullname]->error;
9079 if ($dependenton = $setting->get_dependent_on()) {
9080 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9083 $context->id = 'admin-' . $setting->name;
9084 $context->title = highlightfast($query, $title);
9085 $context->name = highlightfast($query, $context->name);
9086 $context->description = highlight($query, markdown_to_html($description));
9087 $context->element = $form;
9088 $context->forceltr = $setting->get_force_ltr();
9089 $context->customcontrol = $setting->has_custom_form_control();
9091 return $OUTPUT->render_from_template('core_admin/setting', $context);
9095 * Based on find_new_settings{@link ()} in upgradesettings.php
9096 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9098 * @param object $node Instance of admin_category, or admin_settingpage
9099 * @return boolean true if any settings haven't been initialised, false if they all have
9101 function any_new_admin_settings($node) {
9103 if ($node instanceof admin_category) {
9104 $entries = array_keys($node->children);
9105 foreach ($entries as $entry) {
9106 if (any_new_admin_settings($node->children[$entry])) {
9107 return true;
9111 } else if ($node instanceof admin_settingpage) {
9112 foreach ($node->settings as $setting) {
9113 if ($setting->get_setting() === NULL) {
9114 return true;
9119 return false;
9123 * Given a table and optionally a column name should replaces be done?
9125 * @param string $table name
9126 * @param string $column name
9127 * @return bool success or fail
9129 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9131 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9132 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9133 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9135 // Additional skip tables.
9136 if (!empty($additionalskiptables)) {
9137 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9140 // Don't process these.
9141 if (in_array($table, $skiptables)) {
9142 return false;
9145 // To be safe never replace inside a table that looks related to logging.
9146 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9147 return false;
9150 // Do column based exclusions.
9151 if (!empty($column)) {
9152 // Don't touch anything that looks like a hash.
9153 if (preg_match('/hash$/', $column)) {
9154 return false;
9158 return true;
9162 * Moved from admin/replace.php so that we can use this in cron
9164 * @param string $search string to look for
9165 * @param string $replace string to replace
9166 * @return bool success or fail
9168 function db_replace($search, $replace, $additionalskiptables = '') {
9169 global $DB, $CFG, $OUTPUT;
9171 // Turn off time limits, sometimes upgrades can be slow.
9172 core_php_time_limit::raise();
9174 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9175 return false;
9177 foreach ($tables as $table) {
9179 if (!db_should_replace($table, '', $additionalskiptables)) {
9180 continue;
9183 if ($columns = $DB->get_columns($table)) {
9184 $DB->set_debug(true);
9185 foreach ($columns as $column) {
9186 if (!db_should_replace($table, $column->name)) {
9187 continue;
9189 $DB->replace_all_text($table, $column, $search, $replace);
9191 $DB->set_debug(false);
9195 // delete modinfo caches
9196 rebuild_course_cache(0, true);
9198 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9199 $blocks = core_component::get_plugin_list('block');
9200 foreach ($blocks as $blockname=>$fullblock) {
9201 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9202 continue;
9205 if (!is_readable($fullblock.'/lib.php')) {
9206 continue;
9209 $function = 'block_'.$blockname.'_global_db_replace';
9210 include_once($fullblock.'/lib.php');
9211 if (!function_exists($function)) {
9212 continue;
9215 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9216 $function($search, $replace);
9217 echo $OUTPUT->notification("...finished", 'notifysuccess');
9220 // Trigger an event.
9221 $eventargs = [
9222 'context' => context_system::instance(),
9223 'other' => [
9224 'search' => $search,
9225 'replace' => $replace
9228 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9229 $event->trigger();
9231 purge_all_caches();
9233 return true;
9237 * Manage repository settings
9239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9241 class admin_setting_managerepository extends admin_setting {
9242 /** @var string */
9243 private $baseurl;
9246 * calls parent::__construct with specific arguments
9248 public function __construct() {
9249 global $CFG;
9250 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9251 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9255 * Always returns true, does nothing
9257 * @return true
9259 public function get_setting() {
9260 return true;
9264 * Always returns true does nothing
9266 * @return true
9268 public function get_defaultsetting() {
9269 return true;
9273 * Always returns s_managerepository
9275 * @return string Always return 's_managerepository'
9277 public function get_full_name() {
9278 return 's_managerepository';
9282 * Always returns '' doesn't do anything
9284 public function write_setting($data) {
9285 $url = $this->baseurl . '&amp;new=' . $data;
9286 return '';
9287 // TODO
9288 // Should not use redirect and exit here
9289 // Find a better way to do this.
9290 // redirect($url);
9291 // exit;
9295 * Searches repository plugins for one that matches $query
9297 * @param string $query The string to search for
9298 * @return bool true if found, false if not
9300 public function is_related($query) {
9301 if (parent::is_related($query)) {
9302 return true;
9305 $repositories= core_component::get_plugin_list('repository');
9306 foreach ($repositories as $p => $dir) {
9307 if (strpos($p, $query) !== false) {
9308 return true;
9311 foreach (repository::get_types() as $instance) {
9312 $title = $instance->get_typename();
9313 if (strpos(core_text::strtolower($title), $query) !== false) {
9314 return true;
9317 return false;
9321 * Helper function that generates a moodle_url object
9322 * relevant to the repository
9325 function repository_action_url($repository) {
9326 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9330 * Builds XHTML to display the control
9332 * @param string $data Unused
9333 * @param string $query
9334 * @return string XHTML
9336 public function output_html($data, $query='') {
9337 global $CFG, $USER, $OUTPUT;
9339 // Get strings that are used
9340 $strshow = get_string('on', 'repository');
9341 $strhide = get_string('off', 'repository');
9342 $strdelete = get_string('disabled', 'repository');
9344 $actionchoicesforexisting = array(
9345 'show' => $strshow,
9346 'hide' => $strhide,
9347 'delete' => $strdelete
9350 $actionchoicesfornew = array(
9351 'newon' => $strshow,
9352 'newoff' => $strhide,
9353 'delete' => $strdelete
9356 $return = '';
9357 $return .= $OUTPUT->box_start('generalbox');
9359 // Set strings that are used multiple times
9360 $settingsstr = get_string('settings');
9361 $disablestr = get_string('disable');
9363 // Table to list plug-ins
9364 $table = new html_table();
9365 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9366 $table->align = array('left', 'center', 'center', 'center', 'center');
9367 $table->data = array();
9369 // Get list of used plug-ins
9370 $repositorytypes = repository::get_types();
9371 if (!empty($repositorytypes)) {
9372 // Array to store plugins being used
9373 $alreadyplugins = array();
9374 $totalrepositorytypes = count($repositorytypes);
9375 $updowncount = 1;
9376 foreach ($repositorytypes as $i) {
9377 $settings = '';
9378 $typename = $i->get_typename();
9379 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9380 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9381 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9383 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9384 // Calculate number of instances in order to display them for the Moodle administrator
9385 if (!empty($instanceoptionnames)) {
9386 $params = array();
9387 $params['context'] = array(context_system::instance());
9388 $params['onlyvisible'] = false;
9389 $params['type'] = $typename;
9390 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9391 // site instances
9392 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9393 $params['context'] = array();
9394 $instances = repository::static_function($typename, 'get_instances', $params);
9395 $courseinstances = array();
9396 $userinstances = array();
9398 foreach ($instances as $instance) {
9399 $repocontext = context::instance_by_id($instance->instance->contextid);
9400 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9401 $courseinstances[] = $instance;
9402 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9403 $userinstances[] = $instance;
9406 // course instances
9407 $instancenumber = count($courseinstances);
9408 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9410 // user private instances
9411 $instancenumber = count($userinstances);
9412 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9413 } else {
9414 $admininstancenumbertext = "";
9415 $courseinstancenumbertext = "";
9416 $userinstancenumbertext = "";
9419 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9421 $settings .= $OUTPUT->container_start('mdl-left');
9422 $settings .= '<br/>';
9423 $settings .= $admininstancenumbertext;
9424 $settings .= '<br/>';
9425 $settings .= $courseinstancenumbertext;
9426 $settings .= '<br/>';
9427 $settings .= $userinstancenumbertext;
9428 $settings .= $OUTPUT->container_end();
9430 // Get the current visibility
9431 if ($i->get_visible()) {
9432 $currentaction = 'show';
9433 } else {
9434 $currentaction = 'hide';
9437 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9439 // Display up/down link
9440 $updown = '';
9441 // Should be done with CSS instead.
9442 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9444 if ($updowncount > 1) {
9445 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9446 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9448 else {
9449 $updown .= $spacer;
9451 if ($updowncount < $totalrepositorytypes) {
9452 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9453 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9455 else {
9456 $updown .= $spacer;
9459 $updowncount++;
9461 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9463 if (!in_array($typename, $alreadyplugins)) {
9464 $alreadyplugins[] = $typename;
9469 // Get all the plugins that exist on disk
9470 $plugins = core_component::get_plugin_list('repository');
9471 if (!empty($plugins)) {
9472 foreach ($plugins as $plugin => $dir) {
9473 // Check that it has not already been listed
9474 if (!in_array($plugin, $alreadyplugins)) {
9475 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9476 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9481 $return .= html_writer::table($table);
9482 $return .= $OUTPUT->box_end();
9483 return highlight($query, $return);
9488 * Special checkbox for enable mobile web service
9489 * If enable then we store the service id of the mobile service into config table
9490 * If disable then we unstore the service id from the config table
9492 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9494 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9495 private $restuse;
9498 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9500 * @return boolean
9502 private function is_protocol_cap_allowed() {
9503 global $DB, $CFG;
9505 // If the $this->restuse variable is not set, it needs to be set.
9506 if (empty($this->restuse) and $this->restuse!==false) {
9507 $params = array();
9508 $params['permission'] = CAP_ALLOW;
9509 $params['roleid'] = $CFG->defaultuserroleid;
9510 $params['capability'] = 'webservice/rest:use';
9511 $this->restuse = $DB->record_exists('role_capabilities', $params);
9514 return $this->restuse;
9518 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9519 * @param type $status true to allow, false to not set
9521 private function set_protocol_cap($status) {
9522 global $CFG;
9523 if ($status and !$this->is_protocol_cap_allowed()) {
9524 //need to allow the cap
9525 $permission = CAP_ALLOW;
9526 $assign = true;
9527 } else if (!$status and $this->is_protocol_cap_allowed()){
9528 //need to disallow the cap
9529 $permission = CAP_INHERIT;
9530 $assign = true;
9532 if (!empty($assign)) {
9533 $systemcontext = context_system::instance();
9534 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9539 * Builds XHTML to display the control.
9540 * The main purpose of this overloading is to display a warning when https
9541 * is not supported by the server
9542 * @param string $data Unused
9543 * @param string $query
9544 * @return string XHTML
9546 public function output_html($data, $query='') {
9547 global $OUTPUT;
9548 $html = parent::output_html($data, $query);
9550 if ((string)$data === $this->yes) {
9551 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9552 foreach ($notifications as $notification) {
9553 $message = get_string($notification[0], $notification[1]);
9554 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9558 return $html;
9562 * Retrieves the current setting using the objects name
9564 * @return string
9566 public function get_setting() {
9567 global $CFG;
9569 // First check if is not set.
9570 $result = $this->config_read($this->name);
9571 if (is_null($result)) {
9572 return null;
9575 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9576 // Or if web services aren't enabled this can't be,
9577 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9578 return 0;
9581 require_once($CFG->dirroot . '/webservice/lib.php');
9582 $webservicemanager = new webservice();
9583 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9584 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9585 return $result;
9586 } else {
9587 return 0;
9592 * Save the selected setting
9594 * @param string $data The selected site
9595 * @return string empty string or error message
9597 public function write_setting($data) {
9598 global $DB, $CFG;
9600 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9601 if (empty($CFG->defaultuserroleid)) {
9602 return '';
9605 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9607 require_once($CFG->dirroot . '/webservice/lib.php');
9608 $webservicemanager = new webservice();
9610 $updateprotocol = false;
9611 if ((string)$data === $this->yes) {
9612 //code run when enable mobile web service
9613 //enable web service systeme if necessary
9614 set_config('enablewebservices', true);
9616 //enable mobile service
9617 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9618 $mobileservice->enabled = 1;
9619 $webservicemanager->update_external_service($mobileservice);
9621 // Enable REST server.
9622 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9624 if (!in_array('rest', $activeprotocols)) {
9625 $activeprotocols[] = 'rest';
9626 $updateprotocol = true;
9629 if ($updateprotocol) {
9630 set_config('webserviceprotocols', implode(',', $activeprotocols));
9633 // Allow rest:use capability for authenticated user.
9634 $this->set_protocol_cap(true);
9635 } else {
9636 // Disable the mobile service.
9637 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9638 $mobileservice->enabled = 0;
9639 $webservicemanager->update_external_service($mobileservice);
9642 return (parent::write_setting($data));
9647 * Special class for management of external services
9649 * @author Petr Skoda (skodak)
9651 class admin_setting_manageexternalservices extends admin_setting {
9653 * Calls parent::__construct with specific arguments
9655 public function __construct() {
9656 $this->nosave = true;
9657 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9661 * Always returns true, does nothing
9663 * @return true
9665 public function get_setting() {
9666 return true;
9670 * Always returns true, does nothing
9672 * @return true
9674 public function get_defaultsetting() {
9675 return true;
9679 * Always returns '', does not write anything
9681 * @return string Always returns ''
9683 public function write_setting($data) {
9684 // do not write any setting
9685 return '';
9689 * Checks if $query is one of the available external services
9691 * @param string $query The string to search for
9692 * @return bool Returns true if found, false if not
9694 public function is_related($query) {
9695 global $DB;
9697 if (parent::is_related($query)) {
9698 return true;
9701 $services = $DB->get_records('external_services', array(), 'id, name');
9702 foreach ($services as $service) {
9703 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9704 return true;
9707 return false;
9711 * Builds the XHTML to display the control
9713 * @param string $data Unused
9714 * @param string $query
9715 * @return string
9717 public function output_html($data, $query='') {
9718 global $CFG, $OUTPUT, $DB;
9720 // display strings
9721 $stradministration = get_string('administration');
9722 $stredit = get_string('edit');
9723 $strservice = get_string('externalservice', 'webservice');
9724 $strdelete = get_string('delete');
9725 $strplugin = get_string('plugin', 'admin');
9726 $stradd = get_string('add');
9727 $strfunctions = get_string('functions', 'webservice');
9728 $strusers = get_string('users');
9729 $strserviceusers = get_string('serviceusers', 'webservice');
9731 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9732 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9733 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9735 // built in services
9736 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9737 $return = "";
9738 if (!empty($services)) {
9739 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9743 $table = new html_table();
9744 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9745 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9746 $table->id = 'builtinservices';
9747 $table->attributes['class'] = 'admintable externalservices generaltable';
9748 $table->data = array();
9750 // iterate through auth plugins and add to the display table
9751 foreach ($services as $service) {
9752 $name = $service->name;
9754 // hide/show link
9755 if ($service->enabled) {
9756 $displayname = "<span>$name</span>";
9757 } else {
9758 $displayname = "<span class=\"dimmed_text\">$name</span>";
9761 $plugin = $service->component;
9763 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9765 if ($service->restrictedusers) {
9766 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9767 } else {
9768 $users = get_string('allusers', 'webservice');
9771 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9773 // add a row to the table
9774 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9776 $return .= html_writer::table($table);
9779 // Custom services
9780 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9781 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9783 $table = new html_table();
9784 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9785 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9786 $table->id = 'customservices';
9787 $table->attributes['class'] = 'admintable externalservices generaltable';
9788 $table->data = array();
9790 // iterate through auth plugins and add to the display table
9791 foreach ($services as $service) {
9792 $name = $service->name;
9794 // hide/show link
9795 if ($service->enabled) {
9796 $displayname = "<span>$name</span>";
9797 } else {
9798 $displayname = "<span class=\"dimmed_text\">$name</span>";
9801 // delete link
9802 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9804 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9806 if ($service->restrictedusers) {
9807 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9808 } else {
9809 $users = get_string('allusers', 'webservice');
9812 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9814 // add a row to the table
9815 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9817 // add new custom service option
9818 $return .= html_writer::table($table);
9820 $return .= '<br />';
9821 // add a token to the table
9822 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9824 return highlight($query, $return);
9829 * Special class for overview of external services
9831 * @author Jerome Mouneyrac
9833 class admin_setting_webservicesoverview extends admin_setting {
9836 * Calls parent::__construct with specific arguments
9838 public function __construct() {
9839 $this->nosave = true;
9840 parent::__construct('webservicesoverviewui',
9841 get_string('webservicesoverview', 'webservice'), '', '');
9845 * Always returns true, does nothing
9847 * @return true
9849 public function get_setting() {
9850 return true;
9854 * Always returns true, does nothing
9856 * @return true
9858 public function get_defaultsetting() {
9859 return true;
9863 * Always returns '', does not write anything
9865 * @return string Always returns ''
9867 public function write_setting($data) {
9868 // do not write any setting
9869 return '';
9873 * Builds the XHTML to display the control
9875 * @param string $data Unused
9876 * @param string $query
9877 * @return string
9879 public function output_html($data, $query='') {
9880 global $CFG, $OUTPUT;
9882 $return = "";
9883 $brtag = html_writer::empty_tag('br');
9885 /// One system controlling Moodle with Token
9886 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9887 $table = new html_table();
9888 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9889 get_string('description'));
9890 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9891 $table->id = 'onesystemcontrol';
9892 $table->attributes['class'] = 'admintable wsoverview generaltable';
9893 $table->data = array();
9895 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9896 . $brtag . $brtag;
9898 /// 1. Enable Web Services
9899 $row = array();
9900 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9901 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9902 array('href' => $url));
9903 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
9904 if ($CFG->enablewebservices) {
9905 $status = get_string('yes');
9907 $row[1] = $status;
9908 $row[2] = get_string('enablewsdescription', 'webservice');
9909 $table->data[] = $row;
9911 /// 2. Enable protocols
9912 $row = array();
9913 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9914 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9915 array('href' => $url));
9916 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
9917 //retrieve activated protocol
9918 $active_protocols = empty($CFG->webserviceprotocols) ?
9919 array() : explode(',', $CFG->webserviceprotocols);
9920 if (!empty($active_protocols)) {
9921 $status = "";
9922 foreach ($active_protocols as $protocol) {
9923 $status .= $protocol . $brtag;
9926 $row[1] = $status;
9927 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9928 $table->data[] = $row;
9930 /// 3. Create user account
9931 $row = array();
9932 $url = new moodle_url("/user/editadvanced.php?id=-1");
9933 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9934 array('href' => $url));
9935 $row[1] = "";
9936 $row[2] = get_string('createuserdescription', 'webservice');
9937 $table->data[] = $row;
9939 /// 4. Add capability to users
9940 $row = array();
9941 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9942 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9943 array('href' => $url));
9944 $row[1] = "";
9945 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9946 $table->data[] = $row;
9948 /// 5. Select a web service
9949 $row = array();
9950 $url = new moodle_url("/admin/settings.php?section=externalservices");
9951 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9952 array('href' => $url));
9953 $row[1] = "";
9954 $row[2] = get_string('createservicedescription', 'webservice');
9955 $table->data[] = $row;
9957 /// 6. Add functions
9958 $row = array();
9959 $url = new moodle_url("/admin/settings.php?section=externalservices");
9960 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9961 array('href' => $url));
9962 $row[1] = "";
9963 $row[2] = get_string('addfunctionsdescription', 'webservice');
9964 $table->data[] = $row;
9966 /// 7. Add the specific user
9967 $row = array();
9968 $url = new moodle_url("/admin/settings.php?section=externalservices");
9969 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9970 array('href' => $url));
9971 $row[1] = "";
9972 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9973 $table->data[] = $row;
9975 /// 8. Create token for the specific user
9976 $row = array();
9977 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
9978 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9979 array('href' => $url));
9980 $row[1] = "";
9981 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9982 $table->data[] = $row;
9984 /// 9. Enable the documentation
9985 $row = array();
9986 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9987 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9988 array('href' => $url));
9989 $status = '<span class="warning">' . get_string('no') . '</span>';
9990 if ($CFG->enablewsdocumentation) {
9991 $status = get_string('yes');
9993 $row[1] = $status;
9994 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9995 $table->data[] = $row;
9997 /// 10. Test the service
9998 $row = array();
9999 $url = new moodle_url("/admin/webservice/testclient.php");
10000 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10001 array('href' => $url));
10002 $row[1] = "";
10003 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10004 $table->data[] = $row;
10006 $return .= html_writer::table($table);
10008 /// Users as clients with token
10009 $return .= $brtag . $brtag . $brtag;
10010 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10011 $table = new html_table();
10012 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10013 get_string('description'));
10014 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10015 $table->id = 'userasclients';
10016 $table->attributes['class'] = 'admintable wsoverview generaltable';
10017 $table->data = array();
10019 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10020 $brtag . $brtag;
10022 /// 1. Enable Web Services
10023 $row = array();
10024 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10025 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10026 array('href' => $url));
10027 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10028 if ($CFG->enablewebservices) {
10029 $status = get_string('yes');
10031 $row[1] = $status;
10032 $row[2] = get_string('enablewsdescription', 'webservice');
10033 $table->data[] = $row;
10035 /// 2. Enable protocols
10036 $row = array();
10037 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10038 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10039 array('href' => $url));
10040 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10041 //retrieve activated protocol
10042 $active_protocols = empty($CFG->webserviceprotocols) ?
10043 array() : explode(',', $CFG->webserviceprotocols);
10044 if (!empty($active_protocols)) {
10045 $status = "";
10046 foreach ($active_protocols as $protocol) {
10047 $status .= $protocol . $brtag;
10050 $row[1] = $status;
10051 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10052 $table->data[] = $row;
10055 /// 3. Select a web service
10056 $row = array();
10057 $url = new moodle_url("/admin/settings.php?section=externalservices");
10058 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10059 array('href' => $url));
10060 $row[1] = "";
10061 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10062 $table->data[] = $row;
10064 /// 4. Add functions
10065 $row = array();
10066 $url = new moodle_url("/admin/settings.php?section=externalservices");
10067 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10068 array('href' => $url));
10069 $row[1] = "";
10070 $row[2] = get_string('addfunctionsdescription', 'webservice');
10071 $table->data[] = $row;
10073 /// 5. Add capability to users
10074 $row = array();
10075 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10076 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10077 array('href' => $url));
10078 $row[1] = "";
10079 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10080 $table->data[] = $row;
10082 /// 6. Test the service
10083 $row = array();
10084 $url = new moodle_url("/admin/webservice/testclient.php");
10085 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10086 array('href' => $url));
10087 $row[1] = "";
10088 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10089 $table->data[] = $row;
10091 $return .= html_writer::table($table);
10093 return highlight($query, $return);
10100 * Special class for web service protocol administration.
10102 * @author Petr Skoda (skodak)
10104 class admin_setting_managewebserviceprotocols extends admin_setting {
10107 * Calls parent::__construct with specific arguments
10109 public function __construct() {
10110 $this->nosave = true;
10111 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10115 * Always returns true, does nothing
10117 * @return true
10119 public function get_setting() {
10120 return true;
10124 * Always returns true, does nothing
10126 * @return true
10128 public function get_defaultsetting() {
10129 return true;
10133 * Always returns '', does not write anything
10135 * @return string Always returns ''
10137 public function write_setting($data) {
10138 // do not write any setting
10139 return '';
10143 * Checks if $query is one of the available webservices
10145 * @param string $query The string to search for
10146 * @return bool Returns true if found, false if not
10148 public function is_related($query) {
10149 if (parent::is_related($query)) {
10150 return true;
10153 $protocols = core_component::get_plugin_list('webservice');
10154 foreach ($protocols as $protocol=>$location) {
10155 if (strpos($protocol, $query) !== false) {
10156 return true;
10158 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10159 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10160 return true;
10163 return false;
10167 * Builds the XHTML to display the control
10169 * @param string $data Unused
10170 * @param string $query
10171 * @return string
10173 public function output_html($data, $query='') {
10174 global $CFG, $OUTPUT;
10176 // display strings
10177 $stradministration = get_string('administration');
10178 $strsettings = get_string('settings');
10179 $stredit = get_string('edit');
10180 $strprotocol = get_string('protocol', 'webservice');
10181 $strenable = get_string('enable');
10182 $strdisable = get_string('disable');
10183 $strversion = get_string('version');
10185 $protocols_available = core_component::get_plugin_list('webservice');
10186 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10187 ksort($protocols_available);
10189 foreach ($activeprotocols as $key => $protocol) {
10190 if (empty($protocols_available[$protocol])) {
10191 unset($activeprotocols[$key]);
10195 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10196 if (in_array('xmlrpc', $activeprotocols)) {
10197 $notify = new \core\output\notification(get_string('xmlrpcwebserviceenabled', 'admin'),
10198 \core\output\notification::NOTIFY_WARNING);
10199 $return .= $OUTPUT->render($notify);
10201 $return .= $OUTPUT->box_start('generalbox webservicesui');
10203 $table = new html_table();
10204 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10205 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10206 $table->id = 'webserviceprotocols';
10207 $table->attributes['class'] = 'admintable generaltable';
10208 $table->data = array();
10210 // iterate through auth plugins and add to the display table
10211 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10212 foreach ($protocols_available as $protocol => $location) {
10213 $name = get_string('pluginname', 'webservice_'.$protocol);
10215 $plugin = new stdClass();
10216 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10217 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10219 $version = isset($plugin->version) ? $plugin->version : '';
10221 // hide/show link
10222 if (in_array($protocol, $activeprotocols)) {
10223 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10224 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10225 $displayname = "<span>$name</span>";
10226 } else {
10227 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10228 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10229 $displayname = "<span class=\"dimmed_text\">$name</span>";
10232 // settings link
10233 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10234 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10235 } else {
10236 $settings = '';
10239 // add a row to the table
10240 $table->data[] = array($displayname, $version, $hideshow, $settings);
10242 $return .= html_writer::table($table);
10243 $return .= get_string('configwebserviceplugins', 'webservice');
10244 $return .= $OUTPUT->box_end();
10246 return highlight($query, $return);
10251 * Colour picker
10253 * @copyright 2010 Sam Hemelryk
10254 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10256 class admin_setting_configcolourpicker extends admin_setting {
10259 * Information for previewing the colour
10261 * @var array|null
10263 protected $previewconfig = null;
10266 * Use default when empty.
10268 protected $usedefaultwhenempty = true;
10272 * @param string $name
10273 * @param string $visiblename
10274 * @param string $description
10275 * @param string $defaultsetting
10276 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10278 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10279 $usedefaultwhenempty = true) {
10280 $this->previewconfig = $previewconfig;
10281 $this->usedefaultwhenempty = $usedefaultwhenempty;
10282 parent::__construct($name, $visiblename, $description, $defaultsetting);
10283 $this->set_force_ltr(true);
10287 * Return the setting
10289 * @return mixed returns config if successful else null
10291 public function get_setting() {
10292 return $this->config_read($this->name);
10296 * Saves the setting
10298 * @param string $data
10299 * @return bool
10301 public function write_setting($data) {
10302 $data = $this->validate($data);
10303 if ($data === false) {
10304 return get_string('validateerror', 'admin');
10306 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10310 * Validates the colour that was entered by the user
10312 * @param string $data
10313 * @return string|false
10315 protected function validate($data) {
10317 * List of valid HTML colour names
10319 * @var array
10321 $colornames = array(
10322 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10323 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10324 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10325 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10326 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10327 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10328 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10329 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10330 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10331 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10332 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10333 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10334 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10335 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10336 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10337 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10338 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10339 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10340 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10341 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10342 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10343 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10344 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10345 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10346 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10347 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10348 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10349 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10350 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10351 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10352 'whitesmoke', 'yellow', 'yellowgreen'
10355 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10356 if (strpos($data, '#')!==0) {
10357 $data = '#'.$data;
10359 return $data;
10360 } else if (in_array(strtolower($data), $colornames)) {
10361 return $data;
10362 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10363 return $data;
10364 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10365 return $data;
10366 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10367 return $data;
10368 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10369 return $data;
10370 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10371 return $data;
10372 } else if (empty($data)) {
10373 if ($this->usedefaultwhenempty){
10374 return $this->defaultsetting;
10375 } else {
10376 return '';
10378 } else {
10379 return false;
10384 * Generates the HTML for the setting
10386 * @global moodle_page $PAGE
10387 * @global core_renderer $OUTPUT
10388 * @param string $data
10389 * @param string $query
10391 public function output_html($data, $query = '') {
10392 global $PAGE, $OUTPUT;
10394 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10395 $context = (object) [
10396 'id' => $this->get_id(),
10397 'name' => $this->get_full_name(),
10398 'value' => $data,
10399 'icon' => $icon->export_for_template($OUTPUT),
10400 'haspreviewconfig' => !empty($this->previewconfig),
10401 'forceltr' => $this->get_force_ltr(),
10402 'readonly' => $this->is_readonly(),
10405 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10406 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10408 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10409 $this->get_defaultsetting(), $query);
10416 * Class used for uploading of one file into file storage,
10417 * the file name is stored in config table.
10419 * Please note you need to implement your own '_pluginfile' callback function,
10420 * this setting only stores the file, it does not deal with file serving.
10422 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10425 class admin_setting_configstoredfile extends admin_setting {
10426 /** @var array file area options - should be one file only */
10427 protected $options;
10428 /** @var string name of the file area */
10429 protected $filearea;
10430 /** @var int intemid */
10431 protected $itemid;
10432 /** @var string used for detection of changes */
10433 protected $oldhashes;
10436 * Create new stored file setting.
10438 * @param string $name low level setting name
10439 * @param string $visiblename human readable setting name
10440 * @param string $description description of setting
10441 * @param mixed $filearea file area for file storage
10442 * @param int $itemid itemid for file storage
10443 * @param array $options file area options
10445 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10446 parent::__construct($name, $visiblename, $description, '');
10447 $this->filearea = $filearea;
10448 $this->itemid = $itemid;
10449 $this->options = (array)$options;
10450 $this->customcontrol = true;
10454 * Applies defaults and returns all options.
10455 * @return array
10457 protected function get_options() {
10458 global $CFG;
10460 require_once("$CFG->libdir/filelib.php");
10461 require_once("$CFG->dirroot/repository/lib.php");
10462 $defaults = array(
10463 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10464 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10465 'context' => context_system::instance());
10466 foreach($this->options as $k => $v) {
10467 $defaults[$k] = $v;
10470 return $defaults;
10473 public function get_setting() {
10474 return $this->config_read($this->name);
10477 public function write_setting($data) {
10478 global $USER;
10480 // Let's not deal with validation here, this is for admins only.
10481 $current = $this->get_setting();
10482 if (empty($data) && $current === null) {
10483 // This will be the case when applying default settings (installation).
10484 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10485 } else if (!is_number($data)) {
10486 // Draft item id is expected here!
10487 return get_string('errorsetting', 'admin');
10490 $options = $this->get_options();
10491 $fs = get_file_storage();
10492 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10494 $this->oldhashes = null;
10495 if ($current) {
10496 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10497 if ($file = $fs->get_file_by_hash($hash)) {
10498 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10500 unset($file);
10503 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10504 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10505 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10506 // with an error because the draft area does not exist, as he did not use it.
10507 $usercontext = context_user::instance($USER->id);
10508 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10509 return get_string('errorsetting', 'admin');
10513 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10514 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10516 $filepath = '';
10517 if ($files) {
10518 /** @var stored_file $file */
10519 $file = reset($files);
10520 $filepath = $file->get_filepath().$file->get_filename();
10523 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10526 public function post_write_settings($original) {
10527 $options = $this->get_options();
10528 $fs = get_file_storage();
10529 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10531 $current = $this->get_setting();
10532 $newhashes = null;
10533 if ($current) {
10534 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10535 if ($file = $fs->get_file_by_hash($hash)) {
10536 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10538 unset($file);
10541 if ($this->oldhashes === $newhashes) {
10542 $this->oldhashes = null;
10543 return false;
10545 $this->oldhashes = null;
10547 $callbackfunction = $this->updatedcallback;
10548 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10549 $callbackfunction($this->get_full_name());
10551 return true;
10554 public function output_html($data, $query = '') {
10555 global $CFG;
10557 $options = $this->get_options();
10558 $id = $this->get_id();
10559 $elname = $this->get_full_name();
10560 $draftitemid = file_get_submitted_draft_itemid($elname);
10561 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10562 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10564 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10565 require_once("$CFG->dirroot/lib/form/filemanager.php");
10567 $fmoptions = new stdClass();
10568 $fmoptions->mainfile = $options['mainfile'];
10569 $fmoptions->maxbytes = $options['maxbytes'];
10570 $fmoptions->maxfiles = $options['maxfiles'];
10571 $fmoptions->subdirs = $options['subdirs'];
10572 $fmoptions->accepted_types = $options['accepted_types'];
10573 $fmoptions->return_types = $options['return_types'];
10574 $fmoptions->context = $options['context'];
10575 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10577 $fm = new MoodleQuickForm_filemanager($elname, $this->visiblename, ['id' => $id], $fmoptions);
10578 $fm->setValue($draftitemid);
10580 return format_admin_setting($this, $this->visiblename,
10581 '<div class="form-filemanager" data-fieldtype="filemanager">' . $fm->toHtml() . '</div>',
10582 $this->description, true, '', '', $query);
10588 * Administration interface for user specified regular expressions for device detection.
10590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10592 class admin_setting_devicedetectregex extends admin_setting {
10595 * Calls parent::__construct with specific args
10597 * @param string $name
10598 * @param string $visiblename
10599 * @param string $description
10600 * @param mixed $defaultsetting
10602 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10603 global $CFG;
10604 parent::__construct($name, $visiblename, $description, $defaultsetting);
10608 * Return the current setting(s)
10610 * @return array Current settings array
10612 public function get_setting() {
10613 global $CFG;
10615 $config = $this->config_read($this->name);
10616 if (is_null($config)) {
10617 return null;
10620 return $this->prepare_form_data($config);
10624 * Save selected settings
10626 * @param array $data Array of settings to save
10627 * @return bool
10629 public function write_setting($data) {
10630 if (empty($data)) {
10631 $data = array();
10634 if ($this->config_write($this->name, $this->process_form_data($data))) {
10635 return ''; // success
10636 } else {
10637 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10642 * Return XHTML field(s) for regexes
10644 * @param array $data Array of options to set in HTML
10645 * @return string XHTML string for the fields and wrapping div(s)
10647 public function output_html($data, $query='') {
10648 global $OUTPUT;
10650 $context = (object) [
10651 'expressions' => [],
10652 'name' => $this->get_full_name()
10655 if (empty($data)) {
10656 $looplimit = 1;
10657 } else {
10658 $looplimit = (count($data)/2)+1;
10661 for ($i=0; $i<$looplimit; $i++) {
10663 $expressionname = 'expression'.$i;
10665 if (!empty($data[$expressionname])){
10666 $expression = $data[$expressionname];
10667 } else {
10668 $expression = '';
10671 $valuename = 'value'.$i;
10673 if (!empty($data[$valuename])){
10674 $value = $data[$valuename];
10675 } else {
10676 $value= '';
10679 $context->expressions[] = [
10680 'index' => $i,
10681 'expression' => $expression,
10682 'value' => $value
10686 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10688 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10692 * Converts the string of regexes
10694 * @see self::process_form_data()
10695 * @param $regexes string of regexes
10696 * @return array of form fields and their values
10698 protected function prepare_form_data($regexes) {
10700 $regexes = json_decode($regexes);
10702 $form = array();
10704 $i = 0;
10706 foreach ($regexes as $value => $regex) {
10707 $expressionname = 'expression'.$i;
10708 $valuename = 'value'.$i;
10710 $form[$expressionname] = $regex;
10711 $form[$valuename] = $value;
10712 $i++;
10715 return $form;
10719 * Converts the data from admin settings form into a string of regexes
10721 * @see self::prepare_form_data()
10722 * @param array $data array of admin form fields and values
10723 * @return false|string of regexes
10725 protected function process_form_data(array $form) {
10727 $count = count($form); // number of form field values
10729 if ($count % 2) {
10730 // we must get five fields per expression
10731 return false;
10734 $regexes = array();
10735 for ($i = 0; $i < $count / 2; $i++) {
10736 $expressionname = "expression".$i;
10737 $valuename = "value".$i;
10739 $expression = trim($form['expression'.$i]);
10740 $value = trim($form['value'.$i]);
10742 if (empty($expression)){
10743 continue;
10746 $regexes[$value] = $expression;
10749 $regexes = json_encode($regexes);
10751 return $regexes;
10757 * Multiselect for current modules
10759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10761 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10762 private $excludesystem;
10765 * Calls parent::__construct - note array $choices is not required
10767 * @param string $name setting name
10768 * @param string $visiblename localised setting name
10769 * @param string $description setting description
10770 * @param array $defaultsetting a plain array of default module ids
10771 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10773 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10774 $excludesystem = true) {
10775 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10776 $this->excludesystem = $excludesystem;
10780 * Loads an array of current module choices
10782 * @return bool always return true
10784 public function load_choices() {
10785 if (is_array($this->choices)) {
10786 return true;
10788 $this->choices = array();
10790 global $CFG, $DB;
10791 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10792 foreach ($records as $record) {
10793 // Exclude modules if the code doesn't exist
10794 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10795 // Also exclude system modules (if specified)
10796 if (!($this->excludesystem &&
10797 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10798 MOD_ARCHETYPE_SYSTEM)) {
10799 $this->choices[$record->id] = $record->name;
10803 return true;
10808 * Admin setting to show if a php extension is enabled or not.
10810 * @copyright 2013 Damyon Wiese
10811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10813 class admin_setting_php_extension_enabled extends admin_setting {
10815 /** @var string The name of the extension to check for */
10816 private $extension;
10819 * Calls parent::__construct with specific arguments
10821 public function __construct($name, $visiblename, $description, $extension) {
10822 $this->extension = $extension;
10823 $this->nosave = true;
10824 parent::__construct($name, $visiblename, $description, '');
10828 * Always returns true, does nothing
10830 * @return true
10832 public function get_setting() {
10833 return true;
10837 * Always returns true, does nothing
10839 * @return true
10841 public function get_defaultsetting() {
10842 return true;
10846 * Always returns '', does not write anything
10848 * @return string Always returns ''
10850 public function write_setting($data) {
10851 // Do not write any setting.
10852 return '';
10856 * Outputs the html for this setting.
10857 * @return string Returns an XHTML string
10859 public function output_html($data, $query='') {
10860 global $OUTPUT;
10862 $o = '';
10863 if (!extension_loaded($this->extension)) {
10864 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10866 $o .= format_admin_setting($this, $this->visiblename, $warning);
10868 return $o;
10873 * Server timezone setting.
10875 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10877 * @author Petr Skoda <petr.skoda@totaralms.com>
10879 class admin_setting_servertimezone extends admin_setting_configselect {
10881 * Constructor.
10883 public function __construct() {
10884 $default = core_date::get_default_php_timezone();
10885 if ($default === 'UTC') {
10886 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10887 $default = 'Europe/London';
10890 parent::__construct('timezone',
10891 new lang_string('timezone', 'core_admin'),
10892 new lang_string('configtimezone', 'core_admin'), $default, null);
10896 * Lazy load timezone options.
10897 * @return bool true if loaded, false if error
10899 public function load_choices() {
10900 global $CFG;
10901 if (is_array($this->choices)) {
10902 return true;
10905 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10906 $this->choices = core_date::get_list_of_timezones($current, false);
10907 if ($current == 99) {
10908 // Do not show 99 unless it is current value, we want to get rid of it over time.
10909 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10910 core_date::get_default_php_timezone());
10913 return true;
10918 * Forced user timezone setting.
10920 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10921 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10922 * @author Petr Skoda <petr.skoda@totaralms.com>
10924 class admin_setting_forcetimezone extends admin_setting_configselect {
10926 * Constructor.
10928 public function __construct() {
10929 parent::__construct('forcetimezone',
10930 new lang_string('forcetimezone', 'core_admin'),
10931 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10935 * Lazy load timezone options.
10936 * @return bool true if loaded, false if error
10938 public function load_choices() {
10939 global $CFG;
10940 if (is_array($this->choices)) {
10941 return true;
10944 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10945 $this->choices = core_date::get_list_of_timezones($current, true);
10946 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10948 return true;
10954 * Search setup steps info.
10956 * @package core
10957 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10958 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10960 class admin_setting_searchsetupinfo extends admin_setting {
10963 * Calls parent::__construct with specific arguments
10965 public function __construct() {
10966 $this->nosave = true;
10967 parent::__construct('searchsetupinfo', '', '', '');
10971 * Always returns true, does nothing
10973 * @return true
10975 public function get_setting() {
10976 return true;
10980 * Always returns true, does nothing
10982 * @return true
10984 public function get_defaultsetting() {
10985 return true;
10989 * Always returns '', does not write anything
10991 * @param array $data
10992 * @return string Always returns ''
10994 public function write_setting($data) {
10995 // Do not write any setting.
10996 return '';
11000 * Builds the HTML to display the control
11002 * @param string $data Unused
11003 * @param string $query
11004 * @return string
11006 public function output_html($data, $query='') {
11007 global $CFG, $OUTPUT, $ADMIN;
11009 $return = '';
11010 $brtag = html_writer::empty_tag('br');
11012 $searchareas = \core_search\manager::get_search_areas_list();
11013 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11014 $anyindexed = false;
11015 foreach ($searchareas as $areaid => $searcharea) {
11016 list($componentname, $varname) = $searcharea->get_config_var_name();
11017 if (get_config($componentname, $varname . '_indexingstart')) {
11018 $anyindexed = true;
11019 break;
11023 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11025 $table = new html_table();
11026 $table->head = array(get_string('step', 'search'), get_string('status'));
11027 $table->colclasses = array('leftalign step', 'leftalign status');
11028 $table->id = 'searchsetup';
11029 $table->attributes['class'] = 'admintable generaltable';
11030 $table->data = array();
11032 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11034 // Select a search engine.
11035 $row = array();
11036 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11037 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11038 array('href' => $url));
11040 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11041 if (!empty($CFG->searchengine)) {
11042 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11043 array('class' => 'badge badge-success'));
11046 $row[1] = $status;
11047 $table->data[] = $row;
11049 // Available areas.
11050 $row = array();
11051 $url = new moodle_url('/admin/searchareas.php');
11052 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11053 array('href' => $url));
11055 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11056 if ($anyenabled) {
11057 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11060 $row[1] = $status;
11061 $table->data[] = $row;
11063 // Setup search engine.
11064 $row = array();
11065 if (empty($CFG->searchengine)) {
11066 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11067 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11068 } else {
11069 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11070 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11071 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11072 } else {
11073 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11076 // Check the engine status.
11077 $searchengine = \core_search\manager::search_engine_instance();
11078 try {
11079 $serverstatus = $searchengine->is_server_ready();
11080 } catch (\moodle_exception $e) {
11081 $serverstatus = $e->getMessage();
11083 if ($serverstatus === true) {
11084 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11085 } else {
11086 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11088 $row[1] = $status;
11090 $table->data[] = $row;
11092 // Indexed data.
11093 $row = array();
11094 $url = new moodle_url('/admin/searchareas.php');
11095 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11096 if ($anyindexed) {
11097 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11098 } else {
11099 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11101 $row[1] = $status;
11102 $table->data[] = $row;
11104 // Enable global search.
11105 $row = array();
11106 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11107 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11108 array('href' => $url));
11109 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11110 if (\core_search\manager::is_global_search_enabled()) {
11111 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11113 $row[1] = $status;
11114 $table->data[] = $row;
11116 // Replace front page search.
11117 $row = array();
11118 $url = new moodle_url("/admin/search.php?query=searchincludeallcourses");
11119 $row[0] = '6. ' . html_writer::tag('a', get_string('replacefrontsearch', 'admin'),
11120 array('href' => $url));
11121 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11122 if (\core_search\manager::can_replace_course_search()) {
11123 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11125 $row[1] = $status;
11126 $table->data[] = $row;
11128 $return .= html_writer::table($table);
11130 return highlight($query, $return);
11136 * Used to validate the contents of SCSS code and ensuring they are parsable.
11138 * It does not attempt to detect undefined SCSS variables because it is designed
11139 * to be used without knowledge of other config/scss included.
11141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11142 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11144 class admin_setting_scsscode extends admin_setting_configtextarea {
11147 * Validate the contents of the SCSS to ensure its parsable. Does not
11148 * attempt to detect undefined scss variables.
11150 * @param string $data The scss code from text field.
11151 * @return mixed bool true for success or string:error on failure.
11153 public function validate($data) {
11154 if (empty($data)) {
11155 return true;
11158 $scss = new core_scss();
11159 try {
11160 $scss->compile($data);
11161 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11162 return get_string('scssinvalid', 'admin', $e->getMessage());
11163 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11164 // Silently ignore this - it could be a scss variable defined from somewhere
11165 // else which we are not examining here.
11166 return true;
11169 return true;
11175 * Administration setting to define a list of file types.
11177 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11178 * @copyright 2017 David Mudrák <david@moodle.com>
11179 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11181 class admin_setting_filetypes extends admin_setting_configtext {
11183 /** @var array Allow selection from these file types only. */
11184 protected $onlytypes = [];
11186 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11187 protected $allowall = true;
11189 /** @var core_form\filetypes_util instance to use as a helper. */
11190 protected $util = null;
11193 * Constructor.
11195 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11196 * @param string $visiblename Localised label of the setting
11197 * @param string $description Localised description of the setting
11198 * @param string $defaultsetting Default setting value.
11199 * @param array $options Setting widget options, an array with optional keys:
11200 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11201 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11203 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11205 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11207 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11208 $this->onlytypes = $options['onlytypes'];
11211 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11212 $this->allowall = (bool)$options['allowall'];
11215 $this->util = new \core_form\filetypes_util();
11219 * Normalize the user's input and write it to the database as comma separated list.
11221 * Comma separated list as a text representation of the array was chosen to
11222 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11224 * @param string $data Value submitted by the admin.
11225 * @return string Epty string if all good, error message otherwise.
11227 public function write_setting($data) {
11228 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11232 * Validate data before storage
11234 * @param string $data The setting values provided by the admin
11235 * @return bool|string True if ok, the string if error found
11237 public function validate($data) {
11238 $parentcheck = parent::validate($data);
11239 if ($parentcheck !== true) {
11240 return $parentcheck;
11243 // Check for unknown file types.
11244 if ($unknown = $this->util->get_unknown_file_types($data)) {
11245 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11248 // Check for disallowed file types.
11249 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11250 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11253 return true;
11257 * Return an HTML string for the setting element.
11259 * @param string $data The current setting value
11260 * @param string $query Admin search query to be highlighted
11261 * @return string HTML to be displayed
11263 public function output_html($data, $query='') {
11264 global $OUTPUT, $PAGE;
11266 $default = $this->get_defaultsetting();
11267 $context = (object) [
11268 'id' => $this->get_id(),
11269 'name' => $this->get_full_name(),
11270 'value' => $data,
11271 'descriptions' => $this->util->describe_file_types($data),
11273 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11275 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11276 $this->get_id(),
11277 $this->visiblename->out(),
11278 $this->onlytypes,
11279 $this->allowall,
11282 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11286 * Should the values be always displayed in LTR mode?
11288 * We always return true here because these values are not RTL compatible.
11290 * @return bool True because these values are not RTL compatible.
11292 public function get_force_ltr() {
11293 return true;
11298 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11301 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11303 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11306 * Constructor.
11308 * @param string $name
11309 * @param string $visiblename
11310 * @param string $description
11311 * @param mixed $defaultsetting string or array
11312 * @param mixed $paramtype
11313 * @param string $cols
11314 * @param string $rows
11316 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11317 $cols = '60', $rows = '8') {
11318 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11319 // Pre-set force LTR to false.
11320 $this->set_force_ltr(false);
11324 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11326 * @param string $data The age of digital consent map from text field.
11327 * @return mixed bool true for success or string:error on failure.
11329 public function validate($data) {
11330 if (empty($data)) {
11331 return true;
11334 try {
11335 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11336 } catch (\moodle_exception $e) {
11337 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11340 return true;
11345 * Selection of plugins that can work as site policy handlers
11347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11348 * @copyright 2018 Marina Glancy
11350 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11353 * Constructor
11354 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11355 * for ones in config_plugins.
11356 * @param string $visiblename localised
11357 * @param string $description long localised info
11358 * @param string $defaultsetting
11360 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11361 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11365 * Lazy-load the available choices for the select box
11367 public function load_choices() {
11368 if (during_initial_install()) {
11369 return false;
11371 if (is_array($this->choices)) {
11372 return true;
11375 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11376 $manager = new \core_privacy\local\sitepolicy\manager();
11377 $plugins = $manager->get_all_handlers();
11378 foreach ($plugins as $pname => $unused) {
11379 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11380 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11383 return true;
11388 * Used to validate theme presets code and ensuring they compile well.
11390 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11391 * @copyright 2019 Bas Brands <bas@moodle.com>
11393 class admin_setting_configthemepreset extends admin_setting_configselect {
11395 /** @var string The name of the theme to check for */
11396 private $themename;
11399 * Constructor
11400 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11401 * or 'myplugin/mysetting' for ones in config_plugins.
11402 * @param string $visiblename localised
11403 * @param string $description long localised info
11404 * @param string|int $defaultsetting
11405 * @param array $choices array of $value=>$label for each selection
11406 * @param string $themename name of theme to check presets for.
11408 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11409 $this->themename = $themename;
11410 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11414 * Write settings if validated
11416 * @param string $data
11417 * @return string
11419 public function write_setting($data) {
11420 $validated = $this->validate($data);
11421 if ($validated !== true) {
11422 return $validated;
11424 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11428 * Validate the preset file to ensure its parsable.
11430 * @param string $data The preset file chosen.
11431 * @return mixed bool true for success or string:error on failure.
11433 public function validate($data) {
11435 if (in_array($data, ['default.scss', 'plain.scss'])) {
11436 return true;
11439 $fs = get_file_storage();
11440 $theme = theme_config::load($this->themename);
11441 $context = context_system::instance();
11443 // If the preset has not changed there is no need to validate it.
11444 if ($theme->settings->preset == $data) {
11445 return true;
11448 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11449 // This operation uses a lot of resources.
11450 raise_memory_limit(MEMORY_EXTRA);
11451 core_php_time_limit::raise(300);
11453 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11454 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11456 $compiler = new core_scss();
11457 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11458 $compiler->append_raw_scss($presetfile->get_content());
11459 if ($scssproperties = $theme->get_scss_property()) {
11460 $compiler->setImportPaths($scssproperties[0]);
11462 $compiler->append_raw_scss($theme->get_extra_scss_code());
11464 try {
11465 $compiler->to_css();
11466 } catch (Exception $e) {
11467 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11470 // Try to save memory.
11471 $compiler = null;
11472 unset($compiler);
11475 return true;
11480 * Selection of plugins that can work as H5P libraries handlers
11482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11483 * @copyright 2020 Sara Arjona <sara@moodle.com>
11485 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11488 * Constructor
11489 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11490 * for ones in config_plugins.
11491 * @param string $visiblename localised
11492 * @param string $description long localised info
11493 * @param string $defaultsetting
11495 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11496 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11500 * Lazy-load the available choices for the select box
11502 public function load_choices() {
11503 if (during_initial_install()) {
11504 return false;
11506 if (is_array($this->choices)) {
11507 return true;
11510 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11511 foreach ($this->choices as $name => $class) {
11512 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11513 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11516 return true;