Merge branch 'MDL-77433-master' of https://github.com/ferranrecio/moodle
[moodle.git] / lib / adminlib.php
blobc698a55e9d31e1866312cf36b9053b027480f5f8
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 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' => ($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 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8325 $version = $plugininfo->versiondb;
8326 $supports = $plugininfo->supports($usedextensions);
8328 // Hide/show links.
8329 $class = '';
8330 if (!$plugininfo->is_installed_and_upgraded()) {
8331 $hideshow = '';
8332 $enabled = false;
8333 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8334 } else {
8335 $enabled = $plugininfo->is_enabled();
8336 if ($enabled) {
8337 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8338 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8339 } else {
8340 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8341 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8342 $class = 'dimmed_text';
8344 $displayname = $plugin->displayname;
8345 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8346 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8349 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8350 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8351 } else {
8352 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8355 // Up/down link (only if enrol is enabled).
8356 $updown = '';
8357 if ($enabled) {
8358 if ($updowncount > 1) {
8359 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8360 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8361 } else {
8362 $updown = $spacer;
8364 if ($updowncount < count($enabledplugins)) {
8365 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8366 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8367 } else {
8368 $updown .= $spacer;
8370 ++$updowncount;
8373 $uninstall = '';
8374 $status = $plugininfo->get_status();
8375 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8376 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8378 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8379 $uninstall = get_string('status_new', 'core_plugin');
8380 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8381 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8384 $settings = '';
8385 if ($plugininfo->get_settings_url()) {
8386 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8389 // Add a row to the table.
8390 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8391 if ($class) {
8392 $row->attributes['class'] = $class;
8394 $table->data[] = $row;
8396 $printed[$name] = true;
8399 $return .= html_writer::table($table);
8400 $return .= $OUTPUT->box_end();
8401 return highlight($query, $return);
8407 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8409 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8412 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8415 * Calls parent::__construct with specific arguments
8417 public function __construct() {
8418 $this->nosave = true;
8419 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8423 * Always returns true
8425 * @return true
8427 public function get_setting() {
8428 return true;
8432 * Always returns true
8434 * @return true
8436 public function get_defaultsetting() {
8437 return true;
8441 * Always returns '' and doesn't write anything
8443 * @param mixed $data string or array, must not be NULL
8444 * @return string Always returns ''
8446 public function write_setting($data) {
8447 // Do not write any setting.
8448 return '';
8452 * Search to find if Query is related to content bank plugin
8454 * @param string $query The string to search for
8455 * @return bool true for related false for not
8457 public function is_related($query) {
8458 if (parent::is_related($query)) {
8459 return true;
8461 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8462 foreach ($types as $type) {
8463 if (strpos($type->component, $query) !== false ||
8464 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8465 return true;
8468 return false;
8472 * Return XHTML to display control
8474 * @param mixed $data Unused
8475 * @param string $query
8476 * @return string highlight
8478 public function output_html($data, $query='') {
8479 global $CFG, $OUTPUT;
8480 $return = '';
8482 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8483 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8484 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8486 $table = new html_table();
8487 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8488 $table->align = array('left', 'center', 'center', 'center', 'center');
8489 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8490 $table->data = array();
8491 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8493 $totalenabled = 0;
8494 $count = 0;
8495 foreach ($types as $type) {
8496 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8497 $totalenabled++;
8501 foreach ($types as $type) {
8502 $url = new moodle_url('/admin/contentbank.php',
8503 array('sesskey' => sesskey(), 'name' => $type->name));
8505 $class = '';
8506 $strtypename = $type->displayname;
8507 if ($type->is_enabled()) {
8508 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8509 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8510 } else {
8511 $class = 'dimmed_text';
8512 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8513 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8516 $updown = '';
8517 if ($count) {
8518 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8519 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8520 } else {
8521 $updown .= $spacer;
8523 if ($count < count($types) - 1) {
8524 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8525 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8526 } else {
8527 $updown .= $spacer;
8530 $settings = '';
8531 if ($type->get_settings_url()) {
8532 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8535 $uninstall = '';
8536 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8537 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8540 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8541 if ($class) {
8542 $row->attributes['class'] = $class;
8544 $table->data[] = $row;
8545 $count++;
8547 $return .= html_writer::table($table);
8548 return highlight($query, $return);
8553 * Initialise admin page - this function does require login and permission
8554 * checks specified in page definition.
8556 * This function must be called on each admin page before other code.
8558 * @global moodle_page $PAGE
8560 * @param string $section name of page
8561 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8562 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8563 * added to the turn blocks editing on/off form, so this page reloads correctly.
8564 * @param string $actualurl if the actual page being viewed is not the normal one for this
8565 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8566 * @param array $options Additional options that can be specified for page setup.
8567 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8568 * nosearch - Do not display search bar
8570 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8571 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8573 $PAGE->set_context(null); // hack - set context to something, by default to system context
8575 $site = get_site();
8576 require_login(null, false);
8578 if (!empty($options['pagelayout'])) {
8579 // A specific page layout has been requested.
8580 $PAGE->set_pagelayout($options['pagelayout']);
8581 } else if ($section === 'upgradesettings') {
8582 $PAGE->set_pagelayout('maintenance');
8583 } else {
8584 $PAGE->set_pagelayout('admin');
8587 $adminroot = admin_get_root(false, false); // settings not required for external pages
8588 $extpage = $adminroot->locate($section, true);
8590 $hassiteconfig = has_capability('moodle/site:config', context_system::instance());
8591 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8592 // The requested section isn't in the admin tree
8593 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8594 if (!$hassiteconfig) {
8595 // The requested section could depend on a different capability
8596 // but most likely the user has inadequate capabilities
8597 throw new \moodle_exception('accessdenied', 'admin');
8598 } else {
8599 throw new \moodle_exception('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8603 // this eliminates our need to authenticate on the actual pages
8604 if (!$extpage->check_access()) {
8605 throw new \moodle_exception('accessdenied', 'admin');
8606 die;
8609 navigation_node::require_admin_tree();
8611 // $PAGE->set_extra_button($extrabutton); TODO
8613 if (!$actualurl) {
8614 $actualurl = $extpage->url;
8617 $PAGE->set_url($actualurl, $extraurlparams);
8618 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8619 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8622 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8623 // During initial install.
8624 $strinstallation = get_string('installation', 'install');
8625 $strsettings = get_string('settings');
8626 $PAGE->navbar->add($strsettings);
8627 $PAGE->set_title($strinstallation);
8628 $PAGE->set_heading($strinstallation);
8629 $PAGE->set_cacheable(false);
8630 return;
8633 // Locate the current item on the navigation and make it active when found.
8634 $path = $extpage->path;
8635 $node = $PAGE->settingsnav;
8636 while ($node && count($path) > 0) {
8637 $node = $node->get(array_pop($path));
8639 if ($node) {
8640 $node->make_active();
8643 // Normal case.
8644 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8645 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8646 $USER->editing = $adminediting;
8649 $visiblepathtosection = array_reverse($extpage->visiblepath);
8651 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8652 if ($PAGE->user_is_editing()) {
8653 $caption = get_string('blockseditoff');
8654 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8655 } else {
8656 $caption = get_string('blocksediton');
8657 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8659 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8662 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8663 $PAGE->set_heading($SITE->fullname);
8665 if ($hassiteconfig && empty($options['nosearch'])) {
8666 $PAGE->add_header_action($OUTPUT->render_from_template('core_admin/header_search_input', [
8667 'action' => new moodle_url('/admin/search.php'),
8668 'query' => $PAGE->url->get_param('query'),
8669 ]));
8672 // prevent caching in nav block
8673 $PAGE->navigation->clear_cache();
8677 * Returns the reference to admin tree root
8679 * @return object admin_root object
8681 function admin_get_root($reload=false, $requirefulltree=true) {
8682 global $CFG, $DB, $OUTPUT, $ADMIN;
8684 if (is_null($ADMIN)) {
8685 // create the admin tree!
8686 $ADMIN = new admin_root($requirefulltree);
8689 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8690 $ADMIN->purge_children($requirefulltree);
8693 if (!$ADMIN->loaded) {
8694 // we process this file first to create categories first and in correct order
8695 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8697 // now we process all other files in admin/settings to build the admin tree
8698 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8699 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8700 continue;
8702 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8703 // plugins are loaded last - they may insert pages anywhere
8704 continue;
8706 require($file);
8708 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8710 $ADMIN->loaded = true;
8713 return $ADMIN;
8716 /// settings utility functions
8719 * This function applies default settings.
8720 * Because setting the defaults of some settings can enable other settings,
8721 * this function is called recursively until no more new settings are found.
8723 * @param object $node, NULL means complete tree, null by default
8724 * @param bool $unconditional if true overrides all values with defaults, true by default
8725 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8726 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8727 * @return array $settingsoutput The names and values of the changed settings
8729 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8730 $counter = 0;
8732 // This function relies heavily on config cache, so we need to enable in-memory caches if it
8733 // is used during install when normal caching is disabled.
8734 $token = new \core_cache\allow_temporary_caches();
8736 if (is_null($node)) {
8737 core_plugin_manager::reset_caches();
8738 $node = admin_get_root(true, true);
8739 $counter = count($settingsoutput);
8742 if ($node instanceof admin_category) {
8743 $entries = array_keys($node->children);
8744 foreach ($entries as $entry) {
8745 $settingsoutput = admin_apply_default_settings(
8746 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8750 } else if ($node instanceof admin_settingpage) {
8751 foreach ($node->settings as $setting) {
8752 if (!$unconditional && !is_null($setting->get_setting())) {
8753 // Do not override existing defaults.
8754 continue;
8756 $defaultsetting = $setting->get_defaultsetting();
8757 if (is_null($defaultsetting)) {
8758 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8759 continue;
8762 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8764 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8765 $admindefaultsettings[$settingname] = $settingname;
8766 $settingsoutput[$settingname] = $defaultsetting;
8768 // Set the default for this setting.
8769 $setting->write_setting($defaultsetting);
8770 $setting->write_setting_flags(null);
8771 } else {
8772 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8777 // Call this function recursively until all settings are processed.
8778 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8779 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8781 // Just in case somebody modifies the list of active plugins directly.
8782 core_plugin_manager::reset_caches();
8784 return $settingsoutput;
8788 * Store changed settings, this function updates the errors variable in $ADMIN
8790 * @param object $formdata from form
8791 * @return int number of changed settings
8793 function admin_write_settings($formdata) {
8794 global $CFG, $SITE, $DB;
8796 $olddbsessions = !empty($CFG->dbsessions);
8797 $formdata = (array)$formdata;
8799 $data = array();
8800 foreach ($formdata as $fullname=>$value) {
8801 if (strpos($fullname, 's_') !== 0) {
8802 continue; // not a config value
8804 $data[$fullname] = $value;
8807 $adminroot = admin_get_root();
8808 $settings = admin_find_write_settings($adminroot, $data);
8810 $count = 0;
8811 foreach ($settings as $fullname=>$setting) {
8812 /** @var $setting admin_setting */
8813 $original = $setting->get_setting();
8814 $error = $setting->write_setting($data[$fullname]);
8815 if ($error !== '') {
8816 $adminroot->errors[$fullname] = new stdClass();
8817 $adminroot->errors[$fullname]->data = $data[$fullname];
8818 $adminroot->errors[$fullname]->id = $setting->get_id();
8819 $adminroot->errors[$fullname]->error = $error;
8820 } else {
8821 $setting->write_setting_flags($data);
8823 if ($setting->post_write_settings($original)) {
8824 $count++;
8828 if ($olddbsessions != !empty($CFG->dbsessions)) {
8829 require_logout();
8832 // Now update $SITE - just update the fields, in case other people have a
8833 // a reference to it (e.g. $PAGE, $COURSE).
8834 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8835 foreach (get_object_vars($newsite) as $field => $value) {
8836 $SITE->$field = $value;
8839 // now reload all settings - some of them might depend on the changed
8840 admin_get_root(true);
8841 return $count;
8845 * Internal recursive function - finds all settings from submitted form
8847 * @param object $node Instance of admin_category, or admin_settingpage
8848 * @param array $data
8849 * @return array
8851 function admin_find_write_settings($node, $data) {
8852 $return = array();
8854 if (empty($data)) {
8855 return $return;
8858 if ($node instanceof admin_category) {
8859 if ($node->check_access()) {
8860 $entries = array_keys($node->children);
8861 foreach ($entries as $entry) {
8862 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8866 } else if ($node instanceof admin_settingpage) {
8867 if ($node->check_access()) {
8868 foreach ($node->settings as $setting) {
8869 $fullname = $setting->get_full_name();
8870 if (array_key_exists($fullname, $data)) {
8871 $return[$fullname] = $setting;
8878 return $return;
8882 * Internal function - prints the search results
8884 * @param string $query String to search for
8885 * @return string empty or XHTML
8887 function admin_search_settings_html($query) {
8888 global $CFG, $OUTPUT, $PAGE;
8890 if (core_text::strlen($query) < 2) {
8891 return '';
8893 $query = core_text::strtolower($query);
8895 $adminroot = admin_get_root();
8896 $findings = $adminroot->search($query);
8897 $savebutton = false;
8899 $tpldata = (object) [
8900 'actionurl' => $PAGE->url->out(false),
8901 'results' => [],
8902 'sesskey' => sesskey(),
8905 foreach ($findings as $found) {
8906 $page = $found->page;
8907 $settings = $found->settings;
8908 if ($page->is_hidden()) {
8909 // hidden pages are not displayed in search results
8910 continue;
8913 $heading = highlight($query, $page->visiblename);
8914 $headingurl = null;
8915 if ($page instanceof admin_externalpage) {
8916 $headingurl = new moodle_url($page->url);
8917 } else if ($page instanceof admin_settingpage) {
8918 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8919 } else {
8920 continue;
8923 // Locate the page in the admin root and populate its visiblepath attribute.
8924 $path = array();
8925 $located = $adminroot->locate($page->name, true);
8926 if ($located) {
8927 foreach ($located->visiblepath as $pathitem) {
8928 array_unshift($path, (string) $pathitem);
8932 $sectionsettings = [];
8933 if (!empty($settings)) {
8934 foreach ($settings as $setting) {
8935 if (empty($setting->nosave)) {
8936 $savebutton = true;
8938 $fullname = $setting->get_full_name();
8939 if (array_key_exists($fullname, $adminroot->errors)) {
8940 $data = $adminroot->errors[$fullname]->data;
8941 } else {
8942 $data = $setting->get_setting();
8943 // do not use defaults if settings not available - upgradesettings handles the defaults!
8945 $sectionsettings[] = $setting->output_html($data, $query);
8949 $tpldata->results[] = (object) [
8950 'title' => $heading,
8951 'path' => $path,
8952 'url' => $headingurl->out(false),
8953 'settings' => $sectionsettings
8957 $tpldata->showsave = $savebutton;
8958 $tpldata->hasresults = !empty($tpldata->results);
8960 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8964 * Internal function - returns arrays of html pages with uninitialised settings
8966 * @param object $node Instance of admin_category or admin_settingpage
8967 * @return array
8969 function admin_output_new_settings_by_page($node) {
8970 global $OUTPUT;
8971 $return = array();
8973 if ($node instanceof admin_category) {
8974 $entries = array_keys($node->children);
8975 foreach ($entries as $entry) {
8976 $return += admin_output_new_settings_by_page($node->children[$entry]);
8979 } else if ($node instanceof admin_settingpage) {
8980 $newsettings = array();
8981 foreach ($node->settings as $setting) {
8982 if (is_null($setting->get_setting())) {
8983 $newsettings[] = $setting;
8986 if (count($newsettings) > 0) {
8987 $adminroot = admin_get_root();
8988 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8989 $page .= '<fieldset class="adminsettings">'."\n";
8990 foreach ($newsettings as $setting) {
8991 $fullname = $setting->get_full_name();
8992 if (array_key_exists($fullname, $adminroot->errors)) {
8993 $data = $adminroot->errors[$fullname]->data;
8994 } else {
8995 $data = $setting->get_setting();
8996 if (is_null($data)) {
8997 $data = $setting->get_defaultsetting();
9000 $page .= '<div class="clearer"><!-- --></div>'."\n";
9001 $page .= $setting->output_html($data);
9003 $page .= '</fieldset>';
9004 $return[$node->name] = $page;
9008 return $return;
9012 * Format admin settings
9014 * @param object $setting
9015 * @param string $title label element
9016 * @param string $form form fragment, html code - not highlighted automatically
9017 * @param string $description
9018 * @param mixed $label link label to id, true by default or string being the label to connect it to
9019 * @param string $warning warning text
9020 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9021 * @param string $query search query to be highlighted
9022 * @return string XHTML
9024 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9025 global $CFG, $OUTPUT;
9027 $context = (object) [
9028 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9029 'fullname' => $setting->get_full_name(),
9032 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9033 if ($label === true) {
9034 $context->labelfor = $setting->get_id();
9035 } else if ($label === false) {
9036 $context->labelfor = '';
9037 } else {
9038 $context->labelfor = $label;
9041 $form .= $setting->output_setting_flags();
9043 $context->warning = $warning;
9044 $context->override = '';
9045 if (empty($setting->plugin)) {
9046 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
9047 $context->override = get_string('configoverride', 'admin');
9049 } else {
9050 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9051 $context->override = get_string('configoverride', 'admin');
9055 $defaults = array();
9056 if (!is_null($defaultinfo)) {
9057 if ($defaultinfo === '') {
9058 $defaultinfo = get_string('emptysettingvalue', 'admin');
9060 $defaults[] = $defaultinfo;
9063 $context->default = null;
9064 $setting->get_setting_flag_defaults($defaults);
9065 if (!empty($defaults)) {
9066 $defaultinfo = implode(', ', $defaults);
9067 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9068 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9072 $context->error = '';
9073 $adminroot = admin_get_root();
9074 if (array_key_exists($context->fullname, $adminroot->errors)) {
9075 $context->error = $adminroot->errors[$context->fullname]->error;
9078 if ($dependenton = $setting->get_dependent_on()) {
9079 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9082 $context->id = 'admin-' . $setting->name;
9083 $context->title = highlightfast($query, $title);
9084 $context->name = highlightfast($query, $context->name);
9085 $context->description = highlight($query, markdown_to_html($description));
9086 $context->element = $form;
9087 $context->forceltr = $setting->get_force_ltr();
9088 $context->customcontrol = $setting->has_custom_form_control();
9090 return $OUTPUT->render_from_template('core_admin/setting', $context);
9094 * Based on find_new_settings{@link ()} in upgradesettings.php
9095 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9097 * @param object $node Instance of admin_category, or admin_settingpage
9098 * @return boolean true if any settings haven't been initialised, false if they all have
9100 function any_new_admin_settings($node) {
9102 if ($node instanceof admin_category) {
9103 $entries = array_keys($node->children);
9104 foreach ($entries as $entry) {
9105 if (any_new_admin_settings($node->children[$entry])) {
9106 return true;
9110 } else if ($node instanceof admin_settingpage) {
9111 foreach ($node->settings as $setting) {
9112 if ($setting->get_setting() === NULL) {
9113 return true;
9118 return false;
9122 * Given a table and optionally a column name should replaces be done?
9124 * @param string $table name
9125 * @param string $column name
9126 * @return bool success or fail
9128 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9130 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9131 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9132 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9134 // Additional skip tables.
9135 if (!empty($additionalskiptables)) {
9136 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9139 // Don't process these.
9140 if (in_array($table, $skiptables)) {
9141 return false;
9144 // To be safe never replace inside a table that looks related to logging.
9145 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9146 return false;
9149 // Do column based exclusions.
9150 if (!empty($column)) {
9151 // Don't touch anything that looks like a hash.
9152 if (preg_match('/hash$/', $column)) {
9153 return false;
9157 return true;
9161 * Moved from admin/replace.php so that we can use this in cron
9163 * @param string $search string to look for
9164 * @param string $replace string to replace
9165 * @return bool success or fail
9167 function db_replace($search, $replace, $additionalskiptables = '') {
9168 global $DB, $CFG, $OUTPUT;
9170 // Turn off time limits, sometimes upgrades can be slow.
9171 core_php_time_limit::raise();
9173 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9174 return false;
9176 foreach ($tables as $table) {
9178 if (!db_should_replace($table, '', $additionalskiptables)) {
9179 continue;
9182 if ($columns = $DB->get_columns($table)) {
9183 $DB->set_debug(true);
9184 foreach ($columns as $column) {
9185 if (!db_should_replace($table, $column->name)) {
9186 continue;
9188 $DB->replace_all_text($table, $column, $search, $replace);
9190 $DB->set_debug(false);
9194 // delete modinfo caches
9195 rebuild_course_cache(0, true);
9197 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9198 $blocks = core_component::get_plugin_list('block');
9199 foreach ($blocks as $blockname=>$fullblock) {
9200 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9201 continue;
9204 if (!is_readable($fullblock.'/lib.php')) {
9205 continue;
9208 $function = 'block_'.$blockname.'_global_db_replace';
9209 include_once($fullblock.'/lib.php');
9210 if (!function_exists($function)) {
9211 continue;
9214 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9215 $function($search, $replace);
9216 echo $OUTPUT->notification("...finished", 'notifysuccess');
9219 // Trigger an event.
9220 $eventargs = [
9221 'context' => context_system::instance(),
9222 'other' => [
9223 'search' => $search,
9224 'replace' => $replace
9227 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9228 $event->trigger();
9230 purge_all_caches();
9232 return true;
9236 * Manage repository settings
9238 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9240 class admin_setting_managerepository extends admin_setting {
9241 /** @var string */
9242 private $baseurl;
9245 * calls parent::__construct with specific arguments
9247 public function __construct() {
9248 global $CFG;
9249 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9250 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9254 * Always returns true, does nothing
9256 * @return true
9258 public function get_setting() {
9259 return true;
9263 * Always returns true does nothing
9265 * @return true
9267 public function get_defaultsetting() {
9268 return true;
9272 * Always returns s_managerepository
9274 * @return string Always return 's_managerepository'
9276 public function get_full_name() {
9277 return 's_managerepository';
9281 * Always returns '' doesn't do anything
9283 public function write_setting($data) {
9284 $url = $this->baseurl . '&amp;new=' . $data;
9285 return '';
9286 // TODO
9287 // Should not use redirect and exit here
9288 // Find a better way to do this.
9289 // redirect($url);
9290 // exit;
9294 * Searches repository plugins for one that matches $query
9296 * @param string $query The string to search for
9297 * @return bool true if found, false if not
9299 public function is_related($query) {
9300 if (parent::is_related($query)) {
9301 return true;
9304 $repositories= core_component::get_plugin_list('repository');
9305 foreach ($repositories as $p => $dir) {
9306 if (strpos($p, $query) !== false) {
9307 return true;
9310 foreach (repository::get_types() as $instance) {
9311 $title = $instance->get_typename();
9312 if (strpos(core_text::strtolower($title), $query) !== false) {
9313 return true;
9316 return false;
9320 * Helper function that generates a moodle_url object
9321 * relevant to the repository
9324 function repository_action_url($repository) {
9325 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9329 * Builds XHTML to display the control
9331 * @param string $data Unused
9332 * @param string $query
9333 * @return string XHTML
9335 public function output_html($data, $query='') {
9336 global $CFG, $USER, $OUTPUT;
9338 // Get strings that are used
9339 $strshow = get_string('on', 'repository');
9340 $strhide = get_string('off', 'repository');
9341 $strdelete = get_string('disabled', 'repository');
9343 $actionchoicesforexisting = array(
9344 'show' => $strshow,
9345 'hide' => $strhide,
9346 'delete' => $strdelete
9349 $actionchoicesfornew = array(
9350 'newon' => $strshow,
9351 'newoff' => $strhide,
9352 'delete' => $strdelete
9355 $return = '';
9356 $return .= $OUTPUT->box_start('generalbox');
9358 // Set strings that are used multiple times
9359 $settingsstr = get_string('settings');
9360 $disablestr = get_string('disable');
9362 // Table to list plug-ins
9363 $table = new html_table();
9364 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9365 $table->align = array('left', 'center', 'center', 'center', 'center');
9366 $table->data = array();
9368 // Get list of used plug-ins
9369 $repositorytypes = repository::get_types();
9370 if (!empty($repositorytypes)) {
9371 // Array to store plugins being used
9372 $alreadyplugins = array();
9373 $totalrepositorytypes = count($repositorytypes);
9374 $updowncount = 1;
9375 foreach ($repositorytypes as $i) {
9376 $settings = '';
9377 $typename = $i->get_typename();
9378 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9379 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9380 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9382 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9383 // Calculate number of instances in order to display them for the Moodle administrator
9384 if (!empty($instanceoptionnames)) {
9385 $params = array();
9386 $params['context'] = array(context_system::instance());
9387 $params['onlyvisible'] = false;
9388 $params['type'] = $typename;
9389 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9390 // site instances
9391 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9392 $params['context'] = array();
9393 $instances = repository::static_function($typename, 'get_instances', $params);
9394 $courseinstances = array();
9395 $userinstances = array();
9397 foreach ($instances as $instance) {
9398 $repocontext = context::instance_by_id($instance->instance->contextid);
9399 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9400 $courseinstances[] = $instance;
9401 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9402 $userinstances[] = $instance;
9405 // course instances
9406 $instancenumber = count($courseinstances);
9407 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9409 // user private instances
9410 $instancenumber = count($userinstances);
9411 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9412 } else {
9413 $admininstancenumbertext = "";
9414 $courseinstancenumbertext = "";
9415 $userinstancenumbertext = "";
9418 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9420 $settings .= $OUTPUT->container_start('mdl-left');
9421 $settings .= '<br/>';
9422 $settings .= $admininstancenumbertext;
9423 $settings .= '<br/>';
9424 $settings .= $courseinstancenumbertext;
9425 $settings .= '<br/>';
9426 $settings .= $userinstancenumbertext;
9427 $settings .= $OUTPUT->container_end();
9429 // Get the current visibility
9430 if ($i->get_visible()) {
9431 $currentaction = 'show';
9432 } else {
9433 $currentaction = 'hide';
9436 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9438 // Display up/down link
9439 $updown = '';
9440 // Should be done with CSS instead.
9441 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9443 if ($updowncount > 1) {
9444 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9445 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9447 else {
9448 $updown .= $spacer;
9450 if ($updowncount < $totalrepositorytypes) {
9451 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9452 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9454 else {
9455 $updown .= $spacer;
9458 $updowncount++;
9460 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9462 if (!in_array($typename, $alreadyplugins)) {
9463 $alreadyplugins[] = $typename;
9468 // Get all the plugins that exist on disk
9469 $plugins = core_component::get_plugin_list('repository');
9470 if (!empty($plugins)) {
9471 foreach ($plugins as $plugin => $dir) {
9472 // Check that it has not already been listed
9473 if (!in_array($plugin, $alreadyplugins)) {
9474 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9475 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9480 $return .= html_writer::table($table);
9481 $return .= $OUTPUT->box_end();
9482 return highlight($query, $return);
9487 * Special checkbox for enable mobile web service
9488 * If enable then we store the service id of the mobile service into config table
9489 * If disable then we unstore the service id from the config table
9491 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9493 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9494 private $restuse;
9497 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9499 * @return boolean
9501 private function is_protocol_cap_allowed() {
9502 global $DB, $CFG;
9504 // If the $this->restuse variable is not set, it needs to be set.
9505 if (empty($this->restuse) and $this->restuse!==false) {
9506 $params = array();
9507 $params['permission'] = CAP_ALLOW;
9508 $params['roleid'] = $CFG->defaultuserroleid;
9509 $params['capability'] = 'webservice/rest:use';
9510 $this->restuse = $DB->record_exists('role_capabilities', $params);
9513 return $this->restuse;
9517 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9518 * @param type $status true to allow, false to not set
9520 private function set_protocol_cap($status) {
9521 global $CFG;
9522 if ($status and !$this->is_protocol_cap_allowed()) {
9523 //need to allow the cap
9524 $permission = CAP_ALLOW;
9525 $assign = true;
9526 } else if (!$status and $this->is_protocol_cap_allowed()){
9527 //need to disallow the cap
9528 $permission = CAP_INHERIT;
9529 $assign = true;
9531 if (!empty($assign)) {
9532 $systemcontext = context_system::instance();
9533 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9538 * Builds XHTML to display the control.
9539 * The main purpose of this overloading is to display a warning when https
9540 * is not supported by the server
9541 * @param string $data Unused
9542 * @param string $query
9543 * @return string XHTML
9545 public function output_html($data, $query='') {
9546 global $OUTPUT;
9547 $html = parent::output_html($data, $query);
9549 if ((string)$data === $this->yes) {
9550 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9551 foreach ($notifications as $notification) {
9552 $message = get_string($notification[0], $notification[1]);
9553 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9557 return $html;
9561 * Retrieves the current setting using the objects name
9563 * @return string
9565 public function get_setting() {
9566 global $CFG;
9568 // First check if is not set.
9569 $result = $this->config_read($this->name);
9570 if (is_null($result)) {
9571 return null;
9574 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9575 // Or if web services aren't enabled this can't be,
9576 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9577 return 0;
9580 require_once($CFG->dirroot . '/webservice/lib.php');
9581 $webservicemanager = new webservice();
9582 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9583 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9584 return $result;
9585 } else {
9586 return 0;
9591 * Save the selected setting
9593 * @param string $data The selected site
9594 * @return string empty string or error message
9596 public function write_setting($data) {
9597 global $DB, $CFG;
9599 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9600 if (empty($CFG->defaultuserroleid)) {
9601 return '';
9604 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9606 require_once($CFG->dirroot . '/webservice/lib.php');
9607 $webservicemanager = new webservice();
9609 $updateprotocol = false;
9610 if ((string)$data === $this->yes) {
9611 //code run when enable mobile web service
9612 //enable web service systeme if necessary
9613 set_config('enablewebservices', true);
9615 //enable mobile service
9616 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9617 $mobileservice->enabled = 1;
9618 $webservicemanager->update_external_service($mobileservice);
9620 // Enable REST server.
9621 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9623 if (!in_array('rest', $activeprotocols)) {
9624 $activeprotocols[] = 'rest';
9625 $updateprotocol = true;
9628 if ($updateprotocol) {
9629 set_config('webserviceprotocols', implode(',', $activeprotocols));
9632 // Allow rest:use capability for authenticated user.
9633 $this->set_protocol_cap(true);
9634 } else {
9635 // Disable the mobile service.
9636 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9637 $mobileservice->enabled = 0;
9638 $webservicemanager->update_external_service($mobileservice);
9641 return (parent::write_setting($data));
9646 * Special class for management of external services
9648 * @author Petr Skoda (skodak)
9650 class admin_setting_manageexternalservices extends admin_setting {
9652 * Calls parent::__construct with specific arguments
9654 public function __construct() {
9655 $this->nosave = true;
9656 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9660 * Always returns true, does nothing
9662 * @return true
9664 public function get_setting() {
9665 return true;
9669 * Always returns true, does nothing
9671 * @return true
9673 public function get_defaultsetting() {
9674 return true;
9678 * Always returns '', does not write anything
9680 * @return string Always returns ''
9682 public function write_setting($data) {
9683 // do not write any setting
9684 return '';
9688 * Checks if $query is one of the available external services
9690 * @param string $query The string to search for
9691 * @return bool Returns true if found, false if not
9693 public function is_related($query) {
9694 global $DB;
9696 if (parent::is_related($query)) {
9697 return true;
9700 $services = $DB->get_records('external_services', array(), 'id, name');
9701 foreach ($services as $service) {
9702 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9703 return true;
9706 return false;
9710 * Builds the XHTML to display the control
9712 * @param string $data Unused
9713 * @param string $query
9714 * @return string
9716 public function output_html($data, $query='') {
9717 global $CFG, $OUTPUT, $DB;
9719 // display strings
9720 $stradministration = get_string('administration');
9721 $stredit = get_string('edit');
9722 $strservice = get_string('externalservice', 'webservice');
9723 $strdelete = get_string('delete');
9724 $strplugin = get_string('plugin', 'admin');
9725 $stradd = get_string('add');
9726 $strfunctions = get_string('functions', 'webservice');
9727 $strusers = get_string('users');
9728 $strserviceusers = get_string('serviceusers', 'webservice');
9730 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9731 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9732 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9734 // built in services
9735 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9736 $return = "";
9737 if (!empty($services)) {
9738 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9742 $table = new html_table();
9743 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9744 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9745 $table->id = 'builtinservices';
9746 $table->attributes['class'] = 'admintable externalservices generaltable';
9747 $table->data = array();
9749 // iterate through auth plugins and add to the display table
9750 foreach ($services as $service) {
9751 $name = $service->name;
9753 // hide/show link
9754 if ($service->enabled) {
9755 $displayname = "<span>$name</span>";
9756 } else {
9757 $displayname = "<span class=\"dimmed_text\">$name</span>";
9760 $plugin = $service->component;
9762 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9764 if ($service->restrictedusers) {
9765 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9766 } else {
9767 $users = get_string('allusers', 'webservice');
9770 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9772 // add a row to the table
9773 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9775 $return .= html_writer::table($table);
9778 // Custom services
9779 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9780 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9782 $table = new html_table();
9783 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9784 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9785 $table->id = 'customservices';
9786 $table->attributes['class'] = 'admintable externalservices generaltable';
9787 $table->data = array();
9789 // iterate through auth plugins and add to the display table
9790 foreach ($services as $service) {
9791 $name = $service->name;
9793 // hide/show link
9794 if ($service->enabled) {
9795 $displayname = "<span>$name</span>";
9796 } else {
9797 $displayname = "<span class=\"dimmed_text\">$name</span>";
9800 // delete link
9801 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9803 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9805 if ($service->restrictedusers) {
9806 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9807 } else {
9808 $users = get_string('allusers', 'webservice');
9811 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9813 // add a row to the table
9814 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9816 // add new custom service option
9817 $return .= html_writer::table($table);
9819 $return .= '<br />';
9820 // add a token to the table
9821 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9823 return highlight($query, $return);
9828 * Special class for overview of external services
9830 * @author Jerome Mouneyrac
9832 class admin_setting_webservicesoverview extends admin_setting {
9835 * Calls parent::__construct with specific arguments
9837 public function __construct() {
9838 $this->nosave = true;
9839 parent::__construct('webservicesoverviewui',
9840 get_string('webservicesoverview', 'webservice'), '', '');
9844 * Always returns true, does nothing
9846 * @return true
9848 public function get_setting() {
9849 return true;
9853 * Always returns true, does nothing
9855 * @return true
9857 public function get_defaultsetting() {
9858 return true;
9862 * Always returns '', does not write anything
9864 * @return string Always returns ''
9866 public function write_setting($data) {
9867 // do not write any setting
9868 return '';
9872 * Builds the XHTML to display the control
9874 * @param string $data Unused
9875 * @param string $query
9876 * @return string
9878 public function output_html($data, $query='') {
9879 global $CFG, $OUTPUT;
9881 $return = "";
9882 $brtag = html_writer::empty_tag('br');
9884 /// One system controlling Moodle with Token
9885 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9886 $table = new html_table();
9887 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9888 get_string('description'));
9889 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9890 $table->id = 'onesystemcontrol';
9891 $table->attributes['class'] = 'admintable wsoverview generaltable';
9892 $table->data = array();
9894 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9895 . $brtag . $brtag;
9897 /// 1. Enable Web Services
9898 $row = array();
9899 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9900 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9901 array('href' => $url));
9902 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
9903 if ($CFG->enablewebservices) {
9904 $status = get_string('yes');
9906 $row[1] = $status;
9907 $row[2] = get_string('enablewsdescription', 'webservice');
9908 $table->data[] = $row;
9910 /// 2. Enable protocols
9911 $row = array();
9912 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9913 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9914 array('href' => $url));
9915 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
9916 //retrieve activated protocol
9917 $active_protocols = empty($CFG->webserviceprotocols) ?
9918 array() : explode(',', $CFG->webserviceprotocols);
9919 if (!empty($active_protocols)) {
9920 $status = "";
9921 foreach ($active_protocols as $protocol) {
9922 $status .= $protocol . $brtag;
9925 $row[1] = $status;
9926 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9927 $table->data[] = $row;
9929 /// 3. Create user account
9930 $row = array();
9931 $url = new moodle_url("/user/editadvanced.php?id=-1");
9932 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9933 array('href' => $url));
9934 $row[1] = "";
9935 $row[2] = get_string('createuserdescription', 'webservice');
9936 $table->data[] = $row;
9938 /// 4. Add capability to users
9939 $row = array();
9940 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9941 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9942 array('href' => $url));
9943 $row[1] = "";
9944 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9945 $table->data[] = $row;
9947 /// 5. Select a web service
9948 $row = array();
9949 $url = new moodle_url("/admin/settings.php?section=externalservices");
9950 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9951 array('href' => $url));
9952 $row[1] = "";
9953 $row[2] = get_string('createservicedescription', 'webservice');
9954 $table->data[] = $row;
9956 /// 6. Add functions
9957 $row = array();
9958 $url = new moodle_url("/admin/settings.php?section=externalservices");
9959 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9960 array('href' => $url));
9961 $row[1] = "";
9962 $row[2] = get_string('addfunctionsdescription', 'webservice');
9963 $table->data[] = $row;
9965 /// 7. Add the specific user
9966 $row = array();
9967 $url = new moodle_url("/admin/settings.php?section=externalservices");
9968 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9969 array('href' => $url));
9970 $row[1] = "";
9971 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9972 $table->data[] = $row;
9974 /// 8. Create token for the specific user
9975 $row = array();
9976 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
9977 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9978 array('href' => $url));
9979 $row[1] = "";
9980 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9981 $table->data[] = $row;
9983 /// 9. Enable the documentation
9984 $row = array();
9985 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9986 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9987 array('href' => $url));
9988 $status = '<span class="warning">' . get_string('no') . '</span>';
9989 if ($CFG->enablewsdocumentation) {
9990 $status = get_string('yes');
9992 $row[1] = $status;
9993 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9994 $table->data[] = $row;
9996 /// 10. Test the service
9997 $row = array();
9998 $url = new moodle_url("/admin/webservice/testclient.php");
9999 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10000 array('href' => $url));
10001 $row[1] = "";
10002 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10003 $table->data[] = $row;
10005 $return .= html_writer::table($table);
10007 /// Users as clients with token
10008 $return .= $brtag . $brtag . $brtag;
10009 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10010 $table = new html_table();
10011 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10012 get_string('description'));
10013 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10014 $table->id = 'userasclients';
10015 $table->attributes['class'] = 'admintable wsoverview generaltable';
10016 $table->data = array();
10018 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10019 $brtag . $brtag;
10021 /// 1. Enable Web Services
10022 $row = array();
10023 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10024 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10025 array('href' => $url));
10026 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10027 if ($CFG->enablewebservices) {
10028 $status = get_string('yes');
10030 $row[1] = $status;
10031 $row[2] = get_string('enablewsdescription', 'webservice');
10032 $table->data[] = $row;
10034 /// 2. Enable protocols
10035 $row = array();
10036 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10037 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10038 array('href' => $url));
10039 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10040 //retrieve activated protocol
10041 $active_protocols = empty($CFG->webserviceprotocols) ?
10042 array() : explode(',', $CFG->webserviceprotocols);
10043 if (!empty($active_protocols)) {
10044 $status = "";
10045 foreach ($active_protocols as $protocol) {
10046 $status .= $protocol . $brtag;
10049 $row[1] = $status;
10050 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10051 $table->data[] = $row;
10054 /// 3. Select a web service
10055 $row = array();
10056 $url = new moodle_url("/admin/settings.php?section=externalservices");
10057 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10058 array('href' => $url));
10059 $row[1] = "";
10060 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10061 $table->data[] = $row;
10063 /// 4. Add functions
10064 $row = array();
10065 $url = new moodle_url("/admin/settings.php?section=externalservices");
10066 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10067 array('href' => $url));
10068 $row[1] = "";
10069 $row[2] = get_string('addfunctionsdescription', 'webservice');
10070 $table->data[] = $row;
10072 /// 5. Add capability to users
10073 $row = array();
10074 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10075 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10076 array('href' => $url));
10077 $row[1] = "";
10078 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10079 $table->data[] = $row;
10081 /// 6. Test the service
10082 $row = array();
10083 $url = new moodle_url("/admin/webservice/testclient.php");
10084 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10085 array('href' => $url));
10086 $row[1] = "";
10087 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10088 $table->data[] = $row;
10090 $return .= html_writer::table($table);
10092 return highlight($query, $return);
10099 * Special class for web service protocol administration.
10101 * @author Petr Skoda (skodak)
10103 class admin_setting_managewebserviceprotocols extends admin_setting {
10106 * Calls parent::__construct with specific arguments
10108 public function __construct() {
10109 $this->nosave = true;
10110 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10114 * Always returns true, does nothing
10116 * @return true
10118 public function get_setting() {
10119 return true;
10123 * Always returns true, does nothing
10125 * @return true
10127 public function get_defaultsetting() {
10128 return true;
10132 * Always returns '', does not write anything
10134 * @return string Always returns ''
10136 public function write_setting($data) {
10137 // do not write any setting
10138 return '';
10142 * Checks if $query is one of the available webservices
10144 * @param string $query The string to search for
10145 * @return bool Returns true if found, false if not
10147 public function is_related($query) {
10148 if (parent::is_related($query)) {
10149 return true;
10152 $protocols = core_component::get_plugin_list('webservice');
10153 foreach ($protocols as $protocol=>$location) {
10154 if (strpos($protocol, $query) !== false) {
10155 return true;
10157 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10158 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10159 return true;
10162 return false;
10166 * Builds the XHTML to display the control
10168 * @param string $data Unused
10169 * @param string $query
10170 * @return string
10172 public function output_html($data, $query='') {
10173 global $CFG, $OUTPUT;
10175 // display strings
10176 $stradministration = get_string('administration');
10177 $strsettings = get_string('settings');
10178 $stredit = get_string('edit');
10179 $strprotocol = get_string('protocol', 'webservice');
10180 $strenable = get_string('enable');
10181 $strdisable = get_string('disable');
10182 $strversion = get_string('version');
10184 $protocols_available = core_component::get_plugin_list('webservice');
10185 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10186 ksort($protocols_available);
10188 foreach ($activeprotocols as $key => $protocol) {
10189 if (empty($protocols_available[$protocol])) {
10190 unset($activeprotocols[$key]);
10194 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10195 if (in_array('xmlrpc', $activeprotocols)) {
10196 $notify = new \core\output\notification(get_string('xmlrpcwebserviceenabled', 'admin'),
10197 \core\output\notification::NOTIFY_WARNING);
10198 $return .= $OUTPUT->render($notify);
10200 $return .= $OUTPUT->box_start('generalbox webservicesui');
10202 $table = new html_table();
10203 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10204 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10205 $table->id = 'webserviceprotocols';
10206 $table->attributes['class'] = 'admintable generaltable';
10207 $table->data = array();
10209 // iterate through auth plugins and add to the display table
10210 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10211 foreach ($protocols_available as $protocol => $location) {
10212 $name = get_string('pluginname', 'webservice_'.$protocol);
10214 $plugin = new stdClass();
10215 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10216 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10218 $version = isset($plugin->version) ? $plugin->version : '';
10220 // hide/show link
10221 if (in_array($protocol, $activeprotocols)) {
10222 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10223 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10224 $displayname = "<span>$name</span>";
10225 } else {
10226 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10227 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10228 $displayname = "<span class=\"dimmed_text\">$name</span>";
10231 // settings link
10232 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10233 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10234 } else {
10235 $settings = '';
10238 // add a row to the table
10239 $table->data[] = array($displayname, $version, $hideshow, $settings);
10241 $return .= html_writer::table($table);
10242 $return .= get_string('configwebserviceplugins', 'webservice');
10243 $return .= $OUTPUT->box_end();
10245 return highlight($query, $return);
10250 * Colour picker
10252 * @copyright 2010 Sam Hemelryk
10253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10255 class admin_setting_configcolourpicker extends admin_setting {
10258 * Information for previewing the colour
10260 * @var array|null
10262 protected $previewconfig = null;
10265 * Use default when empty.
10267 protected $usedefaultwhenempty = true;
10271 * @param string $name
10272 * @param string $visiblename
10273 * @param string $description
10274 * @param string $defaultsetting
10275 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10277 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10278 $usedefaultwhenempty = true) {
10279 $this->previewconfig = $previewconfig;
10280 $this->usedefaultwhenempty = $usedefaultwhenempty;
10281 parent::__construct($name, $visiblename, $description, $defaultsetting);
10282 $this->set_force_ltr(true);
10286 * Return the setting
10288 * @return mixed returns config if successful else null
10290 public function get_setting() {
10291 return $this->config_read($this->name);
10295 * Saves the setting
10297 * @param string $data
10298 * @return bool
10300 public function write_setting($data) {
10301 $data = $this->validate($data);
10302 if ($data === false) {
10303 return get_string('validateerror', 'admin');
10305 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10309 * Validates the colour that was entered by the user
10311 * @param string $data
10312 * @return string|false
10314 protected function validate($data) {
10316 * List of valid HTML colour names
10318 * @var array
10320 $colornames = array(
10321 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10322 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10323 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10324 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10325 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10326 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10327 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10328 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10329 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10330 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10331 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10332 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10333 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10334 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10335 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10336 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10337 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10338 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10339 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10340 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10341 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10342 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10343 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10344 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10345 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10346 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10347 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10348 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10349 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10350 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10351 'whitesmoke', 'yellow', 'yellowgreen'
10354 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10355 if (strpos($data, '#')!==0) {
10356 $data = '#'.$data;
10358 return $data;
10359 } else if (in_array(strtolower($data), $colornames)) {
10360 return $data;
10361 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10362 return $data;
10363 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10364 return $data;
10365 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10366 return $data;
10367 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10368 return $data;
10369 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10370 return $data;
10371 } else if (empty($data)) {
10372 if ($this->usedefaultwhenempty){
10373 return $this->defaultsetting;
10374 } else {
10375 return '';
10377 } else {
10378 return false;
10383 * Generates the HTML for the setting
10385 * @global moodle_page $PAGE
10386 * @global core_renderer $OUTPUT
10387 * @param string $data
10388 * @param string $query
10390 public function output_html($data, $query = '') {
10391 global $PAGE, $OUTPUT;
10393 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10394 $context = (object) [
10395 'id' => $this->get_id(),
10396 'name' => $this->get_full_name(),
10397 'value' => $data,
10398 'icon' => $icon->export_for_template($OUTPUT),
10399 'haspreviewconfig' => !empty($this->previewconfig),
10400 'forceltr' => $this->get_force_ltr(),
10401 'readonly' => $this->is_readonly(),
10404 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10405 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10407 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10408 $this->get_defaultsetting(), $query);
10415 * Class used for uploading of one file into file storage,
10416 * the file name is stored in config table.
10418 * Please note you need to implement your own '_pluginfile' callback function,
10419 * this setting only stores the file, it does not deal with file serving.
10421 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10424 class admin_setting_configstoredfile extends admin_setting {
10425 /** @var array file area options - should be one file only */
10426 protected $options;
10427 /** @var string name of the file area */
10428 protected $filearea;
10429 /** @var int intemid */
10430 protected $itemid;
10431 /** @var string used for detection of changes */
10432 protected $oldhashes;
10435 * Create new stored file setting.
10437 * @param string $name low level setting name
10438 * @param string $visiblename human readable setting name
10439 * @param string $description description of setting
10440 * @param mixed $filearea file area for file storage
10441 * @param int $itemid itemid for file storage
10442 * @param array $options file area options
10444 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10445 parent::__construct($name, $visiblename, $description, '');
10446 $this->filearea = $filearea;
10447 $this->itemid = $itemid;
10448 $this->options = (array)$options;
10449 $this->customcontrol = true;
10453 * Applies defaults and returns all options.
10454 * @return array
10456 protected function get_options() {
10457 global $CFG;
10459 require_once("$CFG->libdir/filelib.php");
10460 require_once("$CFG->dirroot/repository/lib.php");
10461 $defaults = array(
10462 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10463 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10464 'context' => context_system::instance());
10465 foreach($this->options as $k => $v) {
10466 $defaults[$k] = $v;
10469 return $defaults;
10472 public function get_setting() {
10473 return $this->config_read($this->name);
10476 public function write_setting($data) {
10477 global $USER;
10479 // Let's not deal with validation here, this is for admins only.
10480 $current = $this->get_setting();
10481 if (empty($data) && $current === null) {
10482 // This will be the case when applying default settings (installation).
10483 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10484 } else if (!is_number($data)) {
10485 // Draft item id is expected here!
10486 return get_string('errorsetting', 'admin');
10489 $options = $this->get_options();
10490 $fs = get_file_storage();
10491 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10493 $this->oldhashes = null;
10494 if ($current) {
10495 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10496 if ($file = $fs->get_file_by_hash($hash)) {
10497 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10499 unset($file);
10502 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10503 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10504 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10505 // with an error because the draft area does not exist, as he did not use it.
10506 $usercontext = context_user::instance($USER->id);
10507 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10508 return get_string('errorsetting', 'admin');
10512 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10513 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10515 $filepath = '';
10516 if ($files) {
10517 /** @var stored_file $file */
10518 $file = reset($files);
10519 $filepath = $file->get_filepath().$file->get_filename();
10522 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10525 public function post_write_settings($original) {
10526 $options = $this->get_options();
10527 $fs = get_file_storage();
10528 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10530 $current = $this->get_setting();
10531 $newhashes = null;
10532 if ($current) {
10533 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10534 if ($file = $fs->get_file_by_hash($hash)) {
10535 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10537 unset($file);
10540 if ($this->oldhashes === $newhashes) {
10541 $this->oldhashes = null;
10542 return false;
10544 $this->oldhashes = null;
10546 $callbackfunction = $this->updatedcallback;
10547 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10548 $callbackfunction($this->get_full_name());
10550 return true;
10553 public function output_html($data, $query = '') {
10554 global $CFG;
10556 $options = $this->get_options();
10557 $id = $this->get_id();
10558 $elname = $this->get_full_name();
10559 $draftitemid = file_get_submitted_draft_itemid($elname);
10560 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10561 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10563 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10564 require_once("$CFG->dirroot/lib/form/filemanager.php");
10566 $fmoptions = new stdClass();
10567 $fmoptions->mainfile = $options['mainfile'];
10568 $fmoptions->maxbytes = $options['maxbytes'];
10569 $fmoptions->maxfiles = $options['maxfiles'];
10570 $fmoptions->subdirs = $options['subdirs'];
10571 $fmoptions->accepted_types = $options['accepted_types'];
10572 $fmoptions->return_types = $options['return_types'];
10573 $fmoptions->context = $options['context'];
10574 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10576 $fm = new MoodleQuickForm_filemanager($elname, $this->visiblename, ['id' => $id], $fmoptions);
10577 $fm->setValue($draftitemid);
10579 return format_admin_setting($this, $this->visiblename,
10580 '<div class="form-filemanager" data-fieldtype="filemanager">' . $fm->toHtml() . '</div>',
10581 $this->description, true, '', '', $query);
10587 * Administration interface for user specified regular expressions for device detection.
10589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10591 class admin_setting_devicedetectregex extends admin_setting {
10594 * Calls parent::__construct with specific args
10596 * @param string $name
10597 * @param string $visiblename
10598 * @param string $description
10599 * @param mixed $defaultsetting
10601 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10602 global $CFG;
10603 parent::__construct($name, $visiblename, $description, $defaultsetting);
10607 * Return the current setting(s)
10609 * @return array Current settings array
10611 public function get_setting() {
10612 global $CFG;
10614 $config = $this->config_read($this->name);
10615 if (is_null($config)) {
10616 return null;
10619 return $this->prepare_form_data($config);
10623 * Save selected settings
10625 * @param array $data Array of settings to save
10626 * @return bool
10628 public function write_setting($data) {
10629 if (empty($data)) {
10630 $data = array();
10633 if ($this->config_write($this->name, $this->process_form_data($data))) {
10634 return ''; // success
10635 } else {
10636 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10641 * Return XHTML field(s) for regexes
10643 * @param array $data Array of options to set in HTML
10644 * @return string XHTML string for the fields and wrapping div(s)
10646 public function output_html($data, $query='') {
10647 global $OUTPUT;
10649 $context = (object) [
10650 'expressions' => [],
10651 'name' => $this->get_full_name()
10654 if (empty($data)) {
10655 $looplimit = 1;
10656 } else {
10657 $looplimit = (count($data)/2)+1;
10660 for ($i=0; $i<$looplimit; $i++) {
10662 $expressionname = 'expression'.$i;
10664 if (!empty($data[$expressionname])){
10665 $expression = $data[$expressionname];
10666 } else {
10667 $expression = '';
10670 $valuename = 'value'.$i;
10672 if (!empty($data[$valuename])){
10673 $value = $data[$valuename];
10674 } else {
10675 $value= '';
10678 $context->expressions[] = [
10679 'index' => $i,
10680 'expression' => $expression,
10681 'value' => $value
10685 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10687 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10691 * Converts the string of regexes
10693 * @see self::process_form_data()
10694 * @param $regexes string of regexes
10695 * @return array of form fields and their values
10697 protected function prepare_form_data($regexes) {
10699 $regexes = json_decode($regexes);
10701 $form = array();
10703 $i = 0;
10705 foreach ($regexes as $value => $regex) {
10706 $expressionname = 'expression'.$i;
10707 $valuename = 'value'.$i;
10709 $form[$expressionname] = $regex;
10710 $form[$valuename] = $value;
10711 $i++;
10714 return $form;
10718 * Converts the data from admin settings form into a string of regexes
10720 * @see self::prepare_form_data()
10721 * @param array $data array of admin form fields and values
10722 * @return false|string of regexes
10724 protected function process_form_data(array $form) {
10726 $count = count($form); // number of form field values
10728 if ($count % 2) {
10729 // we must get five fields per expression
10730 return false;
10733 $regexes = array();
10734 for ($i = 0; $i < $count / 2; $i++) {
10735 $expressionname = "expression".$i;
10736 $valuename = "value".$i;
10738 $expression = trim($form['expression'.$i]);
10739 $value = trim($form['value'.$i]);
10741 if (empty($expression)){
10742 continue;
10745 $regexes[$value] = $expression;
10748 $regexes = json_encode($regexes);
10750 return $regexes;
10756 * Multiselect for current modules
10758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10760 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10761 private $excludesystem;
10764 * Calls parent::__construct - note array $choices is not required
10766 * @param string $name setting name
10767 * @param string $visiblename localised setting name
10768 * @param string $description setting description
10769 * @param array $defaultsetting a plain array of default module ids
10770 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10772 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10773 $excludesystem = true) {
10774 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10775 $this->excludesystem = $excludesystem;
10779 * Loads an array of current module choices
10781 * @return bool always return true
10783 public function load_choices() {
10784 if (is_array($this->choices)) {
10785 return true;
10787 $this->choices = array();
10789 global $CFG, $DB;
10790 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10791 foreach ($records as $record) {
10792 // Exclude modules if the code doesn't exist
10793 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10794 // Also exclude system modules (if specified)
10795 if (!($this->excludesystem &&
10796 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10797 MOD_ARCHETYPE_SYSTEM)) {
10798 $this->choices[$record->id] = $record->name;
10802 return true;
10807 * Admin setting to show if a php extension is enabled or not.
10809 * @copyright 2013 Damyon Wiese
10810 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10812 class admin_setting_php_extension_enabled extends admin_setting {
10814 /** @var string The name of the extension to check for */
10815 private $extension;
10818 * Calls parent::__construct with specific arguments
10820 public function __construct($name, $visiblename, $description, $extension) {
10821 $this->extension = $extension;
10822 $this->nosave = true;
10823 parent::__construct($name, $visiblename, $description, '');
10827 * Always returns true, does nothing
10829 * @return true
10831 public function get_setting() {
10832 return true;
10836 * Always returns true, does nothing
10838 * @return true
10840 public function get_defaultsetting() {
10841 return true;
10845 * Always returns '', does not write anything
10847 * @return string Always returns ''
10849 public function write_setting($data) {
10850 // Do not write any setting.
10851 return '';
10855 * Outputs the html for this setting.
10856 * @return string Returns an XHTML string
10858 public function output_html($data, $query='') {
10859 global $OUTPUT;
10861 $o = '';
10862 if (!extension_loaded($this->extension)) {
10863 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10865 $o .= format_admin_setting($this, $this->visiblename, $warning);
10867 return $o;
10872 * Server timezone setting.
10874 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10876 * @author Petr Skoda <petr.skoda@totaralms.com>
10878 class admin_setting_servertimezone extends admin_setting_configselect {
10880 * Constructor.
10882 public function __construct() {
10883 $default = core_date::get_default_php_timezone();
10884 if ($default === 'UTC') {
10885 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10886 $default = 'Europe/London';
10889 parent::__construct('timezone',
10890 new lang_string('timezone', 'core_admin'),
10891 new lang_string('configtimezone', 'core_admin'), $default, null);
10895 * Lazy load timezone options.
10896 * @return bool true if loaded, false if error
10898 public function load_choices() {
10899 global $CFG;
10900 if (is_array($this->choices)) {
10901 return true;
10904 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10905 $this->choices = core_date::get_list_of_timezones($current, false);
10906 if ($current == 99) {
10907 // Do not show 99 unless it is current value, we want to get rid of it over time.
10908 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10909 core_date::get_default_php_timezone());
10912 return true;
10917 * Forced user timezone setting.
10919 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10921 * @author Petr Skoda <petr.skoda@totaralms.com>
10923 class admin_setting_forcetimezone extends admin_setting_configselect {
10925 * Constructor.
10927 public function __construct() {
10928 parent::__construct('forcetimezone',
10929 new lang_string('forcetimezone', 'core_admin'),
10930 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10934 * Lazy load timezone options.
10935 * @return bool true if loaded, false if error
10937 public function load_choices() {
10938 global $CFG;
10939 if (is_array($this->choices)) {
10940 return true;
10943 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10944 $this->choices = core_date::get_list_of_timezones($current, true);
10945 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10947 return true;
10953 * Search setup steps info.
10955 * @package core
10956 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10957 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10959 class admin_setting_searchsetupinfo extends admin_setting {
10962 * Calls parent::__construct with specific arguments
10964 public function __construct() {
10965 $this->nosave = true;
10966 parent::__construct('searchsetupinfo', '', '', '');
10970 * Always returns true, does nothing
10972 * @return true
10974 public function get_setting() {
10975 return true;
10979 * Always returns true, does nothing
10981 * @return true
10983 public function get_defaultsetting() {
10984 return true;
10988 * Always returns '', does not write anything
10990 * @param array $data
10991 * @return string Always returns ''
10993 public function write_setting($data) {
10994 // Do not write any setting.
10995 return '';
10999 * Builds the HTML to display the control
11001 * @param string $data Unused
11002 * @param string $query
11003 * @return string
11005 public function output_html($data, $query='') {
11006 global $CFG, $OUTPUT, $ADMIN;
11008 $return = '';
11009 $brtag = html_writer::empty_tag('br');
11011 $searchareas = \core_search\manager::get_search_areas_list();
11012 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11013 $anyindexed = false;
11014 foreach ($searchareas as $areaid => $searcharea) {
11015 list($componentname, $varname) = $searcharea->get_config_var_name();
11016 if (get_config($componentname, $varname . '_indexingstart')) {
11017 $anyindexed = true;
11018 break;
11022 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11024 $table = new html_table();
11025 $table->head = array(get_string('step', 'search'), get_string('status'));
11026 $table->colclasses = array('leftalign step', 'leftalign status');
11027 $table->id = 'searchsetup';
11028 $table->attributes['class'] = 'admintable generaltable';
11029 $table->data = array();
11031 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11033 // Select a search engine.
11034 $row = array();
11035 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11036 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11037 array('href' => $url));
11039 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11040 if (!empty($CFG->searchengine)) {
11041 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11042 array('class' => 'badge badge-success'));
11045 $row[1] = $status;
11046 $table->data[] = $row;
11048 // Available areas.
11049 $row = array();
11050 $url = new moodle_url('/admin/searchareas.php');
11051 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11052 array('href' => $url));
11054 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11055 if ($anyenabled) {
11056 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11059 $row[1] = $status;
11060 $table->data[] = $row;
11062 // Setup search engine.
11063 $row = array();
11064 if (empty($CFG->searchengine)) {
11065 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11066 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11067 } else {
11068 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11069 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11070 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11071 } else {
11072 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11075 // Check the engine status.
11076 $searchengine = \core_search\manager::search_engine_instance();
11077 try {
11078 $serverstatus = $searchengine->is_server_ready();
11079 } catch (\moodle_exception $e) {
11080 $serverstatus = $e->getMessage();
11082 if ($serverstatus === true) {
11083 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11084 } else {
11085 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11087 $row[1] = $status;
11089 $table->data[] = $row;
11091 // Indexed data.
11092 $row = array();
11093 $url = new moodle_url('/admin/searchareas.php');
11094 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11095 if ($anyindexed) {
11096 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11097 } else {
11098 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11100 $row[1] = $status;
11101 $table->data[] = $row;
11103 // Enable global search.
11104 $row = array();
11105 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11106 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11107 array('href' => $url));
11108 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11109 if (\core_search\manager::is_global_search_enabled()) {
11110 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11112 $row[1] = $status;
11113 $table->data[] = $row;
11115 // Replace front page search.
11116 $row = array();
11117 $url = new moodle_url("/admin/search.php?query=searchincludeallcourses");
11118 $row[0] = '6. ' . html_writer::tag('a', get_string('replacefrontsearch', 'admin'),
11119 array('href' => $url));
11120 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11121 if (\core_search\manager::can_replace_course_search()) {
11122 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11124 $row[1] = $status;
11125 $table->data[] = $row;
11127 $return .= html_writer::table($table);
11129 return highlight($query, $return);
11135 * Used to validate the contents of SCSS code and ensuring they are parsable.
11137 * It does not attempt to detect undefined SCSS variables because it is designed
11138 * to be used without knowledge of other config/scss included.
11140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11141 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11143 class admin_setting_scsscode extends admin_setting_configtextarea {
11146 * Validate the contents of the SCSS to ensure its parsable. Does not
11147 * attempt to detect undefined scss variables.
11149 * @param string $data The scss code from text field.
11150 * @return mixed bool true for success or string:error on failure.
11152 public function validate($data) {
11153 if (empty($data)) {
11154 return true;
11157 $scss = new core_scss();
11158 try {
11159 $scss->compile($data);
11160 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11161 return get_string('scssinvalid', 'admin', $e->getMessage());
11162 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11163 // Silently ignore this - it could be a scss variable defined from somewhere
11164 // else which we are not examining here.
11165 return true;
11168 return true;
11174 * Administration setting to define a list of file types.
11176 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11177 * @copyright 2017 David Mudrák <david@moodle.com>
11178 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11180 class admin_setting_filetypes extends admin_setting_configtext {
11182 /** @var array Allow selection from these file types only. */
11183 protected $onlytypes = [];
11185 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11186 protected $allowall = true;
11188 /** @var core_form\filetypes_util instance to use as a helper. */
11189 protected $util = null;
11192 * Constructor.
11194 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11195 * @param string $visiblename Localised label of the setting
11196 * @param string $description Localised description of the setting
11197 * @param string $defaultsetting Default setting value.
11198 * @param array $options Setting widget options, an array with optional keys:
11199 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11200 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11202 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11204 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11206 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11207 $this->onlytypes = $options['onlytypes'];
11210 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11211 $this->allowall = (bool)$options['allowall'];
11214 $this->util = new \core_form\filetypes_util();
11218 * Normalize the user's input and write it to the database as comma separated list.
11220 * Comma separated list as a text representation of the array was chosen to
11221 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11223 * @param string $data Value submitted by the admin.
11224 * @return string Epty string if all good, error message otherwise.
11226 public function write_setting($data) {
11227 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11231 * Validate data before storage
11233 * @param string $data The setting values provided by the admin
11234 * @return bool|string True if ok, the string if error found
11236 public function validate($data) {
11237 $parentcheck = parent::validate($data);
11238 if ($parentcheck !== true) {
11239 return $parentcheck;
11242 // Check for unknown file types.
11243 if ($unknown = $this->util->get_unknown_file_types($data)) {
11244 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11247 // Check for disallowed file types.
11248 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11249 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11252 return true;
11256 * Return an HTML string for the setting element.
11258 * @param string $data The current setting value
11259 * @param string $query Admin search query to be highlighted
11260 * @return string HTML to be displayed
11262 public function output_html($data, $query='') {
11263 global $OUTPUT, $PAGE;
11265 $default = $this->get_defaultsetting();
11266 $context = (object) [
11267 'id' => $this->get_id(),
11268 'name' => $this->get_full_name(),
11269 'value' => $data,
11270 'descriptions' => $this->util->describe_file_types($data),
11272 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11274 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11275 $this->get_id(),
11276 $this->visiblename->out(),
11277 $this->onlytypes,
11278 $this->allowall,
11281 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11285 * Should the values be always displayed in LTR mode?
11287 * We always return true here because these values are not RTL compatible.
11289 * @return bool True because these values are not RTL compatible.
11291 public function get_force_ltr() {
11292 return true;
11297 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11299 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11300 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11302 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11305 * Constructor.
11307 * @param string $name
11308 * @param string $visiblename
11309 * @param string $description
11310 * @param mixed $defaultsetting string or array
11311 * @param mixed $paramtype
11312 * @param string $cols
11313 * @param string $rows
11315 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11316 $cols = '60', $rows = '8') {
11317 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11318 // Pre-set force LTR to false.
11319 $this->set_force_ltr(false);
11323 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11325 * @param string $data The age of digital consent map from text field.
11326 * @return mixed bool true for success or string:error on failure.
11328 public function validate($data) {
11329 if (empty($data)) {
11330 return true;
11333 try {
11334 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11335 } catch (\moodle_exception $e) {
11336 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11339 return true;
11344 * Selection of plugins that can work as site policy handlers
11346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11347 * @copyright 2018 Marina Glancy
11349 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11352 * Constructor
11353 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11354 * for ones in config_plugins.
11355 * @param string $visiblename localised
11356 * @param string $description long localised info
11357 * @param string $defaultsetting
11359 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11360 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11364 * Lazy-load the available choices for the select box
11366 public function load_choices() {
11367 if (during_initial_install()) {
11368 return false;
11370 if (is_array($this->choices)) {
11371 return true;
11374 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11375 $manager = new \core_privacy\local\sitepolicy\manager();
11376 $plugins = $manager->get_all_handlers();
11377 foreach ($plugins as $pname => $unused) {
11378 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11379 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11382 return true;
11387 * Used to validate theme presets code and ensuring they compile well.
11389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11390 * @copyright 2019 Bas Brands <bas@moodle.com>
11392 class admin_setting_configthemepreset extends admin_setting_configselect {
11394 /** @var string The name of the theme to check for */
11395 private $themename;
11398 * Constructor
11399 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11400 * or 'myplugin/mysetting' for ones in config_plugins.
11401 * @param string $visiblename localised
11402 * @param string $description long localised info
11403 * @param string|int $defaultsetting
11404 * @param array $choices array of $value=>$label for each selection
11405 * @param string $themename name of theme to check presets for.
11407 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11408 $this->themename = $themename;
11409 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11413 * Write settings if validated
11415 * @param string $data
11416 * @return string
11418 public function write_setting($data) {
11419 $validated = $this->validate($data);
11420 if ($validated !== true) {
11421 return $validated;
11423 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11427 * Validate the preset file to ensure its parsable.
11429 * @param string $data The preset file chosen.
11430 * @return mixed bool true for success or string:error on failure.
11432 public function validate($data) {
11434 if (in_array($data, ['default.scss', 'plain.scss'])) {
11435 return true;
11438 $fs = get_file_storage();
11439 $theme = theme_config::load($this->themename);
11440 $context = context_system::instance();
11442 // If the preset has not changed there is no need to validate it.
11443 if ($theme->settings->preset == $data) {
11444 return true;
11447 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11448 // This operation uses a lot of resources.
11449 raise_memory_limit(MEMORY_EXTRA);
11450 core_php_time_limit::raise(300);
11452 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11453 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11455 $compiler = new core_scss();
11456 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11457 $compiler->append_raw_scss($presetfile->get_content());
11458 if ($scssproperties = $theme->get_scss_property()) {
11459 $compiler->setImportPaths($scssproperties[0]);
11461 $compiler->append_raw_scss($theme->get_extra_scss_code());
11463 try {
11464 $compiler->to_css();
11465 } catch (Exception $e) {
11466 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11469 // Try to save memory.
11470 $compiler = null;
11471 unset($compiler);
11474 return true;
11479 * Selection of plugins that can work as H5P libraries handlers
11481 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11482 * @copyright 2020 Sara Arjona <sara@moodle.com>
11484 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11487 * Constructor
11488 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11489 * for ones in config_plugins.
11490 * @param string $visiblename localised
11491 * @param string $description long localised info
11492 * @param string $defaultsetting
11494 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11495 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11499 * Lazy-load the available choices for the select box
11501 public function load_choices() {
11502 if (during_initial_install()) {
11503 return false;
11505 if (is_array($this->choices)) {
11506 return true;
11509 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11510 foreach ($this->choices as $name => $class) {
11511 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11512 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11515 return true;