MDL-70483 forum: Final deprecation of get_forum_discussions_paginated
[moodle.git] / lib / adminlib.php
blobcab188c99d5b90462d83584e339768ae2b001b4d
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)) {
374 $DB->get_manager()->delete_tables_from_xmldb_file($file);
375 return true;
378 // then try to find all tables that start with name and are not in any xml file
379 $used_tables = get_used_table_names();
381 $tables = $DB->get_tables();
383 /// Iterate over, fixing id fields as necessary
384 foreach ($tables as $table) {
385 if (in_array($table, $used_tables)) {
386 continue;
389 if (strpos($table, $name) !== 0) {
390 continue;
393 // found orphan table --> delete it
394 if ($DB->get_manager()->table_exists($table)) {
395 $xmldb_table = new xmldb_table($table);
396 $DB->get_manager()->drop_table($xmldb_table);
400 return true;
404 * Returns names of all known tables == tables that moodle knows about.
406 * @return array Array of lowercase table names
408 function get_used_table_names() {
409 $table_names = array();
410 $dbdirs = get_db_directories();
412 foreach ($dbdirs as $dbdir) {
413 $file = $dbdir.'/install.xml';
415 $xmldb_file = new xmldb_file($file);
417 if (!$xmldb_file->fileExists()) {
418 continue;
421 $loaded = $xmldb_file->loadXMLStructure();
422 $structure = $xmldb_file->getStructure();
424 if ($loaded and $tables = $structure->getTables()) {
425 foreach($tables as $table) {
426 $table_names[] = strtolower($table->getName());
431 return $table_names;
435 * Returns list of all directories where we expect install.xml files
436 * @return array Array of paths
438 function get_db_directories() {
439 global $CFG;
441 $dbdirs = array();
443 /// First, the main one (lib/db)
444 $dbdirs[] = $CFG->libdir.'/db';
446 /// Then, all the ones defined by core_component::get_plugin_types()
447 $plugintypes = core_component::get_plugin_types();
448 foreach ($plugintypes as $plugintype => $pluginbasedir) {
449 if ($plugins = core_component::get_plugin_list($plugintype)) {
450 foreach ($plugins as $plugin => $plugindir) {
451 $dbdirs[] = $plugindir.'/db';
456 return $dbdirs;
460 * Try to obtain or release the cron lock.
461 * @param string $name name of lock
462 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
463 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
464 * @return bool true if lock obtained
466 function set_cron_lock($name, $until, $ignorecurrent=false) {
467 global $DB;
468 if (empty($name)) {
469 debugging("Tried to get a cron lock for a null fieldname");
470 return false;
473 // remove lock by force == remove from config table
474 if (is_null($until)) {
475 set_config($name, null);
476 return true;
479 if (!$ignorecurrent) {
480 // read value from db - other processes might have changed it
481 $value = $DB->get_field('config', 'value', array('name'=>$name));
483 if ($value and $value > time()) {
484 //lock active
485 return false;
489 set_config($name, $until);
490 return true;
494 * Test if and critical warnings are present
495 * @return bool
497 function admin_critical_warnings_present() {
498 global $SESSION;
500 if (!has_capability('moodle/site:config', context_system::instance())) {
501 return 0;
504 if (!isset($SESSION->admin_critical_warning)) {
505 $SESSION->admin_critical_warning = 0;
506 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
507 $SESSION->admin_critical_warning = 1;
511 return $SESSION->admin_critical_warning;
515 * Detects if float supports at least 10 decimal digits
517 * Detects if float supports at least 10 decimal digits
518 * and also if float-->string conversion works as expected.
520 * @return bool true if problem found
522 function is_float_problem() {
523 $num1 = 2009010200.01;
524 $num2 = 2009010200.02;
526 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
530 * Try to verify that dataroot is not accessible from web.
532 * Try to verify that dataroot is not accessible from web.
533 * It is not 100% correct but might help to reduce number of vulnerable sites.
534 * Protection from httpd.conf and .htaccess is not detected properly.
536 * @uses INSECURE_DATAROOT_WARNING
537 * @uses INSECURE_DATAROOT_ERROR
538 * @param bool $fetchtest try to test public access by fetching file, default false
539 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
541 function is_dataroot_insecure($fetchtest=false) {
542 global $CFG;
544 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
546 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
547 $rp = strrev(trim($rp, '/'));
548 $rp = explode('/', $rp);
549 foreach($rp as $r) {
550 if (strpos($siteroot, '/'.$r.'/') === 0) {
551 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
552 } else {
553 break; // probably alias root
557 $siteroot = strrev($siteroot);
558 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
560 if (strpos($dataroot, $siteroot) !== 0) {
561 return false;
564 if (!$fetchtest) {
565 return INSECURE_DATAROOT_WARNING;
568 // now try all methods to fetch a test file using http protocol
570 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
571 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
572 $httpdocroot = $matches[1];
573 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
574 make_upload_directory('diag');
575 $testfile = $CFG->dataroot.'/diag/public.txt';
576 if (!file_exists($testfile)) {
577 file_put_contents($testfile, 'test file, do not delete');
578 @chmod($testfile, $CFG->filepermissions);
580 $teststr = trim(file_get_contents($testfile));
581 if (empty($teststr)) {
582 // hmm, strange
583 return INSECURE_DATAROOT_WARNING;
586 $testurl = $datarooturl.'/diag/public.txt';
587 if (extension_loaded('curl') and
588 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
589 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
590 ($ch = @curl_init($testurl)) !== false) {
591 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
592 curl_setopt($ch, CURLOPT_HEADER, false);
593 $data = curl_exec($ch);
594 if (!curl_errno($ch)) {
595 $data = trim($data);
596 if ($data === $teststr) {
597 curl_close($ch);
598 return INSECURE_DATAROOT_ERROR;
601 curl_close($ch);
604 if ($data = @file_get_contents($testurl)) {
605 $data = trim($data);
606 if ($data === $teststr) {
607 return INSECURE_DATAROOT_ERROR;
611 preg_match('|https?://([^/]+)|i', $testurl, $matches);
612 $sitename = $matches[1];
613 $error = 0;
614 if ($fp = @fsockopen($sitename, 80, $error)) {
615 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
616 $localurl = $matches[1];
617 $out = "GET $localurl HTTP/1.1\r\n";
618 $out .= "Host: $sitename\r\n";
619 $out .= "Connection: Close\r\n\r\n";
620 fwrite($fp, $out);
621 $data = '';
622 $incoming = false;
623 while (!feof($fp)) {
624 if ($incoming) {
625 $data .= fgets($fp, 1024);
626 } else if (@fgets($fp, 1024) === "\r\n") {
627 $incoming = true;
630 fclose($fp);
631 $data = trim($data);
632 if ($data === $teststr) {
633 return INSECURE_DATAROOT_ERROR;
637 return INSECURE_DATAROOT_WARNING;
641 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
643 function enable_cli_maintenance_mode() {
644 global $CFG, $SITE;
646 if (file_exists("$CFG->dataroot/climaintenance.html")) {
647 unlink("$CFG->dataroot/climaintenance.html");
650 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
651 $data = $CFG->maintenance_message;
652 $data = bootstrap_renderer::early_error_content($data, null, null, null);
653 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
655 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
656 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
658 } else {
659 $data = get_string('sitemaintenance', 'admin');
660 $data = bootstrap_renderer::early_error_content($data, null, null, null);
661 $data = bootstrap_renderer::plain_page(get_string('sitemaintenancetitle', 'admin',
662 format_string($SITE->fullname, true, ['context' => context_system::instance()])), $data);
665 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
666 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
669 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
673 * Interface for anything appearing in the admin tree
675 * The interface that is implemented by anything that appears in the admin tree
676 * block. It forces inheriting classes to define a method for checking user permissions
677 * and methods for finding something in the admin tree.
679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681 interface part_of_admin_tree {
684 * Finds a named part_of_admin_tree.
686 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
687 * and not parentable_part_of_admin_tree, then this function should only check if
688 * $this->name matches $name. If it does, it should return a reference to $this,
689 * otherwise, it should return a reference to NULL.
691 * If a class inherits parentable_part_of_admin_tree, this method should be called
692 * recursively on all child objects (assuming, of course, the parent object's name
693 * doesn't match the search criterion).
695 * @param string $name The internal name of the part_of_admin_tree we're searching for.
696 * @return mixed An object reference or a NULL reference.
698 public function locate($name);
701 * Removes named part_of_admin_tree.
703 * @param string $name The internal name of the part_of_admin_tree we want to remove.
704 * @return bool success.
706 public function prune($name);
709 * Search using query
710 * @param string $query
711 * @return mixed array-object structure of found settings and pages
713 public function search($query);
716 * Verifies current user's access to this part_of_admin_tree.
718 * Used to check if the current user has access to this part of the admin tree or
719 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
720 * then this method is usually just a call to has_capability() in the site context.
722 * If a class inherits parentable_part_of_admin_tree, this method should return the
723 * logical OR of the return of check_access() on all child objects.
725 * @return bool True if the user has access, false if she doesn't.
727 public function check_access();
730 * Mostly useful for removing of some parts of the tree in admin tree block.
732 * @return True is hidden from normal list view
734 public function is_hidden();
737 * Show we display Save button at the page bottom?
738 * @return bool
740 public function show_save();
745 * Interface implemented by any part_of_admin_tree that has children.
747 * The interface implemented by any part_of_admin_tree that can be a parent
748 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
749 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
750 * include an add method for adding other part_of_admin_tree objects as children.
752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
754 interface parentable_part_of_admin_tree extends part_of_admin_tree {
757 * Adds a part_of_admin_tree object to the admin tree.
759 * Used to add a part_of_admin_tree object to this object or a child of this
760 * object. $something should only be added if $destinationname matches
761 * $this->name. If it doesn't, add should be called on child objects that are
762 * also parentable_part_of_admin_tree's.
764 * $something should be appended as the last child in the $destinationname. If the
765 * $beforesibling is specified, $something should be prepended to it. If the given
766 * sibling is not found, $something should be appended to the end of $destinationname
767 * and a developer debugging message should be displayed.
769 * @param string $destinationname The internal name of the new parent for $something.
770 * @param part_of_admin_tree $something The object to be added.
771 * @return bool True on success, false on failure.
773 public function add($destinationname, $something, $beforesibling = null);
779 * The object used to represent folders (a.k.a. categories) in the admin tree block.
781 * Each admin_category object contains a number of part_of_admin_tree objects.
783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
785 class admin_category implements parentable_part_of_admin_tree, linkable_settings_page {
787 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
788 protected $children;
789 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
790 public $name;
791 /** @var string The displayed name for this category. Usually obtained through get_string() */
792 public $visiblename;
793 /** @var bool Should this category be hidden in admin tree block? */
794 public $hidden;
795 /** @var mixed Either a string or an array or strings */
796 public $path;
797 /** @var mixed Either a string or an array or strings */
798 public $visiblepath;
800 /** @var array fast lookup category cache, all categories of one tree point to one cache */
801 protected $category_cache;
803 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
804 protected $sort = false;
805 /** @var bool If set to true children will be sorted in ascending order. */
806 protected $sortasc = true;
807 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
808 protected $sortsplit = true;
809 /** @var bool $sorted True if the children have been sorted and don't need resorting */
810 protected $sorted = false;
813 * Constructor for an empty admin category
815 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
816 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
817 * @param bool $hidden hide category in admin tree block, defaults to false
819 public function __construct($name, $visiblename, $hidden=false) {
820 $this->children = array();
821 $this->name = $name;
822 $this->visiblename = $visiblename;
823 $this->hidden = $hidden;
827 * Get the URL to view this settings page.
829 * @return moodle_url
831 public function get_settings_page_url(): moodle_url {
832 return new moodle_url(
833 '/admin/category.php',
835 'category' => $this->name,
841 * Returns a reference to the part_of_admin_tree object with internal name $name.
843 * @param string $name The internal name of the object we want.
844 * @param bool $findpath initialize path and visiblepath arrays
845 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
846 * defaults to false
848 public function locate($name, $findpath=false) {
849 if (!isset($this->category_cache[$this->name])) {
850 // somebody much have purged the cache
851 $this->category_cache[$this->name] = $this;
854 if ($this->name == $name) {
855 if ($findpath) {
856 $this->visiblepath[] = $this->visiblename;
857 $this->path[] = $this->name;
859 return $this;
862 // quick category lookup
863 if (!$findpath and isset($this->category_cache[$name])) {
864 return $this->category_cache[$name];
867 $return = NULL;
868 foreach($this->children as $childid=>$unused) {
869 if ($return = $this->children[$childid]->locate($name, $findpath)) {
870 break;
874 if (!is_null($return) and $findpath) {
875 $return->visiblepath[] = $this->visiblename;
876 $return->path[] = $this->name;
879 return $return;
883 * Search using query
885 * @param string query
886 * @return mixed array-object structure of found settings and pages
888 public function search($query) {
889 $result = array();
890 foreach ($this->get_children() as $child) {
891 $subsearch = $child->search($query);
892 if (!is_array($subsearch)) {
893 debugging('Incorrect search result from '.$child->name);
894 continue;
896 $result = array_merge($result, $subsearch);
898 return $result;
902 * Removes part_of_admin_tree object with internal name $name.
904 * @param string $name The internal name of the object we want to remove.
905 * @return bool success
907 public function prune($name) {
909 if ($this->name == $name) {
910 return false; //can not remove itself
913 foreach($this->children as $precedence => $child) {
914 if ($child->name == $name) {
915 // clear cache and delete self
916 while($this->category_cache) {
917 // delete the cache, but keep the original array address
918 array_pop($this->category_cache);
920 unset($this->children[$precedence]);
921 return true;
922 } else if ($this->children[$precedence]->prune($name)) {
923 return true;
926 return false;
930 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
932 * By default the new part of the tree is appended as the last child of the parent. You
933 * can specify a sibling node that the new part should be prepended to. If the given
934 * sibling is not found, the part is appended to the end (as it would be by default) and
935 * a developer debugging message is displayed.
937 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
938 * @param string $destinationame The internal name of the immediate parent that we want for $something.
939 * @param mixed $something A part_of_admin_tree or setting instance to be added.
940 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
941 * @return bool True if successfully added, false if $something can not be added.
943 public function add($parentname, $something, $beforesibling = null) {
944 global $CFG;
946 $parent = $this->locate($parentname);
947 if (is_null($parent)) {
948 debugging('parent does not exist!');
949 return false;
952 if ($something instanceof part_of_admin_tree) {
953 if (!($parent instanceof parentable_part_of_admin_tree)) {
954 debugging('error - parts of tree can be inserted only into parentable parts');
955 return false;
957 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
958 // The name of the node is already used, simply warn the developer that this should not happen.
959 // It is intentional to check for the debug level before performing the check.
960 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
962 if (is_null($beforesibling)) {
963 // Append $something as the parent's last child.
964 $parent->children[] = $something;
965 } else {
966 if (!is_string($beforesibling) or trim($beforesibling) === '') {
967 throw new coding_exception('Unexpected value of the beforesibling parameter');
969 // Try to find the position of the sibling.
970 $siblingposition = null;
971 foreach ($parent->children as $childposition => $child) {
972 if ($child->name === $beforesibling) {
973 $siblingposition = $childposition;
974 break;
977 if (is_null($siblingposition)) {
978 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
979 $parent->children[] = $something;
980 } else {
981 $parent->children = array_merge(
982 array_slice($parent->children, 0, $siblingposition),
983 array($something),
984 array_slice($parent->children, $siblingposition)
988 if ($something instanceof admin_category) {
989 if (isset($this->category_cache[$something->name])) {
990 debugging('Duplicate admin category name: '.$something->name);
991 } else {
992 $this->category_cache[$something->name] = $something;
993 $something->category_cache =& $this->category_cache;
994 foreach ($something->children as $child) {
995 // just in case somebody already added subcategories
996 if ($child instanceof admin_category) {
997 if (isset($this->category_cache[$child->name])) {
998 debugging('Duplicate admin category name: '.$child->name);
999 } else {
1000 $this->category_cache[$child->name] = $child;
1001 $child->category_cache =& $this->category_cache;
1007 return true;
1009 } else {
1010 debugging('error - can not add this element');
1011 return false;
1017 * Checks if the user has access to anything in this category.
1019 * @return bool True if the user has access to at least one child in this category, false otherwise.
1021 public function check_access() {
1022 foreach ($this->children as $child) {
1023 if ($child->check_access()) {
1024 return true;
1027 return false;
1031 * Is this category hidden in admin tree block?
1033 * @return bool True if hidden
1035 public function is_hidden() {
1036 return $this->hidden;
1040 * Show we display Save button at the page bottom?
1041 * @return bool
1043 public function show_save() {
1044 foreach ($this->children as $child) {
1045 if ($child->show_save()) {
1046 return true;
1049 return false;
1053 * Sets sorting on this category.
1055 * Please note this function doesn't actually do the sorting.
1056 * It can be called anytime.
1057 * Sorting occurs when the user calls get_children.
1058 * Code using the children array directly won't see the sorted results.
1060 * @param bool $sort If set to true children will be sorted, if false they won't be.
1061 * @param bool $asc If true sorting will be ascending, otherwise descending.
1062 * @param bool $split If true we sort pages and sub categories separately.
1064 public function set_sorting($sort, $asc = true, $split = true) {
1065 $this->sort = (bool)$sort;
1066 $this->sortasc = (bool)$asc;
1067 $this->sortsplit = (bool)$split;
1071 * Returns the children associated with this category.
1073 * @return part_of_admin_tree[]
1075 public function get_children() {
1076 // If we should sort and it hasn't already been sorted.
1077 if ($this->sort && !$this->sorted) {
1078 if ($this->sortsplit) {
1079 $categories = array();
1080 $pages = array();
1081 foreach ($this->children as $child) {
1082 if ($child instanceof admin_category) {
1083 $categories[] = $child;
1084 } else {
1085 $pages[] = $child;
1088 core_collator::asort_objects_by_property($categories, 'visiblename');
1089 core_collator::asort_objects_by_property($pages, 'visiblename');
1090 if (!$this->sortasc) {
1091 $categories = array_reverse($categories);
1092 $pages = array_reverse($pages);
1094 $this->children = array_merge($pages, $categories);
1095 } else {
1096 core_collator::asort_objects_by_property($this->children, 'visiblename');
1097 if (!$this->sortasc) {
1098 $this->children = array_reverse($this->children);
1101 $this->sorted = true;
1103 return $this->children;
1107 * Magically gets a property from this object.
1109 * @param $property
1110 * @return part_of_admin_tree[]
1111 * @throws coding_exception
1113 public function __get($property) {
1114 if ($property === 'children') {
1115 return $this->get_children();
1117 throw new coding_exception('Invalid property requested.');
1121 * Magically sets a property against this object.
1123 * @param string $property
1124 * @param mixed $value
1125 * @throws coding_exception
1127 public function __set($property, $value) {
1128 if ($property === 'children') {
1129 $this->sorted = false;
1130 $this->children = $value;
1131 } else {
1132 throw new coding_exception('Invalid property requested.');
1137 * Checks if an inaccessible property is set.
1139 * @param string $property
1140 * @return bool
1141 * @throws coding_exception
1143 public function __isset($property) {
1144 if ($property === 'children') {
1145 return isset($this->children);
1147 throw new coding_exception('Invalid property requested.');
1153 * Root of admin settings tree, does not have any parent.
1155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1157 class admin_root extends admin_category {
1158 /** @var array List of errors */
1159 public $errors;
1160 /** @var string search query */
1161 public $search;
1162 /** @var bool full tree flag - true means all settings required, false only pages required */
1163 public $fulltree;
1164 /** @var bool flag indicating loaded tree */
1165 public $loaded;
1166 /** @var mixed site custom defaults overriding defaults in settings files*/
1167 public $custom_defaults;
1170 * @param bool $fulltree true means all settings required,
1171 * false only pages required
1173 public function __construct($fulltree) {
1174 global $CFG;
1176 parent::__construct('root', get_string('administration'), false);
1177 $this->errors = array();
1178 $this->search = '';
1179 $this->fulltree = $fulltree;
1180 $this->loaded = false;
1182 $this->category_cache = array();
1184 // load custom defaults if found
1185 $this->custom_defaults = null;
1186 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1187 if (is_readable($defaultsfile)) {
1188 $defaults = array();
1189 include($defaultsfile);
1190 if (is_array($defaults) and count($defaults)) {
1191 $this->custom_defaults = $defaults;
1197 * Empties children array, and sets loaded to false
1199 * @param bool $requirefulltree
1201 public function purge_children($requirefulltree) {
1202 $this->children = array();
1203 $this->fulltree = ($requirefulltree || $this->fulltree);
1204 $this->loaded = false;
1205 //break circular dependencies - this helps PHP 5.2
1206 while($this->category_cache) {
1207 array_pop($this->category_cache);
1209 $this->category_cache = array();
1215 * Links external PHP pages into the admin tree.
1217 * See detailed usage example at the top of this document (adminlib.php)
1219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1221 class admin_externalpage implements part_of_admin_tree, linkable_settings_page {
1223 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1224 public $name;
1226 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1227 public $visiblename;
1229 /** @var string The external URL that we should link to when someone requests this external page. */
1230 public $url;
1232 /** @var array The role capability/permission a user must have to access this external page. */
1233 public $req_capability;
1235 /** @var object The context in which capability/permission should be checked, default is site context. */
1236 public $context;
1238 /** @var bool hidden in admin tree block. */
1239 public $hidden;
1241 /** @var mixed either string or array of string */
1242 public $path;
1244 /** @var array list of visible names of page parents */
1245 public $visiblepath;
1248 * Constructor for adding an external page into the admin tree.
1250 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1251 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1252 * @param string $url The external URL that we should link to when someone requests this external page.
1253 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1254 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1255 * @param stdClass $context The context the page relates to. Not sure what happens
1256 * if you specify something other than system or front page. Defaults to system.
1258 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1259 $this->name = $name;
1260 $this->visiblename = $visiblename;
1261 $this->url = $url;
1262 if (is_array($req_capability)) {
1263 $this->req_capability = $req_capability;
1264 } else {
1265 $this->req_capability = array($req_capability);
1267 $this->hidden = $hidden;
1268 $this->context = $context;
1272 * Get the URL to view this settings page.
1274 * @return moodle_url
1276 public function get_settings_page_url(): moodle_url {
1277 return new moodle_url($this->url);
1281 * Returns a reference to the part_of_admin_tree object with internal name $name.
1283 * @param string $name The internal name of the object we want.
1284 * @param bool $findpath defaults to false
1285 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1287 public function locate($name, $findpath=false) {
1288 if ($this->name == $name) {
1289 if ($findpath) {
1290 $this->visiblepath = array($this->visiblename);
1291 $this->path = array($this->name);
1293 return $this;
1294 } else {
1295 $return = NULL;
1296 return $return;
1301 * This function always returns false, required function by interface
1303 * @param string $name
1304 * @return false
1306 public function prune($name) {
1307 return false;
1311 * Search using query
1313 * @param string $query
1314 * @return mixed array-object structure of found settings and pages
1316 public function search($query) {
1317 $found = false;
1318 if (strpos(strtolower($this->name), $query) !== false) {
1319 $found = true;
1320 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1321 $found = true;
1323 if ($found) {
1324 $result = new stdClass();
1325 $result->page = $this;
1326 $result->settings = array();
1327 return array($this->name => $result);
1328 } else {
1329 return array();
1334 * Determines if the current user has access to this external page based on $this->req_capability.
1336 * @return bool True if user has access, false otherwise.
1338 public function check_access() {
1339 global $CFG;
1340 $context = empty($this->context) ? context_system::instance() : $this->context;
1341 foreach($this->req_capability as $cap) {
1342 if (has_capability($cap, $context)) {
1343 return true;
1346 return false;
1350 * Is this external page hidden in admin tree block?
1352 * @return bool True if hidden
1354 public function is_hidden() {
1355 return $this->hidden;
1359 * Show we display Save button at the page bottom?
1360 * @return bool
1362 public function show_save() {
1363 return false;
1368 * Used to store details of the dependency between two settings elements.
1370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1371 * @copyright 2017 Davo Smith, Synergy Learning
1373 class admin_settingdependency {
1374 /** @var string the name of the setting to be shown/hidden */
1375 public $settingname;
1376 /** @var string the setting this is dependent on */
1377 public $dependenton;
1378 /** @var string the condition to show/hide the element */
1379 public $condition;
1380 /** @var string the value to compare against */
1381 public $value;
1383 /** @var string[] list of valid conditions */
1384 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1387 * admin_settingdependency constructor.
1388 * @param string $settingname
1389 * @param string $dependenton
1390 * @param string $condition
1391 * @param string $value
1392 * @throws \coding_exception
1394 public function __construct($settingname, $dependenton, $condition, $value) {
1395 $this->settingname = $this->parse_name($settingname);
1396 $this->dependenton = $this->parse_name($dependenton);
1397 $this->condition = $condition;
1398 $this->value = $value;
1400 if (!in_array($this->condition, self::$validconditions)) {
1401 throw new coding_exception("Invalid condition '$condition'");
1406 * Convert the setting name into the form field name.
1407 * @param string $name
1408 * @return string
1410 private function parse_name($name) {
1411 $bits = explode('/', $name);
1412 $name = array_pop($bits);
1413 $plugin = '';
1414 if ($bits) {
1415 $plugin = array_pop($bits);
1416 if ($plugin === 'moodle') {
1417 $plugin = '';
1420 return 's_'.$plugin.'_'.$name;
1424 * Gather together all the dependencies in a format suitable for initialising javascript
1425 * @param admin_settingdependency[] $dependencies
1426 * @return array
1428 public static function prepare_for_javascript($dependencies) {
1429 $result = [];
1430 foreach ($dependencies as $d) {
1431 if (!isset($result[$d->dependenton])) {
1432 $result[$d->dependenton] = [];
1434 if (!isset($result[$d->dependenton][$d->condition])) {
1435 $result[$d->dependenton][$d->condition] = [];
1437 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1438 $result[$d->dependenton][$d->condition][$d->value] = [];
1440 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1442 return $result;
1447 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1451 class admin_settingpage implements part_of_admin_tree, linkable_settings_page {
1453 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1454 public $name;
1456 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1457 public $visiblename;
1459 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1460 public $settings;
1462 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1463 protected $dependencies = [];
1465 /** @var array The role capability/permission a user must have to access this external page. */
1466 public $req_capability;
1468 /** @var object The context in which capability/permission should be checked, default is site context. */
1469 public $context;
1471 /** @var bool hidden in admin tree block. */
1472 public $hidden;
1474 /** @var mixed string of paths or array of strings of paths */
1475 public $path;
1477 /** @var array list of visible names of page parents */
1478 public $visiblepath;
1481 * see admin_settingpage for details of this function
1483 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1484 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1485 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1486 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1487 * @param stdClass $context The context the page relates to. Not sure what happens
1488 * if you specify something other than system or front page. Defaults to system.
1490 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1491 $this->settings = new stdClass();
1492 $this->name = $name;
1493 $this->visiblename = $visiblename;
1494 if (is_array($req_capability)) {
1495 $this->req_capability = $req_capability;
1496 } else {
1497 $this->req_capability = array($req_capability);
1499 $this->hidden = $hidden;
1500 $this->context = $context;
1504 * Get the URL to view this page.
1506 * @return moodle_url
1508 public function get_settings_page_url(): moodle_url {
1509 return new moodle_url(
1510 '/admin/settings.php',
1512 'section' => $this->name,
1518 * see admin_category
1520 * @param string $name
1521 * @param bool $findpath
1522 * @return mixed Object (this) if name == this->name, else returns null
1524 public function locate($name, $findpath=false) {
1525 if ($this->name == $name) {
1526 if ($findpath) {
1527 $this->visiblepath = array($this->visiblename);
1528 $this->path = array($this->name);
1530 return $this;
1531 } else {
1532 $return = NULL;
1533 return $return;
1538 * Search string in settings page.
1540 * @param string $query
1541 * @return array
1543 public function search($query) {
1544 $found = array();
1546 foreach ($this->settings as $setting) {
1547 if ($setting->is_related($query)) {
1548 $found[] = $setting;
1552 if ($found) {
1553 $result = new stdClass();
1554 $result->page = $this;
1555 $result->settings = $found;
1556 return array($this->name => $result);
1559 $found = false;
1560 if (strpos(strtolower($this->name), $query) !== false) {
1561 $found = true;
1562 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1563 $found = true;
1565 if ($found) {
1566 $result = new stdClass();
1567 $result->page = $this;
1568 $result->settings = array();
1569 return array($this->name => $result);
1570 } else {
1571 return array();
1576 * This function always returns false, required by interface
1578 * @param string $name
1579 * @return bool Always false
1581 public function prune($name) {
1582 return false;
1586 * adds an admin_setting to this admin_settingpage
1588 * 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
1589 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1591 * @param object $setting is the admin_setting object you want to add
1592 * @return bool true if successful, false if not
1594 public function add($setting) {
1595 if (!($setting instanceof admin_setting)) {
1596 debugging('error - not a setting instance');
1597 return false;
1600 $name = $setting->name;
1601 if ($setting->plugin) {
1602 $name = $setting->plugin . $name;
1604 $this->settings->{$name} = $setting;
1605 return true;
1609 * Hide the named setting if the specified condition is matched.
1611 * @param string $settingname
1612 * @param string $dependenton
1613 * @param string $condition
1614 * @param string $value
1616 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1617 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1619 // Reformat the dependency name to the plugin | name format used in the display.
1620 $dependenton = str_replace('/', ' | ', $dependenton);
1622 // Let the setting know, so it can be displayed underneath.
1623 $findname = str_replace('/', '', $settingname);
1624 foreach ($this->settings as $name => $setting) {
1625 if ($name === $findname) {
1626 $setting->add_dependent_on($dependenton);
1632 * see admin_externalpage
1634 * @return bool Returns true for yes false for no
1636 public function check_access() {
1637 global $CFG;
1638 $context = empty($this->context) ? context_system::instance() : $this->context;
1639 foreach($this->req_capability as $cap) {
1640 if (has_capability($cap, $context)) {
1641 return true;
1644 return false;
1648 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1649 * @return string Returns an XHTML string
1651 public function output_html() {
1652 $adminroot = admin_get_root();
1653 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1654 foreach($this->settings as $setting) {
1655 $fullname = $setting->get_full_name();
1656 if (array_key_exists($fullname, $adminroot->errors)) {
1657 $data = $adminroot->errors[$fullname]->data;
1658 } else {
1659 $data = $setting->get_setting();
1660 // do not use defaults if settings not available - upgrade settings handles the defaults!
1662 $return .= $setting->output_html($data);
1664 $return .= '</fieldset>';
1665 return $return;
1669 * Is this settings page hidden in admin tree block?
1671 * @return bool True if hidden
1673 public function is_hidden() {
1674 return $this->hidden;
1678 * Show we display Save button at the page bottom?
1679 * @return bool
1681 public function show_save() {
1682 foreach($this->settings as $setting) {
1683 if (empty($setting->nosave)) {
1684 return true;
1687 return false;
1691 * Should any of the settings on this page be shown / hidden based on conditions?
1692 * @return bool
1694 public function has_dependencies() {
1695 return (bool)$this->dependencies;
1699 * Format the setting show/hide conditions ready to initialise the page javascript
1700 * @return array
1702 public function get_dependencies_for_javascript() {
1703 if (!$this->has_dependencies()) {
1704 return [];
1706 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1712 * Admin settings class. Only exists on setting pages.
1713 * Read & write happens at this level; no authentication.
1715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1717 abstract class admin_setting {
1718 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1719 public $name;
1720 /** @var lang_string|string localised name */
1721 public $visiblename;
1722 /** @var string localised long description in Markdown format */
1723 public $description;
1724 /** @var mixed Can be string or array of string */
1725 public $defaultsetting;
1726 /** @var string */
1727 public $updatedcallback;
1728 /** @var mixed can be String or Null. Null means main config table */
1729 public $plugin; // null means main config table
1730 /** @var bool true indicates this setting does not actually save anything, just information */
1731 public $nosave = false;
1732 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1733 public $affectsmodinfo = false;
1734 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1735 private $flags = array();
1736 /** @var bool Whether this field must be forced LTR. */
1737 private $forceltr = null;
1738 /** @var array list of other settings that may cause this setting to be hidden */
1739 private $dependenton = [];
1740 /** @var bool Whether this setting uses a custom form control */
1741 protected $customcontrol = false;
1742 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1743 public $paramtype;
1746 * Constructor
1747 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1748 * or 'myplugin/mysetting' for ones in config_plugins.
1749 * @param string $visiblename localised name
1750 * @param string $description localised long description
1751 * @param mixed $defaultsetting string or array depending on implementation
1753 public function __construct($name, $visiblename, $description, $defaultsetting) {
1754 $this->parse_setting_name($name);
1755 $this->visiblename = $visiblename;
1756 $this->description = $description;
1757 $this->defaultsetting = $defaultsetting;
1761 * Generic function to add a flag to this admin setting.
1763 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1764 * @param bool $default - The default for the flag
1765 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1766 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1768 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1769 if (empty($this->flags[$shortname])) {
1770 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1771 } else {
1772 $this->flags[$shortname]->set_options($enabled, $default);
1777 * Set the enabled options flag on this admin setting.
1779 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1780 * @param bool $default - The default for the flag
1782 public function set_enabled_flag_options($enabled, $default) {
1783 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1787 * Set the advanced options flag on this admin setting.
1789 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1790 * @param bool $default - The default for the flag
1792 public function set_advanced_flag_options($enabled, $default) {
1793 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1798 * Set the locked options flag on this admin setting.
1800 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1801 * @param bool $default - The default for the flag
1803 public function set_locked_flag_options($enabled, $default) {
1804 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1808 * Set the required options flag on this admin setting.
1810 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1811 * @param bool $default - The default for the flag.
1813 public function set_required_flag_options($enabled, $default) {
1814 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1818 * Is this option forced in config.php?
1820 * @return bool
1822 public function is_readonly(): bool {
1823 global $CFG;
1825 if (empty($this->plugin)) {
1826 if ($this->is_forceable() && array_key_exists($this->name, $CFG->config_php_settings)) {
1827 return true;
1829 } else {
1830 if (array_key_exists($this->plugin, $CFG->forced_plugin_settings)
1831 and array_key_exists($this->name, $CFG->forced_plugin_settings[$this->plugin])) {
1832 return true;
1835 return false;
1839 * Get the currently saved value for a setting flag
1841 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1842 * @return bool
1844 public function get_setting_flag_value(admin_setting_flag $flag) {
1845 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1846 if (!isset($value)) {
1847 $value = $flag->get_default();
1850 return !empty($value);
1854 * Get the list of defaults for the flags on this setting.
1856 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1858 public function get_setting_flag_defaults(& $defaults) {
1859 foreach ($this->flags as $flag) {
1860 if ($flag->is_enabled() && $flag->get_default()) {
1861 $defaults[] = $flag->get_displayname();
1867 * Output the input fields for the advanced and locked flags on this setting.
1869 * @param bool $adv - The current value of the advanced flag.
1870 * @param bool $locked - The current value of the locked flag.
1871 * @return string $output - The html for the flags.
1873 public function output_setting_flags() {
1874 $output = '';
1876 foreach ($this->flags as $flag) {
1877 if ($flag->is_enabled()) {
1878 $output .= $flag->output_setting_flag($this);
1882 if (!empty($output)) {
1883 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1885 return $output;
1889 * Write the values of the flags for this admin setting.
1891 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1892 * @return bool - true if successful.
1894 public function write_setting_flags($data) {
1895 $result = true;
1896 foreach ($this->flags as $flag) {
1897 $result = $result && $flag->write_setting_flag($this, $data);
1899 return $result;
1903 * Set up $this->name and potentially $this->plugin
1905 * Set up $this->name and possibly $this->plugin based on whether $name looks
1906 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1907 * on the names, that is, output a developer debug warning if the name
1908 * contains anything other than [a-zA-Z0-9_]+.
1910 * @param string $name the setting name passed in to the constructor.
1912 private function parse_setting_name($name) {
1913 $bits = explode('/', $name);
1914 if (count($bits) > 2) {
1915 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1917 $this->name = array_pop($bits);
1918 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1919 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1921 if (!empty($bits)) {
1922 $this->plugin = array_pop($bits);
1923 if ($this->plugin === 'moodle') {
1924 $this->plugin = null;
1925 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1926 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1932 * Returns the fullname prefixed by the plugin
1933 * @return string
1935 public function get_full_name() {
1936 return 's_'.$this->plugin.'_'.$this->name;
1940 * Returns the ID string based on plugin and name
1941 * @return string
1943 public function get_id() {
1944 return 'id_s_'.$this->plugin.'_'.$this->name;
1948 * @param bool $affectsmodinfo If true, changes to this setting will
1949 * cause the course cache to be rebuilt
1951 public function set_affects_modinfo($affectsmodinfo) {
1952 $this->affectsmodinfo = $affectsmodinfo;
1956 * Returns the config if possible
1958 * @return mixed returns config if successful else null
1960 public function config_read($name) {
1961 global $CFG;
1962 if (!empty($this->plugin)) {
1963 $value = get_config($this->plugin, $name);
1964 return $value === false ? NULL : $value;
1966 } else {
1967 if (isset($CFG->$name)) {
1968 return $CFG->$name;
1969 } else {
1970 return NULL;
1976 * Used to set a config pair and log change
1978 * @param string $name
1979 * @param mixed $value Gets converted to string if not null
1980 * @return bool Write setting to config table
1982 public function config_write($name, $value) {
1983 global $DB, $USER, $CFG;
1985 if ($this->nosave) {
1986 return true;
1989 // make sure it is a real change
1990 $oldvalue = get_config($this->plugin, $name);
1991 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1992 $value = is_null($value) ? null : (string)$value;
1994 if ($oldvalue === $value) {
1995 return true;
1998 // store change
1999 set_config($name, $value, $this->plugin);
2001 // Some admin settings affect course modinfo
2002 if ($this->affectsmodinfo) {
2003 // Clear course cache for all courses
2004 rebuild_course_cache(0, true);
2007 $this->add_to_config_log($name, $oldvalue, $value);
2009 return true; // BC only
2013 * Log config changes if necessary.
2014 * @param string $name
2015 * @param string $oldvalue
2016 * @param string $value
2018 protected function add_to_config_log($name, $oldvalue, $value) {
2019 add_to_config_log($name, $oldvalue, $value, $this->plugin);
2023 * Returns current value of this setting
2024 * @return mixed array or string depending on instance, NULL means not set yet
2026 public abstract function get_setting();
2029 * Returns default setting if exists
2030 * @return mixed array or string depending on instance; NULL means no default, user must supply
2032 public function get_defaultsetting() {
2033 $adminroot = admin_get_root(false, false);
2034 if (!empty($adminroot->custom_defaults)) {
2035 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
2036 if (isset($adminroot->custom_defaults[$plugin])) {
2037 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
2038 return $adminroot->custom_defaults[$plugin][$this->name];
2042 return $this->defaultsetting;
2046 * Store new setting
2048 * @param mixed $data string or array, must not be NULL
2049 * @return string empty string if ok, string error message otherwise
2051 public abstract function write_setting($data);
2054 * Return part of form with setting
2055 * This function should always be overwritten
2057 * @param mixed $data array or string depending on setting
2058 * @param string $query
2059 * @return string
2061 public function output_html($data, $query='') {
2062 // should be overridden
2063 return;
2067 * Function called if setting updated - cleanup, cache reset, etc.
2068 * @param string $functionname Sets the function name
2069 * @return void
2071 public function set_updatedcallback($functionname) {
2072 $this->updatedcallback = $functionname;
2076 * Execute postupdatecallback if necessary.
2077 * @param mixed $original original value before write_setting()
2078 * @return bool true if changed, false if not.
2080 public function post_write_settings($original) {
2081 // Comparison must work for arrays too.
2082 if (serialize($original) === serialize($this->get_setting())) {
2083 return false;
2086 $callbackfunction = $this->updatedcallback;
2087 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2088 $callbackfunction($this->get_full_name());
2090 return true;
2094 * Is setting related to query text - used when searching
2095 * @param string $query
2096 * @return bool
2098 public function is_related($query) {
2099 if (strpos(strtolower($this->name), $query) !== false) {
2100 return true;
2102 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2103 return true;
2105 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2106 return true;
2108 $current = $this->get_setting();
2109 if (!is_null($current)) {
2110 if (is_string($current)) {
2111 if (strpos(core_text::strtolower($current), $query) !== false) {
2112 return true;
2116 $default = $this->get_defaultsetting();
2117 if (!is_null($default)) {
2118 if (is_string($default)) {
2119 if (strpos(core_text::strtolower($default), $query) !== false) {
2120 return true;
2124 return false;
2128 * Get whether this should be displayed in LTR mode.
2130 * @return bool|null
2132 public function get_force_ltr() {
2133 return $this->forceltr;
2137 * Set whether to force LTR or not.
2139 * @param bool $value True when forced, false when not force, null when unknown.
2141 public function set_force_ltr($value) {
2142 $this->forceltr = $value;
2146 * Add a setting to the list of those that could cause this one to be hidden
2147 * @param string $dependenton
2149 public function add_dependent_on($dependenton) {
2150 $this->dependenton[] = $dependenton;
2154 * Get a list of the settings that could cause this one to be hidden.
2155 * @return array
2157 public function get_dependent_on() {
2158 return $this->dependenton;
2162 * Whether this setting uses a custom form control.
2163 * This function is especially useful to decide if we should render a label element for this setting or not.
2165 * @return bool
2167 public function has_custom_form_control(): bool {
2168 return $this->customcontrol;
2172 * Whether the setting can be overridden in config.php.
2174 * Returning true will allow the setting to be defined and overridden in config.php.
2175 * Returning false will prevent the config setting from being overridden even when it gets defined in config.php.
2177 * @return bool
2179 public function is_forceable(): bool {
2180 return true;
2185 * An additional option that can be applied to an admin setting.
2186 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2190 class admin_setting_flag {
2191 /** @var bool Flag to indicate if this option can be toggled for this setting */
2192 private $enabled = false;
2193 /** @var bool Flag to indicate if this option defaults to true or false */
2194 private $default = false;
2195 /** @var string Short string used to create setting name - e.g. 'adv' */
2196 private $shortname = '';
2197 /** @var string String used as the label for this flag */
2198 private $displayname = '';
2199 /** @var Checkbox for this flag is displayed in admin page */
2200 const ENABLED = true;
2201 /** @var Checkbox for this flag is not displayed in admin page */
2202 const DISABLED = false;
2205 * Constructor
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.
2210 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2211 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2213 public function __construct($enabled, $default, $shortname, $displayname) {
2214 $this->shortname = $shortname;
2215 $this->displayname = $displayname;
2216 $this->set_options($enabled, $default);
2220 * Update the values of this setting options class
2222 * @param bool $enabled Can this option can be toggled.
2223 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2224 * @param bool $default The default checked state for this setting option.
2226 public function set_options($enabled, $default) {
2227 $this->enabled = $enabled;
2228 $this->default = $default;
2232 * Should this option appear in the interface and be toggleable?
2234 * @return bool Is it enabled?
2236 public function is_enabled() {
2237 return $this->enabled;
2241 * Should this option be checked by default?
2243 * @return bool Is it on by default?
2245 public function get_default() {
2246 return $this->default;
2250 * Return the short name for this flag. e.g. 'adv' or 'locked'
2252 * @return string
2254 public function get_shortname() {
2255 return $this->shortname;
2259 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2261 * @return string
2263 public function get_displayname() {
2264 return $this->displayname;
2268 * Save the submitted data for this flag - or set it to the default if $data is null.
2270 * @param admin_setting $setting - The admin setting for this flag
2271 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2272 * @return bool
2274 public function write_setting_flag(admin_setting $setting, $data) {
2275 $result = true;
2276 if ($this->is_enabled()) {
2277 if (!isset($data)) {
2278 $value = $this->get_default();
2279 } else {
2280 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2282 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2285 return $result;
2290 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2292 * @param admin_setting $setting - The admin setting for this flag
2293 * @return string - The html for the checkbox.
2295 public function output_setting_flag(admin_setting $setting) {
2296 global $OUTPUT;
2298 $value = $setting->get_setting_flag_value($this);
2300 $context = new stdClass();
2301 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2302 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2303 $context->value = 1;
2304 $context->checked = $value ? true : false;
2305 $context->label = $this->get_displayname();
2307 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2313 * No setting - just heading and text.
2315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2317 class admin_setting_heading extends admin_setting {
2320 * not a setting, just text
2321 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2322 * @param string $heading heading
2323 * @param string $information text in box
2325 public function __construct($name, $heading, $information) {
2326 $this->nosave = true;
2327 parent::__construct($name, $heading, $information, '');
2331 * Always returns true
2332 * @return bool Always returns true
2334 public function get_setting() {
2335 return true;
2339 * Always returns true
2340 * @return bool Always returns true
2342 public function get_defaultsetting() {
2343 return true;
2347 * Never write settings
2348 * @return string Always returns an empty string
2350 public function write_setting($data) {
2351 // do not write any setting
2352 return '';
2356 * Returns an HTML string
2357 * @return string Returns an HTML string
2359 public function output_html($data, $query='') {
2360 global $OUTPUT;
2361 $context = new stdClass();
2362 $context->title = $this->visiblename;
2363 $context->description = $this->description;
2364 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2365 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2370 * No setting - just name and description in same row.
2372 * @copyright 2018 onwards Amaia Anabitarte
2373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2375 class admin_setting_description extends admin_setting {
2378 * Not a setting, just text
2380 * @param string $name
2381 * @param string $visiblename
2382 * @param string $description
2384 public function __construct($name, $visiblename, $description) {
2385 $this->nosave = true;
2386 parent::__construct($name, $visiblename, $description, '');
2390 * Always returns true
2392 * @return bool Always returns true
2394 public function get_setting() {
2395 return true;
2399 * Always returns true
2401 * @return bool Always returns true
2403 public function get_defaultsetting() {
2404 return true;
2408 * Never write settings
2410 * @param mixed $data Gets converted to str for comparison against yes value
2411 * @return string Always returns an empty string
2413 public function write_setting($data) {
2414 // Do not write any setting.
2415 return '';
2419 * Returns an HTML string
2421 * @param string $data
2422 * @param string $query
2423 * @return string Returns an HTML string
2425 public function output_html($data, $query='') {
2426 global $OUTPUT;
2428 $context = new stdClass();
2429 $context->title = $this->visiblename;
2430 $context->description = $this->description;
2432 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2439 * The most flexible setting, the user enters text.
2441 * This type of field should be used for config settings which are using
2442 * English words and are not localised (passwords, database name, list of values, ...).
2444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2446 class admin_setting_configtext extends admin_setting {
2448 /** @var int default field size */
2449 public $size;
2450 /** @var array List of arbitrary data attributes */
2451 protected $datavalues = [];
2454 * Config text constructor
2456 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2457 * @param string $visiblename localised
2458 * @param string $description long localised info
2459 * @param string $defaultsetting
2460 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2461 * @param int $size default field size
2463 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2464 $this->paramtype = $paramtype;
2465 if (!is_null($size)) {
2466 $this->size = $size;
2467 } else {
2468 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2470 parent::__construct($name, $visiblename, $description, $defaultsetting);
2474 * Get whether this should be displayed in LTR mode.
2476 * Try to guess from the PARAM type unless specifically set.
2478 public function get_force_ltr() {
2479 $forceltr = parent::get_force_ltr();
2480 if ($forceltr === null) {
2481 return !is_rtl_compatible($this->paramtype);
2483 return $forceltr;
2487 * Return the setting
2489 * @return mixed returns config if successful else null
2491 public function get_setting() {
2492 return $this->config_read($this->name);
2495 public function write_setting($data) {
2496 if ($this->paramtype === PARAM_INT and $data === '') {
2497 // do not complain if '' used instead of 0
2498 $data = 0;
2500 // $data is a string
2501 $validated = $this->validate($data);
2502 if ($validated !== true) {
2503 return $validated;
2505 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2509 * Validate data before storage
2510 * @param string data
2511 * @return mixed true if ok string if error found
2513 public function validate($data) {
2514 // allow paramtype to be a custom regex if it is the form of /pattern/
2515 if (preg_match('#^/.*/$#', $this->paramtype)) {
2516 if (preg_match($this->paramtype, $data)) {
2517 return true;
2518 } else {
2519 return get_string('validateerror', 'admin');
2522 } else if ($this->paramtype === PARAM_RAW) {
2523 return true;
2525 } else {
2526 $cleaned = clean_param($data, $this->paramtype);
2527 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2528 return true;
2529 } else {
2530 return get_string('validateerror', 'admin');
2536 * Set arbitrary data attributes for template.
2538 * @param string $key Attribute key for template.
2539 * @param string $value Attribute value for template.
2541 public function set_data_attribute(string $key, string $value): void {
2542 $this->datavalues[] = [
2543 'key' => $key,
2544 'value' => $value,
2549 * Return an XHTML string for the setting
2550 * @return string Returns an XHTML string
2552 public function output_html($data, $query = '') {
2553 global $OUTPUT;
2555 $default = $this->get_defaultsetting();
2556 $context = (object) [
2557 'size' => $this->size,
2558 'id' => $this->get_id(),
2559 'name' => $this->get_full_name(),
2560 'value' => $data,
2561 'forceltr' => $this->get_force_ltr(),
2562 'readonly' => $this->is_readonly(),
2563 'data' => $this->datavalues,
2564 'maxcharacter' => array_key_exists('validation-max-length', $this->datavalues),
2566 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2568 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2573 * Text input with a maximum length constraint.
2575 * @copyright 2015 onwards Ankit Agarwal
2576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2578 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2580 /** @var int maximum number of chars allowed. */
2581 protected $maxlength;
2584 * Config text constructor
2586 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2587 * or 'myplugin/mysetting' for ones in config_plugins.
2588 * @param string $visiblename localised
2589 * @param string $description long localised info
2590 * @param string $defaultsetting
2591 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2592 * @param int $size default field size
2593 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2595 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2596 $size=null, $maxlength = 0) {
2597 $this->maxlength = $maxlength;
2598 $this->set_data_attribute('validation-max-length', $maxlength);
2599 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2603 * Validate data before storage
2605 * @param string $data data
2606 * @return mixed true if ok string if error found
2608 public function validate($data) {
2609 $parentvalidation = parent::validate($data);
2610 if ($parentvalidation === true) {
2611 if ($this->maxlength > 0) {
2612 // Max length check.
2613 $length = core_text::strlen($data);
2614 if ($length > $this->maxlength) {
2615 return get_string('maximumchars', 'moodle', $this->maxlength);
2617 return true;
2618 } else {
2619 return true; // No max length check needed.
2621 } else {
2622 return $parentvalidation;
2627 * Return an XHTML string for the setting.
2629 * @param string $data data.
2630 * @param string $query query statement.
2631 * @return string Returns an XHTML string
2633 public function output_html($data, $query = ''): string {
2634 global $PAGE;
2635 $PAGE->requires->js_call_amd('core_form/configtext_maxlength', 'init');
2637 return parent::output_html($data, $query);
2642 * General text area without html editor.
2644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2646 class admin_setting_configtextarea extends admin_setting_configtext {
2647 private $rows;
2648 private $cols;
2651 * @param string $name
2652 * @param string $visiblename
2653 * @param string $description
2654 * @param mixed $defaultsetting string or array
2655 * @param mixed $paramtype
2656 * @param string $cols The number of columns to make the editor
2657 * @param string $rows The number of rows to make the editor
2659 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2660 $this->rows = $rows;
2661 $this->cols = $cols;
2662 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2666 * Returns an XHTML string for the editor
2668 * @param string $data
2669 * @param string $query
2670 * @return string XHTML string for the editor
2672 public function output_html($data, $query='') {
2673 global $OUTPUT;
2675 $default = $this->get_defaultsetting();
2676 $defaultinfo = $default;
2677 if (!is_null($default) and $default !== '') {
2678 $defaultinfo = "\n".$default;
2681 $context = (object) [
2682 'cols' => $this->cols,
2683 'rows' => $this->rows,
2684 'id' => $this->get_id(),
2685 'name' => $this->get_full_name(),
2686 'value' => $data,
2687 'forceltr' => $this->get_force_ltr(),
2688 'readonly' => $this->is_readonly(),
2690 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2692 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2697 * General text area with html editor.
2699 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2702 * @param string $name
2703 * @param string $visiblename
2704 * @param string $description
2705 * @param mixed $defaultsetting string or array
2706 * @param mixed $paramtype
2708 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2709 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2710 $this->set_force_ltr(false);
2711 editors_head_setup();
2715 * Returns an XHTML string for the editor
2717 * @param string $data
2718 * @param string $query
2719 * @return string XHTML string for the editor
2721 public function output_html($data, $query='') {
2722 $editor = editors_get_preferred_editor(FORMAT_HTML);
2723 $editor->set_text($data);
2724 $editor->use_editor($this->get_id(), array('noclean'=>true));
2725 return parent::output_html($data, $query);
2729 * Checks if data has empty html.
2731 * @param string $data
2732 * @return string Empty when no errors.
2734 public function write_setting($data) {
2735 if (trim(html_to_text($data)) === '') {
2736 $data = '';
2738 return parent::write_setting($data);
2744 * Password field, allows unmasking of password
2746 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2748 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2751 * Constructor
2752 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2753 * @param string $visiblename localised
2754 * @param string $description long localised info
2755 * @param string $defaultsetting default password
2757 public function __construct($name, $visiblename, $description, $defaultsetting) {
2758 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2762 * Log config changes if necessary.
2763 * @param string $name
2764 * @param string $oldvalue
2765 * @param string $value
2767 protected function add_to_config_log($name, $oldvalue, $value) {
2768 if ($value !== '') {
2769 $value = '********';
2771 if ($oldvalue !== '' and $oldvalue !== null) {
2772 $oldvalue = '********';
2774 parent::add_to_config_log($name, $oldvalue, $value);
2778 * Returns HTML for the field.
2780 * @param string $data Value for the field
2781 * @param string $query Passed as final argument for format_admin_setting
2782 * @return string Rendered HTML
2784 public function output_html($data, $query='') {
2785 global $OUTPUT;
2787 $context = (object) [
2788 'id' => $this->get_id(),
2789 'name' => $this->get_full_name(),
2790 'size' => $this->size,
2791 'value' => $this->is_readonly() ? null : $data,
2792 'forceltr' => $this->get_force_ltr(),
2793 'readonly' => $this->is_readonly(),
2795 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2796 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2801 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2804 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2806 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2809 * Constructor
2811 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2812 * @param string $visiblename localised
2813 * @param string $description long localised info
2814 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2816 public function __construct($name, $visiblename, $description, $defaultsetting) {
2817 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2818 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2823 * Admin setting class for encrypted values using secure encryption.
2825 * @copyright 2019 The Open University
2826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2828 class admin_setting_encryptedpassword extends admin_setting {
2831 * Constructor. Same as parent except that the default value is always an empty string.
2833 * @param string $name Internal name used in config table
2834 * @param string $visiblename Name shown on form
2835 * @param string $description Description that appears below field
2837 public function __construct(string $name, string $visiblename, string $description) {
2838 parent::__construct($name, $visiblename, $description, '');
2841 public function get_setting() {
2842 return $this->config_read($this->name);
2845 public function write_setting($data) {
2846 $data = trim($data);
2847 if ($data === '') {
2848 // Value can really be set to nothing.
2849 $savedata = '';
2850 } else {
2851 // Encrypt value before saving it.
2852 $savedata = \core\encryption::encrypt($data);
2854 return ($this->config_write($this->name, $savedata) ? '' : get_string('errorsetting', 'admin'));
2857 public function output_html($data, $query='') {
2858 global $OUTPUT;
2860 $default = $this->get_defaultsetting();
2861 $context = (object) [
2862 'id' => $this->get_id(),
2863 'name' => $this->get_full_name(),
2864 'set' => $data !== '',
2865 'novalue' => $this->get_setting() === null
2867 $element = $OUTPUT->render_from_template('core_admin/setting_encryptedpassword', $context);
2869 return format_admin_setting($this, $this->visiblename, $element, $this->description,
2870 true, '', $default, $query);
2875 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2876 * Note: Only advanced makes sense right now - locked does not.
2878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2880 class admin_setting_configempty extends admin_setting_configtext {
2883 * @param string $name
2884 * @param string $visiblename
2885 * @param string $description
2887 public function __construct($name, $visiblename, $description) {
2888 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2892 * Returns an XHTML string for the hidden field
2894 * @param string $data
2895 * @param string $query
2896 * @return string XHTML string for the editor
2898 public function output_html($data, $query='') {
2899 global $OUTPUT;
2901 $context = (object) [
2902 'id' => $this->get_id(),
2903 'name' => $this->get_full_name()
2905 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2907 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2913 * Path to directory
2915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2917 class admin_setting_configfile extends admin_setting_configtext {
2919 * Constructor
2920 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2921 * @param string $visiblename localised
2922 * @param string $description long localised info
2923 * @param string $defaultdirectory default directory location
2925 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2926 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2930 * Returns XHTML for the field
2932 * Returns XHTML for the field and also checks whether the file
2933 * specified in $data exists using file_exists()
2935 * @param string $data File name and path to use in value attr
2936 * @param string $query
2937 * @return string XHTML field
2939 public function output_html($data, $query='') {
2940 global $CFG, $OUTPUT;
2942 $default = $this->get_defaultsetting();
2943 $context = (object) [
2944 'id' => $this->get_id(),
2945 'name' => $this->get_full_name(),
2946 'size' => $this->size,
2947 'value' => $data,
2948 'showvalidity' => !empty($data),
2949 'valid' => $data && file_exists($data),
2950 'readonly' => !empty($CFG->preventexecpath) || $this->is_readonly(),
2951 'forceltr' => $this->get_force_ltr(),
2954 if ($context->readonly) {
2955 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2958 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2960 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2964 * Checks if execpatch has been disabled in config.php
2966 public function write_setting($data) {
2967 global $CFG;
2968 if (!empty($CFG->preventexecpath)) {
2969 if ($this->get_setting() === null) {
2970 // Use default during installation.
2971 $data = $this->get_defaultsetting();
2972 if ($data === null) {
2973 $data = '';
2975 } else {
2976 return '';
2979 return parent::write_setting($data);
2986 * Path to executable file
2988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2990 class admin_setting_configexecutable extends admin_setting_configfile {
2993 * Returns an XHTML field
2995 * @param string $data This is the value for the field
2996 * @param string $query
2997 * @return string XHTML field
2999 public function output_html($data, $query='') {
3000 global $CFG, $OUTPUT;
3001 $default = $this->get_defaultsetting();
3002 require_once("$CFG->libdir/filelib.php");
3004 $context = (object) [
3005 'id' => $this->get_id(),
3006 'name' => $this->get_full_name(),
3007 'size' => $this->size,
3008 'value' => $data,
3009 'showvalidity' => !empty($data),
3010 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
3011 'readonly' => !empty($CFG->preventexecpath),
3012 'forceltr' => $this->get_force_ltr()
3015 if (!empty($CFG->preventexecpath)) {
3016 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
3019 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
3021 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
3027 * Path to directory
3029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3031 class admin_setting_configdirectory extends admin_setting_configfile {
3034 * Returns an XHTML field
3036 * @param string $data This is the value for the field
3037 * @param string $query
3038 * @return string XHTML
3040 public function output_html($data, $query='') {
3041 global $CFG, $OUTPUT;
3042 $default = $this->get_defaultsetting();
3044 $context = (object) [
3045 'id' => $this->get_id(),
3046 'name' => $this->get_full_name(),
3047 'size' => $this->size,
3048 'value' => $data,
3049 'showvalidity' => !empty($data),
3050 'valid' => $data && file_exists($data) && is_dir($data),
3051 'readonly' => !empty($CFG->preventexecpath),
3052 'forceltr' => $this->get_force_ltr()
3055 if (!empty($CFG->preventexecpath)) {
3056 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
3059 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
3061 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
3067 * Checkbox
3069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3071 class admin_setting_configcheckbox extends admin_setting {
3072 /** @var string Value used when checked */
3073 public $yes;
3074 /** @var string Value used when not checked */
3075 public $no;
3078 * Constructor
3079 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3080 * @param string $visiblename localised
3081 * @param string $description long localised info
3082 * @param string $defaultsetting
3083 * @param string $yes value used when checked
3084 * @param string $no value used when not checked
3086 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3087 parent::__construct($name, $visiblename, $description, $defaultsetting);
3088 $this->yes = (string)$yes;
3089 $this->no = (string)$no;
3093 * Retrieves the current setting using the objects name
3095 * @return string
3097 public function get_setting() {
3098 return $this->config_read($this->name);
3102 * Sets the value for the setting
3104 * Sets the value for the setting to either the yes or no values
3105 * of the object by comparing $data to yes
3107 * @param mixed $data Gets converted to str for comparison against yes value
3108 * @return string empty string or error
3110 public function write_setting($data) {
3111 if ((string)$data === $this->yes) { // convert to strings before comparison
3112 $data = $this->yes;
3113 } else {
3114 $data = $this->no;
3116 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3120 * Returns an XHTML checkbox field
3122 * @param string $data If $data matches yes then checkbox is checked
3123 * @param string $query
3124 * @return string XHTML field
3126 public function output_html($data, $query='') {
3127 global $OUTPUT;
3129 $context = (object) [
3130 'id' => $this->get_id(),
3131 'name' => $this->get_full_name(),
3132 'no' => $this->no,
3133 'value' => $this->yes,
3134 'checked' => (string) $data === $this->yes,
3135 'readonly' => $this->is_readonly(),
3138 $default = $this->get_defaultsetting();
3139 if (!is_null($default)) {
3140 if ((string)$default === $this->yes) {
3141 $defaultinfo = get_string('checkboxyes', 'admin');
3142 } else {
3143 $defaultinfo = get_string('checkboxno', 'admin');
3145 } else {
3146 $defaultinfo = NULL;
3149 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
3151 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3157 * Multiple checkboxes, each represents different value, stored in csv format
3159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3161 class admin_setting_configmulticheckbox extends admin_setting {
3162 /** @var callable|null Loader function for choices */
3163 protected $choiceloader = null;
3165 /** @var array Array of choices value=>label. */
3166 public $choices;
3169 * Constructor: uses parent::__construct
3171 * The $choices parameter may be either an array of $value => $label format,
3172 * e.g. [1 => get_string('yes')], or a callback function which takes no parameters and
3173 * returns an array in that format.
3175 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3176 * @param string $visiblename localised
3177 * @param string $description long localised info
3178 * @param array $defaultsetting array of selected
3179 * @param array|callable $choices array of $value => $label for each checkbox, or a callback
3181 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3182 if (is_array($choices)) {
3183 $this->choices = $choices;
3185 if (is_callable($choices)) {
3186 $this->choiceloader = $choices;
3188 parent::__construct($name, $visiblename, $description, $defaultsetting);
3192 * This function may be used in ancestors for lazy loading of choices
3194 * Override this method if loading of choices is expensive, such
3195 * as when it requires multiple db requests.
3197 * @return bool true if loaded, false if error
3199 public function load_choices() {
3200 if ($this->choiceloader) {
3201 if (!is_array($this->choices)) {
3202 $this->choices = call_user_func($this->choiceloader);
3205 return true;
3209 * Is setting related to query text - used when searching
3211 * @param string $query
3212 * @return bool true on related, false on not or failure
3214 public function is_related($query) {
3215 if (!$this->load_choices() or empty($this->choices)) {
3216 return false;
3218 if (parent::is_related($query)) {
3219 return true;
3222 foreach ($this->choices as $desc) {
3223 if (strpos(core_text::strtolower($desc), $query) !== false) {
3224 return true;
3227 return false;
3231 * Returns the current setting if it is set
3233 * @return mixed null if null, else an array
3235 public function get_setting() {
3236 $result = $this->config_read($this->name);
3238 if (is_null($result)) {
3239 return NULL;
3241 if ($result === '') {
3242 return array();
3244 $enabled = explode(',', $result);
3245 $setting = array();
3246 foreach ($enabled as $option) {
3247 $setting[$option] = 1;
3249 return $setting;
3253 * Saves the setting(s) provided in $data
3255 * @param array $data An array of data, if not array returns empty str
3256 * @return mixed empty string on useless data or bool true=success, false=failed
3258 public function write_setting($data) {
3259 if (!is_array($data)) {
3260 return ''; // ignore it
3262 if (!$this->load_choices() or empty($this->choices)) {
3263 return '';
3265 unset($data['xxxxx']);
3266 $result = array();
3267 foreach ($data as $key => $value) {
3268 if ($value and array_key_exists($key, $this->choices)) {
3269 $result[] = $key;
3272 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3276 * Returns XHTML field(s) as required by choices
3278 * Relies on data being an array should data ever be another valid vartype with
3279 * acceptable value this may cause a warning/error
3280 * if (!is_array($data)) would fix the problem
3282 * @todo Add vartype handling to ensure $data is an array
3284 * @param array $data An array of checked values
3285 * @param string $query
3286 * @return string XHTML field
3288 public function output_html($data, $query='') {
3289 global $OUTPUT;
3291 if (!$this->load_choices() or empty($this->choices)) {
3292 return '';
3295 $default = $this->get_defaultsetting();
3296 if (is_null($default)) {
3297 $default = array();
3299 if (is_null($data)) {
3300 $data = array();
3303 $context = (object) [
3304 'id' => $this->get_id(),
3305 'name' => $this->get_full_name(),
3306 'readonly' => $this->is_readonly(),
3309 $options = array();
3310 $defaults = array();
3311 foreach ($this->choices as $key => $description) {
3312 if (!empty($default[$key])) {
3313 $defaults[] = $description;
3316 $options[] = [
3317 'key' => $key,
3318 'checked' => !empty($data[$key]),
3319 'label' => highlightfast($query, $description)
3323 if (is_null($default)) {
3324 $defaultinfo = null;
3325 } else if (!empty($defaults)) {
3326 $defaultinfo = implode(', ', $defaults);
3327 } else {
3328 $defaultinfo = get_string('none');
3331 $context->options = $options;
3332 $context->hasoptions = !empty($options);
3334 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3336 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3343 * Multiple checkboxes 2, value stored as string 00101011
3345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3347 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3350 * Returns the setting if set
3352 * @return mixed null if not set, else an array of set settings
3354 public function get_setting() {
3355 $result = $this->config_read($this->name);
3356 if (is_null($result)) {
3357 return NULL;
3359 if (!$this->load_choices()) {
3360 return NULL;
3362 $result = str_pad($result, count($this->choices), '0');
3363 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3364 $setting = array();
3365 foreach ($this->choices as $key=>$unused) {
3366 $value = array_shift($result);
3367 if ($value) {
3368 $setting[$key] = 1;
3371 return $setting;
3375 * Save setting(s) provided in $data param
3377 * @param array $data An array of settings to save
3378 * @return mixed empty string for bad data or bool true=>success, false=>error
3380 public function write_setting($data) {
3381 if (!is_array($data)) {
3382 return ''; // ignore it
3384 if (!$this->load_choices() or empty($this->choices)) {
3385 return '';
3387 $result = '';
3388 foreach ($this->choices as $key=>$unused) {
3389 if (!empty($data[$key])) {
3390 $result .= '1';
3391 } else {
3392 $result .= '0';
3395 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3401 * Select one value from list
3403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3405 class admin_setting_configselect extends admin_setting {
3406 /** @var array Array of choices value=>label */
3407 public $choices;
3408 /** @var array Array of choices grouped using optgroups */
3409 public $optgroups;
3410 /** @var callable|null Loader function for choices */
3411 protected $choiceloader = null;
3412 /** @var callable|null Validation function */
3413 protected $validatefunction = null;
3416 * Constructor.
3418 * If you want to lazy-load the choices, pass a callback function that returns a choice
3419 * array for the $choices parameter.
3421 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3422 * @param string $visiblename localised
3423 * @param string $description long localised info
3424 * @param string|int $defaultsetting
3425 * @param array|callable|null $choices array of $value=>$label for each selection, or callback
3427 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3428 // Look for optgroup and single options.
3429 if (is_array($choices)) {
3430 $this->choices = [];
3431 foreach ($choices as $key => $val) {
3432 if (is_array($val)) {
3433 $this->optgroups[$key] = $val;
3434 $this->choices = array_merge($this->choices, $val);
3435 } else {
3436 $this->choices[$key] = $val;
3440 if (is_callable($choices)) {
3441 $this->choiceloader = $choices;
3444 parent::__construct($name, $visiblename, $description, $defaultsetting);
3448 * Sets a validate function.
3450 * The callback will be passed one parameter, the new setting value, and should return either
3451 * an empty string '' if the value is OK, or an error message if not.
3453 * @param callable|null $validatefunction Validate function or null to clear
3454 * @since Moodle 3.10
3456 public function set_validate_function(?callable $validatefunction = null) {
3457 $this->validatefunction = $validatefunction;
3461 * This function may be used in ancestors for lazy loading of choices
3463 * Override this method if loading of choices is expensive, such
3464 * as when it requires multiple db requests.
3466 * @return bool true if loaded, false if error
3468 public function load_choices() {
3469 if ($this->choiceloader) {
3470 if (!is_array($this->choices)) {
3471 $this->choices = call_user_func($this->choiceloader);
3473 return true;
3475 return true;
3479 * Check if this is $query is related to a choice
3481 * @param string $query
3482 * @return bool true if related, false if not
3484 public function is_related($query) {
3485 if (parent::is_related($query)) {
3486 return true;
3488 if (!$this->load_choices()) {
3489 return false;
3491 foreach ($this->choices as $key=>$value) {
3492 if (strpos(core_text::strtolower($key), $query) !== false) {
3493 return true;
3495 if (strpos(core_text::strtolower($value), $query) !== false) {
3496 return true;
3499 return false;
3503 * Return the setting
3505 * @return mixed returns config if successful else null
3507 public function get_setting() {
3508 return $this->config_read($this->name);
3512 * Save a setting
3514 * @param string $data
3515 * @return string empty of error string
3517 public function write_setting($data) {
3518 if (!$this->load_choices() or empty($this->choices)) {
3519 return '';
3521 if (!array_key_exists($data, $this->choices)) {
3522 return ''; // ignore it
3525 // Validate the new setting.
3526 $error = $this->validate_setting($data);
3527 if ($error) {
3528 return $error;
3531 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3535 * Validate the setting. This uses the callback function if provided; subclasses could override
3536 * to carry out validation directly in the class.
3538 * @param string $data New value being set
3539 * @return string Empty string if valid, or error message text
3540 * @since Moodle 3.10
3542 protected function validate_setting(string $data): string {
3543 // If validation function is specified, call it now.
3544 if ($this->validatefunction) {
3545 return call_user_func($this->validatefunction, $data);
3546 } else {
3547 return '';
3552 * Returns XHTML select field
3554 * Ensure the options are loaded, and generate the XHTML for the select
3555 * element and any warning message. Separating this out from output_html
3556 * makes it easier to subclass this class.
3558 * @param string $data the option to show as selected.
3559 * @param string $current the currently selected option in the database, null if none.
3560 * @param string $default the default selected option.
3561 * @return array the HTML for the select element, and a warning message.
3562 * @deprecated since Moodle 3.2
3564 public function output_select_html($data, $current, $default, $extraname = '') {
3565 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3569 * Returns XHTML select field and wrapping div(s)
3571 * @see output_select_html()
3573 * @param string $data the option to show as selected
3574 * @param string $query
3575 * @return string XHTML field and wrapping div
3577 public function output_html($data, $query='') {
3578 global $OUTPUT;
3580 $default = $this->get_defaultsetting();
3581 $current = $this->get_setting();
3583 if (!$this->load_choices() || empty($this->choices)) {
3584 return '';
3587 $context = (object) [
3588 'id' => $this->get_id(),
3589 'name' => $this->get_full_name(),
3592 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3593 $defaultinfo = $this->choices[$default];
3594 } else {
3595 $defaultinfo = NULL;
3598 // Warnings.
3599 $warning = '';
3600 if ($current === null) {
3601 // First run.
3602 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3603 // No warning.
3604 } else if (!array_key_exists($current, $this->choices)) {
3605 $warning = get_string('warningcurrentsetting', 'admin', $current);
3606 if (!is_null($default) && $data == $current) {
3607 $data = $default; // Use default instead of first value when showing the form.
3611 $options = [];
3612 $template = 'core_admin/setting_configselect';
3614 if (!empty($this->optgroups)) {
3615 $optgroups = [];
3616 foreach ($this->optgroups as $label => $choices) {
3617 $optgroup = array('label' => $label, 'options' => []);
3618 foreach ($choices as $value => $name) {
3619 $optgroup['options'][] = [
3620 'value' => $value,
3621 'name' => $name,
3622 'selected' => (string) $value == $data
3624 unset($this->choices[$value]);
3626 $optgroups[] = $optgroup;
3628 $context->options = $options;
3629 $context->optgroups = $optgroups;
3630 $template = 'core_admin/setting_configselect_optgroup';
3633 foreach ($this->choices as $value => $name) {
3634 $options[] = [
3635 'value' => $value,
3636 'name' => $name,
3637 'selected' => (string) $value == $data
3640 $context->options = $options;
3641 $context->readonly = $this->is_readonly();
3643 $element = $OUTPUT->render_from_template($template, $context);
3645 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3650 * Select multiple items from list
3652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3654 class admin_setting_configmultiselect extends admin_setting_configselect {
3656 * Constructor
3657 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3658 * @param string $visiblename localised
3659 * @param string $description long localised info
3660 * @param array $defaultsetting array of selected items
3661 * @param array $choices array of $value=>$label for each list item
3663 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3664 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3668 * Returns the select setting(s)
3670 * @return mixed null or array. Null if no settings else array of setting(s)
3672 public function get_setting() {
3673 $result = $this->config_read($this->name);
3674 if (is_null($result)) {
3675 return NULL;
3677 if ($result === '') {
3678 return array();
3680 return explode(',', $result);
3684 * Saves setting(s) provided through $data
3686 * Potential bug in the works should anyone call with this function
3687 * using a vartype that is not an array
3689 * @param array $data
3691 public function write_setting($data) {
3692 if (!is_array($data)) {
3693 return ''; //ignore it
3695 if (!$this->load_choices() or empty($this->choices)) {
3696 return '';
3699 unset($data['xxxxx']);
3701 $save = array();
3702 foreach ($data as $value) {
3703 if (!array_key_exists($value, $this->choices)) {
3704 continue; // ignore it
3706 $save[] = $value;
3709 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3713 * Is setting related to query text - used when searching
3715 * @param string $query
3716 * @return bool true if related, false if not
3718 public function is_related($query) {
3719 if (!$this->load_choices() or empty($this->choices)) {
3720 return false;
3722 if (parent::is_related($query)) {
3723 return true;
3726 foreach ($this->choices as $desc) {
3727 if (strpos(core_text::strtolower($desc), $query) !== false) {
3728 return true;
3731 return false;
3735 * Returns XHTML multi-select field
3737 * @todo Add vartype handling to ensure $data is an array
3738 * @param array $data Array of values to select by default
3739 * @param string $query
3740 * @return string XHTML multi-select field
3742 public function output_html($data, $query='') {
3743 global $OUTPUT;
3745 if (!$this->load_choices() or empty($this->choices)) {
3746 return '';
3749 $default = $this->get_defaultsetting();
3750 if (is_null($default)) {
3751 $default = array();
3753 if (is_null($data)) {
3754 $data = array();
3757 $context = (object) [
3758 'id' => $this->get_id(),
3759 'name' => $this->get_full_name(),
3760 'size' => min(10, count($this->choices))
3763 $defaults = [];
3764 $options = [];
3765 $template = 'core_admin/setting_configmultiselect';
3767 if (!empty($this->optgroups)) {
3768 $optgroups = [];
3769 foreach ($this->optgroups as $label => $choices) {
3770 $optgroup = array('label' => $label, 'options' => []);
3771 foreach ($choices as $value => $name) {
3772 if (in_array($value, $default)) {
3773 $defaults[] = $name;
3775 $optgroup['options'][] = [
3776 'value' => $value,
3777 'name' => $name,
3778 'selected' => in_array($value, $data)
3780 unset($this->choices[$value]);
3782 $optgroups[] = $optgroup;
3784 $context->optgroups = $optgroups;
3785 $template = 'core_admin/setting_configmultiselect_optgroup';
3788 foreach ($this->choices as $value => $name) {
3789 if (in_array($value, $default)) {
3790 $defaults[] = $name;
3792 $options[] = [
3793 'value' => $value,
3794 'name' => $name,
3795 'selected' => in_array($value, $data)
3798 $context->options = $options;
3799 $context->readonly = $this->is_readonly();
3801 if (is_null($default)) {
3802 $defaultinfo = NULL;
3803 } if (!empty($defaults)) {
3804 $defaultinfo = implode(', ', $defaults);
3805 } else {
3806 $defaultinfo = get_string('none');
3809 $element = $OUTPUT->render_from_template($template, $context);
3811 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3816 * Time selector
3818 * This is a liiitle bit messy. we're using two selects, but we're returning
3819 * them as an array named after $name (so we only use $name2 internally for the setting)
3821 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3823 class admin_setting_configtime extends admin_setting {
3824 /** @var string Used for setting second select (minutes) */
3825 public $name2;
3828 * Constructor
3829 * @param string $hoursname setting for hours
3830 * @param string $minutesname setting for hours
3831 * @param string $visiblename localised
3832 * @param string $description long localised info
3833 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3835 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3836 $this->name2 = $minutesname;
3837 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3841 * Get the selected time
3843 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3845 public function get_setting() {
3846 $result1 = $this->config_read($this->name);
3847 $result2 = $this->config_read($this->name2);
3848 if (is_null($result1) or is_null($result2)) {
3849 return NULL;
3852 return array('h' => $result1, 'm' => $result2);
3856 * Store the time (hours and minutes)
3858 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3859 * @return bool true if success, false if not
3861 public function write_setting($data) {
3862 if (!is_array($data)) {
3863 return '';
3866 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3867 return ($result ? '' : get_string('errorsetting', 'admin'));
3871 * Returns XHTML time select fields
3873 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3874 * @param string $query
3875 * @return string XHTML time select fields and wrapping div(s)
3877 public function output_html($data, $query='') {
3878 global $OUTPUT;
3880 $default = $this->get_defaultsetting();
3881 if (is_array($default)) {
3882 $defaultinfo = $default['h'].':'.$default['m'];
3883 } else {
3884 $defaultinfo = NULL;
3887 $context = (object) [
3888 'id' => $this->get_id(),
3889 'name' => $this->get_full_name(),
3890 'readonly' => $this->is_readonly(),
3891 'hours' => array_map(function($i) use ($data) {
3892 return [
3893 'value' => $i,
3894 'name' => $i,
3895 'selected' => $i == $data['h']
3897 }, range(0, 23)),
3898 'minutes' => array_map(function($i) use ($data) {
3899 return [
3900 'value' => $i,
3901 'name' => $i,
3902 'selected' => $i == $data['m']
3904 }, range(0, 59, 5))
3907 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3909 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3910 $this->get_id() . 'h', '', $defaultinfo, $query);
3917 * Seconds duration setting.
3919 * @copyright 2012 Petr Skoda (http://skodak.org)
3920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3922 class admin_setting_configduration extends admin_setting {
3924 /** @var int default duration unit */
3925 protected $defaultunit;
3926 /** @var callable|null Validation function */
3927 protected $validatefunction = null;
3929 /** @var int The minimum allowed value */
3930 protected int $minduration = 0;
3932 /** @var null|int The maximum allowed value */
3933 protected null|int $maxduration = null;
3936 * Constructor
3937 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3938 * or 'myplugin/mysetting' for ones in config_plugins.
3939 * @param string $visiblename localised name
3940 * @param string $description localised long description
3941 * @param mixed $defaultsetting string or array depending on implementation
3942 * @param int $defaultunit - day, week, etc. (in seconds)
3944 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3945 if (is_number($defaultsetting)) {
3946 $defaultsetting = self::parse_seconds($defaultsetting);
3948 $units = self::get_units();
3949 if (isset($units[$defaultunit])) {
3950 $this->defaultunit = $defaultunit;
3951 } else {
3952 $this->defaultunit = 86400;
3954 parent::__construct($name, $visiblename, $description, $defaultsetting);
3958 * Set the minimum allowed value.
3959 * This must be at least 0.
3961 * @param int $duration
3963 public function set_min_duration(int $duration): void {
3964 if ($duration < 0) {
3965 throw new coding_exception('The minimum duration must be at least 0.');
3968 $this->minduration = $duration;
3972 * Set the maximum allowed value.
3974 * A value of null will disable the maximum duration value.
3976 * @param int|null $duration
3978 public function set_max_duration(?int $duration): void {
3979 $this->maxduration = $duration;
3983 * Sets a validate function.
3985 * The callback will be passed one parameter, the new setting value, and should return either
3986 * an empty string '' if the value is OK, or an error message if not.
3988 * @param callable|null $validatefunction Validate function or null to clear
3989 * @since Moodle 3.10
3991 public function set_validate_function(?callable $validatefunction = null) {
3992 $this->validatefunction = $validatefunction;
3996 * Validate the setting. This uses the callback function if provided; subclasses could override
3997 * to carry out validation directly in the class.
3999 * @param int $data New value being set
4000 * @return string Empty string if valid, or error message text
4001 * @since Moodle 3.10
4003 protected function validate_setting(int $data): string {
4004 if ($data < $this->minduration) {
4005 return get_string(
4006 'configduration_low',
4007 'admin',
4008 self::get_duration_text($this->minduration, get_string('numseconds', 'core', 0))
4012 if ($this->maxduration && $data > $this->maxduration) {
4013 return get_string('configduration_high', 'admin', self::get_duration_text($this->maxduration));
4016 // If validation function is specified, call it now.
4017 if ($this->validatefunction) {
4018 return call_user_func($this->validatefunction, $data);
4020 return '';
4024 * Returns selectable units.
4025 * @static
4026 * @return array
4028 protected static function get_units() {
4029 return array(
4030 604800 => get_string('weeks'),
4031 86400 => get_string('days'),
4032 3600 => get_string('hours'),
4033 60 => get_string('minutes'),
4034 1 => get_string('seconds'),
4039 * Converts seconds to some more user friendly string.
4040 * @static
4041 * @param int $seconds
4042 * @param null|string The value to use when the duration is empty. If not specified, a "None" value is used.
4043 * @return string
4045 protected static function get_duration_text(int $seconds, ?string $emptyvalue = null): string {
4046 if (empty($seconds)) {
4047 if ($emptyvalue !== null) {
4048 return $emptyvalue;
4050 return get_string('none');
4052 $data = self::parse_seconds($seconds);
4053 switch ($data['u']) {
4054 case (60*60*24*7):
4055 return get_string('numweeks', '', $data['v']);
4056 case (60*60*24):
4057 return get_string('numdays', '', $data['v']);
4058 case (60*60):
4059 return get_string('numhours', '', $data['v']);
4060 case (60):
4061 return get_string('numminutes', '', $data['v']);
4062 default:
4063 return get_string('numseconds', '', $data['v']*$data['u']);
4068 * Finds suitable units for given duration.
4069 * @static
4070 * @param int $seconds
4071 * @return array
4073 protected static function parse_seconds($seconds) {
4074 foreach (self::get_units() as $unit => $unused) {
4075 if ($seconds % $unit === 0) {
4076 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
4079 return array('v'=>(int)$seconds, 'u'=>1);
4083 * Get the selected duration as array.
4085 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
4087 public function get_setting() {
4088 $seconds = $this->config_read($this->name);
4089 if (is_null($seconds)) {
4090 return null;
4093 return self::parse_seconds($seconds);
4097 * Store the duration as seconds.
4099 * @param array $data Must be form 'h'=>xx, 'm'=>xx
4100 * @return bool true if success, false if not
4102 public function write_setting($data) {
4103 if (!is_array($data)) {
4104 return '';
4107 $unit = (int)$data['u'];
4108 $value = (int)$data['v'];
4109 $seconds = $value * $unit;
4111 // Validate the new setting.
4112 $error = $this->validate_setting($seconds);
4113 if ($error) {
4114 return $error;
4117 $result = $this->config_write($this->name, $seconds);
4118 return ($result ? '' : get_string('errorsetting', 'admin'));
4122 * Returns duration text+select fields.
4124 * @param array $data Must be form 'v'=>xx, 'u'=>xx
4125 * @param string $query
4126 * @return string duration text+select fields and wrapping div(s)
4128 public function output_html($data, $query='') {
4129 global $OUTPUT;
4131 $default = $this->get_defaultsetting();
4132 if (is_number($default)) {
4133 $defaultinfo = self::get_duration_text($default);
4134 } else if (is_array($default)) {
4135 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
4136 } else {
4137 $defaultinfo = null;
4140 $inputid = $this->get_id() . 'v';
4141 $units = array_filter(self::get_units(), function($unit): bool {
4142 if (!$this->maxduration) {
4143 // No duration limit. All units are valid.
4144 return true;
4147 return $unit <= $this->maxduration;
4148 }, ARRAY_FILTER_USE_KEY);
4150 $defaultunit = $this->defaultunit;
4152 $context = (object) [
4153 'id' => $this->get_id(),
4154 'name' => $this->get_full_name(),
4155 'value' => $data['v'] ?? '',
4156 'readonly' => $this->is_readonly(),
4157 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
4158 return [
4159 'value' => $unit,
4160 'name' => $units[$unit],
4161 'selected' => isset($data) && (($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u'])
4163 }, array_keys($units))
4166 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
4168 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
4174 * Seconds duration setting with an advanced checkbox, that controls a additional
4175 * $name.'_adv' setting.
4177 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4178 * @copyright 2014 The Open University
4180 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
4182 * Constructor
4183 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
4184 * or 'myplugin/mysetting' for ones in config_plugins.
4185 * @param string $visiblename localised name
4186 * @param string $description localised long description
4187 * @param array $defaultsetting array of int value, and bool whether it is
4188 * is advanced by default.
4189 * @param int $defaultunit - day, week, etc. (in seconds)
4191 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
4192 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
4193 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4199 * Used to validate a textarea used for ip addresses
4201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4202 * @copyright 2011 Petr Skoda (http://skodak.org)
4204 class admin_setting_configiplist extends admin_setting_configtextarea {
4207 * Validate the contents of the textarea as IP addresses
4209 * Used to validate a new line separated list of IP addresses collected from
4210 * a textarea control
4212 * @param string $data A list of IP Addresses separated by new lines
4213 * @return mixed bool true for success or string:error on failure
4215 public function validate($data) {
4216 if(!empty($data)) {
4217 $lines = explode("\n", $data);
4218 } else {
4219 return true;
4221 $result = true;
4222 $badips = array();
4223 foreach ($lines as $line) {
4224 $tokens = explode('#', $line);
4225 $ip = trim($tokens[0]);
4226 if (empty($ip)) {
4227 continue;
4229 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
4230 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
4231 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4232 } else {
4233 $result = false;
4234 $badips[] = $ip;
4237 if($result) {
4238 return true;
4239 } else {
4240 return get_string('validateiperror', 'admin', join(', ', $badips));
4246 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
4248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4249 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4251 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
4254 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
4255 * Used to validate a new line separated list of entries collected from a textarea control.
4257 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
4258 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
4259 * via the get_setting() method, which has been overriden.
4261 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
4262 * @return mixed bool true for success or string:error on failure
4264 public function validate($data) {
4265 if (empty($data)) {
4266 return true;
4268 $entries = explode("\n", $data);
4269 $badentries = [];
4271 foreach ($entries as $key => $entry) {
4272 $entry = trim($entry);
4273 if (empty($entry)) {
4274 return get_string('validateemptylineerror', 'admin');
4277 // Validate each string entry against the supported formats.
4278 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
4279 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
4280 || \core\ip_utils::is_domain_matching_pattern($entry)) {
4281 continue;
4284 // Otherwise, the entry is invalid.
4285 $badentries[] = $entry;
4288 if ($badentries) {
4289 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
4291 return true;
4295 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
4297 * @param string $data the setting data, as sent from the web form.
4298 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
4300 protected function ace_encode($data) {
4301 if (empty($data)) {
4302 return $data;
4304 $entries = explode("\n", $data);
4305 foreach ($entries as $key => $entry) {
4306 $entry = trim($entry);
4307 // This regex matches any string that has non-ascii character.
4308 if (preg_match('/[^\x00-\x7f]/', $entry)) {
4309 // If we can convert the unicode string to an idn, do so.
4310 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
4311 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4312 $entries[$key] = $val ? $val : $entry;
4315 return implode("\n", $entries);
4319 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4321 * @param string $data the setting data, as found in the database.
4322 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4324 protected function ace_decode($data) {
4325 $entries = explode("\n", $data);
4326 foreach ($entries as $key => $entry) {
4327 $entry = trim($entry);
4328 if (strpos($entry, 'xn--') !== false) {
4329 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4332 return implode("\n", $entries);
4336 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4338 * @return mixed returns punycode-converted setting string if successful, else null.
4340 public function get_setting() {
4341 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4342 $data = $this->config_read($this->name);
4343 if (function_exists('idn_to_utf8') && !is_null($data)) {
4344 $data = $this->ace_decode($data);
4346 return $data;
4350 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4352 * @param string $data
4353 * @return string
4355 public function write_setting($data) {
4356 if ($this->paramtype === PARAM_INT and $data === '') {
4357 // Do not complain if '' used instead of 0.
4358 $data = 0;
4361 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4362 if (function_exists('idn_to_ascii')) {
4363 $data = $this->ace_encode($data);
4366 $validated = $this->validate($data);
4367 if ($validated !== true) {
4368 return $validated;
4370 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4375 * Used to validate a textarea used for port numbers.
4377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4378 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4380 class admin_setting_configportlist extends admin_setting_configtextarea {
4383 * Validate the contents of the textarea as port numbers.
4384 * Used to validate a new line separated list of ports collected from a textarea control.
4386 * @param string $data A list of ports separated by new lines
4387 * @return mixed bool true for success or string:error on failure
4389 public function validate($data) {
4390 if (empty($data)) {
4391 return true;
4393 $ports = explode("\n", $data);
4394 $badentries = [];
4395 foreach ($ports as $port) {
4396 $port = trim($port);
4397 if (empty($port)) {
4398 return get_string('validateemptylineerror', 'admin');
4401 // Is the string a valid integer number?
4402 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4403 $badentries[] = $port;
4406 if ($badentries) {
4407 return get_string('validateerrorlist', 'admin', $badentries);
4409 return true;
4415 * An admin setting for selecting one or more users who have a capability
4416 * in the system context
4418 * An admin setting for selecting one or more users, who have a particular capability
4419 * in the system context. Warning, make sure the list will never be too long. There is
4420 * no paging or searching of this list.
4422 * To correctly get a list of users from this config setting, you need to call the
4423 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4427 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4428 /** @var string The capabilities name */
4429 protected $capability;
4430 /** @var int include admin users too */
4431 protected $includeadmins;
4434 * Constructor.
4436 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4437 * @param string $visiblename localised name
4438 * @param string $description localised long description
4439 * @param array $defaultsetting array of usernames
4440 * @param string $capability string capability name.
4441 * @param bool $includeadmins include administrators
4443 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4444 $this->capability = $capability;
4445 $this->includeadmins = $includeadmins;
4446 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4450 * Load all of the uses who have the capability into choice array
4452 * @return bool Always returns true
4454 function load_choices() {
4455 if (is_array($this->choices)) {
4456 return true;
4458 list($sort, $sortparams) = users_order_by_sql('u');
4459 if (!empty($sortparams)) {
4460 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4461 'This is unexpected, and a problem because there is no way to pass these ' .
4462 'parameters to get_users_by_capability. See MDL-34657.');
4464 $userfieldsapi = \core_user\fields::for_name();
4465 $userfields = 'u.id, u.username, ' . $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4466 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4467 $this->choices = array(
4468 '$@NONE@$' => get_string('nobody'),
4469 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4471 if ($this->includeadmins) {
4472 $admins = get_admins();
4473 foreach ($admins as $user) {
4474 $this->choices[$user->id] = fullname($user);
4477 if (is_array($users)) {
4478 foreach ($users as $user) {
4479 $this->choices[$user->id] = fullname($user);
4482 return true;
4486 * Returns the default setting for class
4488 * @return mixed Array, or string. Empty string if no default
4490 public function get_defaultsetting() {
4491 $this->load_choices();
4492 $defaultsetting = parent::get_defaultsetting();
4493 if (empty($defaultsetting)) {
4494 return array('$@NONE@$');
4495 } else if (array_key_exists($defaultsetting, $this->choices)) {
4496 return $defaultsetting;
4497 } else {
4498 return '';
4503 * Returns the current setting
4505 * @return mixed array or string
4507 public function get_setting() {
4508 $result = parent::get_setting();
4509 if ($result === null) {
4510 // this is necessary for settings upgrade
4511 return null;
4513 if (empty($result)) {
4514 $result = array('$@NONE@$');
4516 return $result;
4520 * Save the chosen setting provided as $data
4522 * @param array $data
4523 * @return mixed string or array
4525 public function write_setting($data) {
4526 // If all is selected, remove any explicit options.
4527 if (in_array('$@ALL@$', $data)) {
4528 $data = array('$@ALL@$');
4530 // None never needs to be written to the DB.
4531 if (in_array('$@NONE@$', $data)) {
4532 unset($data[array_search('$@NONE@$', $data)]);
4534 return parent::write_setting($data);
4540 * Special checkbox for calendar - resets SESSION vars.
4542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4544 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4546 * Calls the parent::__construct with default values
4548 * name => calendar_adminseesall
4549 * visiblename => get_string('adminseesall', 'admin')
4550 * description => get_string('helpadminseesall', 'admin')
4551 * defaultsetting => 0
4553 public function __construct() {
4554 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4555 get_string('helpadminseesall', 'admin'), '0');
4559 * Stores the setting passed in $data
4561 * @param mixed gets converted to string for comparison
4562 * @return string empty string or error message
4564 public function write_setting($data) {
4565 global $SESSION;
4566 return parent::write_setting($data);
4571 * Special select for settings that are altered in setup.php and can not be altered on the fly
4573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4575 class admin_setting_special_selectsetup extends admin_setting_configselect {
4577 * Reads the setting directly from the database
4579 * @return mixed
4581 public function get_setting() {
4582 // read directly from db!
4583 return get_config(NULL, $this->name);
4587 * Save the setting passed in $data
4589 * @param string $data The setting to save
4590 * @return string empty or error message
4592 public function write_setting($data) {
4593 global $CFG;
4594 // do not change active CFG setting!
4595 $current = $CFG->{$this->name};
4596 $result = parent::write_setting($data);
4597 $CFG->{$this->name} = $current;
4598 return $result;
4604 * Special select for frontpage - stores data in course table
4606 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4608 class admin_setting_sitesetselect extends admin_setting_configselect {
4610 * Returns the site name for the selected site
4612 * @see get_site()
4613 * @return string The site name of the selected site
4615 public function get_setting() {
4616 $site = course_get_format(get_site())->get_course();
4617 return $site->{$this->name};
4621 * Updates the database and save the setting
4623 * @param string data
4624 * @return string empty or error message
4626 public function write_setting($data) {
4627 global $DB, $SITE, $COURSE;
4628 if (!in_array($data, array_keys($this->choices))) {
4629 return get_string('errorsetting', 'admin');
4631 $record = new stdClass();
4632 $record->id = SITEID;
4633 $temp = $this->name;
4634 $record->$temp = $data;
4635 $record->timemodified = time();
4637 course_get_format($SITE)->update_course_format_options($record);
4638 $DB->update_record('course', $record);
4640 // Reset caches.
4641 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4642 if ($SITE->id == $COURSE->id) {
4643 $COURSE = $SITE;
4645 core_courseformat\base::reset_course_cache($SITE->id);
4647 return '';
4652 * admin_setting_sitesetselect is not meant to be overridden in config.php.
4654 * @return bool
4656 public function is_forceable(): bool {
4657 return false;
4663 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4664 * block to hidden.
4666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4668 class admin_setting_bloglevel extends admin_setting_configselect {
4670 * Updates the database and save the setting
4672 * @param string data
4673 * @return string empty or error message
4675 public function write_setting($data) {
4676 global $DB, $CFG;
4677 if ($data == 0) {
4678 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4679 foreach ($blogblocks as $block) {
4680 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4682 } else {
4683 // reenable all blocks only when switching from disabled blogs
4684 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4685 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4686 foreach ($blogblocks as $block) {
4687 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4691 return parent::write_setting($data);
4697 * Special select - lists on the frontpage - hacky
4699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4701 class admin_setting_courselist_frontpage extends admin_setting {
4703 /** @var array Array of choices value=>label. */
4704 public $choices;
4707 * Construct override, requires one param
4709 * @param bool $loggedin Is the user logged in
4711 public function __construct($loggedin) {
4712 global $CFG;
4713 require_once($CFG->dirroot.'/course/lib.php');
4714 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4715 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4716 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4717 $defaults = array(FRONTPAGEALLCOURSELIST);
4718 parent::__construct($name, $visiblename, $description, $defaults);
4722 * Loads the choices available
4724 * @return bool always returns true
4726 public function load_choices() {
4727 if (is_array($this->choices)) {
4728 return true;
4730 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4731 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4732 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4733 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4734 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4735 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4736 'none' => get_string('none'));
4737 if ($this->name === 'frontpage') {
4738 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4740 return true;
4744 * Returns the selected settings
4746 * @param mixed array or setting or null
4748 public function get_setting() {
4749 $result = $this->config_read($this->name);
4750 if (is_null($result)) {
4751 return NULL;
4753 if ($result === '') {
4754 return array();
4756 return explode(',', $result);
4760 * Save the selected options
4762 * @param array $data
4763 * @return mixed empty string (data is not an array) or bool true=success false=failure
4765 public function write_setting($data) {
4766 if (!is_array($data)) {
4767 return '';
4769 $this->load_choices();
4770 $save = array();
4771 foreach($data as $datum) {
4772 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4773 continue;
4775 $save[$datum] = $datum; // no duplicates
4777 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4781 * Return XHTML select field and wrapping div
4783 * @todo Add vartype handling to make sure $data is an array
4784 * @param array $data Array of elements to select by default
4785 * @return string XHTML select field and wrapping div
4787 public function output_html($data, $query='') {
4788 global $OUTPUT;
4790 $this->load_choices();
4791 $currentsetting = array();
4792 foreach ($data as $key) {
4793 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4794 $currentsetting[] = $key; // already selected first
4798 $context = (object) [
4799 'id' => $this->get_id(),
4800 'name' => $this->get_full_name(),
4803 $options = $this->choices;
4804 $selects = [];
4805 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4806 if (!array_key_exists($i, $currentsetting)) {
4807 $currentsetting[$i] = 'none';
4809 $selects[] = [
4810 'key' => $i,
4811 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4812 return [
4813 'name' => $options[$option],
4814 'value' => $option,
4815 'selected' => $currentsetting[$i] == $option
4817 }, array_keys($options))
4820 $context->selects = $selects;
4822 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4824 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4830 * Special checkbox for frontpage - stores data in course table
4832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4834 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4836 * Returns the current sites name
4838 * @return string
4840 public function get_setting() {
4841 $site = course_get_format(get_site())->get_course();
4842 return $site->{$this->name};
4846 * Save the selected setting
4848 * @param string $data The selected site
4849 * @return string empty string or error message
4851 public function write_setting($data) {
4852 global $DB, $SITE, $COURSE;
4853 $record = new stdClass();
4854 $record->id = $SITE->id;
4855 $record->{$this->name} = ($data == '1' ? 1 : 0);
4856 $record->timemodified = time();
4858 course_get_format($SITE)->update_course_format_options($record);
4859 $DB->update_record('course', $record);
4861 // Reset caches.
4862 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4863 if ($SITE->id == $COURSE->id) {
4864 $COURSE = $SITE;
4866 core_courseformat\base::reset_course_cache($SITE->id);
4868 return '';
4872 * admin_setting_sitesetcheckbox is not meant to be overridden in config.php.
4874 * @return bool
4876 public function is_forceable(): bool {
4877 return false;
4882 * Special text for frontpage - stores data in course table.
4883 * Empty string means not set here. Manual setting is required.
4885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4887 class admin_setting_sitesettext extends admin_setting_configtext {
4890 * Constructor.
4892 public function __construct() {
4893 call_user_func_array([parent::class, '__construct'], func_get_args());
4894 $this->set_force_ltr(false);
4898 * Return the current setting
4900 * @return mixed string or null
4902 public function get_setting() {
4903 $site = course_get_format(get_site())->get_course();
4904 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4908 * Validate the selected data
4910 * @param string $data The selected value to validate
4911 * @return mixed true or message string
4913 public function validate($data) {
4914 global $DB, $SITE;
4915 $cleaned = clean_param($data, PARAM_TEXT);
4916 if ($cleaned === '') {
4917 return get_string('required');
4919 if ($this->name ==='shortname' &&
4920 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4921 return get_string('shortnametaken', 'error', $data);
4923 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4924 return true;
4925 } else {
4926 return get_string('validateerror', 'admin');
4931 * Save the selected setting
4933 * @param string $data The selected value
4934 * @return string empty or error message
4936 public function write_setting($data) {
4937 global $DB, $SITE, $COURSE;
4938 $data = trim($data);
4939 $validated = $this->validate($data);
4940 if ($validated !== true) {
4941 return $validated;
4944 $record = new stdClass();
4945 $record->id = $SITE->id;
4946 $record->{$this->name} = $data;
4947 $record->timemodified = time();
4949 course_get_format($SITE)->update_course_format_options($record);
4950 $DB->update_record('course', $record);
4952 // Reset caches.
4953 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4954 if ($SITE->id == $COURSE->id) {
4955 $COURSE = $SITE;
4957 core_courseformat\base::reset_course_cache($SITE->id);
4959 return '';
4963 * admin_setting_sitesettext is not meant to be overridden in config.php.
4965 * @return bool
4967 public function is_forceable(): bool {
4968 return false;
4974 * This type of field should be used for mandatory config settings.
4976 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4978 class admin_setting_requiredtext extends admin_setting_configtext {
4981 * Validate data before storage.
4983 * @param string $data The string to be validated.
4984 * @return bool|string true for success or error string if invalid.
4986 public function validate($data) {
4987 $cleaned = clean_param($data, PARAM_TEXT);
4988 if ($cleaned === '') {
4989 return get_string('required');
4992 return parent::validate($data);
4997 * This type of field should be used for mandatory config settings where setting password is required.
4999 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5001 class admin_setting_requiredpasswordunmask extends admin_setting_configpasswordunmask {
5004 * Validate data before storage.
5006 * @param string $data The string to be validated.
5007 * @return bool|string true for success or error string if invalid.
5009 public function validate($data) {
5010 $cleaned = clean_param($data, PARAM_TEXT);
5011 if ($cleaned === '') {
5012 return get_string('required');
5015 return parent::validate($data);
5020 * Special text editor for site description.
5022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5024 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
5027 * Calls parent::__construct with specific arguments
5029 public function __construct() {
5030 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
5031 PARAM_RAW, 60, 15);
5035 * Return the current setting
5036 * @return string The current setting
5038 public function get_setting() {
5039 $site = course_get_format(get_site())->get_course();
5040 return $site->{$this->name};
5044 * Save the new setting
5046 * @param string $data The new value to save
5047 * @return string empty or error message
5049 public function write_setting($data) {
5050 global $DB, $SITE, $COURSE;
5051 $record = new stdClass();
5052 $record->id = $SITE->id;
5053 $record->{$this->name} = $data;
5054 $record->timemodified = time();
5056 course_get_format($SITE)->update_course_format_options($record);
5057 $DB->update_record('course', $record);
5059 // Reset caches.
5060 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
5061 if ($SITE->id == $COURSE->id) {
5062 $COURSE = $SITE;
5064 core_courseformat\base::reset_course_cache($SITE->id);
5066 return '';
5070 * admin_setting_special_frontpagedesc is not meant to be overridden in config.php.
5072 * @return bool
5074 public function is_forceable(): bool {
5075 return false;
5081 * Administration interface for emoticon_manager settings.
5083 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5085 class admin_setting_emoticons extends admin_setting {
5088 * Calls parent::__construct with specific args
5090 public function __construct() {
5091 global $CFG;
5093 $manager = get_emoticon_manager();
5094 $defaults = $this->prepare_form_data($manager->default_emoticons());
5095 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
5099 * Return the current setting(s)
5101 * @return array Current settings array
5103 public function get_setting() {
5104 global $CFG;
5106 $manager = get_emoticon_manager();
5108 $config = $this->config_read($this->name);
5109 if (is_null($config)) {
5110 return null;
5113 $config = $manager->decode_stored_config($config);
5114 if (is_null($config)) {
5115 return null;
5118 return $this->prepare_form_data($config);
5122 * Save selected settings
5124 * @param array $data Array of settings to save
5125 * @return bool
5127 public function write_setting($data) {
5129 $manager = get_emoticon_manager();
5130 $emoticons = $this->process_form_data($data);
5132 if ($emoticons === false) {
5133 return false;
5136 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
5137 return ''; // success
5138 } else {
5139 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
5144 * Return XHTML field(s) for options
5146 * @param array $data Array of options to set in HTML
5147 * @return string XHTML string for the fields and wrapping div(s)
5149 public function output_html($data, $query='') {
5150 global $OUTPUT;
5152 $context = (object) [
5153 'name' => $this->get_full_name(),
5154 'emoticons' => [],
5155 'forceltr' => true,
5158 $i = 0;
5159 foreach ($data as $field => $value) {
5161 // When $i == 0: text.
5162 // When $i == 1: imagename.
5163 // When $i == 2: imagecomponent.
5164 // When $i == 3: altidentifier.
5165 // When $i == 4: altcomponent.
5166 $fields[$i] = (object) [
5167 'field' => $field,
5168 'value' => $value,
5169 'index' => $i
5171 $i++;
5173 if ($i > 4) {
5174 $icon = null;
5175 if (!empty($fields[1]->value)) {
5176 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
5177 $alt = get_string($fields[3]->value, $fields[4]->value);
5178 } else {
5179 $alt = $fields[0]->value;
5181 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
5183 $context->emoticons[] = [
5184 'fields' => $fields,
5185 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
5187 $fields = [];
5188 $i = 0;
5192 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
5193 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
5194 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5198 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
5200 * @see self::process_form_data()
5201 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
5202 * @return array of form fields and their values
5204 protected function prepare_form_data(array $emoticons) {
5206 $form = array();
5207 $i = 0;
5208 foreach ($emoticons as $emoticon) {
5209 $form['text'.$i] = $emoticon->text;
5210 $form['imagename'.$i] = $emoticon->imagename;
5211 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
5212 $form['altidentifier'.$i] = $emoticon->altidentifier;
5213 $form['altcomponent'.$i] = $emoticon->altcomponent;
5214 $i++;
5216 // add one more blank field set for new object
5217 $form['text'.$i] = '';
5218 $form['imagename'.$i] = '';
5219 $form['imagecomponent'.$i] = '';
5220 $form['altidentifier'.$i] = '';
5221 $form['altcomponent'.$i] = '';
5223 return $form;
5227 * Converts the data from admin settings form into an array of emoticon objects
5229 * @see self::prepare_form_data()
5230 * @param array $data array of admin form fields and values
5231 * @return false|array of emoticon objects
5233 protected function process_form_data(array $form) {
5235 $count = count($form); // number of form field values
5237 if ($count % 5) {
5238 // we must get five fields per emoticon object
5239 return false;
5242 $emoticons = array();
5243 for ($i = 0; $i < $count / 5; $i++) {
5244 $emoticon = new stdClass();
5245 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
5246 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
5247 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
5248 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
5249 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
5251 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
5252 // prevent from breaking http://url.addresses by accident
5253 $emoticon->text = '';
5256 if (strlen($emoticon->text) < 2) {
5257 // do not allow single character emoticons
5258 $emoticon->text = '';
5261 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
5262 // emoticon text must contain some non-alphanumeric character to prevent
5263 // breaking HTML tags
5264 $emoticon->text = '';
5267 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
5268 $emoticons[] = $emoticon;
5271 return $emoticons;
5278 * Special setting for limiting of the list of available languages.
5280 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5282 class admin_setting_langlist extends admin_setting_configtext {
5284 * Calls parent::__construct with specific arguments
5286 public function __construct() {
5287 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
5291 * Validate that each language identifier exists on the site
5293 * @param string $data
5294 * @return bool|string True if validation successful, otherwise error string
5296 public function validate($data) {
5297 $parentcheck = parent::validate($data);
5298 if ($parentcheck !== true) {
5299 return $parentcheck;
5302 if ($data === '') {
5303 return true;
5306 // Normalize language identifiers.
5307 $langcodes = array_map('trim', explode(',', $data));
5308 foreach ($langcodes as $langcode) {
5309 // If the langcode contains optional alias, split it out.
5310 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5312 if (!get_string_manager()->translation_exists($langcode)) {
5313 return get_string('invalidlanguagecode', 'error', $langcode);
5317 return true;
5321 * Save the new setting
5323 * @param string $data The new setting
5324 * @return bool
5326 public function write_setting($data) {
5327 $return = parent::write_setting($data);
5328 get_string_manager()->reset_caches();
5329 return $return;
5335 * Allows to specify comma separated list of known country codes.
5337 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5338 * known codes.
5340 * @package core
5341 * @category admin
5342 * @copyright 2020 David Mudrák <david@moodle.com>
5343 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5345 class admin_setting_countrycodes extends admin_setting_configtext {
5348 * Construct the instance of the setting.
5350 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5351 * @param lang_string|string $visiblename Language string with the field label text.
5352 * @param lang_string|string $description Language string with the field description text.
5353 * @param string $defaultsetting Default value of the setting.
5354 * @param int $size Input text field size.
5356 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5357 parent::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5361 * Validate the setting value before storing it.
5363 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5364 * a comma separated list of such words.
5366 * @param string $data Value inserted into the setting field.
5367 * @return bool|string True if the value is OK, error string otherwise.
5369 public function validate($data) {
5371 $parentcheck = parent::validate($data);
5373 if ($parentcheck !== true) {
5374 return $parentcheck;
5377 if ($data === '') {
5378 return true;
5381 $allcountries = get_string_manager()->get_list_of_countries(true);
5383 foreach (explode(',', $data) as $code) {
5384 if (!isset($allcountries[$code])) {
5385 return get_string('invalidcountrycode', 'core_error', $code);
5389 return true;
5395 * Selection of one of the recognised countries using the list
5396 * returned by {@link get_list_of_countries()}.
5398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5400 class admin_settings_country_select extends admin_setting_configselect {
5401 protected $includeall;
5402 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5403 $this->includeall = $includeall;
5404 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
5408 * Lazy-load the available choices for the select box
5410 public function load_choices() {
5411 global $CFG;
5412 if (is_array($this->choices)) {
5413 return true;
5415 $this->choices = array_merge(
5416 array('0' => get_string('choosedots')),
5417 get_string_manager()->get_list_of_countries($this->includeall));
5418 return true;
5424 * admin_setting_configselect for the default number of sections in a course,
5425 * simply so we can lazy-load the choices.
5427 * @copyright 2011 The Open University
5428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5430 class admin_settings_num_course_sections extends admin_setting_configselect {
5431 public function __construct($name, $visiblename, $description, $defaultsetting) {
5432 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
5435 /** Lazy-load the available choices for the select box */
5436 public function load_choices() {
5437 $max = get_config('moodlecourse', 'maxsections');
5438 if (!isset($max) || !is_numeric($max)) {
5439 $max = 52;
5441 for ($i = 0; $i <= $max; $i++) {
5442 $this->choices[$i] = "$i";
5444 return true;
5450 * Course category selection
5452 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5454 class admin_settings_coursecat_select extends admin_setting_configselect_autocomplete {
5456 * Calls parent::__construct with specific arguments
5458 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5459 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5463 * Load the available choices for the select box
5465 * @return bool
5467 public function load_choices() {
5468 if (is_array($this->choices)) {
5469 return true;
5471 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
5472 return true;
5478 * Special control for selecting days to backup
5480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5482 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
5484 * Calls parent::__construct with specific arguments
5486 public function __construct() {
5487 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5488 $this->plugin = 'backup';
5492 * Load the available choices for the select box
5494 * @return bool Always returns true
5496 public function load_choices() {
5497 if (is_array($this->choices)) {
5498 return true;
5500 $this->choices = array();
5501 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5502 foreach ($days as $day) {
5503 $this->choices[$day] = get_string($day, 'calendar');
5505 return true;
5510 * Special setting for backup auto destination.
5512 * @package core
5513 * @subpackage admin
5514 * @copyright 2014 Frédéric Massart - FMCorz.net
5515 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5517 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5520 * Calls parent::__construct with specific arguments.
5522 public function __construct() {
5523 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5527 * Check if the directory must be set, depending on backup/backup_auto_storage.
5529 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5530 * there will be conflicts if this validation happens before the other one.
5532 * @param string $data Form data.
5533 * @return string Empty when no errors.
5535 public function write_setting($data) {
5536 $storage = (int) get_config('backup', 'backup_auto_storage');
5537 if ($storage !== 0) {
5538 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5539 // The directory must exist and be writable.
5540 return get_string('backuperrorinvaliddestination');
5543 return parent::write_setting($data);
5549 * Special debug setting
5551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5553 class admin_setting_special_debug extends admin_setting_configselect {
5555 * Calls parent::__construct with specific arguments
5557 public function __construct() {
5558 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5562 * Load the available choices for the select box
5564 * @return bool
5566 public function load_choices() {
5567 if (is_array($this->choices)) {
5568 return true;
5570 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5571 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5572 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5573 DEBUG_ALL => get_string('debugall', 'admin'),
5574 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5575 return true;
5581 * Special admin control
5583 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5585 class admin_setting_special_calendar_weekend extends admin_setting {
5587 * Calls parent::__construct with specific arguments
5589 public function __construct() {
5590 $name = 'calendar_weekend';
5591 $visiblename = get_string('calendar_weekend', 'admin');
5592 $description = get_string('helpweekenddays', 'admin');
5593 $default = array ('0', '6'); // Saturdays and Sundays
5594 parent::__construct($name, $visiblename, $description, $default);
5598 * Gets the current settings as an array
5600 * @return mixed Null if none, else array of settings
5602 public function get_setting() {
5603 $result = $this->config_read($this->name);
5604 if (is_null($result)) {
5605 return NULL;
5607 if ($result === '') {
5608 return array();
5610 $settings = array();
5611 for ($i=0; $i<7; $i++) {
5612 if ($result & (1 << $i)) {
5613 $settings[] = $i;
5616 return $settings;
5620 * Save the new settings
5622 * @param array $data Array of new settings
5623 * @return bool
5625 public function write_setting($data) {
5626 if (!is_array($data)) {
5627 return '';
5629 unset($data['xxxxx']);
5630 $result = 0;
5631 foreach($data as $index) {
5632 $result |= 1 << $index;
5634 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5638 * Return XHTML to display the control
5640 * @param array $data array of selected days
5641 * @param string $query
5642 * @return string XHTML for display (field + wrapping div(s)
5644 public function output_html($data, $query='') {
5645 global $OUTPUT;
5647 // The order matters very much because of the implied numeric keys.
5648 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5649 $context = (object) [
5650 'name' => $this->get_full_name(),
5651 'id' => $this->get_id(),
5652 'days' => array_map(function($index) use ($days, $data) {
5653 return [
5654 'index' => $index,
5655 'label' => get_string($days[$index], 'calendar'),
5656 'checked' => in_array($index, $data)
5658 }, array_keys($days))
5661 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5663 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5670 * Admin setting that allows a user to pick a behaviour.
5672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5674 class admin_setting_question_behaviour extends admin_setting_configselect {
5676 * @param string $name name of config variable
5677 * @param string $visiblename display name
5678 * @param string $description description
5679 * @param string $default default.
5681 public function __construct($name, $visiblename, $description, $default) {
5682 parent::__construct($name, $visiblename, $description, $default, null);
5686 * Load list of behaviours as choices
5687 * @return bool true => success, false => error.
5689 public function load_choices() {
5690 global $CFG;
5691 require_once($CFG->dirroot . '/question/engine/lib.php');
5692 $this->choices = question_engine::get_behaviour_options('');
5693 return true;
5699 * Admin setting that allows a user to pick appropriate roles for something.
5701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5703 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5704 /** @var array Array of capabilities which identify roles */
5705 private $types;
5708 * @param string $name Name of config variable
5709 * @param string $visiblename Display name
5710 * @param string $description Description
5711 * @param array $types Array of archetypes which identify
5712 * roles that will be enabled by default.
5714 public function __construct($name, $visiblename, $description, $types) {
5715 parent::__construct($name, $visiblename, $description, NULL, NULL);
5716 $this->types = $types;
5720 * Load roles as choices
5722 * @return bool true=>success, false=>error
5724 public function load_choices() {
5725 global $CFG, $DB;
5726 if (during_initial_install()) {
5727 return false;
5729 if (is_array($this->choices)) {
5730 return true;
5732 if ($roles = get_all_roles()) {
5733 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5734 return true;
5735 } else {
5736 return false;
5741 * Return the default setting for this control
5743 * @return array Array of default settings
5745 public function get_defaultsetting() {
5746 global $CFG;
5748 if (during_initial_install()) {
5749 return null;
5751 $result = array();
5752 foreach($this->types as $archetype) {
5753 if ($caproles = get_archetype_roles($archetype)) {
5754 foreach ($caproles as $caprole) {
5755 $result[$caprole->id] = 1;
5759 return $result;
5765 * Admin setting that is a list of installed filter plugins.
5767 * @copyright 2015 The Open University
5768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5770 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5773 * Constructor
5775 * @param string $name unique ascii name, either 'mysetting' for settings
5776 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5777 * @param string $visiblename localised name
5778 * @param string $description localised long description
5779 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5781 public function __construct($name, $visiblename, $description, $default) {
5782 if (empty($default)) {
5783 $default = array();
5785 $this->load_choices();
5786 foreach ($default as $plugin) {
5787 if (!isset($this->choices[$plugin])) {
5788 unset($default[$plugin]);
5791 parent::__construct($name, $visiblename, $description, $default, null);
5794 public function load_choices() {
5795 if (is_array($this->choices)) {
5796 return true;
5798 $this->choices = array();
5800 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5801 $this->choices[$plugin] = filter_get_name($plugin);
5803 return true;
5809 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5813 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5815 * Constructor
5816 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5817 * @param string $visiblename localised
5818 * @param string $description long localised info
5819 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5820 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5821 * @param int $size default field size
5823 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5824 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5825 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5831 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5833 * @copyright 2009 Petr Skoda (http://skodak.org)
5834 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5836 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5839 * Constructor
5840 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5841 * @param string $visiblename localised
5842 * @param string $description long localised info
5843 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5844 * @param string $yes value used when checked
5845 * @param string $no value used when not checked
5847 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5848 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5849 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5856 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5858 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5860 * @copyright 2010 Sam Hemelryk
5861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5863 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5865 * Constructor
5866 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5867 * @param string $visiblename localised
5868 * @param string $description long localised info
5869 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5870 * @param string $yes value used when checked
5871 * @param string $no value used when not checked
5873 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5874 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5875 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5881 * Autocomplete as you type form element.
5883 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5885 class admin_setting_configselect_autocomplete extends admin_setting_configselect {
5886 /** @var boolean $tags Should we allow typing new entries to the field? */
5887 protected $tags = false;
5888 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5889 protected $ajax = '';
5890 /** @var string $placeholder Placeholder text for an empty list. */
5891 protected $placeholder = '';
5892 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5893 protected $casesensitive = false;
5894 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5895 protected $showsuggestions = true;
5896 /** @var string $noselectionstring String that is shown when there are no selections. */
5897 protected $noselectionstring = '';
5900 * Returns XHTML select field and wrapping div(s)
5902 * @see output_select_html()
5904 * @param string $data the option to show as selected
5905 * @param string $query
5906 * @return string XHTML field and wrapping div
5908 public function output_html($data, $query='') {
5909 global $PAGE;
5911 $html = parent::output_html($data, $query);
5913 if ($html === '') {
5914 return $html;
5917 $this->placeholder = get_string('search');
5919 $params = array('#' . $this->get_id(), $this->tags, $this->ajax,
5920 $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring);
5922 // Load autocomplete wrapper for select2 library.
5923 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params);
5925 return $html;
5930 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5934 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5936 * Calls parent::__construct with specific arguments
5938 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5939 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5940 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5946 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5948 * @copyright 2017 Marina Glancy
5949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5951 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5953 * Constructor
5954 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5955 * or 'myplugin/mysetting' for ones in config_plugins.
5956 * @param string $visiblename localised
5957 * @param string $description long localised info
5958 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5959 * @param array $choices array of $value=>$label for each selection
5961 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5962 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5963 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5969 * Graded roles in gradebook
5971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5973 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5975 * Calls parent::__construct with specific arguments
5977 public function __construct() {
5978 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5979 get_string('configgradebookroles', 'admin'),
5980 array('student'));
5987 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5989 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5991 * Saves the new settings passed in $data
5993 * @param string $data
5994 * @return mixed string or Array
5996 public function write_setting($data) {
5997 global $CFG, $DB;
5999 $oldvalue = $this->config_read($this->name);
6000 $return = parent::write_setting($data);
6001 $newvalue = $this->config_read($this->name);
6003 if ($oldvalue !== $newvalue) {
6004 // force full regrading
6005 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
6008 return $return;
6014 * Which roles to show on course description page
6016 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6018 class admin_setting_special_coursecontact extends admin_setting_pickroles {
6020 * Calls parent::__construct with specific arguments
6022 public function __construct() {
6023 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
6024 get_string('coursecontact_desc', 'admin'),
6025 array('editingteacher'));
6026 $this->set_updatedcallback(function (){
6027 cache::make('core', 'coursecontacts')->purge();
6035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6037 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
6039 * Calls parent::__construct with specific arguments
6041 public function __construct() {
6042 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
6043 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
6047 * Old syntax of class constructor. Deprecated in PHP7.
6049 * @deprecated since Moodle 3.1
6051 public function admin_setting_special_gradelimiting() {
6052 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
6053 self::__construct();
6057 * Force site regrading
6059 function regrade_all() {
6060 global $CFG;
6061 require_once("$CFG->libdir/gradelib.php");
6062 grade_force_site_regrading();
6066 * Saves the new settings
6068 * @param mixed $data
6069 * @return string empty string or error message
6071 function write_setting($data) {
6072 $previous = $this->get_setting();
6074 if ($previous === null) {
6075 if ($data) {
6076 $this->regrade_all();
6078 } else {
6079 if ($data != $previous) {
6080 $this->regrade_all();
6083 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
6089 * Special setting for $CFG->grade_minmaxtouse.
6091 * @package core
6092 * @copyright 2015 Frédéric Massart - FMCorz.net
6093 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6095 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
6098 * Constructor.
6100 public function __construct() {
6101 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
6102 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
6103 array(
6104 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
6105 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
6111 * Saves the new setting.
6113 * @param mixed $data
6114 * @return string empty string or error message
6116 function write_setting($data) {
6117 global $CFG;
6119 $previous = $this->get_setting();
6120 $result = parent::write_setting($data);
6122 // If saved and the value has changed.
6123 if (empty($result) && $previous != $data) {
6124 require_once($CFG->libdir . '/gradelib.php');
6125 grade_force_site_regrading();
6128 return $result;
6135 * Primary grade export plugin - has state tracking.
6137 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6139 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
6141 * Calls parent::__construct with specific arguments
6143 public function __construct() {
6144 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
6145 get_string('configgradeexport', 'admin'), array(), NULL);
6149 * Load the available choices for the multicheckbox
6151 * @return bool always returns true
6153 public function load_choices() {
6154 if (is_array($this->choices)) {
6155 return true;
6157 $this->choices = array();
6159 if ($plugins = core_component::get_plugin_list('gradeexport')) {
6160 foreach($plugins as $plugin => $unused) {
6161 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
6164 return true;
6170 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
6172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6174 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
6176 * Config gradepointmax constructor
6178 * @param string $name Overidden by "gradepointmax"
6179 * @param string $visiblename Overridden by "gradepointmax" language string.
6180 * @param string $description Overridden by "gradepointmax_help" language string.
6181 * @param string $defaultsetting Not used, overridden by 100.
6182 * @param mixed $paramtype Overridden by PARAM_INT.
6183 * @param int $size Overridden by 5.
6185 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6186 $name = 'gradepointdefault';
6187 $visiblename = get_string('gradepointdefault', 'grades');
6188 $description = get_string('gradepointdefault_help', 'grades');
6189 $defaultsetting = 100;
6190 $paramtype = PARAM_INT;
6191 $size = 5;
6192 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6196 * Validate data before storage
6197 * @param string $data The submitted data
6198 * @return bool|string true if ok, string if error found
6200 public function validate($data) {
6201 global $CFG;
6202 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
6203 return true;
6204 } else {
6205 return get_string('gradepointdefault_validateerror', 'grades');
6212 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
6214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6216 class admin_setting_special_gradepointmax extends admin_setting_configtext {
6219 * Config gradepointmax constructor
6221 * @param string $name Overidden by "gradepointmax"
6222 * @param string $visiblename Overridden by "gradepointmax" language string.
6223 * @param string $description Overridden by "gradepointmax_help" language string.
6224 * @param string $defaultsetting Not used, overridden by 100.
6225 * @param mixed $paramtype Overridden by PARAM_INT.
6226 * @param int $size Overridden by 5.
6228 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6229 $name = 'gradepointmax';
6230 $visiblename = get_string('gradepointmax', 'grades');
6231 $description = get_string('gradepointmax_help', 'grades');
6232 $defaultsetting = 100;
6233 $paramtype = PARAM_INT;
6234 $size = 5;
6235 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6239 * Save the selected setting
6241 * @param string $data The selected site
6242 * @return string empty string or error message
6244 public function write_setting($data) {
6245 if ($data === '') {
6246 $data = (int)$this->defaultsetting;
6247 } else {
6248 $data = $data;
6250 return parent::write_setting($data);
6254 * Validate data before storage
6255 * @param string $data The submitted data
6256 * @return bool|string true if ok, string if error found
6258 public function validate($data) {
6259 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6260 return true;
6261 } else {
6262 return get_string('gradepointmax_validateerror', 'grades');
6267 * Return an XHTML string for the setting
6268 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6269 * @param string $query search query to be highlighted
6270 * @return string XHTML to display control
6272 public function output_html($data, $query = '') {
6273 global $OUTPUT;
6275 $default = $this->get_defaultsetting();
6276 $context = (object) [
6277 'size' => $this->size,
6278 'id' => $this->get_id(),
6279 'name' => $this->get_full_name(),
6280 'value' => $data,
6281 'attributes' => [
6282 'maxlength' => 5
6284 'forceltr' => $this->get_force_ltr()
6286 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6288 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
6294 * Grade category settings
6296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6298 class admin_setting_gradecat_combo extends admin_setting {
6300 /** @var array Array of choices value=>label. */
6301 public $choices;
6304 * Sets choices and calls parent::__construct with passed arguments
6305 * @param string $name
6306 * @param string $visiblename
6307 * @param string $description
6308 * @param mixed $defaultsetting string or array depending on implementation
6309 * @param array $choices An array of choices for the control
6311 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6312 $this->choices = $choices;
6313 parent::__construct($name, $visiblename, $description, $defaultsetting);
6317 * Return the current setting(s) array
6319 * @return array Array of value=>xx, forced=>xx, adv=>xx
6321 public function get_setting() {
6322 global $CFG;
6324 $value = $this->config_read($this->name);
6325 $flag = $this->config_read($this->name.'_flag');
6327 if (is_null($value) or is_null($flag)) {
6328 return NULL;
6331 $flag = (int)$flag;
6332 $forced = (boolean)(1 & $flag); // first bit
6333 $adv = (boolean)(2 & $flag); // second bit
6335 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6339 * Save the new settings passed in $data
6341 * @todo Add vartype handling to ensure $data is array
6342 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6343 * @return string empty or error message
6345 public function write_setting($data) {
6346 global $CFG;
6348 $value = $data['value'];
6349 $forced = empty($data['forced']) ? 0 : 1;
6350 $adv = empty($data['adv']) ? 0 : 2;
6351 $flag = ($forced | $adv); //bitwise or
6353 if (!in_array($value, array_keys($this->choices))) {
6354 return 'Error setting ';
6357 $oldvalue = $this->config_read($this->name);
6358 $oldflag = (int)$this->config_read($this->name.'_flag');
6359 $oldforced = (1 & $oldflag); // first bit
6361 $result1 = $this->config_write($this->name, $value);
6362 $result2 = $this->config_write($this->name.'_flag', $flag);
6364 // force regrade if needed
6365 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6366 require_once($CFG->libdir.'/gradelib.php');
6367 grade_category::updated_forced_settings();
6370 if ($result1 and $result2) {
6371 return '';
6372 } else {
6373 return get_string('errorsetting', 'admin');
6378 * Return XHTML to display the field and wrapping div
6380 * @todo Add vartype handling to ensure $data is array
6381 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6382 * @param string $query
6383 * @return string XHTML to display control
6385 public function output_html($data, $query='') {
6386 global $OUTPUT;
6388 $value = $data['value'];
6390 $default = $this->get_defaultsetting();
6391 if (!is_null($default)) {
6392 $defaultinfo = array();
6393 if (isset($this->choices[$default['value']])) {
6394 $defaultinfo[] = $this->choices[$default['value']];
6396 if (!empty($default['forced'])) {
6397 $defaultinfo[] = get_string('force');
6399 if (!empty($default['adv'])) {
6400 $defaultinfo[] = get_string('advanced');
6402 $defaultinfo = implode(', ', $defaultinfo);
6404 } else {
6405 $defaultinfo = NULL;
6408 $options = $this->choices;
6409 $context = (object) [
6410 'id' => $this->get_id(),
6411 'name' => $this->get_full_name(),
6412 'forced' => !empty($data['forced']),
6413 'advanced' => !empty($data['adv']),
6414 'options' => array_map(function($option) use ($options, $value) {
6415 return [
6416 'value' => $option,
6417 'name' => $options[$option],
6418 'selected' => $option == $value
6420 }, array_keys($options)),
6423 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6425 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
6431 * Selection of grade report in user profiles
6433 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6435 class admin_setting_grade_profilereport extends admin_setting_configselect {
6437 * Calls parent::__construct with specific arguments
6439 public function __construct() {
6440 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6444 * Loads an array of choices for the configselect control
6446 * @return bool always return true
6448 public function load_choices() {
6449 if (is_array($this->choices)) {
6450 return true;
6452 $this->choices = array();
6454 global $CFG;
6455 require_once($CFG->libdir.'/gradelib.php');
6457 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6458 if (file_exists($plugindir.'/lib.php')) {
6459 require_once($plugindir.'/lib.php');
6460 $functionname = 'grade_report_'.$plugin.'_profilereport';
6461 if (function_exists($functionname)) {
6462 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6466 return true;
6471 * Provides a selection of grade reports to be used for "grades".
6473 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6476 class admin_setting_my_grades_report extends admin_setting_configselect {
6479 * Calls parent::__construct with specific arguments.
6481 public function __construct() {
6482 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6483 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6487 * Loads an array of choices for the configselect control.
6489 * @return bool always returns true.
6491 public function load_choices() {
6492 global $CFG; // Remove this line and behold the horror of behat test failures!
6493 $this->choices = array();
6494 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6495 if (file_exists($plugindir . '/lib.php')) {
6496 require_once($plugindir . '/lib.php');
6497 // Check to see if the class exists. Check the correct plugin convention first.
6498 if (class_exists('gradereport_' . $plugin)) {
6499 $classname = 'gradereport_' . $plugin;
6500 } else if (class_exists('grade_report_' . $plugin)) {
6501 // We are using the old plugin naming convention.
6502 $classname = 'grade_report_' . $plugin;
6503 } else {
6504 continue;
6506 if ($classname::supports_mygrades()) {
6507 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6511 // Add an option to specify an external url.
6512 $this->choices['external'] = get_string('externalurl', 'grades');
6513 return true;
6518 * Special class for register auth selection
6520 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6522 class admin_setting_special_registerauth extends admin_setting_configselect {
6524 * Calls parent::__construct with specific arguments
6526 public function __construct() {
6527 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6531 * Returns the default option
6533 * @return string empty or default option
6535 public function get_defaultsetting() {
6536 $this->load_choices();
6537 $defaultsetting = parent::get_defaultsetting();
6538 if (array_key_exists($defaultsetting, $this->choices)) {
6539 return $defaultsetting;
6540 } else {
6541 return '';
6546 * Loads the possible choices for the array
6548 * @return bool always returns true
6550 public function load_choices() {
6551 global $CFG;
6553 if (is_array($this->choices)) {
6554 return true;
6556 $this->choices = array();
6557 $this->choices[''] = get_string('disable');
6559 $authsenabled = get_enabled_auth_plugins();
6561 foreach ($authsenabled as $auth) {
6562 $authplugin = get_auth_plugin($auth);
6563 if (!$authplugin->can_signup()) {
6564 continue;
6566 // Get the auth title (from core or own auth lang files)
6567 $authtitle = $authplugin->get_title();
6568 $this->choices[$auth] = $authtitle;
6570 return true;
6576 * General plugins manager
6578 class admin_page_pluginsoverview extends admin_externalpage {
6581 * Sets basic information about the external page
6583 public function __construct() {
6584 global $CFG;
6585 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6586 "$CFG->wwwroot/$CFG->admin/plugins.php");
6591 * Module manage page
6593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6595 class admin_page_managemods extends admin_externalpage {
6597 * Calls parent::__construct with specific arguments
6599 public function __construct() {
6600 global $CFG;
6601 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6605 * Try to find the specified module
6607 * @param string $query The module to search for
6608 * @return array
6610 public function search($query) {
6611 global $CFG, $DB;
6612 if ($result = parent::search($query)) {
6613 return $result;
6616 $found = false;
6617 if ($modules = $DB->get_records('modules')) {
6618 foreach ($modules as $module) {
6619 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6620 continue;
6622 if (strpos($module->name, $query) !== false) {
6623 $found = true;
6624 break;
6626 $strmodulename = get_string('modulename', $module->name);
6627 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6628 $found = true;
6629 break;
6633 if ($found) {
6634 $result = new stdClass();
6635 $result->page = $this;
6636 $result->settings = array();
6637 return array($this->name => $result);
6638 } else {
6639 return array();
6646 * Special class for enrol plugins management.
6648 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6651 class admin_setting_manageenrols extends admin_setting {
6653 * Calls parent::__construct with specific arguments
6655 public function __construct() {
6656 $this->nosave = true;
6657 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6661 * Always returns true, does nothing
6663 * @return true
6665 public function get_setting() {
6666 return true;
6670 * Always returns true, does nothing
6672 * @return true
6674 public function get_defaultsetting() {
6675 return true;
6679 * Always returns '', does not write anything
6681 * @return string Always returns ''
6683 public function write_setting($data) {
6684 // do not write any setting
6685 return '';
6689 * Checks if $query is one of the available enrol plugins
6691 * @param string $query The string to search for
6692 * @return bool Returns true if found, false if not
6694 public function is_related($query) {
6695 if (parent::is_related($query)) {
6696 return true;
6699 $query = core_text::strtolower($query);
6700 $enrols = enrol_get_plugins(false);
6701 foreach ($enrols as $name=>$enrol) {
6702 $localised = get_string('pluginname', 'enrol_'.$name);
6703 if (strpos(core_text::strtolower($name), $query) !== false) {
6704 return true;
6706 if (strpos(core_text::strtolower($localised), $query) !== false) {
6707 return true;
6710 return false;
6714 * Builds the XHTML to display the control
6716 * @param string $data Unused
6717 * @param string $query
6718 * @return string
6720 public function output_html($data, $query='') {
6721 global $CFG, $OUTPUT, $DB, $PAGE;
6723 // Display strings.
6724 $strup = get_string('up');
6725 $strdown = get_string('down');
6726 $strsettings = get_string('settings');
6727 $strenable = get_string('enable');
6728 $strdisable = get_string('disable');
6729 $struninstall = get_string('uninstallplugin', 'core_admin');
6730 $strusage = get_string('enrolusage', 'enrol');
6731 $strversion = get_string('version');
6732 $strtest = get_string('testsettings', 'core_enrol');
6734 $pluginmanager = core_plugin_manager::instance();
6736 $enrols_available = enrol_get_plugins(false);
6737 $active_enrols = enrol_get_plugins(true);
6739 $allenrols = array();
6740 foreach ($active_enrols as $key=>$enrol) {
6741 $allenrols[$key] = true;
6743 foreach ($enrols_available as $key=>$enrol) {
6744 $allenrols[$key] = true;
6746 // Now find all borked plugins and at least allow then to uninstall.
6747 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6748 foreach ($condidates as $candidate) {
6749 if (empty($allenrols[$candidate])) {
6750 $allenrols[$candidate] = true;
6754 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6755 $return .= $OUTPUT->box_start('generalbox enrolsui');
6757 $table = new html_table();
6758 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6759 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6760 $table->id = 'courseenrolmentplugins';
6761 $table->attributes['class'] = 'admintable generaltable';
6762 $table->data = array();
6764 // Iterate through enrol plugins and add to the display table.
6765 $updowncount = 1;
6766 $enrolcount = count($active_enrols);
6767 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6768 $printed = array();
6769 foreach($allenrols as $enrol => $unused) {
6770 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6771 $version = get_config('enrol_'.$enrol, 'version');
6772 if ($version === false) {
6773 $version = '';
6776 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6777 $name = get_string('pluginname', 'enrol_'.$enrol);
6778 } else {
6779 $name = $enrol;
6781 // Usage.
6782 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6783 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6784 $usage = "$ci / $cp";
6786 // Hide/show links.
6787 $class = '';
6788 if (isset($active_enrols[$enrol])) {
6789 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6790 $hideshow = "<a href=\"$aurl\">";
6791 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6792 $enabled = true;
6793 $displayname = $name;
6794 } else if (isset($enrols_available[$enrol])) {
6795 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6796 $hideshow = "<a href=\"$aurl\">";
6797 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6798 $enabled = false;
6799 $displayname = $name;
6800 $class = 'dimmed_text';
6801 } else {
6802 $hideshow = '';
6803 $enabled = false;
6804 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6806 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6807 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6808 } else {
6809 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6812 // Up/down link (only if enrol is enabled).
6813 $updown = '';
6814 if ($enabled) {
6815 if ($updowncount > 1) {
6816 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6817 $updown .= "<a href=\"$aurl\">";
6818 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6819 } else {
6820 $updown .= $OUTPUT->spacer() . '&nbsp;';
6822 if ($updowncount < $enrolcount) {
6823 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6824 $updown .= "<a href=\"$aurl\">";
6825 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6826 } else {
6827 $updown .= $OUTPUT->spacer() . '&nbsp;';
6829 ++$updowncount;
6832 // Add settings link.
6833 if (!$version) {
6834 $settings = '';
6835 } else if ($surl = $plugininfo->get_settings_url()) {
6836 $settings = html_writer::link($surl, $strsettings);
6837 } else {
6838 $settings = '';
6841 // Add uninstall info.
6842 $uninstall = '';
6843 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6844 $uninstall = html_writer::link($uninstallurl, $struninstall);
6847 $test = '';
6848 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6849 $testsettingsurl = new moodle_url('/enrol/test_settings.php', ['enrol' => $enrol]);
6850 $test = html_writer::link($testsettingsurl, $strtest);
6853 // Add a row to the table.
6854 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6855 if ($class) {
6856 $row->attributes['class'] = $class;
6858 $table->data[] = $row;
6860 $printed[$enrol] = true;
6863 $return .= html_writer::table($table);
6864 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6865 $return .= $OUTPUT->box_end();
6866 return highlight($query, $return);
6872 * Blocks manage page
6874 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6876 class admin_page_manageblocks extends admin_externalpage {
6878 * Calls parent::__construct with specific arguments
6880 public function __construct() {
6881 global $CFG;
6882 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6886 * Search for a specific block
6888 * @param string $query The string to search for
6889 * @return array
6891 public function search($query) {
6892 global $CFG, $DB;
6893 if ($result = parent::search($query)) {
6894 return $result;
6897 $found = false;
6898 if ($blocks = $DB->get_records('block')) {
6899 foreach ($blocks as $block) {
6900 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6901 continue;
6903 if (strpos($block->name, $query) !== false) {
6904 $found = true;
6905 break;
6907 $strblockname = get_string('pluginname', 'block_'.$block->name);
6908 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6909 $found = true;
6910 break;
6914 if ($found) {
6915 $result = new stdClass();
6916 $result->page = $this;
6917 $result->settings = array();
6918 return array($this->name => $result);
6919 } else {
6920 return array();
6926 * Message outputs configuration
6928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6930 class admin_page_managemessageoutputs extends admin_externalpage {
6932 * Calls parent::__construct with specific arguments
6934 public function __construct() {
6935 global $CFG;
6936 parent::__construct('managemessageoutputs',
6937 get_string('defaultmessageoutputs', 'message'),
6938 new moodle_url('/admin/message.php')
6943 * Search for a specific message processor
6945 * @param string $query The string to search for
6946 * @return array
6948 public function search($query) {
6949 global $CFG, $DB;
6950 if ($result = parent::search($query)) {
6951 return $result;
6954 $found = false;
6955 if ($processors = get_message_processors()) {
6956 foreach ($processors as $processor) {
6957 if (!$processor->available) {
6958 continue;
6960 if (strpos($processor->name, $query) !== false) {
6961 $found = true;
6962 break;
6964 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6965 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6966 $found = true;
6967 break;
6971 if ($found) {
6972 $result = new stdClass();
6973 $result->page = $this;
6974 $result->settings = array();
6975 return array($this->name => $result);
6976 } else {
6977 return array();
6983 * Manage question behaviours page
6985 * @copyright 2011 The Open University
6986 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6988 class admin_page_manageqbehaviours extends admin_externalpage {
6990 * Constructor
6992 public function __construct() {
6993 global $CFG;
6994 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6995 new moodle_url('/admin/qbehaviours.php'));
6999 * Search question behaviours for the specified string
7001 * @param string $query The string to search for in question behaviours
7002 * @return array
7004 public function search($query) {
7005 global $CFG;
7006 if ($result = parent::search($query)) {
7007 return $result;
7010 $found = false;
7011 require_once($CFG->dirroot . '/question/engine/lib.php');
7012 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
7013 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
7014 $query) !== false) {
7015 $found = true;
7016 break;
7019 if ($found) {
7020 $result = new stdClass();
7021 $result->page = $this;
7022 $result->settings = array();
7023 return array($this->name => $result);
7024 } else {
7025 return array();
7032 * Question type manage page
7034 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7036 class admin_page_manageqtypes extends admin_externalpage {
7038 * Calls parent::__construct with specific arguments
7040 public function __construct() {
7041 global $CFG;
7042 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
7043 new moodle_url('/admin/qtypes.php'));
7047 * Search question types for the specified string
7049 * @param string $query The string to search for in question types
7050 * @return array
7052 public function search($query) {
7053 global $CFG;
7054 if ($result = parent::search($query)) {
7055 return $result;
7058 $found = false;
7059 require_once($CFG->dirroot . '/question/engine/bank.php');
7060 foreach (question_bank::get_all_qtypes() as $qtype) {
7061 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
7062 $found = true;
7063 break;
7066 if ($found) {
7067 $result = new stdClass();
7068 $result->page = $this;
7069 $result->settings = array();
7070 return array($this->name => $result);
7071 } else {
7072 return array();
7078 class admin_page_manageportfolios extends admin_externalpage {
7080 * Calls parent::__construct with specific arguments
7082 public function __construct() {
7083 global $CFG;
7084 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
7085 "$CFG->wwwroot/$CFG->admin/portfolio.php");
7089 * Searches page for the specified string.
7090 * @param string $query The string to search for
7091 * @return bool True if it is found on this page
7093 public function search($query) {
7094 global $CFG;
7095 if ($result = parent::search($query)) {
7096 return $result;
7099 $found = false;
7100 $portfolios = core_component::get_plugin_list('portfolio');
7101 foreach ($portfolios as $p => $dir) {
7102 if (strpos($p, $query) !== false) {
7103 $found = true;
7104 break;
7107 if (!$found) {
7108 foreach (portfolio_instances(false, false) as $instance) {
7109 $title = $instance->get('name');
7110 if (strpos(core_text::strtolower($title), $query) !== false) {
7111 $found = true;
7112 break;
7117 if ($found) {
7118 $result = new stdClass();
7119 $result->page = $this;
7120 $result->settings = array();
7121 return array($this->name => $result);
7122 } else {
7123 return array();
7129 class admin_page_managerepositories extends admin_externalpage {
7131 * Calls parent::__construct with specific arguments
7133 public function __construct() {
7134 global $CFG;
7135 parent::__construct('managerepositories', get_string('manage',
7136 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
7140 * Searches page for the specified string.
7141 * @param string $query The string to search for
7142 * @return bool True if it is found on this page
7144 public function search($query) {
7145 global $CFG;
7146 if ($result = parent::search($query)) {
7147 return $result;
7150 $found = false;
7151 $repositories= core_component::get_plugin_list('repository');
7152 foreach ($repositories as $p => $dir) {
7153 if (strpos($p, $query) !== false) {
7154 $found = true;
7155 break;
7158 if (!$found) {
7159 foreach (repository::get_types() as $instance) {
7160 $title = $instance->get_typename();
7161 if (strpos(core_text::strtolower($title), $query) !== false) {
7162 $found = true;
7163 break;
7168 if ($found) {
7169 $result = new stdClass();
7170 $result->page = $this;
7171 $result->settings = array();
7172 return array($this->name => $result);
7173 } else {
7174 return array();
7181 * Special class for authentication administration.
7183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7185 class admin_setting_manageauths extends admin_setting {
7187 * Calls parent::__construct with specific arguments
7189 public function __construct() {
7190 $this->nosave = true;
7191 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
7195 * Always returns true
7197 * @return true
7199 public function get_setting() {
7200 return true;
7204 * Always returns true
7206 * @return true
7208 public function get_defaultsetting() {
7209 return true;
7213 * Always returns '' and doesn't write anything
7215 * @return string Always returns ''
7217 public function write_setting($data) {
7218 // do not write any setting
7219 return '';
7223 * Search to find if Query is related to auth plugin
7225 * @param string $query The string to search for
7226 * @return bool true for related false for not
7228 public function is_related($query) {
7229 if (parent::is_related($query)) {
7230 return true;
7233 $authsavailable = core_component::get_plugin_list('auth');
7234 foreach ($authsavailable as $auth => $dir) {
7235 if (strpos($auth, $query) !== false) {
7236 return true;
7238 $authplugin = get_auth_plugin($auth);
7239 $authtitle = $authplugin->get_title();
7240 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
7241 return true;
7244 return false;
7248 * Return XHTML to display control
7250 * @param mixed $data Unused
7251 * @param string $query
7252 * @return string highlight
7254 public function output_html($data, $query='') {
7255 global $CFG, $OUTPUT, $DB;
7257 // display strings
7258 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7259 'settings', 'edit', 'name', 'enable', 'disable',
7260 'up', 'down', 'none', 'users'));
7261 $txt->updown = "$txt->up/$txt->down";
7262 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7263 $txt->testsettings = get_string('testsettings', 'core_auth');
7265 $authsavailable = core_component::get_plugin_list('auth');
7266 get_enabled_auth_plugins(true); // fix the list of enabled auths
7267 if (empty($CFG->auth)) {
7268 $authsenabled = array();
7269 } else {
7270 $authsenabled = explode(',', $CFG->auth);
7273 // construct the display array, with enabled auth plugins at the top, in order
7274 $displayauths = array();
7275 $registrationauths = array();
7276 $registrationauths[''] = $txt->disable;
7277 $authplugins = array();
7278 foreach ($authsenabled as $auth) {
7279 $authplugin = get_auth_plugin($auth);
7280 $authplugins[$auth] = $authplugin;
7281 /// Get the auth title (from core or own auth lang files)
7282 $authtitle = $authplugin->get_title();
7283 /// Apply titles
7284 $displayauths[$auth] = $authtitle;
7285 if ($authplugin->can_signup()) {
7286 $registrationauths[$auth] = $authtitle;
7290 foreach ($authsavailable as $auth => $dir) {
7291 if (array_key_exists($auth, $displayauths)) {
7292 continue; //already in the list
7294 $authplugin = get_auth_plugin($auth);
7295 $authplugins[$auth] = $authplugin;
7296 /// Get the auth title (from core or own auth lang files)
7297 $authtitle = $authplugin->get_title();
7298 /// Apply titles
7299 $displayauths[$auth] = $authtitle;
7300 if ($authplugin->can_signup()) {
7301 $registrationauths[$auth] = $authtitle;
7305 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7306 $return .= $OUTPUT->box_start('generalbox authsui');
7308 $table = new html_table();
7309 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
7310 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7311 $table->data = array();
7312 $table->attributes['class'] = 'admintable generaltable';
7313 $table->id = 'manageauthtable';
7315 //add always enabled plugins first
7316 $displayname = $displayauths['manual'];
7317 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7318 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7319 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
7320 $displayname = $displayauths['nologin'];
7321 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7322 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
7325 // iterate through auth plugins and add to the display table
7326 $updowncount = 1;
7327 $authcount = count($authsenabled);
7328 $url = "auth.php?sesskey=" . sesskey();
7329 foreach ($displayauths as $auth => $name) {
7330 if ($auth == 'manual' or $auth == 'nologin') {
7331 continue;
7333 $class = '';
7334 // hide/show link
7335 if (in_array($auth, $authsenabled)) {
7336 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
7337 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7338 $enabled = true;
7339 $displayname = $name;
7341 else {
7342 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
7343 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7344 $enabled = false;
7345 $displayname = $name;
7346 $class = 'dimmed_text';
7349 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7351 // up/down link (only if auth is enabled)
7352 $updown = '';
7353 if ($enabled) {
7354 if ($updowncount > 1) {
7355 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
7356 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7358 else {
7359 $updown .= $OUTPUT->spacer() . '&nbsp;';
7361 if ($updowncount < $authcount) {
7362 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
7363 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7365 else {
7366 $updown .= $OUTPUT->spacer() . '&nbsp;';
7368 ++ $updowncount;
7371 // settings link
7372 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
7373 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7374 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
7375 throw new \coding_exception('config.html is no longer supported, please use settings.php instead.');
7376 } else {
7377 $settings = '';
7380 // Uninstall link.
7381 $uninstall = '';
7382 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7383 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7386 $test = '';
7387 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7388 $testurl = new moodle_url('/auth/test_settings.php', ['auth' => $auth]);
7389 $test = html_writer::link($testurl, $txt->testsettings);
7392 // Add a row to the table.
7393 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7394 if ($class) {
7395 $row->attributes['class'] = $class;
7397 $table->data[] = $row;
7399 $return .= html_writer::table($table);
7400 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7401 $return .= $OUTPUT->box_end();
7402 return highlight($query, $return);
7407 * Special class for antiviruses administration.
7409 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7412 class admin_setting_manageantiviruses extends admin_setting {
7414 * Calls parent::__construct with specific arguments
7416 public function __construct() {
7417 $this->nosave = true;
7418 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7422 * Always returns true, does nothing
7424 * @return true
7426 public function get_setting() {
7427 return true;
7431 * Always returns true, does nothing
7433 * @return true
7435 public function get_defaultsetting() {
7436 return true;
7440 * Always returns '', does not write anything
7442 * @param string $data Unused
7443 * @return string Always returns ''
7445 public function write_setting($data) {
7446 // Do not write any setting.
7447 return '';
7451 * Checks if $query is one of the available editors
7453 * @param string $query The string to search for
7454 * @return bool Returns true if found, false if not
7456 public function is_related($query) {
7457 if (parent::is_related($query)) {
7458 return true;
7461 $antivirusesavailable = \core\antivirus\manager::get_available();
7462 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7463 if (strpos($antivirus, $query) !== false) {
7464 return true;
7466 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7467 return true;
7470 return false;
7474 * Builds the XHTML to display the control
7476 * @param string $data Unused
7477 * @param string $query
7478 * @return string
7480 public function output_html($data, $query='') {
7481 global $CFG, $OUTPUT;
7483 // Display strings.
7484 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7485 'up', 'down', 'none'));
7486 $struninstall = get_string('uninstallplugin', 'core_admin');
7488 $txt->updown = "$txt->up/$txt->down";
7490 $antivirusesavailable = \core\antivirus\manager::get_available();
7491 $activeantiviruses = explode(',', $CFG->antiviruses);
7493 $activeantiviruses = array_reverse($activeantiviruses);
7494 foreach ($activeantiviruses as $key => $antivirus) {
7495 if (empty($antivirusesavailable[$antivirus])) {
7496 unset($activeantiviruses[$key]);
7497 } else {
7498 $name = $antivirusesavailable[$antivirus];
7499 unset($antivirusesavailable[$antivirus]);
7500 $antivirusesavailable[$antivirus] = $name;
7503 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7504 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7505 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7507 $table = new html_table();
7508 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7509 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7510 $table->id = 'antivirusmanagement';
7511 $table->attributes['class'] = 'admintable generaltable';
7512 $table->data = array();
7514 // Iterate through auth plugins and add to the display table.
7515 $updowncount = 1;
7516 $antiviruscount = count($activeantiviruses);
7517 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7518 foreach ($antivirusesavailable as $antivirus => $name) {
7519 // Hide/show link.
7520 $class = '';
7521 if (in_array($antivirus, $activeantiviruses)) {
7522 $hideshowurl = $baseurl;
7523 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7524 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7525 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7526 $enabled = true;
7527 $displayname = $name;
7528 } else {
7529 $hideshowurl = $baseurl;
7530 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7531 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7532 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7533 $enabled = false;
7534 $displayname = $name;
7535 $class = 'dimmed_text';
7538 // Up/down link.
7539 $updown = '';
7540 if ($enabled) {
7541 if ($updowncount > 1) {
7542 $updownurl = $baseurl;
7543 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7544 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7545 $updown = html_writer::link($updownurl, $updownimg);
7546 } else {
7547 $updownimg = $OUTPUT->spacer();
7549 if ($updowncount < $antiviruscount) {
7550 $updownurl = $baseurl;
7551 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7552 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7553 $updown = html_writer::link($updownurl, $updownimg);
7554 } else {
7555 $updownimg = $OUTPUT->spacer();
7557 ++ $updowncount;
7560 // Settings link.
7561 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7562 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7563 $settings = html_writer::link($eurl, $txt->settings);
7564 } else {
7565 $settings = '';
7568 $uninstall = '';
7569 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7570 $uninstall = html_writer::link($uninstallurl, $struninstall);
7573 // Add a row to the table.
7574 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7575 if ($class) {
7576 $row->attributes['class'] = $class;
7578 $table->data[] = $row;
7580 $return .= html_writer::table($table);
7581 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7582 $return .= $OUTPUT->box_end();
7583 return highlight($query, $return);
7588 * Course formats manager. Allows to enable/disable formats and jump to settings
7590 class admin_setting_manageformats extends admin_setting {
7593 * Calls parent::__construct with specific arguments
7595 public function __construct() {
7596 $this->nosave = true;
7597 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7601 * Always returns true
7603 * @return true
7605 public function get_setting() {
7606 return true;
7610 * Always returns true
7612 * @return true
7614 public function get_defaultsetting() {
7615 return true;
7619 * Always returns '' and doesn't write anything
7621 * @param mixed $data string or array, must not be NULL
7622 * @return string Always returns ''
7624 public function write_setting($data) {
7625 // do not write any setting
7626 return '';
7630 * Search to find if Query is related to format plugin
7632 * @param string $query The string to search for
7633 * @return bool true for related false for not
7635 public function is_related($query) {
7636 if (parent::is_related($query)) {
7637 return true;
7639 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7640 foreach ($formats as $format) {
7641 if (strpos($format->component, $query) !== false ||
7642 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7643 return true;
7646 return false;
7650 * Return XHTML to display control
7652 * @param mixed $data Unused
7653 * @param string $query
7654 * @return string highlight
7656 public function output_html($data, $query='') {
7657 global $CFG, $OUTPUT;
7658 $return = '';
7659 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7660 $return .= $OUTPUT->box_start('generalbox formatsui');
7662 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7664 // display strings
7665 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7666 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7667 $txt->updown = "$txt->up/$txt->down";
7669 $table = new html_table();
7670 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7671 $table->align = array('left', 'center', 'center', 'center', 'center');
7672 $table->attributes['class'] = 'manageformattable generaltable admintable';
7673 $table->data = array();
7675 $cnt = 0;
7676 $defaultformat = get_config('moodlecourse', 'format');
7677 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7678 foreach ($formats as $format) {
7679 $url = new moodle_url('/admin/courseformats.php',
7680 array('sesskey' => sesskey(), 'format' => $format->name));
7681 $isdefault = '';
7682 $class = '';
7683 if ($format->is_enabled()) {
7684 $strformatname = $format->displayname;
7685 if ($defaultformat === $format->name) {
7686 $hideshow = $txt->default;
7687 } else {
7688 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7689 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7691 } else {
7692 $strformatname = $format->displayname;
7693 $class = 'dimmed_text';
7694 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7695 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7697 $updown = '';
7698 if ($cnt) {
7699 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7700 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7701 } else {
7702 $updown .= $spacer;
7704 if ($cnt < count($formats) - 1) {
7705 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7706 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7707 } else {
7708 $updown .= $spacer;
7710 $cnt++;
7711 $settings = '';
7712 if ($format->get_settings_url()) {
7713 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7715 $uninstall = '';
7716 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7717 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7719 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7720 if ($class) {
7721 $row->attributes['class'] = $class;
7723 $table->data[] = $row;
7725 $return .= html_writer::table($table);
7726 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7727 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7728 $return .= $OUTPUT->box_end();
7729 return highlight($query, $return);
7734 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7736 * @package core
7737 * @copyright 2018 Toni Barbera
7738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7740 class admin_setting_managecustomfields extends admin_setting {
7743 * Calls parent::__construct with specific arguments
7745 public function __construct() {
7746 $this->nosave = true;
7747 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7751 * Always returns true
7753 * @return true
7755 public function get_setting() {
7756 return true;
7760 * Always returns true
7762 * @return true
7764 public function get_defaultsetting() {
7765 return true;
7769 * Always returns '' and doesn't write anything
7771 * @param mixed $data string or array, must not be NULL
7772 * @return string Always returns ''
7774 public function write_setting($data) {
7775 // Do not write any setting.
7776 return '';
7780 * Search to find if Query is related to format plugin
7782 * @param string $query The string to search for
7783 * @return bool true for related false for not
7785 public function is_related($query) {
7786 if (parent::is_related($query)) {
7787 return true;
7789 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7790 foreach ($formats as $format) {
7791 if (strpos($format->component, $query) !== false ||
7792 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7793 return true;
7796 return false;
7800 * Return XHTML to display control
7802 * @param mixed $data Unused
7803 * @param string $query
7804 * @return string highlight
7806 public function output_html($data, $query='') {
7807 global $CFG, $OUTPUT;
7808 $return = '';
7809 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7810 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7812 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7814 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7815 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7816 $txt->updown = "$txt->up/$txt->down";
7818 $table = new html_table();
7819 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7820 $table->align = array('left', 'center', 'center', 'center');
7821 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7822 $table->data = array();
7824 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7825 foreach ($fields as $field) {
7826 $url = new moodle_url('/admin/customfields.php',
7827 array('sesskey' => sesskey(), 'field' => $field->name));
7829 if ($field->is_enabled()) {
7830 $strfieldname = $field->displayname;
7831 $class = '';
7832 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7833 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7834 } else {
7835 $strfieldname = $field->displayname;
7836 $class = 'dimmed_text';
7837 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7838 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7840 $settings = '';
7841 if ($field->get_settings_url()) {
7842 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7844 $uninstall = '';
7845 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7846 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7848 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7849 $row->attributes['class'] = $class;
7850 $table->data[] = $row;
7852 $return .= html_writer::table($table);
7853 $return .= $OUTPUT->box_end();
7854 return highlight($query, $return);
7859 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7861 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7862 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7864 class admin_setting_managedataformats extends admin_setting {
7867 * Calls parent::__construct with specific arguments
7869 public function __construct() {
7870 $this->nosave = true;
7871 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7875 * Always returns true
7877 * @return true
7879 public function get_setting() {
7880 return true;
7884 * Always returns true
7886 * @return true
7888 public function get_defaultsetting() {
7889 return true;
7893 * Always returns '' and doesn't write anything
7895 * @param mixed $data string or array, must not be NULL
7896 * @return string Always returns ''
7898 public function write_setting($data) {
7899 // Do not write any setting.
7900 return '';
7904 * Search to find if Query is related to format plugin
7906 * @param string $query The string to search for
7907 * @return bool true for related false for not
7909 public function is_related($query) {
7910 if (parent::is_related($query)) {
7911 return true;
7913 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7914 foreach ($formats as $format) {
7915 if (strpos($format->component, $query) !== false ||
7916 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7917 return true;
7920 return false;
7924 * Return XHTML to display control
7926 * @param mixed $data Unused
7927 * @param string $query
7928 * @return string highlight
7930 public function output_html($data, $query='') {
7931 global $CFG, $OUTPUT;
7932 $return = '';
7934 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7936 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7937 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7938 $txt->updown = "$txt->up/$txt->down";
7940 $table = new html_table();
7941 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7942 $table->align = array('left', 'center', 'center', 'center', 'center');
7943 $table->attributes['class'] = 'manageformattable generaltable admintable';
7944 $table->data = array();
7946 $cnt = 0;
7947 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7948 $totalenabled = 0;
7949 foreach ($formats as $format) {
7950 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7951 $totalenabled++;
7954 foreach ($formats as $format) {
7955 $status = $format->get_status();
7956 $url = new moodle_url('/admin/dataformats.php',
7957 array('sesskey' => sesskey(), 'name' => $format->name));
7959 $class = '';
7960 if ($format->is_enabled()) {
7961 $strformatname = $format->displayname;
7962 if ($totalenabled == 1&& $format->is_enabled()) {
7963 $hideshow = '';
7964 } else {
7965 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7966 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7968 } else {
7969 $class = 'dimmed_text';
7970 $strformatname = $format->displayname;
7971 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7972 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7975 $updown = '';
7976 if ($cnt) {
7977 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7978 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7979 } else {
7980 $updown .= $spacer;
7982 if ($cnt < count($formats) - 1) {
7983 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7984 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7985 } else {
7986 $updown .= $spacer;
7989 $uninstall = '';
7990 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7991 $uninstall = get_string('status_missing', 'core_plugin');
7992 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7993 $uninstall = get_string('status_new', 'core_plugin');
7994 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7995 if ($totalenabled != 1 || !$format->is_enabled()) {
7996 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8000 $settings = '';
8001 if ($format->get_settings_url()) {
8002 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
8005 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
8006 if ($class) {
8007 $row->attributes['class'] = $class;
8009 $table->data[] = $row;
8010 $cnt++;
8012 $return .= html_writer::table($table);
8013 return highlight($query, $return);
8018 * Special class for filter administration.
8020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8022 class admin_page_managefilters extends admin_externalpage {
8024 * Calls parent::__construct with specific arguments
8026 public function __construct() {
8027 global $CFG;
8028 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
8032 * Searches all installed filters for specified filter
8034 * @param string $query The filter(string) to search for
8035 * @param string $query
8037 public function search($query) {
8038 global $CFG;
8039 if ($result = parent::search($query)) {
8040 return $result;
8043 $found = false;
8044 $filternames = filter_get_all_installed();
8045 foreach ($filternames as $path => $strfiltername) {
8046 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
8047 $found = true;
8048 break;
8050 if (strpos($path, $query) !== false) {
8051 $found = true;
8052 break;
8056 if ($found) {
8057 $result = new stdClass;
8058 $result->page = $this;
8059 $result->settings = array();
8060 return array($this->name => $result);
8061 } else {
8062 return array();
8068 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8069 * Requires a get_rank method on the plugininfo class for sorting.
8071 * @copyright 2017 Damyon Wiese
8072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8074 abstract class admin_setting_manage_plugins extends admin_setting {
8077 * Get the admin settings section name (just a unique string)
8079 * @return string
8081 public function get_section_name() {
8082 return 'manage' . $this->get_plugin_type() . 'plugins';
8086 * Get the admin settings section title (use get_string).
8088 * @return string
8090 abstract public function get_section_title();
8093 * Get the type of plugin to manage.
8095 * @return string
8097 abstract public function get_plugin_type();
8100 * Get the name of the second column.
8102 * @return string
8104 public function get_info_column_name() {
8105 return '';
8109 * Get the type of plugin to manage.
8111 * @param plugininfo The plugin info class.
8112 * @return string
8114 abstract public function get_info_column($plugininfo);
8117 * Calls parent::__construct with specific arguments
8119 public function __construct() {
8120 $this->nosave = true;
8121 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8125 * Always returns true, does nothing
8127 * @return true
8129 public function get_setting() {
8130 return true;
8134 * Always returns true, does nothing
8136 * @return true
8138 public function get_defaultsetting() {
8139 return true;
8143 * Always returns '', does not write anything
8145 * @param mixed $data
8146 * @return string Always returns ''
8148 public function write_setting($data) {
8149 // Do not write any setting.
8150 return '';
8154 * Checks if $query is one of the available plugins of this type
8156 * @param string $query The string to search for
8157 * @return bool Returns true if found, false if not
8159 public function is_related($query) {
8160 if (parent::is_related($query)) {
8161 return true;
8164 $query = core_text::strtolower($query);
8165 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
8166 foreach ($plugins as $name => $plugin) {
8167 $localised = $plugin->displayname;
8168 if (strpos(core_text::strtolower($name), $query) !== false) {
8169 return true;
8171 if (strpos(core_text::strtolower($localised), $query) !== false) {
8172 return true;
8175 return false;
8179 * The URL for the management page for this plugintype.
8181 * @return moodle_url
8183 protected function get_manage_url() {
8184 return new moodle_url('/admin/updatesetting.php');
8188 * Builds the HTML to display the control.
8190 * @param string $data Unused
8191 * @param string $query
8192 * @return string
8194 public function output_html($data, $query = '') {
8195 global $CFG, $OUTPUT, $DB, $PAGE;
8197 $context = (object) [
8198 'manageurl' => new moodle_url($this->get_manage_url(), [
8199 'type' => $this->get_plugin_type(),
8200 'sesskey' => sesskey(),
8202 'infocolumnname' => $this->get_info_column_name(),
8203 'plugins' => [],
8206 $pluginmanager = core_plugin_manager::instance();
8207 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8208 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8209 $plugins = array_merge($enabled, $allplugins);
8210 foreach ($plugins as $key => $plugin) {
8211 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
8213 $pluginkey = (object) [
8214 'plugin' => $plugin->displayname,
8215 'enabled' => $plugin->is_enabled(),
8216 'togglelink' => '',
8217 'moveuplink' => '',
8218 'movedownlink' => '',
8219 'settingslink' => $plugin->get_settings_url(),
8220 'uninstalllink' => '',
8221 'info' => '',
8224 // Enable/Disable link.
8225 $togglelink = new moodle_url($pluginlink);
8226 if ($plugin->is_enabled()) {
8227 $toggletarget = false;
8228 $togglelink->param('action', 'disable');
8230 if (count($context->plugins)) {
8231 // This is not the first plugin.
8232 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
8235 if (count($enabled) > count($context->plugins) + 1) {
8236 // This is not the last plugin.
8237 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
8240 $pluginkey->info = $this->get_info_column($plugin);
8241 } else {
8242 $toggletarget = true;
8243 $togglelink->param('action', 'enable');
8246 $pluginkey->toggletarget = $toggletarget;
8247 $pluginkey->togglelink = $togglelink;
8249 $frankenstyle = $plugin->type . '_' . $plugin->name;
8250 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8251 // This plugin supports uninstallation.
8252 $pluginkey->uninstalllink = $uninstalllink;
8255 if (!empty($this->get_info_column_name())) {
8256 // This plugintype has an info column.
8257 $pluginkey->info = $this->get_info_column($plugin);
8260 $context->plugins[] = $pluginkey;
8263 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8264 return highlight($query, $str);
8269 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8270 * Requires a get_rank method on the plugininfo class for sorting.
8272 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8275 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8276 public function get_section_title() {
8277 return get_string('type_fileconverter_plural', 'plugin');
8280 public function get_plugin_type() {
8281 return 'fileconverter';
8284 public function get_info_column_name() {
8285 return get_string('supportedconversions', 'plugin');
8288 public function get_info_column($plugininfo) {
8289 return $plugininfo->get_supported_conversions();
8294 * Special class for media player plugins management.
8296 * @copyright 2016 Marina Glancy
8297 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8299 class admin_setting_managemediaplayers extends admin_setting {
8301 * Calls parent::__construct with specific arguments
8303 public function __construct() {
8304 $this->nosave = true;
8305 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8309 * Always returns true, does nothing
8311 * @return true
8313 public function get_setting() {
8314 return true;
8318 * Always returns true, does nothing
8320 * @return true
8322 public function get_defaultsetting() {
8323 return true;
8327 * Always returns '', does not write anything
8329 * @param mixed $data
8330 * @return string Always returns ''
8332 public function write_setting($data) {
8333 // Do not write any setting.
8334 return '';
8338 * Checks if $query is one of the available enrol plugins
8340 * @param string $query The string to search for
8341 * @return bool Returns true if found, false if not
8343 public function is_related($query) {
8344 if (parent::is_related($query)) {
8345 return true;
8348 $query = core_text::strtolower($query);
8349 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8350 foreach ($plugins as $name => $plugin) {
8351 $localised = $plugin->displayname;
8352 if (strpos(core_text::strtolower($name), $query) !== false) {
8353 return true;
8355 if (strpos(core_text::strtolower($localised), $query) !== false) {
8356 return true;
8359 return false;
8363 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8364 * @return \core\plugininfo\media[]
8366 protected function get_sorted_plugins() {
8367 $pluginmanager = core_plugin_manager::instance();
8369 $plugins = $pluginmanager->get_plugins_of_type('media');
8370 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8372 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8373 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8375 $order = array_values($enabledplugins);
8376 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8378 $sortedplugins = array();
8379 foreach ($order as $name) {
8380 $sortedplugins[$name] = $plugins[$name];
8383 return $sortedplugins;
8387 * Builds the XHTML to display the control
8389 * @param string $data Unused
8390 * @param string $query
8391 * @return string
8393 public function output_html($data, $query='') {
8394 global $CFG, $OUTPUT, $DB, $PAGE;
8396 // Display strings.
8397 $strup = get_string('up');
8398 $strdown = get_string('down');
8399 $strsettings = get_string('settings');
8400 $strenable = get_string('enable');
8401 $strdisable = get_string('disable');
8402 $struninstall = get_string('uninstallplugin', 'core_admin');
8403 $strversion = get_string('version');
8404 $strname = get_string('name');
8405 $strsupports = get_string('supports', 'core_media');
8407 $pluginmanager = core_plugin_manager::instance();
8409 $plugins = $this->get_sorted_plugins();
8410 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8412 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8414 $table = new html_table();
8415 $table->head = array($strname, $strsupports, $strversion,
8416 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8417 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8418 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8419 $table->id = 'mediaplayerplugins';
8420 $table->attributes['class'] = 'admintable generaltable';
8421 $table->data = array();
8423 // Iterate through media plugins and add to the display table.
8424 $updowncount = 1;
8425 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8426 $printed = array();
8427 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8429 $usedextensions = [];
8430 foreach ($plugins as $name => $plugin) {
8431 $url->param('media', $name);
8432 /** @var \core\plugininfo\media $plugininfo */
8433 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8434 $version = $plugininfo->versiondb;
8435 $supports = $plugininfo->supports($usedextensions);
8437 // Hide/show links.
8438 $class = '';
8439 if (!$plugininfo->is_installed_and_upgraded()) {
8440 $hideshow = '';
8441 $enabled = false;
8442 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8443 } else {
8444 $enabled = $plugininfo->is_enabled();
8445 if ($enabled) {
8446 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8447 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8448 } else {
8449 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8450 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8451 $class = 'dimmed_text';
8453 $displayname = $plugin->displayname;
8454 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8455 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8458 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8459 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8460 } else {
8461 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8464 // Up/down link (only if enrol is enabled).
8465 $updown = '';
8466 if ($enabled) {
8467 if ($updowncount > 1) {
8468 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8469 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8470 } else {
8471 $updown = $spacer;
8473 if ($updowncount < count($enabledplugins)) {
8474 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8475 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8476 } else {
8477 $updown .= $spacer;
8479 ++$updowncount;
8482 $uninstall = '';
8483 $status = $plugininfo->get_status();
8484 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8485 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8487 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8488 $uninstall = get_string('status_new', 'core_plugin');
8489 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8490 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8493 $settings = '';
8494 if ($plugininfo->get_settings_url()) {
8495 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8498 // Add a row to the table.
8499 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8500 if ($class) {
8501 $row->attributes['class'] = $class;
8503 $table->data[] = $row;
8505 $printed[$name] = true;
8508 $return .= html_writer::table($table);
8509 $return .= $OUTPUT->box_end();
8510 return highlight($query, $return);
8516 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8518 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8521 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8524 * Calls parent::__construct with specific arguments
8526 public function __construct() {
8527 $this->nosave = true;
8528 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8532 * Always returns true
8534 * @return true
8536 public function get_setting() {
8537 return true;
8541 * Always returns true
8543 * @return true
8545 public function get_defaultsetting() {
8546 return true;
8550 * Always returns '' and doesn't write anything
8552 * @param mixed $data string or array, must not be NULL
8553 * @return string Always returns ''
8555 public function write_setting($data) {
8556 // Do not write any setting.
8557 return '';
8561 * Search to find if Query is related to content bank plugin
8563 * @param string $query The string to search for
8564 * @return bool true for related false for not
8566 public function is_related($query) {
8567 if (parent::is_related($query)) {
8568 return true;
8570 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8571 foreach ($types as $type) {
8572 if (strpos($type->component, $query) !== false ||
8573 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8574 return true;
8577 return false;
8581 * Return XHTML to display control
8583 * @param mixed $data Unused
8584 * @param string $query
8585 * @return string highlight
8587 public function output_html($data, $query='') {
8588 global $CFG, $OUTPUT;
8589 $return = '';
8591 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8592 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8593 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8595 $table = new html_table();
8596 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8597 $table->align = array('left', 'center', 'center', 'center', 'center');
8598 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8599 $table->data = array();
8600 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8602 $totalenabled = 0;
8603 $count = 0;
8604 foreach ($types as $type) {
8605 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8606 $totalenabled++;
8610 foreach ($types as $type) {
8611 $url = new moodle_url('/admin/contentbank.php',
8612 array('sesskey' => sesskey(), 'name' => $type->name));
8614 $class = '';
8615 $strtypename = $type->displayname;
8616 if ($type->is_enabled()) {
8617 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8618 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8619 } else {
8620 $class = 'dimmed_text';
8621 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8622 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8625 $updown = '';
8626 if ($count) {
8627 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8628 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8629 } else {
8630 $updown .= $spacer;
8632 if ($count < count($types) - 1) {
8633 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8634 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8635 } else {
8636 $updown .= $spacer;
8639 $settings = '';
8640 if ($type->get_settings_url()) {
8641 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8644 $uninstall = '';
8645 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8646 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8649 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8650 if ($class) {
8651 $row->attributes['class'] = $class;
8653 $table->data[] = $row;
8654 $count++;
8656 $return .= html_writer::table($table);
8657 return highlight($query, $return);
8662 * Initialise admin page - this function does require login and permission
8663 * checks specified in page definition.
8665 * This function must be called on each admin page before other code.
8667 * @global moodle_page $PAGE
8669 * @param string $section name of page
8670 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8671 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8672 * added to the turn blocks editing on/off form, so this page reloads correctly.
8673 * @param string $actualurl if the actual page being viewed is not the normal one for this
8674 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8675 * @param array $options Additional options that can be specified for page setup.
8676 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8677 * nosearch - Do not display search bar
8679 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8680 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8682 $PAGE->set_context(null); // hack - set context to something, by default to system context
8684 $site = get_site();
8685 require_login(null, false);
8687 if (!empty($options['pagelayout'])) {
8688 // A specific page layout has been requested.
8689 $PAGE->set_pagelayout($options['pagelayout']);
8690 } else if ($section === 'upgradesettings') {
8691 $PAGE->set_pagelayout('maintenance');
8692 } else {
8693 $PAGE->set_pagelayout('admin');
8696 $adminroot = admin_get_root(false, false); // settings not required for external pages
8697 $extpage = $adminroot->locate($section, true);
8699 $hassiteconfig = has_capability('moodle/site:config', context_system::instance());
8700 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8701 // The requested section isn't in the admin tree
8702 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8703 if (!$hassiteconfig) {
8704 // The requested section could depend on a different capability
8705 // but most likely the user has inadequate capabilities
8706 throw new \moodle_exception('accessdenied', 'admin');
8707 } else {
8708 throw new \moodle_exception('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8712 // this eliminates our need to authenticate on the actual pages
8713 if (!$extpage->check_access()) {
8714 throw new \moodle_exception('accessdenied', 'admin');
8715 die;
8718 navigation_node::require_admin_tree();
8720 // $PAGE->set_extra_button($extrabutton); TODO
8722 if (!$actualurl) {
8723 $actualurl = $extpage->url;
8726 $PAGE->set_url($actualurl, $extraurlparams);
8727 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8728 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8731 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8732 // During initial install.
8733 $strinstallation = get_string('installation', 'install');
8734 $strsettings = get_string('settings');
8735 $PAGE->navbar->add($strsettings);
8736 $PAGE->set_title($strinstallation);
8737 $PAGE->set_heading($strinstallation);
8738 $PAGE->set_cacheable(false);
8739 return;
8742 // Locate the current item on the navigation and make it active when found.
8743 $path = $extpage->path;
8744 $node = $PAGE->settingsnav;
8745 while ($node && count($path) > 0) {
8746 $node = $node->get(array_pop($path));
8748 if ($node) {
8749 $node->make_active();
8752 // Normal case.
8753 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8754 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8755 $USER->editing = $adminediting;
8758 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8759 if ($PAGE->user_is_editing()) {
8760 $caption = get_string('blockseditoff');
8761 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8762 } else {
8763 $caption = get_string('blocksediton');
8764 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8766 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8769 $PAGE->set_title(implode(moodle_page::TITLE_SEPARATOR, $extpage->visiblepath));
8770 $PAGE->set_heading($SITE->fullname);
8772 if ($hassiteconfig && empty($options['nosearch'])) {
8773 $PAGE->add_header_action($OUTPUT->render_from_template('core_admin/header_search_input', [
8774 'action' => new moodle_url('/admin/search.php'),
8775 'query' => $PAGE->url->get_param('query'),
8776 ]));
8779 // prevent caching in nav block
8780 $PAGE->navigation->clear_cache();
8784 * Returns the reference to admin tree root
8786 * @return object admin_root object
8788 function admin_get_root($reload=false, $requirefulltree=true) {
8789 global $CFG, $DB, $OUTPUT, $ADMIN;
8791 if (is_null($ADMIN)) {
8792 // create the admin tree!
8793 $ADMIN = new admin_root($requirefulltree);
8796 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8797 $ADMIN->purge_children($requirefulltree);
8800 if (!$ADMIN->loaded) {
8801 // we process this file first to create categories first and in correct order
8802 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8804 // now we process all other files in admin/settings to build the admin tree
8805 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8806 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8807 continue;
8809 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8810 // plugins are loaded last - they may insert pages anywhere
8811 continue;
8813 require($file);
8815 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8817 $ADMIN->loaded = true;
8820 return $ADMIN;
8823 /// settings utility functions
8826 * This function applies default settings recursively.
8828 * Because setting the defaults of some settings can enable other settings,
8829 * this function calls itself repeatedly (max 4 times) until no more new settings are saved.
8831 * NOTE: previous "internal" parameters $admindefaultsettings, $settingsoutput were removed in Moodle 4.3.
8833 * @param part_of_admin_tree|null $node NULL means apply all settings with repeated recursion
8834 * @param bool $unconditional if true overrides all values with defaults (true for installation, false for CLI upgrade)
8835 * @return array The names and values of the applied setting defaults
8837 function admin_apply_default_settings(?part_of_admin_tree $node = null, bool $unconditional = true): array {
8838 if (is_null($node)) {
8839 // This function relies heavily on config cache, so we need to enable in-memory caches if it
8840 // is used during install when normal caching is disabled.
8841 $token = new \core_cache\allow_temporary_caches(); // Value not used intentionally, see its destructor.
8843 core_plugin_manager::reset_caches();
8844 $root = admin_get_root(true, true);
8845 $saved = admin_apply_default_settings($root, $unconditional);
8846 if (!$saved) {
8847 return [];
8850 for ($i = 1; $i <= 3; $i++) {
8851 core_plugin_manager::reset_caches();
8852 $root = admin_get_root(true, true);
8853 // No need to force defaults in repeated runs.
8854 $moresaved = admin_apply_default_settings($root, false);
8855 if (!$moresaved) {
8856 // No more setting defaults to save.
8857 return $saved;
8859 $saved += $moresaved;
8862 // We should not get here unless there are some problematic settings.php files.
8863 core_plugin_manager::reset_caches();
8864 return $saved;
8867 // Recursive applying of defaults in admin tree.
8868 $saved = [];
8869 if ($node instanceof admin_category) {
8870 foreach ($node->children as $child) {
8871 if ($child === null) {
8872 // This should not happen,
8873 // this is to prevent theoretical infinite loops.
8874 continue;
8876 if ($child instanceof admin_externalpage) {
8877 continue;
8879 $saved += admin_apply_default_settings($child, $unconditional);
8882 } else if ($node instanceof admin_settingpage) {
8883 /** @var admin_setting $setting */
8884 foreach ((array)$node->settings as $setting) {
8885 if ($setting->nosave) {
8886 // Not a real setting, must be a heading or description.
8887 continue;
8889 if (!$unconditional && !is_null($setting->get_setting())) {
8890 // Do not override existing defaults.
8891 continue;
8893 $defaultsetting = $setting->get_defaultsetting();
8894 if (is_null($defaultsetting)) {
8895 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8896 continue;
8898 // This should be unique-enough setting name that matches administration UI.
8899 if ($setting->plugin === null) {
8900 $settingname = $setting->name;
8901 } else {
8902 $settingname = $setting->plugin . '/' . $setting->name;
8904 // Set the default for this setting.
8905 $error = $setting->write_setting($defaultsetting);
8906 if ($error === '') {
8907 $setting->write_setting_flags(null);
8908 if (is_int($defaultsetting) || $defaultsetting instanceof lang_string
8909 || $defaultsetting instanceof moodle_url) {
8910 $defaultsetting = (string)$defaultsetting;
8912 $saved[$settingname] = $defaultsetting;
8913 } else {
8914 debugging("Error applying default setting '$settingname': " . $error, DEBUG_DEVELOPER);
8919 return $saved;
8923 * Store changed settings, this function updates the errors variable in $ADMIN
8925 * @param object $formdata from form
8926 * @return int number of changed settings
8928 function admin_write_settings($formdata) {
8929 global $CFG, $SITE, $DB;
8931 $olddbsessions = !empty($CFG->dbsessions);
8932 $formdata = (array)$formdata;
8934 $data = array();
8935 foreach ($formdata as $fullname=>$value) {
8936 if (strpos($fullname, 's_') !== 0) {
8937 continue; // not a config value
8939 $data[$fullname] = $value;
8942 $adminroot = admin_get_root();
8943 $settings = admin_find_write_settings($adminroot, $data);
8945 $count = 0;
8946 foreach ($settings as $fullname=>$setting) {
8947 /** @var $setting admin_setting */
8948 $original = $setting->get_setting();
8949 $error = $setting->write_setting($data[$fullname]);
8950 if ($error !== '') {
8951 $adminroot->errors[$fullname] = new stdClass();
8952 $adminroot->errors[$fullname]->data = $data[$fullname];
8953 $adminroot->errors[$fullname]->id = $setting->get_id();
8954 $adminroot->errors[$fullname]->error = $error;
8955 } else {
8956 $setting->write_setting_flags($data);
8958 if ($setting->post_write_settings($original)) {
8959 $count++;
8963 if ($olddbsessions != !empty($CFG->dbsessions)) {
8964 require_logout();
8967 // Now update $SITE - just update the fields, in case other people have a
8968 // a reference to it (e.g. $PAGE, $COURSE).
8969 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8970 foreach (get_object_vars($newsite) as $field => $value) {
8971 $SITE->$field = $value;
8974 // now reload all settings - some of them might depend on the changed
8975 admin_get_root(true);
8976 return $count;
8980 * Internal recursive function - finds all settings from submitted form
8982 * @param object $node Instance of admin_category, or admin_settingpage
8983 * @param array $data
8984 * @return array
8986 function admin_find_write_settings($node, $data) {
8987 $return = array();
8989 if (empty($data)) {
8990 return $return;
8993 if ($node instanceof admin_category) {
8994 if ($node->check_access()) {
8995 $entries = array_keys($node->children);
8996 foreach ($entries as $entry) {
8997 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
9001 } else if ($node instanceof admin_settingpage) {
9002 if ($node->check_access()) {
9003 foreach ($node->settings as $setting) {
9004 $fullname = $setting->get_full_name();
9005 if (array_key_exists($fullname, $data)) {
9006 $return[$fullname] = $setting;
9013 return $return;
9017 * Internal function - prints the search results
9019 * @param string $query String to search for
9020 * @return string empty or XHTML
9022 function admin_search_settings_html($query) {
9023 global $CFG, $OUTPUT, $PAGE;
9025 if (core_text::strlen($query) < 2) {
9026 return '';
9028 $query = core_text::strtolower($query);
9030 $adminroot = admin_get_root();
9031 $findings = $adminroot->search($query);
9032 $savebutton = false;
9034 $tpldata = (object) [
9035 'actionurl' => $PAGE->url->out(false),
9036 'results' => [],
9037 'sesskey' => sesskey(),
9040 foreach ($findings as $found) {
9041 $page = $found->page;
9042 $settings = $found->settings;
9043 if ($page->is_hidden()) {
9044 // hidden pages are not displayed in search results
9045 continue;
9048 $heading = highlight($query, $page->visiblename);
9049 $headingurl = null;
9050 if ($page instanceof admin_externalpage) {
9051 $headingurl = new moodle_url($page->url);
9052 } else if ($page instanceof admin_settingpage) {
9053 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
9054 } else {
9055 continue;
9058 // Locate the page in the admin root and populate its visiblepath attribute.
9059 $path = array();
9060 $located = $adminroot->locate($page->name, true);
9061 if ($located) {
9062 foreach ($located->visiblepath as $pathitem) {
9063 array_unshift($path, (string) $pathitem);
9067 $sectionsettings = [];
9068 if (!empty($settings)) {
9069 foreach ($settings as $setting) {
9070 if (empty($setting->nosave)) {
9071 $savebutton = true;
9073 $fullname = $setting->get_full_name();
9074 if (array_key_exists($fullname, $adminroot->errors)) {
9075 $data = $adminroot->errors[$fullname]->data;
9076 } else {
9077 $data = $setting->get_setting();
9078 // do not use defaults if settings not available - upgradesettings handles the defaults!
9080 $sectionsettings[] = $setting->output_html($data, $query);
9084 $tpldata->results[] = (object) [
9085 'title' => $heading,
9086 'path' => $path,
9087 'url' => $headingurl->out(false),
9088 'settings' => $sectionsettings
9092 $tpldata->showsave = $savebutton;
9093 $tpldata->hasresults = !empty($tpldata->results);
9095 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
9099 * Internal function - returns arrays of html pages with uninitialised settings
9101 * @param object $node Instance of admin_category or admin_settingpage
9102 * @return array
9104 function admin_output_new_settings_by_page($node) {
9105 global $OUTPUT;
9106 $return = array();
9108 if ($node instanceof admin_category) {
9109 $entries = array_keys($node->children);
9110 foreach ($entries as $entry) {
9111 $return += admin_output_new_settings_by_page($node->children[$entry]);
9114 } else if ($node instanceof admin_settingpage) {
9115 $newsettings = array();
9116 foreach ($node->settings as $setting) {
9117 if (is_null($setting->get_setting())) {
9118 $newsettings[] = $setting;
9121 if (count($newsettings) > 0) {
9122 $adminroot = admin_get_root();
9123 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
9124 $page .= '<fieldset class="adminsettings">'."\n";
9125 foreach ($newsettings as $setting) {
9126 $fullname = $setting->get_full_name();
9127 if (array_key_exists($fullname, $adminroot->errors)) {
9128 $data = $adminroot->errors[$fullname]->data;
9129 } else {
9130 $data = $setting->get_setting();
9131 if (is_null($data)) {
9132 $data = $setting->get_defaultsetting();
9135 $page .= '<div class="clearer"><!-- --></div>'."\n";
9136 $page .= $setting->output_html($data);
9138 $page .= '</fieldset>';
9139 $return[$node->name] = $page;
9143 return $return;
9147 * Format admin settings
9149 * @param object $setting
9150 * @param string $title label element
9151 * @param string $form form fragment, html code - not highlighted automatically
9152 * @param string $description
9153 * @param mixed $label link label to id, true by default or string being the label to connect it to
9154 * @param string $warning warning text
9155 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9156 * @param string $query search query to be highlighted
9157 * @return string XHTML
9159 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9160 global $CFG, $OUTPUT;
9162 $context = (object) [
9163 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9164 'fullname' => $setting->get_full_name(),
9167 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9168 if ($label === true) {
9169 $context->labelfor = $setting->get_id();
9170 } else if ($label === false) {
9171 $context->labelfor = '';
9172 } else {
9173 $context->labelfor = $label;
9176 $form .= $setting->output_setting_flags();
9178 $context->warning = $warning;
9179 $context->override = '';
9180 if (empty($setting->plugin)) {
9181 if ($setting->is_forceable() && array_key_exists($setting->name, $CFG->config_php_settings)) {
9182 $context->override = get_string('configoverride', 'admin');
9184 } else {
9185 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9186 $context->override = get_string('configoverride', 'admin');
9190 $defaults = array();
9191 if (!is_null($defaultinfo)) {
9192 if ($defaultinfo === '') {
9193 $defaultinfo = get_string('emptysettingvalue', 'admin');
9195 $defaults[] = $defaultinfo;
9198 $context->default = null;
9199 $setting->get_setting_flag_defaults($defaults);
9200 if (!empty($defaults)) {
9201 $defaultinfo = implode(', ', $defaults);
9202 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9203 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9207 $context->error = '';
9208 $adminroot = admin_get_root();
9209 if (array_key_exists($context->fullname, $adminroot->errors)) {
9210 $context->error = $adminroot->errors[$context->fullname]->error;
9213 if ($dependenton = $setting->get_dependent_on()) {
9214 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9217 $context->id = 'admin-' . $setting->name;
9218 $context->title = highlightfast($query, $title);
9219 $context->name = highlightfast($query, $context->name);
9220 $context->description = highlight($query, markdown_to_html($description));
9221 $context->element = $form;
9222 $context->forceltr = $setting->get_force_ltr();
9223 $context->customcontrol = $setting->has_custom_form_control();
9225 return $OUTPUT->render_from_template('core_admin/setting', $context);
9229 * Based on find_new_settings{@link ()} in upgradesettings.php
9230 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9232 * @param object $node Instance of admin_category, or admin_settingpage
9233 * @return boolean true if any settings haven't been initialised, false if they all have
9235 function any_new_admin_settings($node) {
9237 if ($node instanceof admin_category) {
9238 $entries = array_keys($node->children);
9239 foreach ($entries as $entry) {
9240 if (any_new_admin_settings($node->children[$entry])) {
9241 return true;
9245 } else if ($node instanceof admin_settingpage) {
9246 foreach ($node->settings as $setting) {
9247 if ($setting->get_setting() === NULL) {
9248 return true;
9253 return false;
9257 * Given a table and optionally a column name should replaces be done?
9259 * @param string $table name
9260 * @param string $column name
9261 * @return bool success or fail
9263 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9265 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9266 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9267 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9269 // Additional skip tables.
9270 if (!empty($additionalskiptables)) {
9271 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9274 // Don't process these.
9275 if (in_array($table, $skiptables)) {
9276 return false;
9279 // To be safe never replace inside a table that looks related to logging.
9280 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9281 return false;
9284 // Do column based exclusions.
9285 if (!empty($column)) {
9286 // Don't touch anything that looks like a hash.
9287 if (preg_match('/hash$/', $column)) {
9288 return false;
9292 return true;
9296 * Moved from admin/replace.php so that we can use this in cron
9298 * @param string $search string to look for
9299 * @param string $replace string to replace
9300 * @return bool success or fail
9302 function db_replace($search, $replace, $additionalskiptables = '') {
9303 global $DB, $CFG, $OUTPUT;
9305 // Turn off time limits, sometimes upgrades can be slow.
9306 core_php_time_limit::raise();
9308 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9309 return false;
9311 foreach ($tables as $table) {
9313 if (!db_should_replace($table, '', $additionalskiptables)) {
9314 continue;
9317 if ($columns = $DB->get_columns($table)) {
9318 $DB->set_debug(true);
9319 foreach ($columns as $column) {
9320 if (!db_should_replace($table, $column->name)) {
9321 continue;
9323 $DB->replace_all_text($table, $column, $search, $replace);
9325 $DB->set_debug(false);
9329 // delete modinfo caches
9330 rebuild_course_cache(0, true);
9332 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9333 $blocks = core_component::get_plugin_list('block');
9334 foreach ($blocks as $blockname=>$fullblock) {
9335 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9336 continue;
9339 if (!is_readable($fullblock.'/lib.php')) {
9340 continue;
9343 $function = 'block_'.$blockname.'_global_db_replace';
9344 include_once($fullblock.'/lib.php');
9345 if (!function_exists($function)) {
9346 continue;
9349 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9350 $function($search, $replace);
9351 echo $OUTPUT->notification("...finished", 'notifysuccess');
9354 // Trigger an event.
9355 $eventargs = [
9356 'context' => context_system::instance(),
9357 'other' => [
9358 'search' => $search,
9359 'replace' => $replace
9362 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9363 $event->trigger();
9365 purge_all_caches();
9367 return true;
9371 * Manage repository settings
9373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9375 class admin_setting_managerepository extends admin_setting {
9376 /** @var string */
9377 private $baseurl;
9380 * calls parent::__construct with specific arguments
9382 public function __construct() {
9383 global $CFG;
9384 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9385 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9389 * Always returns true, does nothing
9391 * @return true
9393 public function get_setting() {
9394 return true;
9398 * Always returns true does nothing
9400 * @return true
9402 public function get_defaultsetting() {
9403 return true;
9407 * Always returns s_managerepository
9409 * @return string Always return 's_managerepository'
9411 public function get_full_name() {
9412 return 's_managerepository';
9416 * Always returns '' doesn't do anything
9418 public function write_setting($data) {
9419 $url = $this->baseurl . '&amp;new=' . $data;
9420 return '';
9421 // TODO
9422 // Should not use redirect and exit here
9423 // Find a better way to do this.
9424 // redirect($url);
9425 // exit;
9429 * Searches repository plugins for one that matches $query
9431 * @param string $query The string to search for
9432 * @return bool true if found, false if not
9434 public function is_related($query) {
9435 if (parent::is_related($query)) {
9436 return true;
9439 $repositories= core_component::get_plugin_list('repository');
9440 foreach ($repositories as $p => $dir) {
9441 if (strpos($p, $query) !== false) {
9442 return true;
9445 foreach (repository::get_types() as $instance) {
9446 $title = $instance->get_typename();
9447 if (strpos(core_text::strtolower($title), $query) !== false) {
9448 return true;
9451 return false;
9455 * Helper function that generates a moodle_url object
9456 * relevant to the repository
9459 function repository_action_url($repository) {
9460 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9464 * Builds XHTML to display the control
9466 * @param string $data Unused
9467 * @param string $query
9468 * @return string XHTML
9470 public function output_html($data, $query='') {
9471 global $CFG, $USER, $OUTPUT;
9473 // Get strings that are used
9474 $strshow = get_string('on', 'repository');
9475 $strhide = get_string('off', 'repository');
9476 $strdelete = get_string('disabled', 'repository');
9478 $actionchoicesforexisting = array(
9479 'show' => $strshow,
9480 'hide' => $strhide,
9481 'delete' => $strdelete
9484 $actionchoicesfornew = array(
9485 'newon' => $strshow,
9486 'newoff' => $strhide,
9487 'delete' => $strdelete
9490 $return = '';
9491 $return .= $OUTPUT->box_start('generalbox');
9493 // Set strings that are used multiple times
9494 $settingsstr = get_string('settings');
9495 $disablestr = get_string('disable');
9497 // Table to list plug-ins
9498 $table = new html_table();
9499 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9500 $table->align = array('left', 'center', 'center', 'center', 'center');
9501 $table->data = array();
9503 // Get list of used plug-ins
9504 $repositorytypes = repository::get_types();
9505 if (!empty($repositorytypes)) {
9506 // Array to store plugins being used
9507 $alreadyplugins = array();
9508 $totalrepositorytypes = count($repositorytypes);
9509 $updowncount = 1;
9510 foreach ($repositorytypes as $i) {
9511 $settings = '';
9512 $typename = $i->get_typename();
9513 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9514 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9515 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9517 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9518 // Calculate number of instances in order to display them for the Moodle administrator
9519 if (!empty($instanceoptionnames)) {
9520 $params = array();
9521 $params['context'] = array(context_system::instance());
9522 $params['onlyvisible'] = false;
9523 $params['type'] = $typename;
9524 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9525 // site instances
9526 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9527 $params['context'] = array();
9528 $instances = repository::static_function($typename, 'get_instances', $params);
9529 $courseinstances = array();
9530 $userinstances = array();
9532 foreach ($instances as $instance) {
9533 $repocontext = context::instance_by_id($instance->instance->contextid);
9534 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9535 $courseinstances[] = $instance;
9536 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9537 $userinstances[] = $instance;
9540 // course instances
9541 $instancenumber = count($courseinstances);
9542 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9544 // user private instances
9545 $instancenumber = count($userinstances);
9546 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9547 } else {
9548 $admininstancenumbertext = "";
9549 $courseinstancenumbertext = "";
9550 $userinstancenumbertext = "";
9553 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9555 $settings .= $OUTPUT->container_start('mdl-left');
9556 $settings .= '<br/>';
9557 $settings .= $admininstancenumbertext;
9558 $settings .= '<br/>';
9559 $settings .= $courseinstancenumbertext;
9560 $settings .= '<br/>';
9561 $settings .= $userinstancenumbertext;
9562 $settings .= $OUTPUT->container_end();
9564 // Get the current visibility
9565 if ($i->get_visible()) {
9566 $currentaction = 'show';
9567 } else {
9568 $currentaction = 'hide';
9571 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9573 // Display up/down link
9574 $updown = '';
9575 // Should be done with CSS instead.
9576 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9578 if ($updowncount > 1) {
9579 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9580 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9582 else {
9583 $updown .= $spacer;
9585 if ($updowncount < $totalrepositorytypes) {
9586 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9587 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9589 else {
9590 $updown .= $spacer;
9593 $updowncount++;
9595 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9597 if (!in_array($typename, $alreadyplugins)) {
9598 $alreadyplugins[] = $typename;
9603 // Get all the plugins that exist on disk
9604 $plugins = core_component::get_plugin_list('repository');
9605 if (!empty($plugins)) {
9606 foreach ($plugins as $plugin => $dir) {
9607 // Check that it has not already been listed
9608 if (!in_array($plugin, $alreadyplugins)) {
9609 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9610 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9615 $return .= html_writer::table($table);
9616 $return .= $OUTPUT->box_end();
9617 return highlight($query, $return);
9622 * Special checkbox for enable mobile web service
9623 * If enable then we store the service id of the mobile service into config table
9624 * If disable then we unstore the service id from the config table
9626 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9628 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9629 private $restuse;
9632 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9634 * @return boolean
9636 private function is_protocol_cap_allowed() {
9637 global $DB, $CFG;
9639 // If the $this->restuse variable is not set, it needs to be set.
9640 if (empty($this->restuse) and $this->restuse!==false) {
9641 $params = array();
9642 $params['permission'] = CAP_ALLOW;
9643 $params['roleid'] = $CFG->defaultuserroleid;
9644 $params['capability'] = 'webservice/rest:use';
9645 $this->restuse = $DB->record_exists('role_capabilities', $params);
9648 return $this->restuse;
9652 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9653 * @param type $status true to allow, false to not set
9655 private function set_protocol_cap($status) {
9656 global $CFG;
9657 if ($status and !$this->is_protocol_cap_allowed()) {
9658 //need to allow the cap
9659 $permission = CAP_ALLOW;
9660 $assign = true;
9661 } else if (!$status and $this->is_protocol_cap_allowed()){
9662 //need to disallow the cap
9663 $permission = CAP_INHERIT;
9664 $assign = true;
9666 if (!empty($assign)) {
9667 $systemcontext = context_system::instance();
9668 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9673 * Builds XHTML to display the control.
9674 * The main purpose of this overloading is to display a warning when https
9675 * is not supported by the server
9676 * @param string $data Unused
9677 * @param string $query
9678 * @return string XHTML
9680 public function output_html($data, $query='') {
9681 global $OUTPUT;
9682 $html = parent::output_html($data, $query);
9684 if ((string)$data === $this->yes) {
9685 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9686 foreach ($notifications as $notification) {
9687 $message = get_string($notification[0], $notification[1]);
9688 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9692 return $html;
9696 * Retrieves the current setting using the objects name
9698 * @return string
9700 public function get_setting() {
9701 global $CFG;
9703 // First check if is not set.
9704 $result = $this->config_read($this->name);
9705 if (is_null($result)) {
9706 return null;
9709 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9710 // Or if web services aren't enabled this can't be,
9711 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9712 return 0;
9715 require_once($CFG->dirroot . '/webservice/lib.php');
9716 $webservicemanager = new webservice();
9717 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9718 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9719 return $result;
9720 } else {
9721 return 0;
9726 * Save the selected setting
9728 * @param string $data The selected site
9729 * @return string empty string or error message
9731 public function write_setting($data) {
9732 global $DB, $CFG;
9734 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9735 if (empty($CFG->defaultuserroleid)) {
9736 return '';
9739 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9741 require_once($CFG->dirroot . '/webservice/lib.php');
9742 $webservicemanager = new webservice();
9744 $updateprotocol = false;
9745 if ((string)$data === $this->yes) {
9746 //code run when enable mobile web service
9747 //enable web service systeme if necessary
9748 set_config('enablewebservices', true);
9750 //enable mobile service
9751 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9752 $mobileservice->enabled = 1;
9753 $webservicemanager->update_external_service($mobileservice);
9755 // Enable REST server.
9756 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9758 if (!in_array('rest', $activeprotocols)) {
9759 $activeprotocols[] = 'rest';
9760 $updateprotocol = true;
9763 if ($updateprotocol) {
9764 set_config('webserviceprotocols', implode(',', $activeprotocols));
9767 // Allow rest:use capability for authenticated user.
9768 $this->set_protocol_cap(true);
9769 } else {
9770 // Disable the mobile service.
9771 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9772 $mobileservice->enabled = 0;
9773 $webservicemanager->update_external_service($mobileservice);
9776 return (parent::write_setting($data));
9781 * Special class for management of external services
9783 * @author Petr Skoda (skodak)
9785 class admin_setting_manageexternalservices extends admin_setting {
9787 * Calls parent::__construct with specific arguments
9789 public function __construct() {
9790 $this->nosave = true;
9791 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9795 * Always returns true, does nothing
9797 * @return true
9799 public function get_setting() {
9800 return true;
9804 * Always returns true, does nothing
9806 * @return true
9808 public function get_defaultsetting() {
9809 return true;
9813 * Always returns '', does not write anything
9815 * @return string Always returns ''
9817 public function write_setting($data) {
9818 // do not write any setting
9819 return '';
9823 * Checks if $query is one of the available external services
9825 * @param string $query The string to search for
9826 * @return bool Returns true if found, false if not
9828 public function is_related($query) {
9829 global $DB;
9831 if (parent::is_related($query)) {
9832 return true;
9835 $services = $DB->get_records('external_services', array(), 'id, name');
9836 foreach ($services as $service) {
9837 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9838 return true;
9841 return false;
9845 * Builds the XHTML to display the control
9847 * @param string $data Unused
9848 * @param string $query
9849 * @return string
9851 public function output_html($data, $query='') {
9852 global $CFG, $OUTPUT, $DB;
9854 // display strings
9855 $stradministration = get_string('administration');
9856 $stredit = get_string('edit');
9857 $strservice = get_string('externalservice', 'webservice');
9858 $strdelete = get_string('delete');
9859 $strplugin = get_string('plugin', 'admin');
9860 $stradd = get_string('add');
9861 $strfunctions = get_string('functions', 'webservice');
9862 $strusers = get_string('users');
9863 $strserviceusers = get_string('serviceusers', 'webservice');
9865 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9866 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9867 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9869 // built in services
9870 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9871 $return = "";
9872 if (!empty($services)) {
9873 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9877 $table = new html_table();
9878 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9879 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9880 $table->id = 'builtinservices';
9881 $table->attributes['class'] = 'admintable externalservices generaltable';
9882 $table->data = array();
9884 // iterate through auth plugins and add to the display table
9885 foreach ($services as $service) {
9886 $name = $service->name;
9888 // hide/show link
9889 if ($service->enabled) {
9890 $displayname = "<span>$name</span>";
9891 } else {
9892 $displayname = "<span class=\"dimmed_text\">$name</span>";
9895 $plugin = $service->component;
9897 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9899 if ($service->restrictedusers) {
9900 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9901 } else {
9902 $users = get_string('allusers', 'webservice');
9905 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9907 // add a row to the table
9908 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9910 $return .= html_writer::table($table);
9913 // Custom services
9914 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9915 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9917 $table = new html_table();
9918 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9919 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9920 $table->id = 'customservices';
9921 $table->attributes['class'] = 'admintable externalservices generaltable';
9922 $table->data = array();
9924 // iterate through auth plugins and add to the display table
9925 foreach ($services as $service) {
9926 $name = $service->name;
9928 // hide/show link
9929 if ($service->enabled) {
9930 $displayname = "<span>$name</span>";
9931 } else {
9932 $displayname = "<span class=\"dimmed_text\">$name</span>";
9935 // delete link
9936 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9938 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9940 if ($service->restrictedusers) {
9941 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9942 } else {
9943 $users = get_string('allusers', 'webservice');
9946 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9948 // add a row to the table
9949 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9951 // add new custom service option
9952 $return .= html_writer::table($table);
9954 $return .= '<br />';
9955 // add a token to the table
9956 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9958 return highlight($query, $return);
9963 * Special class for overview of external services
9965 * @author Jerome Mouneyrac
9967 class admin_setting_webservicesoverview extends admin_setting {
9970 * Calls parent::__construct with specific arguments
9972 public function __construct() {
9973 $this->nosave = true;
9974 parent::__construct('webservicesoverviewui',
9975 get_string('webservicesoverview', 'webservice'), '', '');
9979 * Always returns true, does nothing
9981 * @return true
9983 public function get_setting() {
9984 return true;
9988 * Always returns true, does nothing
9990 * @return true
9992 public function get_defaultsetting() {
9993 return true;
9997 * Always returns '', does not write anything
9999 * @return string Always returns ''
10001 public function write_setting($data) {
10002 // do not write any setting
10003 return '';
10007 * Builds the XHTML to display the control
10009 * @param string $data Unused
10010 * @param string $query
10011 * @return string
10013 public function output_html($data, $query='') {
10014 global $CFG, $OUTPUT;
10016 $return = "";
10017 $brtag = html_writer::empty_tag('br');
10019 /// One system controlling Moodle with Token
10020 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
10021 $table = new html_table();
10022 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10023 get_string('description'));
10024 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10025 $table->id = 'onesystemcontrol';
10026 $table->attributes['class'] = 'admintable wsoverview generaltable';
10027 $table->data = array();
10029 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
10030 . $brtag . $brtag;
10032 /// 1. Enable Web Services
10033 $row = array();
10034 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10035 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10036 array('href' => $url));
10037 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10038 if ($CFG->enablewebservices) {
10039 $status = get_string('yes');
10041 $row[1] = $status;
10042 $row[2] = get_string('enablewsdescription', 'webservice');
10043 $table->data[] = $row;
10045 /// 2. Enable protocols
10046 $row = array();
10047 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10048 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10049 array('href' => $url));
10050 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10051 //retrieve activated protocol
10052 $active_protocols = empty($CFG->webserviceprotocols) ?
10053 array() : explode(',', $CFG->webserviceprotocols);
10054 if (!empty($active_protocols)) {
10055 $status = "";
10056 foreach ($active_protocols as $protocol) {
10057 $status .= $protocol . $brtag;
10060 $row[1] = $status;
10061 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10062 $table->data[] = $row;
10064 /// 3. Create user account
10065 $row = array();
10066 $url = new moodle_url("/user/editadvanced.php?id=-1");
10067 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
10068 array('href' => $url));
10069 $row[1] = "";
10070 $row[2] = get_string('createuserdescription', 'webservice');
10071 $table->data[] = $row;
10073 /// 4. Add capability to users
10074 $row = array();
10075 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10076 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
10077 array('href' => $url));
10078 $row[1] = "";
10079 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
10080 $table->data[] = $row;
10082 /// 5. Select a web service
10083 $row = array();
10084 $url = new moodle_url("/admin/settings.php?section=externalservices");
10085 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10086 array('href' => $url));
10087 $row[1] = "";
10088 $row[2] = get_string('createservicedescription', 'webservice');
10089 $table->data[] = $row;
10091 /// 6. Add functions
10092 $row = array();
10093 $url = new moodle_url("/admin/settings.php?section=externalservices");
10094 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10095 array('href' => $url));
10096 $row[1] = "";
10097 $row[2] = get_string('addfunctionsdescription', 'webservice');
10098 $table->data[] = $row;
10100 /// 7. Add the specific user
10101 $row = array();
10102 $url = new moodle_url("/admin/settings.php?section=externalservices");
10103 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
10104 array('href' => $url));
10105 $row[1] = "";
10106 $row[2] = get_string('selectspecificuserdescription', 'webservice');
10107 $table->data[] = $row;
10109 /// 8. Create token for the specific user
10110 $row = array();
10111 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
10112 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
10113 array('href' => $url));
10114 $row[1] = "";
10115 $row[2] = get_string('createtokenforuserdescription', 'webservice');
10116 $table->data[] = $row;
10118 /// 9. Enable the documentation
10119 $row = array();
10120 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
10121 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
10122 array('href' => $url));
10123 $status = '<span class="warning">' . get_string('no') . '</span>';
10124 if ($CFG->enablewsdocumentation) {
10125 $status = get_string('yes');
10127 $row[1] = $status;
10128 $row[2] = get_string('enabledocumentationdescription', 'webservice');
10129 $table->data[] = $row;
10131 /// 10. Test the service
10132 $row = array();
10133 $url = new moodle_url("/admin/webservice/testclient.php");
10134 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10135 array('href' => $url));
10136 $row[1] = "";
10137 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10138 $table->data[] = $row;
10140 $return .= html_writer::table($table);
10142 /// Users as clients with token
10143 $return .= $brtag . $brtag . $brtag;
10144 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10145 $table = new html_table();
10146 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10147 get_string('description'));
10148 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10149 $table->id = 'userasclients';
10150 $table->attributes['class'] = 'admintable wsoverview generaltable';
10151 $table->data = array();
10153 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10154 $brtag . $brtag;
10156 /// 1. Enable Web Services
10157 $row = array();
10158 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10159 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10160 array('href' => $url));
10161 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10162 if ($CFG->enablewebservices) {
10163 $status = get_string('yes');
10165 $row[1] = $status;
10166 $row[2] = get_string('enablewsdescription', 'webservice');
10167 $table->data[] = $row;
10169 /// 2. Enable protocols
10170 $row = array();
10171 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10172 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10173 array('href' => $url));
10174 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10175 //retrieve activated protocol
10176 $active_protocols = empty($CFG->webserviceprotocols) ?
10177 array() : explode(',', $CFG->webserviceprotocols);
10178 if (!empty($active_protocols)) {
10179 $status = "";
10180 foreach ($active_protocols as $protocol) {
10181 $status .= $protocol . $brtag;
10184 $row[1] = $status;
10185 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10186 $table->data[] = $row;
10189 /// 3. Select a web service
10190 $row = array();
10191 $url = new moodle_url("/admin/settings.php?section=externalservices");
10192 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10193 array('href' => $url));
10194 $row[1] = "";
10195 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10196 $table->data[] = $row;
10198 /// 4. Add functions
10199 $row = array();
10200 $url = new moodle_url("/admin/settings.php?section=externalservices");
10201 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10202 array('href' => $url));
10203 $row[1] = "";
10204 $row[2] = get_string('addfunctionsdescription', 'webservice');
10205 $table->data[] = $row;
10207 /// 5. Add capability to users
10208 $row = array();
10209 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10210 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10211 array('href' => $url));
10212 $row[1] = "";
10213 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10214 $table->data[] = $row;
10216 /// 6. Test the service
10217 $row = array();
10218 $url = new moodle_url("/admin/webservice/testclient.php");
10219 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10220 array('href' => $url));
10221 $row[1] = "";
10222 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10223 $table->data[] = $row;
10225 $return .= html_writer::table($table);
10227 return highlight($query, $return);
10234 * Special class for web service protocol administration.
10236 * @author Petr Skoda (skodak)
10238 class admin_setting_managewebserviceprotocols extends admin_setting {
10241 * Calls parent::__construct with specific arguments
10243 public function __construct() {
10244 $this->nosave = true;
10245 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10249 * Always returns true, does nothing
10251 * @return true
10253 public function get_setting() {
10254 return true;
10258 * Always returns true, does nothing
10260 * @return true
10262 public function get_defaultsetting() {
10263 return true;
10267 * Always returns '', does not write anything
10269 * @return string Always returns ''
10271 public function write_setting($data) {
10272 // do not write any setting
10273 return '';
10277 * Checks if $query is one of the available webservices
10279 * @param string $query The string to search for
10280 * @return bool Returns true if found, false if not
10282 public function is_related($query) {
10283 if (parent::is_related($query)) {
10284 return true;
10287 $protocols = core_component::get_plugin_list('webservice');
10288 foreach ($protocols as $protocol=>$location) {
10289 if (strpos($protocol, $query) !== false) {
10290 return true;
10292 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10293 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10294 return true;
10297 return false;
10301 * Builds the XHTML to display the control
10303 * @param string $data Unused
10304 * @param string $query
10305 * @return string
10307 public function output_html($data, $query='') {
10308 global $CFG, $OUTPUT;
10310 // display strings
10311 $stradministration = get_string('administration');
10312 $strsettings = get_string('settings');
10313 $stredit = get_string('edit');
10314 $strprotocol = get_string('protocol', 'webservice');
10315 $strenable = get_string('enable');
10316 $strdisable = get_string('disable');
10317 $strversion = get_string('version');
10319 $protocols_available = core_component::get_plugin_list('webservice');
10320 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10321 ksort($protocols_available);
10323 foreach ($activeprotocols as $key => $protocol) {
10324 if (empty($protocols_available[$protocol])) {
10325 unset($activeprotocols[$key]);
10329 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10330 if (in_array('xmlrpc', $activeprotocols)) {
10331 $notify = new \core\output\notification(get_string('xmlrpcwebserviceenabled', 'admin'),
10332 \core\output\notification::NOTIFY_WARNING);
10333 $return .= $OUTPUT->render($notify);
10335 $return .= $OUTPUT->box_start('generalbox webservicesui');
10337 $table = new html_table();
10338 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10339 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10340 $table->id = 'webserviceprotocols';
10341 $table->attributes['class'] = 'admintable generaltable';
10342 $table->data = array();
10344 // iterate through auth plugins and add to the display table
10345 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10346 foreach ($protocols_available as $protocol => $location) {
10347 $name = get_string('pluginname', 'webservice_'.$protocol);
10349 $plugin = new stdClass();
10350 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10351 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10353 $version = isset($plugin->version) ? $plugin->version : '';
10355 // hide/show link
10356 if (in_array($protocol, $activeprotocols)) {
10357 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10358 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10359 $displayname = "<span>$name</span>";
10360 } else {
10361 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10362 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10363 $displayname = "<span class=\"dimmed_text\">$name</span>";
10366 // settings link
10367 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10368 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10369 } else {
10370 $settings = '';
10373 // add a row to the table
10374 $table->data[] = array($displayname, $version, $hideshow, $settings);
10376 $return .= html_writer::table($table);
10377 $return .= get_string('configwebserviceplugins', 'webservice');
10378 $return .= $OUTPUT->box_end();
10380 return highlight($query, $return);
10385 * Colour picker
10387 * @copyright 2010 Sam Hemelryk
10388 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10390 class admin_setting_configcolourpicker extends admin_setting {
10393 * Information for previewing the colour
10395 * @var array|null
10397 protected $previewconfig = null;
10400 * Use default when empty.
10402 protected $usedefaultwhenempty = true;
10406 * @param string $name
10407 * @param string $visiblename
10408 * @param string $description
10409 * @param string $defaultsetting
10410 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10412 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10413 $usedefaultwhenempty = true) {
10414 $this->previewconfig = $previewconfig;
10415 $this->usedefaultwhenempty = $usedefaultwhenempty;
10416 parent::__construct($name, $visiblename, $description, $defaultsetting);
10417 $this->set_force_ltr(true);
10421 * Return the setting
10423 * @return mixed returns config if successful else null
10425 public function get_setting() {
10426 return $this->config_read($this->name);
10430 * Saves the setting
10432 * @param string $data
10433 * @return bool
10435 public function write_setting($data) {
10436 $data = $this->validate($data);
10437 if ($data === false) {
10438 return get_string('validateerror', 'admin');
10440 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10444 * Validates the colour that was entered by the user
10446 * @param string $data
10447 * @return string|false
10449 protected function validate($data) {
10451 * List of valid HTML colour names
10453 * @var array
10455 $colornames = array(
10456 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10457 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10458 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10459 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10460 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10461 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10462 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10463 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10464 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10465 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10466 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10467 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10468 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10469 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10470 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10471 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10472 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10473 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10474 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10475 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10476 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10477 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10478 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10479 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10480 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10481 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10482 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10483 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10484 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10485 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10486 'whitesmoke', 'yellow', 'yellowgreen'
10489 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10490 if (strpos($data, '#')!==0) {
10491 $data = '#'.$data;
10493 return $data;
10494 } else if (in_array(strtolower($data), $colornames)) {
10495 return $data;
10496 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10497 return $data;
10498 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10499 return $data;
10500 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10501 return $data;
10502 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10503 return $data;
10504 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10505 return $data;
10506 } else if (empty($data)) {
10507 if ($this->usedefaultwhenempty){
10508 return $this->defaultsetting;
10509 } else {
10510 return '';
10512 } else {
10513 return false;
10518 * Generates the HTML for the setting
10520 * @global moodle_page $PAGE
10521 * @global core_renderer $OUTPUT
10522 * @param string $data
10523 * @param string $query
10525 public function output_html($data, $query = '') {
10526 global $PAGE, $OUTPUT;
10528 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10529 $context = (object) [
10530 'id' => $this->get_id(),
10531 'name' => $this->get_full_name(),
10532 'value' => $data,
10533 'icon' => $icon->export_for_template($OUTPUT),
10534 'haspreviewconfig' => !empty($this->previewconfig),
10535 'forceltr' => $this->get_force_ltr(),
10536 'readonly' => $this->is_readonly(),
10539 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10540 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10542 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10543 $this->get_defaultsetting(), $query);
10550 * Class used for uploading of one file into file storage,
10551 * the file name is stored in config table.
10553 * Please note you need to implement your own '_pluginfile' callback function,
10554 * this setting only stores the file, it does not deal with file serving.
10556 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10559 class admin_setting_configstoredfile extends admin_setting {
10560 /** @var array file area options - should be one file only */
10561 protected $options;
10562 /** @var string name of the file area */
10563 protected $filearea;
10564 /** @var int intemid */
10565 protected $itemid;
10566 /** @var string used for detection of changes */
10567 protected $oldhashes;
10570 * Create new stored file setting.
10572 * @param string $name low level setting name
10573 * @param string $visiblename human readable setting name
10574 * @param string $description description of setting
10575 * @param mixed $filearea file area for file storage
10576 * @param int $itemid itemid for file storage
10577 * @param array $options file area options
10579 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10580 parent::__construct($name, $visiblename, $description, '');
10581 $this->filearea = $filearea;
10582 $this->itemid = $itemid;
10583 $this->options = (array)$options;
10584 $this->customcontrol = true;
10588 * Applies defaults and returns all options.
10589 * @return array
10591 protected function get_options() {
10592 global $CFG;
10594 require_once("$CFG->libdir/filelib.php");
10595 require_once("$CFG->dirroot/repository/lib.php");
10596 $defaults = array(
10597 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10598 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10599 'context' => context_system::instance());
10600 foreach($this->options as $k => $v) {
10601 $defaults[$k] = $v;
10604 return $defaults;
10607 public function get_setting() {
10608 return $this->config_read($this->name);
10611 public function write_setting($data) {
10612 global $USER;
10614 // Let's not deal with validation here, this is for admins only.
10615 $current = $this->get_setting();
10616 if (empty($data) && ($current === null || $current === '')) {
10617 // This will be the case when applying default settings (installation).
10618 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10619 } else if (!is_number($data)) {
10620 // Draft item id is expected here!
10621 return get_string('errorsetting', 'admin');
10624 $options = $this->get_options();
10625 $fs = get_file_storage();
10626 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10628 $this->oldhashes = null;
10629 if ($current) {
10630 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10631 if ($file = $fs->get_file_by_hash($hash)) {
10632 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10634 unset($file);
10637 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10638 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10639 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10640 // with an error because the draft area does not exist, as he did not use it.
10641 $usercontext = context_user::instance($USER->id);
10642 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10643 return get_string('errorsetting', 'admin');
10647 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10648 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10650 $filepath = '';
10651 if ($files) {
10652 /** @var stored_file $file */
10653 $file = reset($files);
10654 $filepath = $file->get_filepath().$file->get_filename();
10657 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10660 public function post_write_settings($original) {
10661 $options = $this->get_options();
10662 $fs = get_file_storage();
10663 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10665 $current = $this->get_setting();
10666 $newhashes = null;
10667 if ($current) {
10668 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10669 if ($file = $fs->get_file_by_hash($hash)) {
10670 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10672 unset($file);
10675 if ($this->oldhashes === $newhashes) {
10676 $this->oldhashes = null;
10677 return false;
10679 $this->oldhashes = null;
10681 $callbackfunction = $this->updatedcallback;
10682 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10683 $callbackfunction($this->get_full_name());
10685 return true;
10688 public function output_html($data, $query = '') {
10689 global $CFG;
10691 $options = $this->get_options();
10692 $id = $this->get_id();
10693 $elname = $this->get_full_name();
10694 $draftitemid = file_get_submitted_draft_itemid($elname);
10695 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10696 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10698 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10699 require_once("$CFG->dirroot/lib/form/filemanager.php");
10701 $fmoptions = new stdClass();
10702 $fmoptions->mainfile = $options['mainfile'];
10703 $fmoptions->maxbytes = $options['maxbytes'];
10704 $fmoptions->maxfiles = $options['maxfiles'];
10705 $fmoptions->subdirs = $options['subdirs'];
10706 $fmoptions->accepted_types = $options['accepted_types'];
10707 $fmoptions->return_types = $options['return_types'];
10708 $fmoptions->context = $options['context'];
10709 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10711 $fm = new MoodleQuickForm_filemanager($elname, $this->visiblename, ['id' => $id], $fmoptions);
10712 $fm->setValue($draftitemid);
10714 return format_admin_setting($this, $this->visiblename,
10715 '<div class="form-filemanager" data-fieldtype="filemanager">' . $fm->toHtml() . '</div>',
10716 $this->description, true, '', '', $query);
10722 * Administration interface for user specified regular expressions for device detection.
10724 * @deprecated Moodle 4.3 MDL-78468 - No longer used since the devicedetectregex was removed.
10725 * @todo Final deprecation on Moodle 4.7 MDL-79052
10726 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10728 class admin_setting_devicedetectregex extends admin_setting {
10731 * Calls parent::__construct with specific args
10733 * @deprecated Moodle 4.3 MDL-78468 - No longer used since the devicedetectregex was removed.
10734 * @todo Final deprecation on Moodle 4.7 MDL-79052
10735 * @param string $name
10736 * @param string $visiblename
10737 * @param string $description
10738 * @param mixed $defaultsetting
10740 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10741 debugging(
10742 __FUNCTION__ . '() is deprecated.' .
10743 'All functions associated with devicedetectregex theme setting are being removed.',
10744 DEBUG_DEVELOPER
10746 global $CFG;
10747 parent::__construct($name, $visiblename, $description, $defaultsetting);
10751 * Return the current setting(s)
10753 * @deprecated Moodle 4.3 MDL-78468 - No longer used since the devicedetectregex was removed.
10754 * @todo Final deprecation on Moodle 4.7 MDL-79052
10755 * @return array Current settings array
10757 public function get_setting() {
10758 debugging(
10759 __FUNCTION__ . '() is deprecated.' .
10760 'All functions associated with devicedetectregex theme setting are being removed.',
10761 DEBUG_DEVELOPER
10763 global $CFG;
10765 $config = $this->config_read($this->name);
10766 if (is_null($config)) {
10767 return null;
10770 return $this->prepare_form_data($config);
10774 * Save selected settings
10776 * @deprecated Moodle 4.3 MDL-78468 - No longer used since the devicedetectregex was removed.
10777 * @todo Final deprecation on Moodle 4.7 MDL-79052
10778 * @param array $data Array of settings to save
10779 * @return bool
10781 public function write_setting($data) {
10782 debugging(
10783 __FUNCTION__ . '() is deprecated.' .
10784 'All functions associated with devicedetectregex theme setting are being removed.',
10785 DEBUG_DEVELOPER
10787 if (empty($data)) {
10788 $data = array();
10791 if ($this->config_write($this->name, $this->process_form_data($data))) {
10792 return ''; // success
10793 } else {
10794 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10799 * Return XHTML field(s) for regexes
10801 * @deprecated Moodle 4.3 MDL-78468 - No longer used since the devicedetectregex was removed.
10802 * @todo Final deprecation on Moodle 4.7 MDL-79052
10803 * @param array $data Array of options to set in HTML
10804 * @return string XHTML string for the fields and wrapping div(s)
10806 public function output_html($data, $query='') {
10807 debugging(
10808 __FUNCTION__ . '() is deprecated.' .
10809 'All functions associated with devicedetectregex theme setting are being removed.',
10810 DEBUG_DEVELOPER
10812 global $OUTPUT;
10814 $context = (object) [
10815 'expressions' => [],
10816 'name' => $this->get_full_name()
10819 if (empty($data)) {
10820 $looplimit = 1;
10821 } else {
10822 $looplimit = (count($data)/2)+1;
10825 for ($i=0; $i<$looplimit; $i++) {
10827 $expressionname = 'expression'.$i;
10829 if (!empty($data[$expressionname])){
10830 $expression = $data[$expressionname];
10831 } else {
10832 $expression = '';
10835 $valuename = 'value'.$i;
10837 if (!empty($data[$valuename])){
10838 $value = $data[$valuename];
10839 } else {
10840 $value= '';
10843 $context->expressions[] = [
10844 'index' => $i,
10845 'expression' => $expression,
10846 'value' => $value
10850 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10852 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10856 * Converts the string of regexes
10858 * @see self::process_form_data()
10859 * @param $regexes string of regexes
10860 * @return array of form fields and their values
10862 protected function prepare_form_data($regexes) {
10864 $regexes = json_decode($regexes);
10866 $form = array();
10868 $i = 0;
10870 foreach ($regexes as $value => $regex) {
10871 $expressionname = 'expression'.$i;
10872 $valuename = 'value'.$i;
10874 $form[$expressionname] = $regex;
10875 $form[$valuename] = $value;
10876 $i++;
10879 return $form;
10883 * Converts the data from admin settings form into a string of regexes
10885 * @see self::prepare_form_data()
10886 * @param array $data array of admin form fields and values
10887 * @return false|string of regexes
10889 protected function process_form_data(array $form) {
10891 $count = count($form); // number of form field values
10893 if ($count % 2) {
10894 // we must get five fields per expression
10895 return false;
10898 $regexes = array();
10899 for ($i = 0; $i < $count / 2; $i++) {
10900 $expressionname = "expression".$i;
10901 $valuename = "value".$i;
10903 $expression = trim($form['expression'.$i]);
10904 $value = trim($form['value'.$i]);
10906 if (empty($expression)){
10907 continue;
10910 $regexes[$value] = $expression;
10913 $regexes = json_encode($regexes);
10915 return $regexes;
10921 * Multiselect for current modules
10923 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10925 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10926 private $excludesystem;
10929 * Calls parent::__construct - note array $choices is not required
10931 * @param string $name setting name
10932 * @param string $visiblename localised setting name
10933 * @param string $description setting description
10934 * @param array $defaultsetting a plain array of default module ids
10935 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10937 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10938 $excludesystem = true) {
10939 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10940 $this->excludesystem = $excludesystem;
10944 * Loads an array of current module choices
10946 * @return bool always return true
10948 public function load_choices() {
10949 if (is_array($this->choices)) {
10950 return true;
10952 $this->choices = array();
10954 global $CFG, $DB;
10955 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10956 foreach ($records as $record) {
10957 // Exclude modules if the code doesn't exist
10958 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10959 // Also exclude system modules (if specified)
10960 if (!($this->excludesystem &&
10961 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10962 MOD_ARCHETYPE_SYSTEM)) {
10963 $this->choices[$record->id] = $record->name;
10967 return true;
10972 * Admin setting to show if a php extension is enabled or not.
10974 * @copyright 2013 Damyon Wiese
10975 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10977 class admin_setting_php_extension_enabled extends admin_setting {
10979 /** @var string The name of the extension to check for */
10980 private $extension;
10983 * Calls parent::__construct with specific arguments
10985 public function __construct($name, $visiblename, $description, $extension) {
10986 $this->extension = $extension;
10987 $this->nosave = true;
10988 parent::__construct($name, $visiblename, $description, '');
10992 * Always returns true, does nothing
10994 * @return true
10996 public function get_setting() {
10997 return true;
11001 * Always returns true, does nothing
11003 * @return true
11005 public function get_defaultsetting() {
11006 return true;
11010 * Always returns '', does not write anything
11012 * @return string Always returns ''
11014 public function write_setting($data) {
11015 // Do not write any setting.
11016 return '';
11020 * Outputs the html for this setting.
11021 * @return string Returns an XHTML string
11023 public function output_html($data, $query='') {
11024 global $OUTPUT;
11026 $o = '';
11027 if (!extension_loaded($this->extension)) {
11028 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
11030 $o .= format_admin_setting($this, $this->visiblename, $warning);
11032 return $o;
11037 * Server timezone setting.
11039 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11040 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11041 * @author Petr Skoda <petr.skoda@totaralms.com>
11043 class admin_setting_servertimezone extends admin_setting_configselect {
11045 * Constructor.
11047 public function __construct() {
11048 $default = core_date::get_default_php_timezone();
11049 if ($default === 'UTC') {
11050 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
11051 $default = 'Europe/London';
11054 parent::__construct('timezone',
11055 new lang_string('timezone', 'core_admin'),
11056 new lang_string('configtimezone', 'core_admin'), $default, null);
11060 * Lazy load timezone options.
11061 * @return bool true if loaded, false if error
11063 public function load_choices() {
11064 global $CFG;
11065 if (is_array($this->choices)) {
11066 return true;
11069 $current = isset($CFG->timezone) ? $CFG->timezone : null;
11070 $this->choices = core_date::get_list_of_timezones($current, false);
11071 if ($current == 99) {
11072 // Do not show 99 unless it is current value, we want to get rid of it over time.
11073 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
11074 core_date::get_default_php_timezone());
11077 return true;
11082 * Forced user timezone setting.
11084 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11086 * @author Petr Skoda <petr.skoda@totaralms.com>
11088 class admin_setting_forcetimezone extends admin_setting_configselect {
11090 * Constructor.
11092 public function __construct() {
11093 parent::__construct('forcetimezone',
11094 new lang_string('forcetimezone', 'core_admin'),
11095 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
11099 * Lazy load timezone options.
11100 * @return bool true if loaded, false if error
11102 public function load_choices() {
11103 global $CFG;
11104 if (is_array($this->choices)) {
11105 return true;
11108 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
11109 $this->choices = core_date::get_list_of_timezones($current, true);
11110 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
11112 return true;
11118 * Search setup steps info.
11120 * @package core
11121 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
11122 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11124 class admin_setting_searchsetupinfo extends admin_setting {
11127 * Calls parent::__construct with specific arguments
11129 public function __construct() {
11130 $this->nosave = true;
11131 parent::__construct('searchsetupinfo', '', '', '');
11135 * Always returns true, does nothing
11137 * @return true
11139 public function get_setting() {
11140 return true;
11144 * Always returns true, does nothing
11146 * @return true
11148 public function get_defaultsetting() {
11149 return true;
11153 * Always returns '', does not write anything
11155 * @param array $data
11156 * @return string Always returns ''
11158 public function write_setting($data) {
11159 // Do not write any setting.
11160 return '';
11164 * Builds the HTML to display the control
11166 * @param string $data Unused
11167 * @param string $query
11168 * @return string
11170 public function output_html($data, $query='') {
11171 global $CFG, $OUTPUT, $ADMIN;
11173 $return = '';
11174 $brtag = html_writer::empty_tag('br');
11176 $searchareas = \core_search\manager::get_search_areas_list();
11177 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11178 $anyindexed = false;
11179 foreach ($searchareas as $areaid => $searcharea) {
11180 list($componentname, $varname) = $searcharea->get_config_var_name();
11181 if (get_config($componentname, $varname . '_indexingstart')) {
11182 $anyindexed = true;
11183 break;
11187 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11189 $table = new html_table();
11190 $table->head = array(get_string('step', 'search'), get_string('status'));
11191 $table->colclasses = array('leftalign step', 'leftalign status');
11192 $table->id = 'searchsetup';
11193 $table->attributes['class'] = 'admintable generaltable';
11194 $table->data = array();
11196 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11198 // Select a search engine.
11199 $row = array();
11200 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11201 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11202 array('href' => $url));
11204 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11205 if (!empty($CFG->searchengine)) {
11206 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11207 array('class' => 'badge badge-success'));
11210 $row[1] = $status;
11211 $table->data[] = $row;
11213 // Available areas.
11214 $row = array();
11215 $url = new moodle_url('/admin/searchareas.php');
11216 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11217 array('href' => $url));
11219 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11220 if ($anyenabled) {
11221 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11224 $row[1] = $status;
11225 $table->data[] = $row;
11227 // Setup search engine.
11228 $row = array();
11229 if (empty($CFG->searchengine)) {
11230 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11231 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11232 } else {
11233 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11234 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11235 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11236 } else {
11237 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11240 // Check the engine status.
11241 $searchengine = \core_search\manager::search_engine_instance();
11242 try {
11243 $serverstatus = $searchengine->is_server_ready();
11244 } catch (\moodle_exception $e) {
11245 $serverstatus = $e->getMessage();
11247 if ($serverstatus === true) {
11248 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11249 } else {
11250 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11252 $row[1] = $status;
11254 $table->data[] = $row;
11256 // Indexed data.
11257 $row = array();
11258 $url = new moodle_url('/admin/searchareas.php');
11259 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11260 if ($anyindexed) {
11261 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11262 } else {
11263 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11265 $row[1] = $status;
11266 $table->data[] = $row;
11268 // Enable global search.
11269 $row = array();
11270 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11271 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11272 array('href' => $url));
11273 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11274 if (\core_search\manager::is_global_search_enabled()) {
11275 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11277 $row[1] = $status;
11278 $table->data[] = $row;
11280 // Replace front page search.
11281 $row = array();
11282 $url = new moodle_url("/admin/search.php?query=searchincludeallcourses");
11283 $row[0] = '6. ' . html_writer::tag('a', get_string('replacefrontsearch', 'admin'),
11284 array('href' => $url));
11285 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11286 if (\core_search\manager::can_replace_course_search()) {
11287 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11289 $row[1] = $status;
11290 $table->data[] = $row;
11292 $return .= html_writer::table($table);
11294 return highlight($query, $return);
11300 * Used to validate the contents of SCSS code and ensuring they are parsable.
11302 * It does not attempt to detect undefined SCSS variables because it is designed
11303 * to be used without knowledge of other config/scss included.
11305 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11306 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11308 class admin_setting_scsscode extends admin_setting_configtextarea {
11311 * Validate the contents of the SCSS to ensure its parsable. Does not
11312 * attempt to detect undefined scss variables.
11314 * @param string $data The scss code from text field.
11315 * @return mixed bool true for success or string:error on failure.
11317 public function validate($data) {
11318 if (empty($data)) {
11319 return true;
11322 $scss = new core_scss();
11323 try {
11324 $scss->compile($data);
11325 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11326 return get_string('scssinvalid', 'admin', $e->getMessage());
11327 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11328 // Silently ignore this - it could be a scss variable defined from somewhere
11329 // else which we are not examining here.
11330 return true;
11333 return true;
11339 * Administration setting to define a list of file types.
11341 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11342 * @copyright 2017 David Mudrák <david@moodle.com>
11343 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11345 class admin_setting_filetypes extends admin_setting_configtext {
11347 /** @var array Allow selection from these file types only. */
11348 protected $onlytypes = [];
11350 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11351 protected $allowall = true;
11353 /** @var core_form\filetypes_util instance to use as a helper. */
11354 protected $util = null;
11357 * Constructor.
11359 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11360 * @param string $visiblename Localised label of the setting
11361 * @param string $description Localised description of the setting
11362 * @param string $defaultsetting Default setting value.
11363 * @param array $options Setting widget options, an array with optional keys:
11364 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11365 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11367 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11369 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11371 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11372 $this->onlytypes = $options['onlytypes'];
11375 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11376 $this->allowall = (bool)$options['allowall'];
11379 $this->util = new \core_form\filetypes_util();
11383 * Normalize the user's input and write it to the database as comma separated list.
11385 * Comma separated list as a text representation of the array was chosen to
11386 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11388 * @param string $data Value submitted by the admin.
11389 * @return string Epty string if all good, error message otherwise.
11391 public function write_setting($data) {
11392 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11396 * Validate data before storage
11398 * @param string $data The setting values provided by the admin
11399 * @return bool|string True if ok, the string if error found
11401 public function validate($data) {
11402 $parentcheck = parent::validate($data);
11403 if ($parentcheck !== true) {
11404 return $parentcheck;
11407 // Check for unknown file types.
11408 if ($unknown = $this->util->get_unknown_file_types($data)) {
11409 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11412 // Check for disallowed file types.
11413 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11414 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11417 return true;
11421 * Return an HTML string for the setting element.
11423 * @param string $data The current setting value
11424 * @param string $query Admin search query to be highlighted
11425 * @return string HTML to be displayed
11427 public function output_html($data, $query='') {
11428 global $OUTPUT, $PAGE;
11430 $default = $this->get_defaultsetting();
11431 $context = (object) [
11432 'id' => $this->get_id(),
11433 'name' => $this->get_full_name(),
11434 'value' => $data,
11435 'descriptions' => $this->util->describe_file_types($data),
11437 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11439 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11440 $this->get_id(),
11441 $this->visiblename->out(),
11442 $this->onlytypes,
11443 $this->allowall,
11446 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11450 * Should the values be always displayed in LTR mode?
11452 * We always return true here because these values are not RTL compatible.
11454 * @return bool True because these values are not RTL compatible.
11456 public function get_force_ltr() {
11457 return true;
11462 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11465 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11467 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11470 * Constructor.
11472 * @param string $name
11473 * @param string $visiblename
11474 * @param string $description
11475 * @param mixed $defaultsetting string or array
11476 * @param mixed $paramtype
11477 * @param string $cols
11478 * @param string $rows
11480 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11481 $cols = '60', $rows = '8') {
11482 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11483 // Pre-set force LTR to false.
11484 $this->set_force_ltr(false);
11488 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11490 * @param string $data The age of digital consent map from text field.
11491 * @return mixed bool true for success or string:error on failure.
11493 public function validate($data) {
11494 if (empty($data)) {
11495 return true;
11498 try {
11499 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11500 } catch (\moodle_exception $e) {
11501 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11504 return true;
11509 * Selection of plugins that can work as site policy handlers
11511 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11512 * @copyright 2018 Marina Glancy
11514 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11517 * Constructor
11518 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11519 * for ones in config_plugins.
11520 * @param string $visiblename localised
11521 * @param string $description long localised info
11522 * @param string $defaultsetting
11524 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11525 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11529 * Lazy-load the available choices for the select box
11531 public function load_choices() {
11532 if (during_initial_install()) {
11533 return false;
11535 if (is_array($this->choices)) {
11536 return true;
11539 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11540 $manager = new \core_privacy\local\sitepolicy\manager();
11541 $plugins = $manager->get_all_handlers();
11542 foreach ($plugins as $pname => $unused) {
11543 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11544 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11547 return true;
11552 * Used to validate theme presets code and ensuring they compile well.
11554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11555 * @copyright 2019 Bas Brands <bas@moodle.com>
11557 class admin_setting_configthemepreset extends admin_setting_configselect {
11559 /** @var string The name of the theme to check for */
11560 private $themename;
11563 * Constructor
11564 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11565 * or 'myplugin/mysetting' for ones in config_plugins.
11566 * @param string $visiblename localised
11567 * @param string $description long localised info
11568 * @param string|int $defaultsetting
11569 * @param array $choices array of $value=>$label for each selection
11570 * @param string $themename name of theme to check presets for.
11572 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11573 $this->themename = $themename;
11574 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11578 * Write settings if validated
11580 * @param string $data
11581 * @return string
11583 public function write_setting($data) {
11584 $validated = $this->validate($data);
11585 if ($validated !== true) {
11586 return $validated;
11588 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11592 * Validate the preset file to ensure its parsable.
11594 * @param string $data The preset file chosen.
11595 * @return mixed bool true for success or string:error on failure.
11597 public function validate($data) {
11599 if (in_array($data, ['default.scss', 'plain.scss'])) {
11600 return true;
11603 $fs = get_file_storage();
11604 $theme = theme_config::load($this->themename);
11605 $context = context_system::instance();
11607 // If the preset has not changed there is no need to validate it.
11608 if ($theme->settings->preset == $data) {
11609 return true;
11612 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11613 // This operation uses a lot of resources.
11614 raise_memory_limit(MEMORY_EXTRA);
11615 core_php_time_limit::raise(300);
11617 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11618 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11620 $compiler = new core_scss();
11621 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11622 $compiler->append_raw_scss($presetfile->get_content());
11623 if ($scssproperties = $theme->get_scss_property()) {
11624 $compiler->setImportPaths($scssproperties[0]);
11626 $compiler->append_raw_scss($theme->get_extra_scss_code());
11628 try {
11629 $compiler->to_css();
11630 } catch (Exception $e) {
11631 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11634 // Try to save memory.
11635 $compiler = null;
11636 unset($compiler);
11639 return true;
11644 * Selection of plugins that can work as H5P libraries handlers
11646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11647 * @copyright 2020 Sara Arjona <sara@moodle.com>
11649 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11652 * Constructor
11653 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11654 * for ones in config_plugins.
11655 * @param string $visiblename localised
11656 * @param string $description long localised info
11657 * @param string $defaultsetting
11659 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11660 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11664 * Lazy-load the available choices for the select box
11666 public function load_choices() {
11667 if (during_initial_install()) {
11668 return false;
11670 if (is_array($this->choices)) {
11671 return true;
11674 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11675 foreach ($this->choices as $name => $class) {
11676 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11677 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11680 return true;
11685 * Displays the result of a check via ajax.
11687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11688 * @author Matthew Hilton <matthewhilton@catalyst-au.net>
11689 * @copyright Catalyst IT, 2023
11691 class admin_setting_check extends admin_setting {
11693 /** @var \core\check\check $check the check to use **/
11694 private $check;
11696 /** @var bool $includedetails if the details of result are included. **/
11697 private $includedetails;
11700 * Creates check setting.
11702 * @param string $name name of setting
11703 * @param \core\check\check $check The check linked to this setting.
11704 * @param bool $includedetails if the details of the result are included
11706 public function __construct(string $name, \core\check\check $check, bool $includedetails = false) {
11707 $this->check = $check;
11708 $this->includedetails = $includedetails;
11709 $heading = $check->get_name();
11711 parent::__construct($name, $heading, '', '');
11715 * Returns the check linked to this setting.
11717 * @return \core\check\check
11719 public function get_check() {
11720 return $this->check;
11724 * Returns setting (unused)
11726 * @return true
11728 public function get_setting() {
11729 return true;
11733 * Writes the setting (unused)
11735 * @param mixed $data
11737 public function write_setting($data) {
11738 return '';
11742 * Outputs the admin setting HTML to be rendered.
11744 * @param mixed $data
11745 * @param string $query
11746 * @return string html
11748 public function output_html($data, $query = '') {
11749 global $PAGE, $OUTPUT;
11751 $domref = uniqid($this->check->get_ref());
11753 // The actual result is obtained via ajax,
11754 // since its likely somewhat slow to obtain.
11755 $context = [
11756 'domselector' => '[data-check-reference="' . $domref . '"]',
11757 'admintreeid' => $this->get_id(),
11758 'settingname' => $this->name,
11759 'includedetails' => $this->includedetails,
11761 $PAGE->requires->js_call_amd('core/check/check_result', 'getAndRender', $context);
11763 // Render a generic loading icon while waiting for ajax.
11764 $loadingstr = get_string('checkloading', '', $this->check->get_name());
11765 $loadingicon = $OUTPUT->pix_icon('i/loading', $loadingstr);
11767 // Wrap it in a notification so we reduce style changes when loading is finished.
11768 $output = $OUTPUT->notification($loadingicon . $loadingstr, \core\output\notification::NOTIFY_INFO, false);
11770 // Add the action link.
11771 $output .= $OUTPUT->render($this->check->get_action_link());
11773 // Wrap in a div with a reference. The JS getAndRender will replace this with the response from the webservice.
11774 $statusdiv = \html_writer::div($output, '', ['data-check-reference' => $domref]);
11776 return format_admin_setting($this, $this->visiblename, '', $statusdiv);