Merge branch 'MDL-76500' of https://github.com/paulholden/moodle
[moodle.git] / lib / adminlib.php
blob052a0d47f2f9b5f52b3c3c2e99fd19856b501362
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(__DIR__.'/../../config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 use core_admin\local\settings\linkable_settings_page;
107 defined('MOODLE_INTERNAL') || die();
109 /// Add libraries
110 require_once($CFG->libdir.'/ddllib.php');
111 require_once($CFG->libdir.'/xmlize.php');
112 require_once($CFG->libdir.'/messagelib.php');
114 // Add classes, traits, and interfaces which should be autoloaded.
115 // The autoloader is configured late in setup.php, after ABORT_AFTER_CONFIG.
116 // This is also required where the setup system is not included at all.
117 require_once($CFG->dirroot.'/'.$CFG->admin.'/classes/local/settings/linkable_settings_page.php');
119 define('INSECURE_DATAROOT_WARNING', 1);
120 define('INSECURE_DATAROOT_ERROR', 2);
123 * Automatically clean-up all plugin data and remove the plugin DB tables
125 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
127 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
128 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
129 * @uses global $OUTPUT to produce notices and other messages
130 * @return void
132 function uninstall_plugin($type, $name) {
133 global $CFG, $DB, $OUTPUT;
135 // This may take a long time.
136 core_php_time_limit::raise();
138 // Recursively uninstall all subplugins first.
139 $subplugintypes = core_component::get_plugin_types_with_subplugins();
140 if (isset($subplugintypes[$type])) {
141 $base = core_component::get_plugin_directory($type, $name);
143 $subpluginsfile = "{$base}/db/subplugins.json";
144 if (file_exists($subpluginsfile)) {
145 $subplugins = (array) json_decode(file_get_contents($subpluginsfile))->plugintypes;
146 } else if (file_exists("{$base}/db/subplugins.php")) {
147 debugging('Use of subplugins.php has been deprecated. ' .
148 'Please update your plugin to provide a subplugins.json file instead.',
149 DEBUG_DEVELOPER);
150 $subplugins = [];
151 include("{$base}/db/subplugins.php");
154 if (!empty($subplugins)) {
155 foreach (array_keys($subplugins) as $subplugintype) {
156 $instances = core_component::get_plugin_list($subplugintype);
157 foreach ($instances as $subpluginname => $notusedpluginpath) {
158 uninstall_plugin($subplugintype, $subpluginname);
164 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
166 if ($type === 'mod') {
167 $pluginname = $name; // eg. 'forum'
168 if (get_string_manager()->string_exists('modulename', $component)) {
169 $strpluginname = get_string('modulename', $component);
170 } else {
171 $strpluginname = $component;
174 } else {
175 $pluginname = $component;
176 if (get_string_manager()->string_exists('pluginname', $component)) {
177 $strpluginname = get_string('pluginname', $component);
178 } else {
179 $strpluginname = $component;
183 echo $OUTPUT->heading($pluginname);
185 // Delete all tag areas, collections and instances associated with this plugin.
186 core_tag_area::uninstall($component);
188 // Custom plugin uninstall.
189 $plugindirectory = core_component::get_plugin_directory($type, $name);
190 $uninstalllib = $plugindirectory . '/db/uninstall.php';
191 if (file_exists($uninstalllib)) {
192 require_once($uninstalllib);
193 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
194 if (function_exists($uninstallfunction)) {
195 // Do not verify result, let plugin complain if necessary.
196 $uninstallfunction();
200 // Specific plugin type cleanup.
201 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
202 if ($plugininfo) {
203 $plugininfo->uninstall_cleanup();
204 core_plugin_manager::reset_caches();
206 $plugininfo = null;
208 // perform clean-up task common for all the plugin/subplugin types
210 //delete the web service functions and pre-built services
211 require_once($CFG->dirroot.'/lib/externallib.php');
212 external_delete_descriptions($component);
214 // delete calendar events
215 $DB->delete_records('event', array('modulename' => $pluginname));
216 $DB->delete_records('event', ['component' => $component]);
218 // Delete scheduled tasks.
219 $DB->delete_records('task_adhoc', ['component' => $component]);
220 $DB->delete_records('task_scheduled', array('component' => $component));
222 // Delete Inbound Message datakeys.
223 $DB->delete_records_select('messageinbound_datakeys',
224 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
226 // Delete Inbound Message handlers.
227 $DB->delete_records('messageinbound_handlers', array('component' => $component));
229 // delete all the logs
230 $DB->delete_records('log', array('module' => $pluginname));
232 // delete log_display information
233 $DB->delete_records('log_display', array('component' => $component));
235 // delete the module configuration records
236 unset_all_config_for_plugin($component);
237 if ($type === 'mod') {
238 unset_all_config_for_plugin($pluginname);
241 // delete message provider
242 message_provider_uninstall($component);
244 // delete the plugin tables
245 $xmldbfilepath = $plugindirectory . '/db/install.xml';
246 drop_plugin_tables($component, $xmldbfilepath, false);
247 if ($type === 'mod' or $type === 'block') {
248 // non-frankenstyle table prefixes
249 drop_plugin_tables($name, $xmldbfilepath, false);
252 // delete the capabilities that were defined by this module
253 capabilities_cleanup($component);
255 // Delete all remaining files in the filepool owned by the component.
256 $fs = get_file_storage();
257 $fs->delete_component_files($component);
259 // Finally purge all caches.
260 purge_all_caches();
262 // Invalidate the hash used for upgrade detections.
263 set_config('allversionshash', '');
265 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
269 * Returns the version of installed component
271 * @param string $component component name
272 * @param string $source either 'disk' or 'installed' - where to get the version information from
273 * @return string|bool version number or false if the component is not found
275 function get_component_version($component, $source='installed') {
276 global $CFG, $DB;
278 list($type, $name) = core_component::normalize_component($component);
280 // moodle core or a core subsystem
281 if ($type === 'core') {
282 if ($source === 'installed') {
283 if (empty($CFG->version)) {
284 return false;
285 } else {
286 return $CFG->version;
288 } else {
289 if (!is_readable($CFG->dirroot.'/version.php')) {
290 return false;
291 } else {
292 $version = null; //initialize variable for IDEs
293 include($CFG->dirroot.'/version.php');
294 return $version;
299 // activity module
300 if ($type === 'mod') {
301 if ($source === 'installed') {
302 if ($CFG->version < 2013092001.02) {
303 return $DB->get_field('modules', 'version', array('name'=>$name));
304 } else {
305 return get_config('mod_'.$name, 'version');
308 } else {
309 $mods = core_component::get_plugin_list('mod');
310 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
311 return false;
312 } else {
313 $plugin = new stdClass();
314 $plugin->version = null;
315 $module = $plugin;
316 include($mods[$name].'/version.php');
317 return $plugin->version;
322 // block
323 if ($type === 'block') {
324 if ($source === 'installed') {
325 if ($CFG->version < 2013092001.02) {
326 return $DB->get_field('block', 'version', array('name'=>$name));
327 } else {
328 return get_config('block_'.$name, 'version');
330 } else {
331 $blocks = core_component::get_plugin_list('block');
332 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($blocks[$name].'/version.php');
337 return $plugin->version;
342 // all other plugin types
343 if ($source === 'installed') {
344 return get_config($type.'_'.$name, 'version');
345 } else {
346 $plugins = core_component::get_plugin_list($type);
347 if (empty($plugins[$name])) {
348 return false;
349 } else {
350 $plugin = new stdclass();
351 include($plugins[$name].'/version.php');
352 return $plugin->version;
358 * Delete all plugin tables
360 * @param string $name Name of plugin, used as table prefix
361 * @param string $file Path to install.xml file
362 * @param bool $feedback defaults to true
363 * @return bool Always returns true
365 function drop_plugin_tables($name, $file, $feedback=true) {
366 global $CFG, $DB;
368 // first try normal delete
369 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
370 return true;
373 // then try to find all tables that start with name and are not in any xml file
374 $used_tables = get_used_table_names();
376 $tables = $DB->get_tables();
378 /// Iterate over, fixing id fields as necessary
379 foreach ($tables as $table) {
380 if (in_array($table, $used_tables)) {
381 continue;
384 if (strpos($table, $name) !== 0) {
385 continue;
388 // found orphan table --> delete it
389 if ($DB->get_manager()->table_exists($table)) {
390 $xmldb_table = new xmldb_table($table);
391 $DB->get_manager()->drop_table($xmldb_table);
395 return true;
399 * Returns names of all known tables == tables that moodle knows about.
401 * @return array Array of lowercase table names
403 function get_used_table_names() {
404 $table_names = array();
405 $dbdirs = get_db_directories();
407 foreach ($dbdirs as $dbdir) {
408 $file = $dbdir.'/install.xml';
410 $xmldb_file = new xmldb_file($file);
412 if (!$xmldb_file->fileExists()) {
413 continue;
416 $loaded = $xmldb_file->loadXMLStructure();
417 $structure = $xmldb_file->getStructure();
419 if ($loaded and $tables = $structure->getTables()) {
420 foreach($tables as $table) {
421 $table_names[] = strtolower($table->getName());
426 return $table_names;
430 * Returns list of all directories where we expect install.xml files
431 * @return array Array of paths
433 function get_db_directories() {
434 global $CFG;
436 $dbdirs = array();
438 /// First, the main one (lib/db)
439 $dbdirs[] = $CFG->libdir.'/db';
441 /// Then, all the ones defined by core_component::get_plugin_types()
442 $plugintypes = core_component::get_plugin_types();
443 foreach ($plugintypes as $plugintype => $pluginbasedir) {
444 if ($plugins = core_component::get_plugin_list($plugintype)) {
445 foreach ($plugins as $plugin => $plugindir) {
446 $dbdirs[] = $plugindir.'/db';
451 return $dbdirs;
455 * Try to obtain or release the cron lock.
456 * @param string $name name of lock
457 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
458 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
459 * @return bool true if lock obtained
461 function set_cron_lock($name, $until, $ignorecurrent=false) {
462 global $DB;
463 if (empty($name)) {
464 debugging("Tried to get a cron lock for a null fieldname");
465 return false;
468 // remove lock by force == remove from config table
469 if (is_null($until)) {
470 set_config($name, null);
471 return true;
474 if (!$ignorecurrent) {
475 // read value from db - other processes might have changed it
476 $value = $DB->get_field('config', 'value', array('name'=>$name));
478 if ($value and $value > time()) {
479 //lock active
480 return false;
484 set_config($name, $until);
485 return true;
489 * Test if and critical warnings are present
490 * @return bool
492 function admin_critical_warnings_present() {
493 global $SESSION;
495 if (!has_capability('moodle/site:config', context_system::instance())) {
496 return 0;
499 if (!isset($SESSION->admin_critical_warning)) {
500 $SESSION->admin_critical_warning = 0;
501 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
502 $SESSION->admin_critical_warning = 1;
506 return $SESSION->admin_critical_warning;
510 * Detects if float supports at least 10 decimal digits
512 * Detects if float supports at least 10 decimal digits
513 * and also if float-->string conversion works as expected.
515 * @return bool true if problem found
517 function is_float_problem() {
518 $num1 = 2009010200.01;
519 $num2 = 2009010200.02;
521 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
525 * Try to verify that dataroot is not accessible from web.
527 * Try to verify that dataroot is not accessible from web.
528 * It is not 100% correct but might help to reduce number of vulnerable sites.
529 * Protection from httpd.conf and .htaccess is not detected properly.
531 * @uses INSECURE_DATAROOT_WARNING
532 * @uses INSECURE_DATAROOT_ERROR
533 * @param bool $fetchtest try to test public access by fetching file, default false
534 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
536 function is_dataroot_insecure($fetchtest=false) {
537 global $CFG;
539 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
541 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
542 $rp = strrev(trim($rp, '/'));
543 $rp = explode('/', $rp);
544 foreach($rp as $r) {
545 if (strpos($siteroot, '/'.$r.'/') === 0) {
546 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
547 } else {
548 break; // probably alias root
552 $siteroot = strrev($siteroot);
553 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
555 if (strpos($dataroot, $siteroot) !== 0) {
556 return false;
559 if (!$fetchtest) {
560 return INSECURE_DATAROOT_WARNING;
563 // now try all methods to fetch a test file using http protocol
565 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
566 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
567 $httpdocroot = $matches[1];
568 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
569 make_upload_directory('diag');
570 $testfile = $CFG->dataroot.'/diag/public.txt';
571 if (!file_exists($testfile)) {
572 file_put_contents($testfile, 'test file, do not delete');
573 @chmod($testfile, $CFG->filepermissions);
575 $teststr = trim(file_get_contents($testfile));
576 if (empty($teststr)) {
577 // hmm, strange
578 return INSECURE_DATAROOT_WARNING;
581 $testurl = $datarooturl.'/diag/public.txt';
582 if (extension_loaded('curl') and
583 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
584 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
585 ($ch = @curl_init($testurl)) !== false) {
586 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
587 curl_setopt($ch, CURLOPT_HEADER, false);
588 $data = curl_exec($ch);
589 if (!curl_errno($ch)) {
590 $data = trim($data);
591 if ($data === $teststr) {
592 curl_close($ch);
593 return INSECURE_DATAROOT_ERROR;
596 curl_close($ch);
599 if ($data = @file_get_contents($testurl)) {
600 $data = trim($data);
601 if ($data === $teststr) {
602 return INSECURE_DATAROOT_ERROR;
606 preg_match('|https?://([^/]+)|i', $testurl, $matches);
607 $sitename = $matches[1];
608 $error = 0;
609 if ($fp = @fsockopen($sitename, 80, $error)) {
610 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
611 $localurl = $matches[1];
612 $out = "GET $localurl HTTP/1.1\r\n";
613 $out .= "Host: $sitename\r\n";
614 $out .= "Connection: Close\r\n\r\n";
615 fwrite($fp, $out);
616 $data = '';
617 $incoming = false;
618 while (!feof($fp)) {
619 if ($incoming) {
620 $data .= fgets($fp, 1024);
621 } else if (@fgets($fp, 1024) === "\r\n") {
622 $incoming = true;
625 fclose($fp);
626 $data = trim($data);
627 if ($data === $teststr) {
628 return INSECURE_DATAROOT_ERROR;
632 return INSECURE_DATAROOT_WARNING;
636 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
638 function enable_cli_maintenance_mode() {
639 global $CFG, $SITE;
641 if (file_exists("$CFG->dataroot/climaintenance.html")) {
642 unlink("$CFG->dataroot/climaintenance.html");
645 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
646 $data = $CFG->maintenance_message;
647 $data = bootstrap_renderer::early_error_content($data, null, null, null);
648 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
650 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
651 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
653 } else {
654 $data = get_string('sitemaintenance', 'admin');
655 $data = bootstrap_renderer::early_error_content($data, null, null, null);
656 $data = bootstrap_renderer::plain_page(get_string('sitemaintenancetitle', 'admin',
657 format_string($SITE->fullname, true, ['context' => context_system::instance()])), $data);
660 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
661 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
664 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
668 * Interface for anything appearing in the admin tree
670 * The interface that is implemented by anything that appears in the admin tree
671 * block. It forces inheriting classes to define a method for checking user permissions
672 * and methods for finding something in the admin tree.
674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676 interface part_of_admin_tree {
679 * Finds a named part_of_admin_tree.
681 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
682 * and not parentable_part_of_admin_tree, then this function should only check if
683 * $this->name matches $name. If it does, it should return a reference to $this,
684 * otherwise, it should return a reference to NULL.
686 * If a class inherits parentable_part_of_admin_tree, this method should be called
687 * recursively on all child objects (assuming, of course, the parent object's name
688 * doesn't match the search criterion).
690 * @param string $name The internal name of the part_of_admin_tree we're searching for.
691 * @return mixed An object reference or a NULL reference.
693 public function locate($name);
696 * Removes named part_of_admin_tree.
698 * @param string $name The internal name of the part_of_admin_tree we want to remove.
699 * @return bool success.
701 public function prune($name);
704 * Search using query
705 * @param string $query
706 * @return mixed array-object structure of found settings and pages
708 public function search($query);
711 * Verifies current user's access to this part_of_admin_tree.
713 * Used to check if the current user has access to this part of the admin tree or
714 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
715 * then this method is usually just a call to has_capability() in the site context.
717 * If a class inherits parentable_part_of_admin_tree, this method should return the
718 * logical OR of the return of check_access() on all child objects.
720 * @return bool True if the user has access, false if she doesn't.
722 public function check_access();
725 * Mostly useful for removing of some parts of the tree in admin tree block.
727 * @return True is hidden from normal list view
729 public function is_hidden();
732 * Show we display Save button at the page bottom?
733 * @return bool
735 public function show_save();
740 * Interface implemented by any part_of_admin_tree that has children.
742 * The interface implemented by any part_of_admin_tree that can be a parent
743 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
744 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
745 * include an add method for adding other part_of_admin_tree objects as children.
747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
749 interface parentable_part_of_admin_tree extends part_of_admin_tree {
752 * Adds a part_of_admin_tree object to the admin tree.
754 * Used to add a part_of_admin_tree object to this object or a child of this
755 * object. $something should only be added if $destinationname matches
756 * $this->name. If it doesn't, add should be called on child objects that are
757 * also parentable_part_of_admin_tree's.
759 * $something should be appended as the last child in the $destinationname. If the
760 * $beforesibling is specified, $something should be prepended to it. If the given
761 * sibling is not found, $something should be appended to the end of $destinationname
762 * and a developer debugging message should be displayed.
764 * @param string $destinationname The internal name of the new parent for $something.
765 * @param part_of_admin_tree $something The object to be added.
766 * @return bool True on success, false on failure.
768 public function add($destinationname, $something, $beforesibling = null);
774 * The object used to represent folders (a.k.a. categories) in the admin tree block.
776 * Each admin_category object contains a number of part_of_admin_tree objects.
778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
780 class admin_category implements parentable_part_of_admin_tree, linkable_settings_page {
782 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
783 protected $children;
784 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
785 public $name;
786 /** @var string The displayed name for this category. Usually obtained through get_string() */
787 public $visiblename;
788 /** @var bool Should this category be hidden in admin tree block? */
789 public $hidden;
790 /** @var mixed Either a string or an array or strings */
791 public $path;
792 /** @var mixed Either a string or an array or strings */
793 public $visiblepath;
795 /** @var array fast lookup category cache, all categories of one tree point to one cache */
796 protected $category_cache;
798 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
799 protected $sort = false;
800 /** @var bool If set to true children will be sorted in ascending order. */
801 protected $sortasc = true;
802 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
803 protected $sortsplit = true;
804 /** @var bool $sorted True if the children have been sorted and don't need resorting */
805 protected $sorted = false;
808 * Constructor for an empty admin category
810 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
811 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
812 * @param bool $hidden hide category in admin tree block, defaults to false
814 public function __construct($name, $visiblename, $hidden=false) {
815 $this->children = array();
816 $this->name = $name;
817 $this->visiblename = $visiblename;
818 $this->hidden = $hidden;
822 * Get the URL to view this settings page.
824 * @return moodle_url
826 public function get_settings_page_url(): moodle_url {
827 return new moodle_url(
828 '/admin/category.php',
830 'category' => $this->name,
836 * Returns a reference to the part_of_admin_tree object with internal name $name.
838 * @param string $name The internal name of the object we want.
839 * @param bool $findpath initialize path and visiblepath arrays
840 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
841 * defaults to false
843 public function locate($name, $findpath=false) {
844 if (!isset($this->category_cache[$this->name])) {
845 // somebody much have purged the cache
846 $this->category_cache[$this->name] = $this;
849 if ($this->name == $name) {
850 if ($findpath) {
851 $this->visiblepath[] = $this->visiblename;
852 $this->path[] = $this->name;
854 return $this;
857 // quick category lookup
858 if (!$findpath and isset($this->category_cache[$name])) {
859 return $this->category_cache[$name];
862 $return = NULL;
863 foreach($this->children as $childid=>$unused) {
864 if ($return = $this->children[$childid]->locate($name, $findpath)) {
865 break;
869 if (!is_null($return) and $findpath) {
870 $return->visiblepath[] = $this->visiblename;
871 $return->path[] = $this->name;
874 return $return;
878 * Search using query
880 * @param string query
881 * @return mixed array-object structure of found settings and pages
883 public function search($query) {
884 $result = array();
885 foreach ($this->get_children() as $child) {
886 $subsearch = $child->search($query);
887 if (!is_array($subsearch)) {
888 debugging('Incorrect search result from '.$child->name);
889 continue;
891 $result = array_merge($result, $subsearch);
893 return $result;
897 * Removes part_of_admin_tree object with internal name $name.
899 * @param string $name The internal name of the object we want to remove.
900 * @return bool success
902 public function prune($name) {
904 if ($this->name == $name) {
905 return false; //can not remove itself
908 foreach($this->children as $precedence => $child) {
909 if ($child->name == $name) {
910 // clear cache and delete self
911 while($this->category_cache) {
912 // delete the cache, but keep the original array address
913 array_pop($this->category_cache);
915 unset($this->children[$precedence]);
916 return true;
917 } else if ($this->children[$precedence]->prune($name)) {
918 return true;
921 return false;
925 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
927 * By default the new part of the tree is appended as the last child of the parent. You
928 * can specify a sibling node that the new part should be prepended to. If the given
929 * sibling is not found, the part is appended to the end (as it would be by default) and
930 * a developer debugging message is displayed.
932 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
933 * @param string $destinationame The internal name of the immediate parent that we want for $something.
934 * @param mixed $something A part_of_admin_tree or setting instance to be added.
935 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
936 * @return bool True if successfully added, false if $something can not be added.
938 public function add($parentname, $something, $beforesibling = null) {
939 global $CFG;
941 $parent = $this->locate($parentname);
942 if (is_null($parent)) {
943 debugging('parent does not exist!');
944 return false;
947 if ($something instanceof part_of_admin_tree) {
948 if (!($parent instanceof parentable_part_of_admin_tree)) {
949 debugging('error - parts of tree can be inserted only into parentable parts');
950 return false;
952 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
953 // The name of the node is already used, simply warn the developer that this should not happen.
954 // It is intentional to check for the debug level before performing the check.
955 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
957 if (is_null($beforesibling)) {
958 // Append $something as the parent's last child.
959 $parent->children[] = $something;
960 } else {
961 if (!is_string($beforesibling) or trim($beforesibling) === '') {
962 throw new coding_exception('Unexpected value of the beforesibling parameter');
964 // Try to find the position of the sibling.
965 $siblingposition = null;
966 foreach ($parent->children as $childposition => $child) {
967 if ($child->name === $beforesibling) {
968 $siblingposition = $childposition;
969 break;
972 if (is_null($siblingposition)) {
973 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
974 $parent->children[] = $something;
975 } else {
976 $parent->children = array_merge(
977 array_slice($parent->children, 0, $siblingposition),
978 array($something),
979 array_slice($parent->children, $siblingposition)
983 if ($something instanceof admin_category) {
984 if (isset($this->category_cache[$something->name])) {
985 debugging('Duplicate admin category name: '.$something->name);
986 } else {
987 $this->category_cache[$something->name] = $something;
988 $something->category_cache =& $this->category_cache;
989 foreach ($something->children as $child) {
990 // just in case somebody already added subcategories
991 if ($child instanceof admin_category) {
992 if (isset($this->category_cache[$child->name])) {
993 debugging('Duplicate admin category name: '.$child->name);
994 } else {
995 $this->category_cache[$child->name] = $child;
996 $child->category_cache =& $this->category_cache;
1002 return true;
1004 } else {
1005 debugging('error - can not add this element');
1006 return false;
1012 * Checks if the user has access to anything in this category.
1014 * @return bool True if the user has access to at least one child in this category, false otherwise.
1016 public function check_access() {
1017 foreach ($this->children as $child) {
1018 if ($child->check_access()) {
1019 return true;
1022 return false;
1026 * Is this category hidden in admin tree block?
1028 * @return bool True if hidden
1030 public function is_hidden() {
1031 return $this->hidden;
1035 * Show we display Save button at the page bottom?
1036 * @return bool
1038 public function show_save() {
1039 foreach ($this->children as $child) {
1040 if ($child->show_save()) {
1041 return true;
1044 return false;
1048 * Sets sorting on this category.
1050 * Please note this function doesn't actually do the sorting.
1051 * It can be called anytime.
1052 * Sorting occurs when the user calls get_children.
1053 * Code using the children array directly won't see the sorted results.
1055 * @param bool $sort If set to true children will be sorted, if false they won't be.
1056 * @param bool $asc If true sorting will be ascending, otherwise descending.
1057 * @param bool $split If true we sort pages and sub categories separately.
1059 public function set_sorting($sort, $asc = true, $split = true) {
1060 $this->sort = (bool)$sort;
1061 $this->sortasc = (bool)$asc;
1062 $this->sortsplit = (bool)$split;
1066 * Returns the children associated with this category.
1068 * @return part_of_admin_tree[]
1070 public function get_children() {
1071 // If we should sort and it hasn't already been sorted.
1072 if ($this->sort && !$this->sorted) {
1073 if ($this->sortsplit) {
1074 $categories = array();
1075 $pages = array();
1076 foreach ($this->children as $child) {
1077 if ($child instanceof admin_category) {
1078 $categories[] = $child;
1079 } else {
1080 $pages[] = $child;
1083 core_collator::asort_objects_by_property($categories, 'visiblename');
1084 core_collator::asort_objects_by_property($pages, 'visiblename');
1085 if (!$this->sortasc) {
1086 $categories = array_reverse($categories);
1087 $pages = array_reverse($pages);
1089 $this->children = array_merge($pages, $categories);
1090 } else {
1091 core_collator::asort_objects_by_property($this->children, 'visiblename');
1092 if (!$this->sortasc) {
1093 $this->children = array_reverse($this->children);
1096 $this->sorted = true;
1098 return $this->children;
1102 * Magically gets a property from this object.
1104 * @param $property
1105 * @return part_of_admin_tree[]
1106 * @throws coding_exception
1108 public function __get($property) {
1109 if ($property === 'children') {
1110 return $this->get_children();
1112 throw new coding_exception('Invalid property requested.');
1116 * Magically sets a property against this object.
1118 * @param string $property
1119 * @param mixed $value
1120 * @throws coding_exception
1122 public function __set($property, $value) {
1123 if ($property === 'children') {
1124 $this->sorted = false;
1125 $this->children = $value;
1126 } else {
1127 throw new coding_exception('Invalid property requested.');
1132 * Checks if an inaccessible property is set.
1134 * @param string $property
1135 * @return bool
1136 * @throws coding_exception
1138 public function __isset($property) {
1139 if ($property === 'children') {
1140 return isset($this->children);
1142 throw new coding_exception('Invalid property requested.');
1148 * Root of admin settings tree, does not have any parent.
1150 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1152 class admin_root extends admin_category {
1153 /** @var array List of errors */
1154 public $errors;
1155 /** @var string search query */
1156 public $search;
1157 /** @var bool full tree flag - true means all settings required, false only pages required */
1158 public $fulltree;
1159 /** @var bool flag indicating loaded tree */
1160 public $loaded;
1161 /** @var mixed site custom defaults overriding defaults in settings files*/
1162 public $custom_defaults;
1165 * @param bool $fulltree true means all settings required,
1166 * false only pages required
1168 public function __construct($fulltree) {
1169 global $CFG;
1171 parent::__construct('root', get_string('administration'), false);
1172 $this->errors = array();
1173 $this->search = '';
1174 $this->fulltree = $fulltree;
1175 $this->loaded = false;
1177 $this->category_cache = array();
1179 // load custom defaults if found
1180 $this->custom_defaults = null;
1181 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1182 if (is_readable($defaultsfile)) {
1183 $defaults = array();
1184 include($defaultsfile);
1185 if (is_array($defaults) and count($defaults)) {
1186 $this->custom_defaults = $defaults;
1192 * Empties children array, and sets loaded to false
1194 * @param bool $requirefulltree
1196 public function purge_children($requirefulltree) {
1197 $this->children = array();
1198 $this->fulltree = ($requirefulltree || $this->fulltree);
1199 $this->loaded = false;
1200 //break circular dependencies - this helps PHP 5.2
1201 while($this->category_cache) {
1202 array_pop($this->category_cache);
1204 $this->category_cache = array();
1210 * Links external PHP pages into the admin tree.
1212 * See detailed usage example at the top of this document (adminlib.php)
1214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1216 class admin_externalpage implements part_of_admin_tree, linkable_settings_page {
1218 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1219 public $name;
1221 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1222 public $visiblename;
1224 /** @var string The external URL that we should link to when someone requests this external page. */
1225 public $url;
1227 /** @var array The role capability/permission a user must have to access this external page. */
1228 public $req_capability;
1230 /** @var object The context in which capability/permission should be checked, default is site context. */
1231 public $context;
1233 /** @var bool hidden in admin tree block. */
1234 public $hidden;
1236 /** @var mixed either string or array of string */
1237 public $path;
1239 /** @var array list of visible names of page parents */
1240 public $visiblepath;
1243 * Constructor for adding an external page into the admin tree.
1245 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1246 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1247 * @param string $url The external URL that we should link to when someone requests this external page.
1248 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1249 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1250 * @param stdClass $context The context the page relates to. Not sure what happens
1251 * if you specify something other than system or front page. Defaults to system.
1253 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1254 $this->name = $name;
1255 $this->visiblename = $visiblename;
1256 $this->url = $url;
1257 if (is_array($req_capability)) {
1258 $this->req_capability = $req_capability;
1259 } else {
1260 $this->req_capability = array($req_capability);
1262 $this->hidden = $hidden;
1263 $this->context = $context;
1267 * Get the URL to view this settings page.
1269 * @return moodle_url
1271 public function get_settings_page_url(): moodle_url {
1272 return new moodle_url($this->url);
1276 * Returns a reference to the part_of_admin_tree object with internal name $name.
1278 * @param string $name The internal name of the object we want.
1279 * @param bool $findpath defaults to false
1280 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1282 public function locate($name, $findpath=false) {
1283 if ($this->name == $name) {
1284 if ($findpath) {
1285 $this->visiblepath = array($this->visiblename);
1286 $this->path = array($this->name);
1288 return $this;
1289 } else {
1290 $return = NULL;
1291 return $return;
1296 * This function always returns false, required function by interface
1298 * @param string $name
1299 * @return false
1301 public function prune($name) {
1302 return false;
1306 * Search using query
1308 * @param string $query
1309 * @return mixed array-object structure of found settings and pages
1311 public function search($query) {
1312 $found = false;
1313 if (strpos(strtolower($this->name), $query) !== false) {
1314 $found = true;
1315 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1316 $found = true;
1318 if ($found) {
1319 $result = new stdClass();
1320 $result->page = $this;
1321 $result->settings = array();
1322 return array($this->name => $result);
1323 } else {
1324 return array();
1329 * Determines if the current user has access to this external page based on $this->req_capability.
1331 * @return bool True if user has access, false otherwise.
1333 public function check_access() {
1334 global $CFG;
1335 $context = empty($this->context) ? context_system::instance() : $this->context;
1336 foreach($this->req_capability as $cap) {
1337 if (has_capability($cap, $context)) {
1338 return true;
1341 return false;
1345 * Is this external page hidden in admin tree block?
1347 * @return bool True if hidden
1349 public function is_hidden() {
1350 return $this->hidden;
1354 * Show we display Save button at the page bottom?
1355 * @return bool
1357 public function show_save() {
1358 return false;
1363 * Used to store details of the dependency between two settings elements.
1365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1366 * @copyright 2017 Davo Smith, Synergy Learning
1368 class admin_settingdependency {
1369 /** @var string the name of the setting to be shown/hidden */
1370 public $settingname;
1371 /** @var string the setting this is dependent on */
1372 public $dependenton;
1373 /** @var string the condition to show/hide the element */
1374 public $condition;
1375 /** @var string the value to compare against */
1376 public $value;
1378 /** @var string[] list of valid conditions */
1379 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1382 * admin_settingdependency constructor.
1383 * @param string $settingname
1384 * @param string $dependenton
1385 * @param string $condition
1386 * @param string $value
1387 * @throws \coding_exception
1389 public function __construct($settingname, $dependenton, $condition, $value) {
1390 $this->settingname = $this->parse_name($settingname);
1391 $this->dependenton = $this->parse_name($dependenton);
1392 $this->condition = $condition;
1393 $this->value = $value;
1395 if (!in_array($this->condition, self::$validconditions)) {
1396 throw new coding_exception("Invalid condition '$condition'");
1401 * Convert the setting name into the form field name.
1402 * @param string $name
1403 * @return string
1405 private function parse_name($name) {
1406 $bits = explode('/', $name);
1407 $name = array_pop($bits);
1408 $plugin = '';
1409 if ($bits) {
1410 $plugin = array_pop($bits);
1411 if ($plugin === 'moodle') {
1412 $plugin = '';
1415 return 's_'.$plugin.'_'.$name;
1419 * Gather together all the dependencies in a format suitable for initialising javascript
1420 * @param admin_settingdependency[] $dependencies
1421 * @return array
1423 public static function prepare_for_javascript($dependencies) {
1424 $result = [];
1425 foreach ($dependencies as $d) {
1426 if (!isset($result[$d->dependenton])) {
1427 $result[$d->dependenton] = [];
1429 if (!isset($result[$d->dependenton][$d->condition])) {
1430 $result[$d->dependenton][$d->condition] = [];
1432 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1433 $result[$d->dependenton][$d->condition][$d->value] = [];
1435 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1437 return $result;
1442 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1444 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1446 class admin_settingpage implements part_of_admin_tree, linkable_settings_page {
1448 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1449 public $name;
1451 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1452 public $visiblename;
1454 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1455 public $settings;
1457 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1458 protected $dependencies = [];
1460 /** @var array The role capability/permission a user must have to access this external page. */
1461 public $req_capability;
1463 /** @var object The context in which capability/permission should be checked, default is site context. */
1464 public $context;
1466 /** @var bool hidden in admin tree block. */
1467 public $hidden;
1469 /** @var mixed string of paths or array of strings of paths */
1470 public $path;
1472 /** @var array list of visible names of page parents */
1473 public $visiblepath;
1476 * see admin_settingpage for details of this function
1478 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1479 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1480 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1481 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1482 * @param stdClass $context The context the page relates to. Not sure what happens
1483 * if you specify something other than system or front page. Defaults to system.
1485 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1486 $this->settings = new stdClass();
1487 $this->name = $name;
1488 $this->visiblename = $visiblename;
1489 if (is_array($req_capability)) {
1490 $this->req_capability = $req_capability;
1491 } else {
1492 $this->req_capability = array($req_capability);
1494 $this->hidden = $hidden;
1495 $this->context = $context;
1499 * Get the URL to view this page.
1501 * @return moodle_url
1503 public function get_settings_page_url(): moodle_url {
1504 return new moodle_url(
1505 '/admin/settings.php',
1507 'section' => $this->name,
1513 * see admin_category
1515 * @param string $name
1516 * @param bool $findpath
1517 * @return mixed Object (this) if name == this->name, else returns null
1519 public function locate($name, $findpath=false) {
1520 if ($this->name == $name) {
1521 if ($findpath) {
1522 $this->visiblepath = array($this->visiblename);
1523 $this->path = array($this->name);
1525 return $this;
1526 } else {
1527 $return = NULL;
1528 return $return;
1533 * Search string in settings page.
1535 * @param string $query
1536 * @return array
1538 public function search($query) {
1539 $found = array();
1541 foreach ($this->settings as $setting) {
1542 if ($setting->is_related($query)) {
1543 $found[] = $setting;
1547 if ($found) {
1548 $result = new stdClass();
1549 $result->page = $this;
1550 $result->settings = $found;
1551 return array($this->name => $result);
1554 $found = false;
1555 if (strpos(strtolower($this->name), $query) !== false) {
1556 $found = true;
1557 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1558 $found = true;
1560 if ($found) {
1561 $result = new stdClass();
1562 $result->page = $this;
1563 $result->settings = array();
1564 return array($this->name => $result);
1565 } else {
1566 return array();
1571 * This function always returns false, required by interface
1573 * @param string $name
1574 * @return bool Always false
1576 public function prune($name) {
1577 return false;
1581 * adds an admin_setting to this admin_settingpage
1583 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1584 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1586 * @param object $setting is the admin_setting object you want to add
1587 * @return bool true if successful, false if not
1589 public function add($setting) {
1590 if (!($setting instanceof admin_setting)) {
1591 debugging('error - not a setting instance');
1592 return false;
1595 $name = $setting->name;
1596 if ($setting->plugin) {
1597 $name = $setting->plugin . $name;
1599 $this->settings->{$name} = $setting;
1600 return true;
1604 * Hide the named setting if the specified condition is matched.
1606 * @param string $settingname
1607 * @param string $dependenton
1608 * @param string $condition
1609 * @param string $value
1611 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1612 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1614 // Reformat the dependency name to the plugin | name format used in the display.
1615 $dependenton = str_replace('/', ' | ', $dependenton);
1617 // Let the setting know, so it can be displayed underneath.
1618 $findname = str_replace('/', '', $settingname);
1619 foreach ($this->settings as $name => $setting) {
1620 if ($name === $findname) {
1621 $setting->add_dependent_on($dependenton);
1627 * see admin_externalpage
1629 * @return bool Returns true for yes false for no
1631 public function check_access() {
1632 global $CFG;
1633 $context = empty($this->context) ? context_system::instance() : $this->context;
1634 foreach($this->req_capability as $cap) {
1635 if (has_capability($cap, $context)) {
1636 return true;
1639 return false;
1643 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1644 * @return string Returns an XHTML string
1646 public function output_html() {
1647 $adminroot = admin_get_root();
1648 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1649 foreach($this->settings as $setting) {
1650 $fullname = $setting->get_full_name();
1651 if (array_key_exists($fullname, $adminroot->errors)) {
1652 $data = $adminroot->errors[$fullname]->data;
1653 } else {
1654 $data = $setting->get_setting();
1655 // do not use defaults if settings not available - upgrade settings handles the defaults!
1657 $return .= $setting->output_html($data);
1659 $return .= '</fieldset>';
1660 return $return;
1664 * Is this settings page hidden in admin tree block?
1666 * @return bool True if hidden
1668 public function is_hidden() {
1669 return $this->hidden;
1673 * Show we display Save button at the page bottom?
1674 * @return bool
1676 public function show_save() {
1677 foreach($this->settings as $setting) {
1678 if (empty($setting->nosave)) {
1679 return true;
1682 return false;
1686 * Should any of the settings on this page be shown / hidden based on conditions?
1687 * @return bool
1689 public function has_dependencies() {
1690 return (bool)$this->dependencies;
1694 * Format the setting show/hide conditions ready to initialise the page javascript
1695 * @return array
1697 public function get_dependencies_for_javascript() {
1698 if (!$this->has_dependencies()) {
1699 return [];
1701 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1707 * Admin settings class. Only exists on setting pages.
1708 * Read & write happens at this level; no authentication.
1710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1712 abstract class admin_setting {
1713 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1714 public $name;
1715 /** @var string localised name */
1716 public $visiblename;
1717 /** @var string localised long description in Markdown format */
1718 public $description;
1719 /** @var mixed Can be string or array of string */
1720 public $defaultsetting;
1721 /** @var string */
1722 public $updatedcallback;
1723 /** @var mixed can be String or Null. Null means main config table */
1724 public $plugin; // null means main config table
1725 /** @var bool true indicates this setting does not actually save anything, just information */
1726 public $nosave = false;
1727 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1728 public $affectsmodinfo = false;
1729 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1730 private $flags = array();
1731 /** @var bool Whether this field must be forced LTR. */
1732 private $forceltr = null;
1733 /** @var array list of other settings that may cause this setting to be hidden */
1734 private $dependenton = [];
1735 /** @var bool Whether this setting uses a custom form control */
1736 protected $customcontrol = false;
1739 * Constructor
1740 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1741 * or 'myplugin/mysetting' for ones in config_plugins.
1742 * @param string $visiblename localised name
1743 * @param string $description localised long description
1744 * @param mixed $defaultsetting string or array depending on implementation
1746 public function __construct($name, $visiblename, $description, $defaultsetting) {
1747 $this->parse_setting_name($name);
1748 $this->visiblename = $visiblename;
1749 $this->description = $description;
1750 $this->defaultsetting = $defaultsetting;
1754 * Generic function to add a flag to this admin setting.
1756 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1757 * @param bool $default - The default for the flag
1758 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1759 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1761 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1762 if (empty($this->flags[$shortname])) {
1763 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1764 } else {
1765 $this->flags[$shortname]->set_options($enabled, $default);
1770 * Set the enabled options flag on this admin setting.
1772 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1773 * @param bool $default - The default for the flag
1775 public function set_enabled_flag_options($enabled, $default) {
1776 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1780 * Set the advanced options flag on this admin setting.
1782 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1783 * @param bool $default - The default for the flag
1785 public function set_advanced_flag_options($enabled, $default) {
1786 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1791 * Set the locked options flag on this admin setting.
1793 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1794 * @param bool $default - The default for the flag
1796 public function set_locked_flag_options($enabled, $default) {
1797 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1801 * Set the required options flag on this admin setting.
1803 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1804 * @param bool $default - The default for the flag.
1806 public function set_required_flag_options($enabled, $default) {
1807 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1811 * Is this option forced in config.php?
1813 * @return bool
1815 public function is_readonly(): bool {
1816 global $CFG;
1818 if (empty($this->plugin)) {
1819 if (array_key_exists($this->name, $CFG->config_php_settings)) {
1820 return true;
1822 } else {
1823 if (array_key_exists($this->plugin, $CFG->forced_plugin_settings)
1824 and array_key_exists($this->name, $CFG->forced_plugin_settings[$this->plugin])) {
1825 return true;
1828 return false;
1832 * Get the currently saved value for a setting flag
1834 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1835 * @return bool
1837 public function get_setting_flag_value(admin_setting_flag $flag) {
1838 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1839 if (!isset($value)) {
1840 $value = $flag->get_default();
1843 return !empty($value);
1847 * Get the list of defaults for the flags on this setting.
1849 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1851 public function get_setting_flag_defaults(& $defaults) {
1852 foreach ($this->flags as $flag) {
1853 if ($flag->is_enabled() && $flag->get_default()) {
1854 $defaults[] = $flag->get_displayname();
1860 * Output the input fields for the advanced and locked flags on this setting.
1862 * @param bool $adv - The current value of the advanced flag.
1863 * @param bool $locked - The current value of the locked flag.
1864 * @return string $output - The html for the flags.
1866 public function output_setting_flags() {
1867 $output = '';
1869 foreach ($this->flags as $flag) {
1870 if ($flag->is_enabled()) {
1871 $output .= $flag->output_setting_flag($this);
1875 if (!empty($output)) {
1876 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1878 return $output;
1882 * Write the values of the flags for this admin setting.
1884 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1885 * @return bool - true if successful.
1887 public function write_setting_flags($data) {
1888 $result = true;
1889 foreach ($this->flags as $flag) {
1890 $result = $result && $flag->write_setting_flag($this, $data);
1892 return $result;
1896 * Set up $this->name and potentially $this->plugin
1898 * Set up $this->name and possibly $this->plugin based on whether $name looks
1899 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1900 * on the names, that is, output a developer debug warning if the name
1901 * contains anything other than [a-zA-Z0-9_]+.
1903 * @param string $name the setting name passed in to the constructor.
1905 private function parse_setting_name($name) {
1906 $bits = explode('/', $name);
1907 if (count($bits) > 2) {
1908 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1910 $this->name = array_pop($bits);
1911 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1912 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1914 if (!empty($bits)) {
1915 $this->plugin = array_pop($bits);
1916 if ($this->plugin === 'moodle') {
1917 $this->plugin = null;
1918 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1919 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1925 * Returns the fullname prefixed by the plugin
1926 * @return string
1928 public function get_full_name() {
1929 return 's_'.$this->plugin.'_'.$this->name;
1933 * Returns the ID string based on plugin and name
1934 * @return string
1936 public function get_id() {
1937 return 'id_s_'.$this->plugin.'_'.$this->name;
1941 * @param bool $affectsmodinfo If true, changes to this setting will
1942 * cause the course cache to be rebuilt
1944 public function set_affects_modinfo($affectsmodinfo) {
1945 $this->affectsmodinfo = $affectsmodinfo;
1949 * Returns the config if possible
1951 * @return mixed returns config if successful else null
1953 public function config_read($name) {
1954 global $CFG;
1955 if (!empty($this->plugin)) {
1956 $value = get_config($this->plugin, $name);
1957 return $value === false ? NULL : $value;
1959 } else {
1960 if (isset($CFG->$name)) {
1961 return $CFG->$name;
1962 } else {
1963 return NULL;
1969 * Used to set a config pair and log change
1971 * @param string $name
1972 * @param mixed $value Gets converted to string if not null
1973 * @return bool Write setting to config table
1975 public function config_write($name, $value) {
1976 global $DB, $USER, $CFG;
1978 if ($this->nosave) {
1979 return true;
1982 // make sure it is a real change
1983 $oldvalue = get_config($this->plugin, $name);
1984 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1985 $value = is_null($value) ? null : (string)$value;
1987 if ($oldvalue === $value) {
1988 return true;
1991 // store change
1992 set_config($name, $value, $this->plugin);
1994 // Some admin settings affect course modinfo
1995 if ($this->affectsmodinfo) {
1996 // Clear course cache for all courses
1997 rebuild_course_cache(0, true);
2000 $this->add_to_config_log($name, $oldvalue, $value);
2002 return true; // BC only
2006 * Log config changes if necessary.
2007 * @param string $name
2008 * @param string $oldvalue
2009 * @param string $value
2011 protected function add_to_config_log($name, $oldvalue, $value) {
2012 add_to_config_log($name, $oldvalue, $value, $this->plugin);
2016 * Returns current value of this setting
2017 * @return mixed array or string depending on instance, NULL means not set yet
2019 public abstract function get_setting();
2022 * Returns default setting if exists
2023 * @return mixed array or string depending on instance; NULL means no default, user must supply
2025 public function get_defaultsetting() {
2026 $adminroot = admin_get_root(false, false);
2027 if (!empty($adminroot->custom_defaults)) {
2028 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
2029 if (isset($adminroot->custom_defaults[$plugin])) {
2030 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
2031 return $adminroot->custom_defaults[$plugin][$this->name];
2035 return $this->defaultsetting;
2039 * Store new setting
2041 * @param mixed $data string or array, must not be NULL
2042 * @return string empty string if ok, string error message otherwise
2044 public abstract function write_setting($data);
2047 * Return part of form with setting
2048 * This function should always be overwritten
2050 * @param mixed $data array or string depending on setting
2051 * @param string $query
2052 * @return string
2054 public function output_html($data, $query='') {
2055 // should be overridden
2056 return;
2060 * Function called if setting updated - cleanup, cache reset, etc.
2061 * @param string $functionname Sets the function name
2062 * @return void
2064 public function set_updatedcallback($functionname) {
2065 $this->updatedcallback = $functionname;
2069 * Execute postupdatecallback if necessary.
2070 * @param mixed $original original value before write_setting()
2071 * @return bool true if changed, false if not.
2073 public function post_write_settings($original) {
2074 // Comparison must work for arrays too.
2075 if (serialize($original) === serialize($this->get_setting())) {
2076 return false;
2079 $callbackfunction = $this->updatedcallback;
2080 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2081 $callbackfunction($this->get_full_name());
2083 return true;
2087 * Is setting related to query text - used when searching
2088 * @param string $query
2089 * @return bool
2091 public function is_related($query) {
2092 if (strpos(strtolower($this->name), $query) !== false) {
2093 return true;
2095 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2096 return true;
2098 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2099 return true;
2101 $current = $this->get_setting();
2102 if (!is_null($current)) {
2103 if (is_string($current)) {
2104 if (strpos(core_text::strtolower($current), $query) !== false) {
2105 return true;
2109 $default = $this->get_defaultsetting();
2110 if (!is_null($default)) {
2111 if (is_string($default)) {
2112 if (strpos(core_text::strtolower($default), $query) !== false) {
2113 return true;
2117 return false;
2121 * Get whether this should be displayed in LTR mode.
2123 * @return bool|null
2125 public function get_force_ltr() {
2126 return $this->forceltr;
2130 * Set whether to force LTR or not.
2132 * @param bool $value True when forced, false when not force, null when unknown.
2134 public function set_force_ltr($value) {
2135 $this->forceltr = $value;
2139 * Add a setting to the list of those that could cause this one to be hidden
2140 * @param string $dependenton
2142 public function add_dependent_on($dependenton) {
2143 $this->dependenton[] = $dependenton;
2147 * Get a list of the settings that could cause this one to be hidden.
2148 * @return array
2150 public function get_dependent_on() {
2151 return $this->dependenton;
2155 * Whether this setting uses a custom form control.
2156 * This function is especially useful to decide if we should render a label element for this setting or not.
2158 * @return bool
2160 public function has_custom_form_control(): bool {
2161 return $this->customcontrol;
2166 * An additional option that can be applied to an admin setting.
2167 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2171 class admin_setting_flag {
2172 /** @var bool Flag to indicate if this option can be toggled for this setting */
2173 private $enabled = false;
2174 /** @var bool Flag to indicate if this option defaults to true or false */
2175 private $default = false;
2176 /** @var string Short string used to create setting name - e.g. 'adv' */
2177 private $shortname = '';
2178 /** @var string String used as the label for this flag */
2179 private $displayname = '';
2180 /** @const Checkbox for this flag is displayed in admin page */
2181 const ENABLED = true;
2182 /** @const Checkbox for this flag is not displayed in admin page */
2183 const DISABLED = false;
2186 * Constructor
2188 * @param bool $enabled Can this option can be toggled.
2189 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2190 * @param bool $default The default checked state for this setting option.
2191 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2192 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2194 public function __construct($enabled, $default, $shortname, $displayname) {
2195 $this->shortname = $shortname;
2196 $this->displayname = $displayname;
2197 $this->set_options($enabled, $default);
2201 * Update the values of this setting options class
2203 * @param bool $enabled Can this option can be toggled.
2204 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2205 * @param bool $default The default checked state for this setting option.
2207 public function set_options($enabled, $default) {
2208 $this->enabled = $enabled;
2209 $this->default = $default;
2213 * Should this option appear in the interface and be toggleable?
2215 * @return bool Is it enabled?
2217 public function is_enabled() {
2218 return $this->enabled;
2222 * Should this option be checked by default?
2224 * @return bool Is it on by default?
2226 public function get_default() {
2227 return $this->default;
2231 * Return the short name for this flag. e.g. 'adv' or 'locked'
2233 * @return string
2235 public function get_shortname() {
2236 return $this->shortname;
2240 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2242 * @return string
2244 public function get_displayname() {
2245 return $this->displayname;
2249 * Save the submitted data for this flag - or set it to the default if $data is null.
2251 * @param admin_setting $setting - The admin setting for this flag
2252 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2253 * @return bool
2255 public function write_setting_flag(admin_setting $setting, $data) {
2256 $result = true;
2257 if ($this->is_enabled()) {
2258 if (!isset($data)) {
2259 $value = $this->get_default();
2260 } else {
2261 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2263 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2266 return $result;
2271 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2273 * @param admin_setting $setting - The admin setting for this flag
2274 * @return string - The html for the checkbox.
2276 public function output_setting_flag(admin_setting $setting) {
2277 global $OUTPUT;
2279 $value = $setting->get_setting_flag_value($this);
2281 $context = new stdClass();
2282 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2283 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2284 $context->value = 1;
2285 $context->checked = $value ? true : false;
2286 $context->label = $this->get_displayname();
2288 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2294 * No setting - just heading and text.
2296 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2298 class admin_setting_heading extends admin_setting {
2301 * not a setting, just text
2302 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2303 * @param string $heading heading
2304 * @param string $information text in box
2306 public function __construct($name, $heading, $information) {
2307 $this->nosave = true;
2308 parent::__construct($name, $heading, $information, '');
2312 * Always returns true
2313 * @return bool Always returns true
2315 public function get_setting() {
2316 return true;
2320 * Always returns true
2321 * @return bool Always returns true
2323 public function get_defaultsetting() {
2324 return true;
2328 * Never write settings
2329 * @return string Always returns an empty string
2331 public function write_setting($data) {
2332 // do not write any setting
2333 return '';
2337 * Returns an HTML string
2338 * @return string Returns an HTML string
2340 public function output_html($data, $query='') {
2341 global $OUTPUT;
2342 $context = new stdClass();
2343 $context->title = $this->visiblename;
2344 $context->description = $this->description;
2345 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2346 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2351 * No setting - just name and description in same row.
2353 * @copyright 2018 onwards Amaia Anabitarte
2354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2356 class admin_setting_description extends admin_setting {
2359 * Not a setting, just text
2361 * @param string $name
2362 * @param string $visiblename
2363 * @param string $description
2365 public function __construct($name, $visiblename, $description) {
2366 $this->nosave = true;
2367 parent::__construct($name, $visiblename, $description, '');
2371 * Always returns true
2373 * @return bool Always returns true
2375 public function get_setting() {
2376 return true;
2380 * Always returns true
2382 * @return bool Always returns true
2384 public function get_defaultsetting() {
2385 return true;
2389 * Never write settings
2391 * @param mixed $data Gets converted to str for comparison against yes value
2392 * @return string Always returns an empty string
2394 public function write_setting($data) {
2395 // Do not write any setting.
2396 return '';
2400 * Returns an HTML string
2402 * @param string $data
2403 * @param string $query
2404 * @return string Returns an HTML string
2406 public function output_html($data, $query='') {
2407 global $OUTPUT;
2409 $context = new stdClass();
2410 $context->title = $this->visiblename;
2411 $context->description = $this->description;
2413 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2420 * The most flexible setting, the user enters text.
2422 * This type of field should be used for config settings which are using
2423 * English words and are not localised (passwords, database name, list of values, ...).
2425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2427 class admin_setting_configtext extends admin_setting {
2429 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2430 public $paramtype;
2431 /** @var int default field size */
2432 public $size;
2435 * Config text constructor
2437 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2438 * @param string $visiblename localised
2439 * @param string $description long localised info
2440 * @param string $defaultsetting
2441 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2442 * @param int $size default field size
2444 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2445 $this->paramtype = $paramtype;
2446 if (!is_null($size)) {
2447 $this->size = $size;
2448 } else {
2449 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2451 parent::__construct($name, $visiblename, $description, $defaultsetting);
2455 * Get whether this should be displayed in LTR mode.
2457 * Try to guess from the PARAM type unless specifically set.
2459 public function get_force_ltr() {
2460 $forceltr = parent::get_force_ltr();
2461 if ($forceltr === null) {
2462 return !is_rtl_compatible($this->paramtype);
2464 return $forceltr;
2468 * Return the setting
2470 * @return mixed returns config if successful else null
2472 public function get_setting() {
2473 return $this->config_read($this->name);
2476 public function write_setting($data) {
2477 if ($this->paramtype === PARAM_INT and $data === '') {
2478 // do not complain if '' used instead of 0
2479 $data = 0;
2481 // $data is a string
2482 $validated = $this->validate($data);
2483 if ($validated !== true) {
2484 return $validated;
2486 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2490 * Validate data before storage
2491 * @param string data
2492 * @return mixed true if ok string if error found
2494 public function validate($data) {
2495 // allow paramtype to be a custom regex if it is the form of /pattern/
2496 if (preg_match('#^/.*/$#', $this->paramtype)) {
2497 if (preg_match($this->paramtype, $data)) {
2498 return true;
2499 } else {
2500 return get_string('validateerror', 'admin');
2503 } else if ($this->paramtype === PARAM_RAW) {
2504 return true;
2506 } else {
2507 $cleaned = clean_param($data, $this->paramtype);
2508 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2509 return true;
2510 } else {
2511 return get_string('validateerror', 'admin');
2517 * Return an XHTML string for the setting
2518 * @return string Returns an XHTML string
2520 public function output_html($data, $query='') {
2521 global $OUTPUT;
2523 $default = $this->get_defaultsetting();
2524 $context = (object) [
2525 'size' => $this->size,
2526 'id' => $this->get_id(),
2527 'name' => $this->get_full_name(),
2528 'value' => $data,
2529 'forceltr' => $this->get_force_ltr(),
2530 'readonly' => $this->is_readonly(),
2532 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2534 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2539 * Text input with a maximum length constraint.
2541 * @copyright 2015 onwards Ankit Agarwal
2542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2544 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2546 /** @var int maximum number of chars allowed. */
2547 protected $maxlength;
2550 * Config text constructor
2552 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2553 * or 'myplugin/mysetting' for ones in config_plugins.
2554 * @param string $visiblename localised
2555 * @param string $description long localised info
2556 * @param string $defaultsetting
2557 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2558 * @param int $size default field size
2559 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2561 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2562 $size=null, $maxlength = 0) {
2563 $this->maxlength = $maxlength;
2564 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2568 * Validate data before storage
2570 * @param string $data data
2571 * @return mixed true if ok string if error found
2573 public function validate($data) {
2574 $parentvalidation = parent::validate($data);
2575 if ($parentvalidation === true) {
2576 if ($this->maxlength > 0) {
2577 // Max length check.
2578 $length = core_text::strlen($data);
2579 if ($length > $this->maxlength) {
2580 return get_string('maximumchars', 'moodle', $this->maxlength);
2582 return true;
2583 } else {
2584 return true; // No max length check needed.
2586 } else {
2587 return $parentvalidation;
2593 * General text area without html editor.
2595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2597 class admin_setting_configtextarea extends admin_setting_configtext {
2598 private $rows;
2599 private $cols;
2602 * @param string $name
2603 * @param string $visiblename
2604 * @param string $description
2605 * @param mixed $defaultsetting string or array
2606 * @param mixed $paramtype
2607 * @param string $cols The number of columns to make the editor
2608 * @param string $rows The number of rows to make the editor
2610 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2611 $this->rows = $rows;
2612 $this->cols = $cols;
2613 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2617 * Returns an XHTML string for the editor
2619 * @param string $data
2620 * @param string $query
2621 * @return string XHTML string for the editor
2623 public function output_html($data, $query='') {
2624 global $OUTPUT;
2626 $default = $this->get_defaultsetting();
2627 $defaultinfo = $default;
2628 if (!is_null($default) and $default !== '') {
2629 $defaultinfo = "\n".$default;
2632 $context = (object) [
2633 'cols' => $this->cols,
2634 'rows' => $this->rows,
2635 'id' => $this->get_id(),
2636 'name' => $this->get_full_name(),
2637 'value' => $data,
2638 'forceltr' => $this->get_force_ltr(),
2639 'readonly' => $this->is_readonly(),
2641 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2643 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2648 * General text area with html editor.
2650 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2653 * @param string $name
2654 * @param string $visiblename
2655 * @param string $description
2656 * @param mixed $defaultsetting string or array
2657 * @param mixed $paramtype
2659 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2660 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2661 $this->set_force_ltr(false);
2662 editors_head_setup();
2666 * Returns an XHTML string for the editor
2668 * @param string $data
2669 * @param string $query
2670 * @return string XHTML string for the editor
2672 public function output_html($data, $query='') {
2673 $editor = editors_get_preferred_editor(FORMAT_HTML);
2674 $editor->set_text($data);
2675 $editor->use_editor($this->get_id(), array('noclean'=>true));
2676 return parent::output_html($data, $query);
2680 * Checks if data has empty html.
2682 * @param string $data
2683 * @return string Empty when no errors.
2685 public function write_setting($data) {
2686 if (trim(html_to_text($data)) === '') {
2687 $data = '';
2689 return parent::write_setting($data);
2695 * Password field, allows unmasking of password
2697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2699 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2702 * Constructor
2703 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2704 * @param string $visiblename localised
2705 * @param string $description long localised info
2706 * @param string $defaultsetting default password
2708 public function __construct($name, $visiblename, $description, $defaultsetting) {
2709 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2713 * Log config changes if necessary.
2714 * @param string $name
2715 * @param string $oldvalue
2716 * @param string $value
2718 protected function add_to_config_log($name, $oldvalue, $value) {
2719 if ($value !== '') {
2720 $value = '********';
2722 if ($oldvalue !== '' and $oldvalue !== null) {
2723 $oldvalue = '********';
2725 parent::add_to_config_log($name, $oldvalue, $value);
2729 * Returns HTML for the field.
2731 * @param string $data Value for the field
2732 * @param string $query Passed as final argument for format_admin_setting
2733 * @return string Rendered HTML
2735 public function output_html($data, $query='') {
2736 global $OUTPUT;
2738 $context = (object) [
2739 'id' => $this->get_id(),
2740 'name' => $this->get_full_name(),
2741 'size' => $this->size,
2742 'value' => $this->is_readonly() ? null : $data,
2743 'forceltr' => $this->get_force_ltr(),
2744 'readonly' => $this->is_readonly(),
2746 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2747 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2752 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2755 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2757 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2760 * Constructor
2762 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2763 * @param string $visiblename localised
2764 * @param string $description long localised info
2765 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2767 public function __construct($name, $visiblename, $description, $defaultsetting) {
2768 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2769 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2774 * Admin setting class for encrypted values using secure encryption.
2776 * @copyright 2019 The Open University
2777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2779 class admin_setting_encryptedpassword extends admin_setting {
2782 * Constructor. Same as parent except that the default value is always an empty string.
2784 * @param string $name Internal name used in config table
2785 * @param string $visiblename Name shown on form
2786 * @param string $description Description that appears below field
2788 public function __construct(string $name, string $visiblename, string $description) {
2789 parent::__construct($name, $visiblename, $description, '');
2792 public function get_setting() {
2793 return $this->config_read($this->name);
2796 public function write_setting($data) {
2797 $data = trim($data);
2798 if ($data === '') {
2799 // Value can really be set to nothing.
2800 $savedata = '';
2801 } else {
2802 // Encrypt value before saving it.
2803 $savedata = \core\encryption::encrypt($data);
2805 return ($this->config_write($this->name, $savedata) ? '' : get_string('errorsetting', 'admin'));
2808 public function output_html($data, $query='') {
2809 global $OUTPUT;
2811 $default = $this->get_defaultsetting();
2812 $context = (object) [
2813 'id' => $this->get_id(),
2814 'name' => $this->get_full_name(),
2815 'set' => $data !== '',
2816 'novalue' => $this->get_setting() === null
2818 $element = $OUTPUT->render_from_template('core_admin/setting_encryptedpassword', $context);
2820 return format_admin_setting($this, $this->visiblename, $element, $this->description,
2821 true, '', $default, $query);
2826 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2827 * Note: Only advanced makes sense right now - locked does not.
2829 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2831 class admin_setting_configempty extends admin_setting_configtext {
2834 * @param string $name
2835 * @param string $visiblename
2836 * @param string $description
2838 public function __construct($name, $visiblename, $description) {
2839 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2843 * Returns an XHTML string for the hidden field
2845 * @param string $data
2846 * @param string $query
2847 * @return string XHTML string for the editor
2849 public function output_html($data, $query='') {
2850 global $OUTPUT;
2852 $context = (object) [
2853 'id' => $this->get_id(),
2854 'name' => $this->get_full_name()
2856 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2858 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2864 * Path to directory
2866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2868 class admin_setting_configfile extends admin_setting_configtext {
2870 * Constructor
2871 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2872 * @param string $visiblename localised
2873 * @param string $description long localised info
2874 * @param string $defaultdirectory default directory location
2876 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2877 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2881 * Returns XHTML for the field
2883 * Returns XHTML for the field and also checks whether the file
2884 * specified in $data exists using file_exists()
2886 * @param string $data File name and path to use in value attr
2887 * @param string $query
2888 * @return string XHTML field
2890 public function output_html($data, $query='') {
2891 global $CFG, $OUTPUT;
2893 $default = $this->get_defaultsetting();
2894 $context = (object) [
2895 'id' => $this->get_id(),
2896 'name' => $this->get_full_name(),
2897 'size' => $this->size,
2898 'value' => $data,
2899 'showvalidity' => !empty($data),
2900 'valid' => $data && file_exists($data),
2901 'readonly' => !empty($CFG->preventexecpath) || $this->is_readonly(),
2902 'forceltr' => $this->get_force_ltr(),
2905 if ($context->readonly) {
2906 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2909 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2911 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2915 * Checks if execpatch has been disabled in config.php
2917 public function write_setting($data) {
2918 global $CFG;
2919 if (!empty($CFG->preventexecpath)) {
2920 if ($this->get_setting() === null) {
2921 // Use default during installation.
2922 $data = $this->get_defaultsetting();
2923 if ($data === null) {
2924 $data = '';
2926 } else {
2927 return '';
2930 return parent::write_setting($data);
2937 * Path to executable file
2939 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2941 class admin_setting_configexecutable extends admin_setting_configfile {
2944 * Returns an XHTML field
2946 * @param string $data This is the value for the field
2947 * @param string $query
2948 * @return string XHTML field
2950 public function output_html($data, $query='') {
2951 global $CFG, $OUTPUT;
2952 $default = $this->get_defaultsetting();
2953 require_once("$CFG->libdir/filelib.php");
2955 $context = (object) [
2956 'id' => $this->get_id(),
2957 'name' => $this->get_full_name(),
2958 'size' => $this->size,
2959 'value' => $data,
2960 'showvalidity' => !empty($data),
2961 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2962 'readonly' => !empty($CFG->preventexecpath),
2963 'forceltr' => $this->get_force_ltr()
2966 if (!empty($CFG->preventexecpath)) {
2967 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2970 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2972 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2978 * Path to directory
2980 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2982 class admin_setting_configdirectory extends admin_setting_configfile {
2985 * Returns an XHTML field
2987 * @param string $data This is the value for the field
2988 * @param string $query
2989 * @return string XHTML
2991 public function output_html($data, $query='') {
2992 global $CFG, $OUTPUT;
2993 $default = $this->get_defaultsetting();
2995 $context = (object) [
2996 'id' => $this->get_id(),
2997 'name' => $this->get_full_name(),
2998 'size' => $this->size,
2999 'value' => $data,
3000 'showvalidity' => !empty($data),
3001 'valid' => $data && file_exists($data) && is_dir($data),
3002 'readonly' => !empty($CFG->preventexecpath),
3003 'forceltr' => $this->get_force_ltr()
3006 if (!empty($CFG->preventexecpath)) {
3007 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
3010 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
3012 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
3018 * Checkbox
3020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3022 class admin_setting_configcheckbox extends admin_setting {
3023 /** @var string Value used when checked */
3024 public $yes;
3025 /** @var string Value used when not checked */
3026 public $no;
3029 * Constructor
3030 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3031 * @param string $visiblename localised
3032 * @param string $description long localised info
3033 * @param string $defaultsetting
3034 * @param string $yes value used when checked
3035 * @param string $no value used when not checked
3037 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3038 parent::__construct($name, $visiblename, $description, $defaultsetting);
3039 $this->yes = (string)$yes;
3040 $this->no = (string)$no;
3044 * Retrieves the current setting using the objects name
3046 * @return string
3048 public function get_setting() {
3049 return $this->config_read($this->name);
3053 * Sets the value for the setting
3055 * Sets the value for the setting to either the yes or no values
3056 * of the object by comparing $data to yes
3058 * @param mixed $data Gets converted to str for comparison against yes value
3059 * @return string empty string or error
3061 public function write_setting($data) {
3062 if ((string)$data === $this->yes) { // convert to strings before comparison
3063 $data = $this->yes;
3064 } else {
3065 $data = $this->no;
3067 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3071 * Returns an XHTML checkbox field
3073 * @param string $data If $data matches yes then checkbox is checked
3074 * @param string $query
3075 * @return string XHTML field
3077 public function output_html($data, $query='') {
3078 global $OUTPUT;
3080 $context = (object) [
3081 'id' => $this->get_id(),
3082 'name' => $this->get_full_name(),
3083 'no' => $this->no,
3084 'value' => $this->yes,
3085 'checked' => (string) $data === $this->yes,
3086 'readonly' => $this->is_readonly(),
3089 $default = $this->get_defaultsetting();
3090 if (!is_null($default)) {
3091 if ((string)$default === $this->yes) {
3092 $defaultinfo = get_string('checkboxyes', 'admin');
3093 } else {
3094 $defaultinfo = get_string('checkboxno', 'admin');
3096 } else {
3097 $defaultinfo = NULL;
3100 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
3102 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3108 * Multiple checkboxes, each represents different value, stored in csv format
3110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3112 class admin_setting_configmulticheckbox extends admin_setting {
3113 /** @var array Array of choices value=>label */
3114 public $choices;
3115 /** @var callable|null Loader function for choices */
3116 protected $choiceloader = null;
3119 * Constructor: uses parent::__construct
3121 * The $choices parameter may be either an array of $value => $label format,
3122 * e.g. [1 => get_string('yes')], or a callback function which takes no parameters and
3123 * returns an array in that format.
3125 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3126 * @param string $visiblename localised
3127 * @param string $description long localised info
3128 * @param array $defaultsetting array of selected
3129 * @param array|callable $choices array of $value => $label for each checkbox, or a callback
3131 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3132 if (is_array($choices)) {
3133 $this->choices = $choices;
3135 if (is_callable($choices)) {
3136 $this->choiceloader = $choices;
3138 parent::__construct($name, $visiblename, $description, $defaultsetting);
3142 * This function may be used in ancestors for lazy loading of choices
3144 * Override this method if loading of choices is expensive, such
3145 * as when it requires multiple db requests.
3147 * @return bool true if loaded, false if error
3149 public function load_choices() {
3150 if ($this->choiceloader) {
3151 if (!is_array($this->choices)) {
3152 $this->choices = call_user_func($this->choiceloader);
3155 return true;
3159 * Is setting related to query text - used when searching
3161 * @param string $query
3162 * @return bool true on related, false on not or failure
3164 public function is_related($query) {
3165 if (!$this->load_choices() or empty($this->choices)) {
3166 return false;
3168 if (parent::is_related($query)) {
3169 return true;
3172 foreach ($this->choices as $desc) {
3173 if (strpos(core_text::strtolower($desc), $query) !== false) {
3174 return true;
3177 return false;
3181 * Returns the current setting if it is set
3183 * @return mixed null if null, else an array
3185 public function get_setting() {
3186 $result = $this->config_read($this->name);
3188 if (is_null($result)) {
3189 return NULL;
3191 if ($result === '') {
3192 return array();
3194 $enabled = explode(',', $result);
3195 $setting = array();
3196 foreach ($enabled as $option) {
3197 $setting[$option] = 1;
3199 return $setting;
3203 * Saves the setting(s) provided in $data
3205 * @param array $data An array of data, if not array returns empty str
3206 * @return mixed empty string on useless data or bool true=success, false=failed
3208 public function write_setting($data) {
3209 if (!is_array($data)) {
3210 return ''; // ignore it
3212 if (!$this->load_choices() or empty($this->choices)) {
3213 return '';
3215 unset($data['xxxxx']);
3216 $result = array();
3217 foreach ($data as $key => $value) {
3218 if ($value and array_key_exists($key, $this->choices)) {
3219 $result[] = $key;
3222 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3226 * Returns XHTML field(s) as required by choices
3228 * Relies on data being an array should data ever be another valid vartype with
3229 * acceptable value this may cause a warning/error
3230 * if (!is_array($data)) would fix the problem
3232 * @todo Add vartype handling to ensure $data is an array
3234 * @param array $data An array of checked values
3235 * @param string $query
3236 * @return string XHTML field
3238 public function output_html($data, $query='') {
3239 global $OUTPUT;
3241 if (!$this->load_choices() or empty($this->choices)) {
3242 return '';
3245 $default = $this->get_defaultsetting();
3246 if (is_null($default)) {
3247 $default = array();
3249 if (is_null($data)) {
3250 $data = array();
3253 $context = (object) [
3254 'id' => $this->get_id(),
3255 'name' => $this->get_full_name(),
3258 $options = array();
3259 $defaults = array();
3260 foreach ($this->choices as $key => $description) {
3261 if (!empty($default[$key])) {
3262 $defaults[] = $description;
3265 $options[] = [
3266 'key' => $key,
3267 'checked' => !empty($data[$key]),
3268 'label' => highlightfast($query, $description)
3272 if (is_null($default)) {
3273 $defaultinfo = null;
3274 } else if (!empty($defaults)) {
3275 $defaultinfo = implode(', ', $defaults);
3276 } else {
3277 $defaultinfo = get_string('none');
3280 $context->options = $options;
3281 $context->hasoptions = !empty($options);
3283 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3285 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3292 * Multiple checkboxes 2, value stored as string 00101011
3294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3296 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3299 * Returns the setting if set
3301 * @return mixed null if not set, else an array of set settings
3303 public function get_setting() {
3304 $result = $this->config_read($this->name);
3305 if (is_null($result)) {
3306 return NULL;
3308 if (!$this->load_choices()) {
3309 return NULL;
3311 $result = str_pad($result, count($this->choices), '0');
3312 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3313 $setting = array();
3314 foreach ($this->choices as $key=>$unused) {
3315 $value = array_shift($result);
3316 if ($value) {
3317 $setting[$key] = 1;
3320 return $setting;
3324 * Save setting(s) provided in $data param
3326 * @param array $data An array of settings to save
3327 * @return mixed empty string for bad data or bool true=>success, false=>error
3329 public function write_setting($data) {
3330 if (!is_array($data)) {
3331 return ''; // ignore it
3333 if (!$this->load_choices() or empty($this->choices)) {
3334 return '';
3336 $result = '';
3337 foreach ($this->choices as $key=>$unused) {
3338 if (!empty($data[$key])) {
3339 $result .= '1';
3340 } else {
3341 $result .= '0';
3344 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3350 * Select one value from list
3352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3354 class admin_setting_configselect extends admin_setting {
3355 /** @var array Array of choices value=>label */
3356 public $choices;
3357 /** @var array Array of choices grouped using optgroups */
3358 public $optgroups;
3359 /** @var callable|null Loader function for choices */
3360 protected $choiceloader = null;
3361 /** @var callable|null Validation function */
3362 protected $validatefunction = null;
3365 * Constructor.
3367 * If you want to lazy-load the choices, pass a callback function that returns a choice
3368 * array for the $choices parameter.
3370 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3371 * @param string $visiblename localised
3372 * @param string $description long localised info
3373 * @param string|int $defaultsetting
3374 * @param array|callable|null $choices array of $value=>$label for each selection, or callback
3376 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3377 // Look for optgroup and single options.
3378 if (is_array($choices)) {
3379 $this->choices = [];
3380 foreach ($choices as $key => $val) {
3381 if (is_array($val)) {
3382 $this->optgroups[$key] = $val;
3383 $this->choices = array_merge($this->choices, $val);
3384 } else {
3385 $this->choices[$key] = $val;
3389 if (is_callable($choices)) {
3390 $this->choiceloader = $choices;
3393 parent::__construct($name, $visiblename, $description, $defaultsetting);
3397 * Sets a validate function.
3399 * The callback will be passed one parameter, the new setting value, and should return either
3400 * an empty string '' if the value is OK, or an error message if not.
3402 * @param callable|null $validatefunction Validate function or null to clear
3403 * @since Moodle 3.10
3405 public function set_validate_function(?callable $validatefunction = null) {
3406 $this->validatefunction = $validatefunction;
3410 * This function may be used in ancestors for lazy loading of choices
3412 * Override this method if loading of choices is expensive, such
3413 * as when it requires multiple db requests.
3415 * @return bool true if loaded, false if error
3417 public function load_choices() {
3418 if ($this->choiceloader) {
3419 if (!is_array($this->choices)) {
3420 $this->choices = call_user_func($this->choiceloader);
3422 return true;
3424 return true;
3428 * Check if this is $query is related to a choice
3430 * @param string $query
3431 * @return bool true if related, false if not
3433 public function is_related($query) {
3434 if (parent::is_related($query)) {
3435 return true;
3437 if (!$this->load_choices()) {
3438 return false;
3440 foreach ($this->choices as $key=>$value) {
3441 if (strpos(core_text::strtolower($key), $query) !== false) {
3442 return true;
3444 if (strpos(core_text::strtolower($value), $query) !== false) {
3445 return true;
3448 return false;
3452 * Return the setting
3454 * @return mixed returns config if successful else null
3456 public function get_setting() {
3457 return $this->config_read($this->name);
3461 * Save a setting
3463 * @param string $data
3464 * @return string empty of error string
3466 public function write_setting($data) {
3467 if (!$this->load_choices() or empty($this->choices)) {
3468 return '';
3470 if (!array_key_exists($data, $this->choices)) {
3471 return ''; // ignore it
3474 // Validate the new setting.
3475 $error = $this->validate_setting($data);
3476 if ($error) {
3477 return $error;
3480 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3484 * Validate the setting. This uses the callback function if provided; subclasses could override
3485 * to carry out validation directly in the class.
3487 * @param string $data New value being set
3488 * @return string Empty string if valid, or error message text
3489 * @since Moodle 3.10
3491 protected function validate_setting(string $data): string {
3492 // If validation function is specified, call it now.
3493 if ($this->validatefunction) {
3494 return call_user_func($this->validatefunction, $data);
3495 } else {
3496 return '';
3501 * Returns XHTML select field
3503 * Ensure the options are loaded, and generate the XHTML for the select
3504 * element and any warning message. Separating this out from output_html
3505 * makes it easier to subclass this class.
3507 * @param string $data the option to show as selected.
3508 * @param string $current the currently selected option in the database, null if none.
3509 * @param string $default the default selected option.
3510 * @return array the HTML for the select element, and a warning message.
3511 * @deprecated since Moodle 3.2
3513 public function output_select_html($data, $current, $default, $extraname = '') {
3514 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3518 * Returns XHTML select field and wrapping div(s)
3520 * @see output_select_html()
3522 * @param string $data the option to show as selected
3523 * @param string $query
3524 * @return string XHTML field and wrapping div
3526 public function output_html($data, $query='') {
3527 global $OUTPUT;
3529 $default = $this->get_defaultsetting();
3530 $current = $this->get_setting();
3532 if (!$this->load_choices() || empty($this->choices)) {
3533 return '';
3536 $context = (object) [
3537 'id' => $this->get_id(),
3538 'name' => $this->get_full_name(),
3541 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3542 $defaultinfo = $this->choices[$default];
3543 } else {
3544 $defaultinfo = NULL;
3547 // Warnings.
3548 $warning = '';
3549 if ($current === null) {
3550 // First run.
3551 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3552 // No warning.
3553 } else if (!array_key_exists($current, $this->choices)) {
3554 $warning = get_string('warningcurrentsetting', 'admin', $current);
3555 if (!is_null($default) && $data == $current) {
3556 $data = $default; // Use default instead of first value when showing the form.
3560 $options = [];
3561 $template = 'core_admin/setting_configselect';
3563 if (!empty($this->optgroups)) {
3564 $optgroups = [];
3565 foreach ($this->optgroups as $label => $choices) {
3566 $optgroup = array('label' => $label, 'options' => []);
3567 foreach ($choices as $value => $name) {
3568 $optgroup['options'][] = [
3569 'value' => $value,
3570 'name' => $name,
3571 'selected' => (string) $value == $data
3573 unset($this->choices[$value]);
3575 $optgroups[] = $optgroup;
3577 $context->options = $options;
3578 $context->optgroups = $optgroups;
3579 $template = 'core_admin/setting_configselect_optgroup';
3582 foreach ($this->choices as $value => $name) {
3583 $options[] = [
3584 'value' => $value,
3585 'name' => $name,
3586 'selected' => (string) $value == $data
3589 $context->options = $options;
3590 $context->readonly = $this->is_readonly();
3592 $element = $OUTPUT->render_from_template($template, $context);
3594 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3599 * Select multiple items from list
3601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3603 class admin_setting_configmultiselect extends admin_setting_configselect {
3605 * Constructor
3606 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3607 * @param string $visiblename localised
3608 * @param string $description long localised info
3609 * @param array $defaultsetting array of selected items
3610 * @param array $choices array of $value=>$label for each list item
3612 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3613 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3617 * Returns the select setting(s)
3619 * @return mixed null or array. Null if no settings else array of setting(s)
3621 public function get_setting() {
3622 $result = $this->config_read($this->name);
3623 if (is_null($result)) {
3624 return NULL;
3626 if ($result === '') {
3627 return array();
3629 return explode(',', $result);
3633 * Saves setting(s) provided through $data
3635 * Potential bug in the works should anyone call with this function
3636 * using a vartype that is not an array
3638 * @param array $data
3640 public function write_setting($data) {
3641 if (!is_array($data)) {
3642 return ''; //ignore it
3644 if (!$this->load_choices() or empty($this->choices)) {
3645 return '';
3648 unset($data['xxxxx']);
3650 $save = array();
3651 foreach ($data as $value) {
3652 if (!array_key_exists($value, $this->choices)) {
3653 continue; // ignore it
3655 $save[] = $value;
3658 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3662 * Is setting related to query text - used when searching
3664 * @param string $query
3665 * @return bool true if related, false if not
3667 public function is_related($query) {
3668 if (!$this->load_choices() or empty($this->choices)) {
3669 return false;
3671 if (parent::is_related($query)) {
3672 return true;
3675 foreach ($this->choices as $desc) {
3676 if (strpos(core_text::strtolower($desc), $query) !== false) {
3677 return true;
3680 return false;
3684 * Returns XHTML multi-select field
3686 * @todo Add vartype handling to ensure $data is an array
3687 * @param array $data Array of values to select by default
3688 * @param string $query
3689 * @return string XHTML multi-select field
3691 public function output_html($data, $query='') {
3692 global $OUTPUT;
3694 if (!$this->load_choices() or empty($this->choices)) {
3695 return '';
3698 $default = $this->get_defaultsetting();
3699 if (is_null($default)) {
3700 $default = array();
3702 if (is_null($data)) {
3703 $data = array();
3706 $context = (object) [
3707 'id' => $this->get_id(),
3708 'name' => $this->get_full_name(),
3709 'size' => min(10, count($this->choices))
3712 $defaults = [];
3713 $options = [];
3714 $template = 'core_admin/setting_configmultiselect';
3716 if (!empty($this->optgroups)) {
3717 $optgroups = [];
3718 foreach ($this->optgroups as $label => $choices) {
3719 $optgroup = array('label' => $label, 'options' => []);
3720 foreach ($choices as $value => $name) {
3721 if (in_array($value, $default)) {
3722 $defaults[] = $name;
3724 $optgroup['options'][] = [
3725 'value' => $value,
3726 'name' => $name,
3727 'selected' => in_array($value, $data)
3729 unset($this->choices[$value]);
3731 $optgroups[] = $optgroup;
3733 $context->optgroups = $optgroups;
3734 $template = 'core_admin/setting_configmultiselect_optgroup';
3737 foreach ($this->choices as $value => $name) {
3738 if (in_array($value, $default)) {
3739 $defaults[] = $name;
3741 $options[] = [
3742 'value' => $value,
3743 'name' => $name,
3744 'selected' => in_array($value, $data)
3747 $context->options = $options;
3748 $context->readonly = $this->is_readonly();
3750 if (is_null($default)) {
3751 $defaultinfo = NULL;
3752 } if (!empty($defaults)) {
3753 $defaultinfo = implode(', ', $defaults);
3754 } else {
3755 $defaultinfo = get_string('none');
3758 $element = $OUTPUT->render_from_template($template, $context);
3760 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3765 * Time selector
3767 * This is a liiitle bit messy. we're using two selects, but we're returning
3768 * them as an array named after $name (so we only use $name2 internally for the setting)
3770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3772 class admin_setting_configtime extends admin_setting {
3773 /** @var string Used for setting second select (minutes) */
3774 public $name2;
3777 * Constructor
3778 * @param string $hoursname setting for hours
3779 * @param string $minutesname setting for hours
3780 * @param string $visiblename localised
3781 * @param string $description long localised info
3782 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3784 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3785 $this->name2 = $minutesname;
3786 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3790 * Get the selected time
3792 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3794 public function get_setting() {
3795 $result1 = $this->config_read($this->name);
3796 $result2 = $this->config_read($this->name2);
3797 if (is_null($result1) or is_null($result2)) {
3798 return NULL;
3801 return array('h' => $result1, 'm' => $result2);
3805 * Store the time (hours and minutes)
3807 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3808 * @return bool true if success, false if not
3810 public function write_setting($data) {
3811 if (!is_array($data)) {
3812 return '';
3815 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3816 return ($result ? '' : get_string('errorsetting', 'admin'));
3820 * Returns XHTML time select fields
3822 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3823 * @param string $query
3824 * @return string XHTML time select fields and wrapping div(s)
3826 public function output_html($data, $query='') {
3827 global $OUTPUT;
3829 $default = $this->get_defaultsetting();
3830 if (is_array($default)) {
3831 $defaultinfo = $default['h'].':'.$default['m'];
3832 } else {
3833 $defaultinfo = NULL;
3836 $context = (object) [
3837 'id' => $this->get_id(),
3838 'name' => $this->get_full_name(),
3839 'readonly' => $this->is_readonly(),
3840 'hours' => array_map(function($i) use ($data) {
3841 return [
3842 'value' => $i,
3843 'name' => $i,
3844 'selected' => $i == $data['h']
3846 }, range(0, 23)),
3847 'minutes' => array_map(function($i) use ($data) {
3848 return [
3849 'value' => $i,
3850 'name' => $i,
3851 'selected' => $i == $data['m']
3853 }, range(0, 59, 5))
3856 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3858 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3859 $this->get_id() . 'h', '', $defaultinfo, $query);
3866 * Seconds duration setting.
3868 * @copyright 2012 Petr Skoda (http://skodak.org)
3869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3871 class admin_setting_configduration extends admin_setting {
3873 /** @var int default duration unit */
3874 protected $defaultunit;
3875 /** @var callable|null Validation function */
3876 protected $validatefunction = null;
3879 * Constructor
3880 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3881 * or 'myplugin/mysetting' for ones in config_plugins.
3882 * @param string $visiblename localised name
3883 * @param string $description localised long description
3884 * @param mixed $defaultsetting string or array depending on implementation
3885 * @param int $defaultunit - day, week, etc. (in seconds)
3887 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3888 if (is_number($defaultsetting)) {
3889 $defaultsetting = self::parse_seconds($defaultsetting);
3891 $units = self::get_units();
3892 if (isset($units[$defaultunit])) {
3893 $this->defaultunit = $defaultunit;
3894 } else {
3895 $this->defaultunit = 86400;
3897 parent::__construct($name, $visiblename, $description, $defaultsetting);
3901 * Sets a validate function.
3903 * The callback will be passed one parameter, the new setting value, and should return either
3904 * an empty string '' if the value is OK, or an error message if not.
3906 * @param callable|null $validatefunction Validate function or null to clear
3907 * @since Moodle 3.10
3909 public function set_validate_function(?callable $validatefunction = null) {
3910 $this->validatefunction = $validatefunction;
3914 * Validate the setting. This uses the callback function if provided; subclasses could override
3915 * to carry out validation directly in the class.
3917 * @param int $data New value being set
3918 * @return string Empty string if valid, or error message text
3919 * @since Moodle 3.10
3921 protected function validate_setting(int $data): string {
3922 // If validation function is specified, call it now.
3923 if ($this->validatefunction) {
3924 return call_user_func($this->validatefunction, $data);
3925 } else {
3926 if ($data < 0) {
3927 return get_string('errorsetting', 'admin');
3929 return '';
3934 * Returns selectable units.
3935 * @static
3936 * @return array
3938 protected static function get_units() {
3939 return array(
3940 604800 => get_string('weeks'),
3941 86400 => get_string('days'),
3942 3600 => get_string('hours'),
3943 60 => get_string('minutes'),
3944 1 => get_string('seconds'),
3949 * Converts seconds to some more user friendly string.
3950 * @static
3951 * @param int $seconds
3952 * @return string
3954 protected static function get_duration_text($seconds) {
3955 if (empty($seconds)) {
3956 return get_string('none');
3958 $data = self::parse_seconds($seconds);
3959 switch ($data['u']) {
3960 case (60*60*24*7):
3961 return get_string('numweeks', '', $data['v']);
3962 case (60*60*24):
3963 return get_string('numdays', '', $data['v']);
3964 case (60*60):
3965 return get_string('numhours', '', $data['v']);
3966 case (60):
3967 return get_string('numminutes', '', $data['v']);
3968 default:
3969 return get_string('numseconds', '', $data['v']*$data['u']);
3974 * Finds suitable units for given duration.
3975 * @static
3976 * @param int $seconds
3977 * @return array
3979 protected static function parse_seconds($seconds) {
3980 foreach (self::get_units() as $unit => $unused) {
3981 if ($seconds % $unit === 0) {
3982 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3985 return array('v'=>(int)$seconds, 'u'=>1);
3989 * Get the selected duration as array.
3991 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3993 public function get_setting() {
3994 $seconds = $this->config_read($this->name);
3995 if (is_null($seconds)) {
3996 return null;
3999 return self::parse_seconds($seconds);
4003 * Store the duration as seconds.
4005 * @param array $data Must be form 'h'=>xx, 'm'=>xx
4006 * @return bool true if success, false if not
4008 public function write_setting($data) {
4009 if (!is_array($data)) {
4010 return '';
4013 $unit = (int)$data['u'];
4014 $value = (int)$data['v'];
4015 $seconds = $value * $unit;
4017 // Validate the new setting.
4018 $error = $this->validate_setting($seconds);
4019 if ($error) {
4020 return $error;
4023 $result = $this->config_write($this->name, $seconds);
4024 return ($result ? '' : get_string('errorsetting', 'admin'));
4028 * Returns duration text+select fields.
4030 * @param array $data Must be form 'v'=>xx, 'u'=>xx
4031 * @param string $query
4032 * @return string duration text+select fields and wrapping div(s)
4034 public function output_html($data, $query='') {
4035 global $OUTPUT;
4037 $default = $this->get_defaultsetting();
4038 if (is_number($default)) {
4039 $defaultinfo = self::get_duration_text($default);
4040 } else if (is_array($default)) {
4041 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
4042 } else {
4043 $defaultinfo = null;
4046 $inputid = $this->get_id() . 'v';
4047 $units = self::get_units();
4048 $defaultunit = $this->defaultunit;
4050 $context = (object) [
4051 'id' => $this->get_id(),
4052 'name' => $this->get_full_name(),
4053 'value' => $data['v'],
4054 'readonly' => $this->is_readonly(),
4055 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
4056 return [
4057 'value' => $unit,
4058 'name' => $units[$unit],
4059 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
4061 }, array_keys($units))
4064 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
4066 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
4072 * Seconds duration setting with an advanced checkbox, that controls a additional
4073 * $name.'_adv' setting.
4075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4076 * @copyright 2014 The Open University
4078 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
4080 * Constructor
4081 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
4082 * or 'myplugin/mysetting' for ones in config_plugins.
4083 * @param string $visiblename localised name
4084 * @param string $description localised long description
4085 * @param array $defaultsetting array of int value, and bool whether it is
4086 * is advanced by default.
4087 * @param int $defaultunit - day, week, etc. (in seconds)
4089 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
4090 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
4091 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4097 * Used to validate a textarea used for ip addresses
4099 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4100 * @copyright 2011 Petr Skoda (http://skodak.org)
4102 class admin_setting_configiplist extends admin_setting_configtextarea {
4105 * Validate the contents of the textarea as IP addresses
4107 * Used to validate a new line separated list of IP addresses collected from
4108 * a textarea control
4110 * @param string $data A list of IP Addresses separated by new lines
4111 * @return mixed bool true for success or string:error on failure
4113 public function validate($data) {
4114 if(!empty($data)) {
4115 $lines = explode("\n", $data);
4116 } else {
4117 return true;
4119 $result = true;
4120 $badips = array();
4121 foreach ($lines as $line) {
4122 $tokens = explode('#', $line);
4123 $ip = trim($tokens[0]);
4124 if (empty($ip)) {
4125 continue;
4127 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
4128 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
4129 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4130 } else {
4131 $result = false;
4132 $badips[] = $ip;
4135 if($result) {
4136 return true;
4137 } else {
4138 return get_string('validateiperror', 'admin', join(', ', $badips));
4144 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
4146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4147 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4149 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
4152 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
4153 * Used to validate a new line separated list of entries collected from a textarea control.
4155 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
4156 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
4157 * via the get_setting() method, which has been overriden.
4159 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
4160 * @return mixed bool true for success or string:error on failure
4162 public function validate($data) {
4163 if (empty($data)) {
4164 return true;
4166 $entries = explode("\n", $data);
4167 $badentries = [];
4169 foreach ($entries as $key => $entry) {
4170 $entry = trim($entry);
4171 if (empty($entry)) {
4172 return get_string('validateemptylineerror', 'admin');
4175 // Validate each string entry against the supported formats.
4176 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
4177 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
4178 || \core\ip_utils::is_domain_matching_pattern($entry)) {
4179 continue;
4182 // Otherwise, the entry is invalid.
4183 $badentries[] = $entry;
4186 if ($badentries) {
4187 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
4189 return true;
4193 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
4195 * @param string $data the setting data, as sent from the web form.
4196 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
4198 protected function ace_encode($data) {
4199 if (empty($data)) {
4200 return $data;
4202 $entries = explode("\n", $data);
4203 foreach ($entries as $key => $entry) {
4204 $entry = trim($entry);
4205 // This regex matches any string that has non-ascii character.
4206 if (preg_match('/[^\x00-\x7f]/', $entry)) {
4207 // If we can convert the unicode string to an idn, do so.
4208 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
4209 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4210 $entries[$key] = $val ? $val : $entry;
4213 return implode("\n", $entries);
4217 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4219 * @param string $data the setting data, as found in the database.
4220 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4222 protected function ace_decode($data) {
4223 $entries = explode("\n", $data);
4224 foreach ($entries as $key => $entry) {
4225 $entry = trim($entry);
4226 if (strpos($entry, 'xn--') !== false) {
4227 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4230 return implode("\n", $entries);
4234 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4236 * @return mixed returns punycode-converted setting string if successful, else null.
4238 public function get_setting() {
4239 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4240 $data = $this->config_read($this->name);
4241 if (function_exists('idn_to_utf8') && !is_null($data)) {
4242 $data = $this->ace_decode($data);
4244 return $data;
4248 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4250 * @param string $data
4251 * @return string
4253 public function write_setting($data) {
4254 if ($this->paramtype === PARAM_INT and $data === '') {
4255 // Do not complain if '' used instead of 0.
4256 $data = 0;
4259 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4260 if (function_exists('idn_to_ascii')) {
4261 $data = $this->ace_encode($data);
4264 $validated = $this->validate($data);
4265 if ($validated !== true) {
4266 return $validated;
4268 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4273 * Used to validate a textarea used for port numbers.
4275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4276 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4278 class admin_setting_configportlist extends admin_setting_configtextarea {
4281 * Validate the contents of the textarea as port numbers.
4282 * Used to validate a new line separated list of ports collected from a textarea control.
4284 * @param string $data A list of ports separated by new lines
4285 * @return mixed bool true for success or string:error on failure
4287 public function validate($data) {
4288 if (empty($data)) {
4289 return true;
4291 $ports = explode("\n", $data);
4292 $badentries = [];
4293 foreach ($ports as $port) {
4294 $port = trim($port);
4295 if (empty($port)) {
4296 return get_string('validateemptylineerror', 'admin');
4299 // Is the string a valid integer number?
4300 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4301 $badentries[] = $port;
4304 if ($badentries) {
4305 return get_string('validateerrorlist', 'admin', $badentries);
4307 return true;
4313 * An admin setting for selecting one or more users who have a capability
4314 * in the system context
4316 * An admin setting for selecting one or more users, who have a particular capability
4317 * in the system context. Warning, make sure the list will never be too long. There is
4318 * no paging or searching of this list.
4320 * To correctly get a list of users from this config setting, you need to call the
4321 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4325 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4326 /** @var string The capabilities name */
4327 protected $capability;
4328 /** @var int include admin users too */
4329 protected $includeadmins;
4332 * Constructor.
4334 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4335 * @param string $visiblename localised name
4336 * @param string $description localised long description
4337 * @param array $defaultsetting array of usernames
4338 * @param string $capability string capability name.
4339 * @param bool $includeadmins include administrators
4341 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4342 $this->capability = $capability;
4343 $this->includeadmins = $includeadmins;
4344 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4348 * Load all of the uses who have the capability into choice array
4350 * @return bool Always returns true
4352 function load_choices() {
4353 if (is_array($this->choices)) {
4354 return true;
4356 list($sort, $sortparams) = users_order_by_sql('u');
4357 if (!empty($sortparams)) {
4358 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4359 'This is unexpected, and a problem because there is no way to pass these ' .
4360 'parameters to get_users_by_capability. See MDL-34657.');
4362 $userfieldsapi = \core_user\fields::for_name();
4363 $userfields = 'u.id, u.username, ' . $userfieldsapi->get_sql('u', false, '', '', false)->selects;
4364 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4365 $this->choices = array(
4366 '$@NONE@$' => get_string('nobody'),
4367 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4369 if ($this->includeadmins) {
4370 $admins = get_admins();
4371 foreach ($admins as $user) {
4372 $this->choices[$user->id] = fullname($user);
4375 if (is_array($users)) {
4376 foreach ($users as $user) {
4377 $this->choices[$user->id] = fullname($user);
4380 return true;
4384 * Returns the default setting for class
4386 * @return mixed Array, or string. Empty string if no default
4388 public function get_defaultsetting() {
4389 $this->load_choices();
4390 $defaultsetting = parent::get_defaultsetting();
4391 if (empty($defaultsetting)) {
4392 return array('$@NONE@$');
4393 } else if (array_key_exists($defaultsetting, $this->choices)) {
4394 return $defaultsetting;
4395 } else {
4396 return '';
4401 * Returns the current setting
4403 * @return mixed array or string
4405 public function get_setting() {
4406 $result = parent::get_setting();
4407 if ($result === null) {
4408 // this is necessary for settings upgrade
4409 return null;
4411 if (empty($result)) {
4412 $result = array('$@NONE@$');
4414 return $result;
4418 * Save the chosen setting provided as $data
4420 * @param array $data
4421 * @return mixed string or array
4423 public function write_setting($data) {
4424 // If all is selected, remove any explicit options.
4425 if (in_array('$@ALL@$', $data)) {
4426 $data = array('$@ALL@$');
4428 // None never needs to be written to the DB.
4429 if (in_array('$@NONE@$', $data)) {
4430 unset($data[array_search('$@NONE@$', $data)]);
4432 return parent::write_setting($data);
4438 * Special checkbox for calendar - resets SESSION vars.
4440 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4442 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4444 * Calls the parent::__construct with default values
4446 * name => calendar_adminseesall
4447 * visiblename => get_string('adminseesall', 'admin')
4448 * description => get_string('helpadminseesall', 'admin')
4449 * defaultsetting => 0
4451 public function __construct() {
4452 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4453 get_string('helpadminseesall', 'admin'), '0');
4457 * Stores the setting passed in $data
4459 * @param mixed gets converted to string for comparison
4460 * @return string empty string or error message
4462 public function write_setting($data) {
4463 global $SESSION;
4464 return parent::write_setting($data);
4469 * Special select for settings that are altered in setup.php and can not be altered on the fly
4471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4473 class admin_setting_special_selectsetup extends admin_setting_configselect {
4475 * Reads the setting directly from the database
4477 * @return mixed
4479 public function get_setting() {
4480 // read directly from db!
4481 return get_config(NULL, $this->name);
4485 * Save the setting passed in $data
4487 * @param string $data The setting to save
4488 * @return string empty or error message
4490 public function write_setting($data) {
4491 global $CFG;
4492 // do not change active CFG setting!
4493 $current = $CFG->{$this->name};
4494 $result = parent::write_setting($data);
4495 $CFG->{$this->name} = $current;
4496 return $result;
4502 * Special select for frontpage - stores data in course table
4504 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4506 class admin_setting_sitesetselect extends admin_setting_configselect {
4508 * Returns the site name for the selected site
4510 * @see get_site()
4511 * @return string The site name of the selected site
4513 public function get_setting() {
4514 $site = course_get_format(get_site())->get_course();
4515 return $site->{$this->name};
4519 * Updates the database and save the setting
4521 * @param string data
4522 * @return string empty or error message
4524 public function write_setting($data) {
4525 global $DB, $SITE, $COURSE;
4526 if (!in_array($data, array_keys($this->choices))) {
4527 return get_string('errorsetting', 'admin');
4529 $record = new stdClass();
4530 $record->id = SITEID;
4531 $temp = $this->name;
4532 $record->$temp = $data;
4533 $record->timemodified = time();
4535 course_get_format($SITE)->update_course_format_options($record);
4536 $DB->update_record('course', $record);
4538 // Reset caches.
4539 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4540 if ($SITE->id == $COURSE->id) {
4541 $COURSE = $SITE;
4543 core_courseformat\base::reset_course_cache($SITE->id);
4545 return '';
4552 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4553 * block to hidden.
4555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4557 class admin_setting_bloglevel extends admin_setting_configselect {
4559 * Updates the database and save the setting
4561 * @param string data
4562 * @return string empty or error message
4564 public function write_setting($data) {
4565 global $DB, $CFG;
4566 if ($data == 0) {
4567 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4568 foreach ($blogblocks as $block) {
4569 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4571 } else {
4572 // reenable all blocks only when switching from disabled blogs
4573 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4574 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4575 foreach ($blogblocks as $block) {
4576 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4580 return parent::write_setting($data);
4586 * Special select - lists on the frontpage - hacky
4588 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4590 class admin_setting_courselist_frontpage extends admin_setting {
4591 /** @var array Array of choices value=>label */
4592 public $choices;
4595 * Construct override, requires one param
4597 * @param bool $loggedin Is the user logged in
4599 public function __construct($loggedin) {
4600 global $CFG;
4601 require_once($CFG->dirroot.'/course/lib.php');
4602 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4603 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4604 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4605 $defaults = array(FRONTPAGEALLCOURSELIST);
4606 parent::__construct($name, $visiblename, $description, $defaults);
4610 * Loads the choices available
4612 * @return bool always returns true
4614 public function load_choices() {
4615 if (is_array($this->choices)) {
4616 return true;
4618 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4619 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4620 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4621 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4622 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4623 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4624 'none' => get_string('none'));
4625 if ($this->name === 'frontpage') {
4626 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4628 return true;
4632 * Returns the selected settings
4634 * @param mixed array or setting or null
4636 public function get_setting() {
4637 $result = $this->config_read($this->name);
4638 if (is_null($result)) {
4639 return NULL;
4641 if ($result === '') {
4642 return array();
4644 return explode(',', $result);
4648 * Save the selected options
4650 * @param array $data
4651 * @return mixed empty string (data is not an array) or bool true=success false=failure
4653 public function write_setting($data) {
4654 if (!is_array($data)) {
4655 return '';
4657 $this->load_choices();
4658 $save = array();
4659 foreach($data as $datum) {
4660 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4661 continue;
4663 $save[$datum] = $datum; // no duplicates
4665 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4669 * Return XHTML select field and wrapping div
4671 * @todo Add vartype handling to make sure $data is an array
4672 * @param array $data Array of elements to select by default
4673 * @return string XHTML select field and wrapping div
4675 public function output_html($data, $query='') {
4676 global $OUTPUT;
4678 $this->load_choices();
4679 $currentsetting = array();
4680 foreach ($data as $key) {
4681 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4682 $currentsetting[] = $key; // already selected first
4686 $context = (object) [
4687 'id' => $this->get_id(),
4688 'name' => $this->get_full_name(),
4691 $options = $this->choices;
4692 $selects = [];
4693 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4694 if (!array_key_exists($i, $currentsetting)) {
4695 $currentsetting[$i] = 'none';
4697 $selects[] = [
4698 'key' => $i,
4699 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4700 return [
4701 'name' => $options[$option],
4702 'value' => $option,
4703 'selected' => $currentsetting[$i] == $option
4705 }, array_keys($options))
4708 $context->selects = $selects;
4710 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4712 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4718 * Special checkbox for frontpage - stores data in course table
4720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4722 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4724 * Returns the current sites name
4726 * @return string
4728 public function get_setting() {
4729 $site = course_get_format(get_site())->get_course();
4730 return $site->{$this->name};
4734 * Save the selected setting
4736 * @param string $data The selected site
4737 * @return string empty string or error message
4739 public function write_setting($data) {
4740 global $DB, $SITE, $COURSE;
4741 $record = new stdClass();
4742 $record->id = $SITE->id;
4743 $record->{$this->name} = ($data == '1' ? 1 : 0);
4744 $record->timemodified = time();
4746 course_get_format($SITE)->update_course_format_options($record);
4747 $DB->update_record('course', $record);
4749 // Reset caches.
4750 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4751 if ($SITE->id == $COURSE->id) {
4752 $COURSE = $SITE;
4754 core_courseformat\base::reset_course_cache($SITE->id);
4756 return '';
4761 * Special text for frontpage - stores data in course table.
4762 * Empty string means not set here. Manual setting is required.
4764 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4766 class admin_setting_sitesettext extends admin_setting_configtext {
4769 * Constructor.
4771 public function __construct() {
4772 call_user_func_array(['parent', '__construct'], func_get_args());
4773 $this->set_force_ltr(false);
4777 * Return the current setting
4779 * @return mixed string or null
4781 public function get_setting() {
4782 $site = course_get_format(get_site())->get_course();
4783 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4787 * Validate the selected data
4789 * @param string $data The selected value to validate
4790 * @return mixed true or message string
4792 public function validate($data) {
4793 global $DB, $SITE;
4794 $cleaned = clean_param($data, PARAM_TEXT);
4795 if ($cleaned === '') {
4796 return get_string('required');
4798 if ($this->name ==='shortname' &&
4799 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4800 return get_string('shortnametaken', 'error', $data);
4802 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4803 return true;
4804 } else {
4805 return get_string('validateerror', 'admin');
4810 * Save the selected setting
4812 * @param string $data The selected value
4813 * @return string empty or error message
4815 public function write_setting($data) {
4816 global $DB, $SITE, $COURSE;
4817 $data = trim($data);
4818 $validated = $this->validate($data);
4819 if ($validated !== true) {
4820 return $validated;
4823 $record = new stdClass();
4824 $record->id = $SITE->id;
4825 $record->{$this->name} = $data;
4826 $record->timemodified = time();
4828 course_get_format($SITE)->update_course_format_options($record);
4829 $DB->update_record('course', $record);
4831 // Reset caches.
4832 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4833 if ($SITE->id == $COURSE->id) {
4834 $COURSE = $SITE;
4836 core_courseformat\base::reset_course_cache($SITE->id);
4838 return '';
4844 * This type of field should be used for mandatory config settings.
4846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4848 class admin_setting_requiredtext extends admin_setting_configtext {
4851 * Validate data before storage.
4853 * @param string $data The string to be validated.
4854 * @return bool|string true for success or error string if invalid.
4856 public function validate($data) {
4857 $cleaned = clean_param($data, PARAM_TEXT);
4858 if ($cleaned === '') {
4859 return get_string('required');
4862 return parent::validate($data);
4867 * Special text editor for site description.
4869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4871 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4874 * Calls parent::__construct with specific arguments
4876 public function __construct() {
4877 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4878 PARAM_RAW, 60, 15);
4882 * Return the current setting
4883 * @return string The current setting
4885 public function get_setting() {
4886 $site = course_get_format(get_site())->get_course();
4887 return $site->{$this->name};
4891 * Save the new setting
4893 * @param string $data The new value to save
4894 * @return string empty or error message
4896 public function write_setting($data) {
4897 global $DB, $SITE, $COURSE;
4898 $record = new stdClass();
4899 $record->id = $SITE->id;
4900 $record->{$this->name} = $data;
4901 $record->timemodified = time();
4903 course_get_format($SITE)->update_course_format_options($record);
4904 $DB->update_record('course', $record);
4906 // Reset caches.
4907 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4908 if ($SITE->id == $COURSE->id) {
4909 $COURSE = $SITE;
4911 core_courseformat\base::reset_course_cache($SITE->id);
4913 return '';
4919 * Administration interface for emoticon_manager settings.
4921 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4923 class admin_setting_emoticons extends admin_setting {
4926 * Calls parent::__construct with specific args
4928 public function __construct() {
4929 global $CFG;
4931 $manager = get_emoticon_manager();
4932 $defaults = $this->prepare_form_data($manager->default_emoticons());
4933 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4937 * Return the current setting(s)
4939 * @return array Current settings array
4941 public function get_setting() {
4942 global $CFG;
4944 $manager = get_emoticon_manager();
4946 $config = $this->config_read($this->name);
4947 if (is_null($config)) {
4948 return null;
4951 $config = $manager->decode_stored_config($config);
4952 if (is_null($config)) {
4953 return null;
4956 return $this->prepare_form_data($config);
4960 * Save selected settings
4962 * @param array $data Array of settings to save
4963 * @return bool
4965 public function write_setting($data) {
4967 $manager = get_emoticon_manager();
4968 $emoticons = $this->process_form_data($data);
4970 if ($emoticons === false) {
4971 return false;
4974 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4975 return ''; // success
4976 } else {
4977 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4982 * Return XHTML field(s) for options
4984 * @param array $data Array of options to set in HTML
4985 * @return string XHTML string for the fields and wrapping div(s)
4987 public function output_html($data, $query='') {
4988 global $OUTPUT;
4990 $context = (object) [
4991 'name' => $this->get_full_name(),
4992 'emoticons' => [],
4993 'forceltr' => true,
4996 $i = 0;
4997 foreach ($data as $field => $value) {
4999 // When $i == 0: text.
5000 // When $i == 1: imagename.
5001 // When $i == 2: imagecomponent.
5002 // When $i == 3: altidentifier.
5003 // When $i == 4: altcomponent.
5004 $fields[$i] = (object) [
5005 'field' => $field,
5006 'value' => $value,
5007 'index' => $i
5009 $i++;
5011 if ($i > 4) {
5012 $icon = null;
5013 if (!empty($fields[1]->value)) {
5014 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
5015 $alt = get_string($fields[3]->value, $fields[4]->value);
5016 } else {
5017 $alt = $fields[0]->value;
5019 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
5021 $context->emoticons[] = [
5022 'fields' => $fields,
5023 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
5025 $fields = [];
5026 $i = 0;
5030 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
5031 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
5032 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5036 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
5038 * @see self::process_form_data()
5039 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
5040 * @return array of form fields and their values
5042 protected function prepare_form_data(array $emoticons) {
5044 $form = array();
5045 $i = 0;
5046 foreach ($emoticons as $emoticon) {
5047 $form['text'.$i] = $emoticon->text;
5048 $form['imagename'.$i] = $emoticon->imagename;
5049 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
5050 $form['altidentifier'.$i] = $emoticon->altidentifier;
5051 $form['altcomponent'.$i] = $emoticon->altcomponent;
5052 $i++;
5054 // add one more blank field set for new object
5055 $form['text'.$i] = '';
5056 $form['imagename'.$i] = '';
5057 $form['imagecomponent'.$i] = '';
5058 $form['altidentifier'.$i] = '';
5059 $form['altcomponent'.$i] = '';
5061 return $form;
5065 * Converts the data from admin settings form into an array of emoticon objects
5067 * @see self::prepare_form_data()
5068 * @param array $data array of admin form fields and values
5069 * @return false|array of emoticon objects
5071 protected function process_form_data(array $form) {
5073 $count = count($form); // number of form field values
5075 if ($count % 5) {
5076 // we must get five fields per emoticon object
5077 return false;
5080 $emoticons = array();
5081 for ($i = 0; $i < $count / 5; $i++) {
5082 $emoticon = new stdClass();
5083 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
5084 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
5085 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
5086 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
5087 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
5089 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
5090 // prevent from breaking http://url.addresses by accident
5091 $emoticon->text = '';
5094 if (strlen($emoticon->text) < 2) {
5095 // do not allow single character emoticons
5096 $emoticon->text = '';
5099 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
5100 // emoticon text must contain some non-alphanumeric character to prevent
5101 // breaking HTML tags
5102 $emoticon->text = '';
5105 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
5106 $emoticons[] = $emoticon;
5109 return $emoticons;
5116 * Special setting for limiting of the list of available languages.
5118 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5120 class admin_setting_langlist extends admin_setting_configtext {
5122 * Calls parent::__construct with specific arguments
5124 public function __construct() {
5125 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
5129 * Validate that each language identifier exists on the site
5131 * @param string $data
5132 * @return bool|string True if validation successful, otherwise error string
5134 public function validate($data) {
5135 $parentcheck = parent::validate($data);
5136 if ($parentcheck !== true) {
5137 return $parentcheck;
5140 if ($data === '') {
5141 return true;
5144 // Normalize language identifiers.
5145 $langcodes = array_map('trim', explode(',', $data));
5146 foreach ($langcodes as $langcode) {
5147 // If the langcode contains optional alias, split it out.
5148 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5150 if (!get_string_manager()->translation_exists($langcode)) {
5151 return get_string('invalidlanguagecode', 'error', $langcode);
5155 return true;
5159 * Save the new setting
5161 * @param string $data The new setting
5162 * @return bool
5164 public function write_setting($data) {
5165 $return = parent::write_setting($data);
5166 get_string_manager()->reset_caches();
5167 return $return;
5173 * Allows to specify comma separated list of known country codes.
5175 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5176 * known codes.
5178 * @package core
5179 * @category admin
5180 * @copyright 2020 David Mudrák <david@moodle.com>
5181 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5183 class admin_setting_countrycodes extends admin_setting_configtext {
5186 * Construct the instance of the setting.
5188 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5189 * @param lang_string|string $visiblename Language string with the field label text.
5190 * @param lang_string|string $description Language string with the field description text.
5191 * @param string $defaultsetting Default value of the setting.
5192 * @param int $size Input text field size.
5194 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5195 parent::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5199 * Validate the setting value before storing it.
5201 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5202 * a comma separated list of such words.
5204 * @param string $data Value inserted into the setting field.
5205 * @return bool|string True if the value is OK, error string otherwise.
5207 public function validate($data) {
5209 $parentcheck = parent::validate($data);
5211 if ($parentcheck !== true) {
5212 return $parentcheck;
5215 if ($data === '') {
5216 return true;
5219 $allcountries = get_string_manager()->get_list_of_countries(true);
5221 foreach (explode(',', $data) as $code) {
5222 if (!isset($allcountries[$code])) {
5223 return get_string('invalidcountrycode', 'core_error', $code);
5227 return true;
5233 * Selection of one of the recognised countries using the list
5234 * returned by {@link get_list_of_countries()}.
5236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5238 class admin_settings_country_select extends admin_setting_configselect {
5239 protected $includeall;
5240 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5241 $this->includeall = $includeall;
5242 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
5246 * Lazy-load the available choices for the select box
5248 public function load_choices() {
5249 global $CFG;
5250 if (is_array($this->choices)) {
5251 return true;
5253 $this->choices = array_merge(
5254 array('0' => get_string('choosedots')),
5255 get_string_manager()->get_list_of_countries($this->includeall));
5256 return true;
5262 * admin_setting_configselect for the default number of sections in a course,
5263 * simply so we can lazy-load the choices.
5265 * @copyright 2011 The Open University
5266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5268 class admin_settings_num_course_sections extends admin_setting_configselect {
5269 public function __construct($name, $visiblename, $description, $defaultsetting) {
5270 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
5273 /** Lazy-load the available choices for the select box */
5274 public function load_choices() {
5275 $max = get_config('moodlecourse', 'maxsections');
5276 if (!isset($max) || !is_numeric($max)) {
5277 $max = 52;
5279 for ($i = 0; $i <= $max; $i++) {
5280 $this->choices[$i] = "$i";
5282 return true;
5288 * Course category selection
5290 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5292 class admin_settings_coursecat_select extends admin_setting_configselect_autocomplete {
5294 * Calls parent::__construct with specific arguments
5296 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5297 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5301 * Load the available choices for the select box
5303 * @return bool
5305 public function load_choices() {
5306 if (is_array($this->choices)) {
5307 return true;
5309 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
5310 return true;
5316 * Special control for selecting days to backup
5318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5320 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
5322 * Calls parent::__construct with specific arguments
5324 public function __construct() {
5325 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5326 $this->plugin = 'backup';
5330 * Load the available choices for the select box
5332 * @return bool Always returns true
5334 public function load_choices() {
5335 if (is_array($this->choices)) {
5336 return true;
5338 $this->choices = array();
5339 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5340 foreach ($days as $day) {
5341 $this->choices[$day] = get_string($day, 'calendar');
5343 return true;
5348 * Special setting for backup auto destination.
5350 * @package core
5351 * @subpackage admin
5352 * @copyright 2014 Frédéric Massart - FMCorz.net
5353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5355 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5358 * Calls parent::__construct with specific arguments.
5360 public function __construct() {
5361 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5365 * Check if the directory must be set, depending on backup/backup_auto_storage.
5367 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5368 * there will be conflicts if this validation happens before the other one.
5370 * @param string $data Form data.
5371 * @return string Empty when no errors.
5373 public function write_setting($data) {
5374 $storage = (int) get_config('backup', 'backup_auto_storage');
5375 if ($storage !== 0) {
5376 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5377 // The directory must exist and be writable.
5378 return get_string('backuperrorinvaliddestination');
5381 return parent::write_setting($data);
5387 * Special debug setting
5389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5391 class admin_setting_special_debug extends admin_setting_configselect {
5393 * Calls parent::__construct with specific arguments
5395 public function __construct() {
5396 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5400 * Load the available choices for the select box
5402 * @return bool
5404 public function load_choices() {
5405 if (is_array($this->choices)) {
5406 return true;
5408 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5409 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5410 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5411 DEBUG_ALL => get_string('debugall', 'admin'),
5412 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5413 return true;
5419 * Special admin control
5421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5423 class admin_setting_special_calendar_weekend extends admin_setting {
5425 * Calls parent::__construct with specific arguments
5427 public function __construct() {
5428 $name = 'calendar_weekend';
5429 $visiblename = get_string('calendar_weekend', 'admin');
5430 $description = get_string('helpweekenddays', 'admin');
5431 $default = array ('0', '6'); // Saturdays and Sundays
5432 parent::__construct($name, $visiblename, $description, $default);
5436 * Gets the current settings as an array
5438 * @return mixed Null if none, else array of settings
5440 public function get_setting() {
5441 $result = $this->config_read($this->name);
5442 if (is_null($result)) {
5443 return NULL;
5445 if ($result === '') {
5446 return array();
5448 $settings = array();
5449 for ($i=0; $i<7; $i++) {
5450 if ($result & (1 << $i)) {
5451 $settings[] = $i;
5454 return $settings;
5458 * Save the new settings
5460 * @param array $data Array of new settings
5461 * @return bool
5463 public function write_setting($data) {
5464 if (!is_array($data)) {
5465 return '';
5467 unset($data['xxxxx']);
5468 $result = 0;
5469 foreach($data as $index) {
5470 $result |= 1 << $index;
5472 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5476 * Return XHTML to display the control
5478 * @param array $data array of selected days
5479 * @param string $query
5480 * @return string XHTML for display (field + wrapping div(s)
5482 public function output_html($data, $query='') {
5483 global $OUTPUT;
5485 // The order matters very much because of the implied numeric keys.
5486 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5487 $context = (object) [
5488 'name' => $this->get_full_name(),
5489 'id' => $this->get_id(),
5490 'days' => array_map(function($index) use ($days, $data) {
5491 return [
5492 'index' => $index,
5493 'label' => get_string($days[$index], 'calendar'),
5494 'checked' => in_array($index, $data)
5496 }, array_keys($days))
5499 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5501 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5508 * Admin setting that allows a user to pick a behaviour.
5510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5512 class admin_setting_question_behaviour extends admin_setting_configselect {
5514 * @param string $name name of config variable
5515 * @param string $visiblename display name
5516 * @param string $description description
5517 * @param string $default default.
5519 public function __construct($name, $visiblename, $description, $default) {
5520 parent::__construct($name, $visiblename, $description, $default, null);
5524 * Load list of behaviours as choices
5525 * @return bool true => success, false => error.
5527 public function load_choices() {
5528 global $CFG;
5529 require_once($CFG->dirroot . '/question/engine/lib.php');
5530 $this->choices = question_engine::get_behaviour_options('');
5531 return true;
5537 * Admin setting that allows a user to pick appropriate roles for something.
5539 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5541 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5542 /** @var array Array of capabilities which identify roles */
5543 private $types;
5546 * @param string $name Name of config variable
5547 * @param string $visiblename Display name
5548 * @param string $description Description
5549 * @param array $types Array of archetypes which identify
5550 * roles that will be enabled by default.
5552 public function __construct($name, $visiblename, $description, $types) {
5553 parent::__construct($name, $visiblename, $description, NULL, NULL);
5554 $this->types = $types;
5558 * Load roles as choices
5560 * @return bool true=>success, false=>error
5562 public function load_choices() {
5563 global $CFG, $DB;
5564 if (during_initial_install()) {
5565 return false;
5567 if (is_array($this->choices)) {
5568 return true;
5570 if ($roles = get_all_roles()) {
5571 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5572 return true;
5573 } else {
5574 return false;
5579 * Return the default setting for this control
5581 * @return array Array of default settings
5583 public function get_defaultsetting() {
5584 global $CFG;
5586 if (during_initial_install()) {
5587 return null;
5589 $result = array();
5590 foreach($this->types as $archetype) {
5591 if ($caproles = get_archetype_roles($archetype)) {
5592 foreach ($caproles as $caprole) {
5593 $result[$caprole->id] = 1;
5597 return $result;
5603 * Admin setting that is a list of installed filter plugins.
5605 * @copyright 2015 The Open University
5606 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5608 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5611 * Constructor
5613 * @param string $name unique ascii name, either 'mysetting' for settings
5614 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5615 * @param string $visiblename localised name
5616 * @param string $description localised long description
5617 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5619 public function __construct($name, $visiblename, $description, $default) {
5620 if (empty($default)) {
5621 $default = array();
5623 $this->load_choices();
5624 foreach ($default as $plugin) {
5625 if (!isset($this->choices[$plugin])) {
5626 unset($default[$plugin]);
5629 parent::__construct($name, $visiblename, $description, $default, null);
5632 public function load_choices() {
5633 if (is_array($this->choices)) {
5634 return true;
5636 $this->choices = array();
5638 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5639 $this->choices[$plugin] = filter_get_name($plugin);
5641 return true;
5647 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5651 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5653 * Constructor
5654 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5655 * @param string $visiblename localised
5656 * @param string $description long localised info
5657 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5658 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5659 * @param int $size default field size
5661 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5662 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5663 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5669 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5671 * @copyright 2009 Petr Skoda (http://skodak.org)
5672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5674 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5677 * Constructor
5678 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5679 * @param string $visiblename localised
5680 * @param string $description long localised info
5681 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5682 * @param string $yes value used when checked
5683 * @param string $no value used when not checked
5685 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5686 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5687 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5694 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5696 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5698 * @copyright 2010 Sam Hemelryk
5699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5701 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5703 * Constructor
5704 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5705 * @param string $visiblename localised
5706 * @param string $description long localised info
5707 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5708 * @param string $yes value used when checked
5709 * @param string $no value used when not checked
5711 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5712 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5713 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5719 * Autocomplete as you type form element.
5721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5723 class admin_setting_configselect_autocomplete extends admin_setting_configselect {
5724 /** @var boolean $tags Should we allow typing new entries to the field? */
5725 protected $tags = false;
5726 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5727 protected $ajax = '';
5728 /** @var string $placeholder Placeholder text for an empty list. */
5729 protected $placeholder = '';
5730 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5731 protected $casesensitive = false;
5732 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5733 protected $showsuggestions = true;
5734 /** @var string $noselectionstring String that is shown when there are no selections. */
5735 protected $noselectionstring = '';
5738 * Returns XHTML select field and wrapping div(s)
5740 * @see output_select_html()
5742 * @param string $data the option to show as selected
5743 * @param string $query
5744 * @return string XHTML field and wrapping div
5746 public function output_html($data, $query='') {
5747 global $PAGE;
5749 $html = parent::output_html($data, $query);
5751 if ($html === '') {
5752 return $html;
5755 $this->placeholder = get_string('search');
5757 $params = array('#' . $this->get_id(), $this->tags, $this->ajax,
5758 $this->placeholder, $this->casesensitive, $this->showsuggestions, $this->noselectionstring);
5760 // Load autocomplete wrapper for select2 library.
5761 $PAGE->requires->js_call_amd('core/form-autocomplete', 'enhance', $params);
5763 return $html;
5768 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5772 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5774 * Calls parent::__construct with specific arguments
5776 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5777 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5778 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5784 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5786 * @copyright 2017 Marina Glancy
5787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5789 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5791 * Constructor
5792 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5793 * or 'myplugin/mysetting' for ones in config_plugins.
5794 * @param string $visiblename localised
5795 * @param string $description long localised info
5796 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5797 * @param array $choices array of $value=>$label for each selection
5799 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5800 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5801 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5807 * Graded roles in gradebook
5809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5811 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5813 * Calls parent::__construct with specific arguments
5815 public function __construct() {
5816 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5817 get_string('configgradebookroles', 'admin'),
5818 array('student'));
5825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5827 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5829 * Saves the new settings passed in $data
5831 * @param string $data
5832 * @return mixed string or Array
5834 public function write_setting($data) {
5835 global $CFG, $DB;
5837 $oldvalue = $this->config_read($this->name);
5838 $return = parent::write_setting($data);
5839 $newvalue = $this->config_read($this->name);
5841 if ($oldvalue !== $newvalue) {
5842 // force full regrading
5843 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5846 return $return;
5852 * Which roles to show on course description page
5854 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5856 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5858 * Calls parent::__construct with specific arguments
5860 public function __construct() {
5861 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5862 get_string('coursecontact_desc', 'admin'),
5863 array('editingteacher'));
5864 $this->set_updatedcallback(function (){
5865 cache::make('core', 'coursecontacts')->purge();
5873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5875 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5877 * Calls parent::__construct with specific arguments
5879 public function __construct() {
5880 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5881 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5885 * Old syntax of class constructor. Deprecated in PHP7.
5887 * @deprecated since Moodle 3.1
5889 public function admin_setting_special_gradelimiting() {
5890 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5891 self::__construct();
5895 * Force site regrading
5897 function regrade_all() {
5898 global $CFG;
5899 require_once("$CFG->libdir/gradelib.php");
5900 grade_force_site_regrading();
5904 * Saves the new settings
5906 * @param mixed $data
5907 * @return string empty string or error message
5909 function write_setting($data) {
5910 $previous = $this->get_setting();
5912 if ($previous === null) {
5913 if ($data) {
5914 $this->regrade_all();
5916 } else {
5917 if ($data != $previous) {
5918 $this->regrade_all();
5921 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5927 * Special setting for $CFG->grade_minmaxtouse.
5929 * @package core
5930 * @copyright 2015 Frédéric Massart - FMCorz.net
5931 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5933 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5936 * Constructor.
5938 public function __construct() {
5939 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5940 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5941 array(
5942 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5943 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5949 * Saves the new setting.
5951 * @param mixed $data
5952 * @return string empty string or error message
5954 function write_setting($data) {
5955 global $CFG;
5957 $previous = $this->get_setting();
5958 $result = parent::write_setting($data);
5960 // If saved and the value has changed.
5961 if (empty($result) && $previous != $data) {
5962 require_once($CFG->libdir . '/gradelib.php');
5963 grade_force_site_regrading();
5966 return $result;
5973 * Primary grade export plugin - has state tracking.
5975 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5977 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5979 * Calls parent::__construct with specific arguments
5981 public function __construct() {
5982 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5983 get_string('configgradeexport', 'admin'), array(), NULL);
5987 * Load the available choices for the multicheckbox
5989 * @return bool always returns true
5991 public function load_choices() {
5992 if (is_array($this->choices)) {
5993 return true;
5995 $this->choices = array();
5997 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5998 foreach($plugins as $plugin => $unused) {
5999 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
6002 return true;
6008 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
6010 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6012 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
6014 * Config gradepointmax constructor
6016 * @param string $name Overidden by "gradepointmax"
6017 * @param string $visiblename Overridden by "gradepointmax" language string.
6018 * @param string $description Overridden by "gradepointmax_help" language string.
6019 * @param string $defaultsetting Not used, overridden by 100.
6020 * @param mixed $paramtype Overridden by PARAM_INT.
6021 * @param int $size Overridden by 5.
6023 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6024 $name = 'gradepointdefault';
6025 $visiblename = get_string('gradepointdefault', 'grades');
6026 $description = get_string('gradepointdefault_help', 'grades');
6027 $defaultsetting = 100;
6028 $paramtype = PARAM_INT;
6029 $size = 5;
6030 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6034 * Validate data before storage
6035 * @param string $data The submitted data
6036 * @return bool|string true if ok, string if error found
6038 public function validate($data) {
6039 global $CFG;
6040 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
6041 return true;
6042 } else {
6043 return get_string('gradepointdefault_validateerror', 'grades');
6050 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
6052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6054 class admin_setting_special_gradepointmax extends admin_setting_configtext {
6057 * Config gradepointmax constructor
6059 * @param string $name Overidden by "gradepointmax"
6060 * @param string $visiblename Overridden by "gradepointmax" language string.
6061 * @param string $description Overridden by "gradepointmax_help" language string.
6062 * @param string $defaultsetting Not used, overridden by 100.
6063 * @param mixed $paramtype Overridden by PARAM_INT.
6064 * @param int $size Overridden by 5.
6066 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
6067 $name = 'gradepointmax';
6068 $visiblename = get_string('gradepointmax', 'grades');
6069 $description = get_string('gradepointmax_help', 'grades');
6070 $defaultsetting = 100;
6071 $paramtype = PARAM_INT;
6072 $size = 5;
6073 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6077 * Save the selected setting
6079 * @param string $data The selected site
6080 * @return string empty string or error message
6082 public function write_setting($data) {
6083 if ($data === '') {
6084 $data = (int)$this->defaultsetting;
6085 } else {
6086 $data = $data;
6088 return parent::write_setting($data);
6092 * Validate data before storage
6093 * @param string $data The submitted data
6094 * @return bool|string true if ok, string if error found
6096 public function validate($data) {
6097 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6098 return true;
6099 } else {
6100 return get_string('gradepointmax_validateerror', 'grades');
6105 * Return an XHTML string for the setting
6106 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6107 * @param string $query search query to be highlighted
6108 * @return string XHTML to display control
6110 public function output_html($data, $query = '') {
6111 global $OUTPUT;
6113 $default = $this->get_defaultsetting();
6114 $context = (object) [
6115 'size' => $this->size,
6116 'id' => $this->get_id(),
6117 'name' => $this->get_full_name(),
6118 'value' => $data,
6119 'attributes' => [
6120 'maxlength' => 5
6122 'forceltr' => $this->get_force_ltr()
6124 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6126 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
6132 * Grade category settings
6134 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6136 class admin_setting_gradecat_combo extends admin_setting {
6137 /** @var array Array of choices */
6138 public $choices;
6141 * Sets choices and calls parent::__construct with passed arguments
6142 * @param string $name
6143 * @param string $visiblename
6144 * @param string $description
6145 * @param mixed $defaultsetting string or array depending on implementation
6146 * @param array $choices An array of choices for the control
6148 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6149 $this->choices = $choices;
6150 parent::__construct($name, $visiblename, $description, $defaultsetting);
6154 * Return the current setting(s) array
6156 * @return array Array of value=>xx, forced=>xx, adv=>xx
6158 public function get_setting() {
6159 global $CFG;
6161 $value = $this->config_read($this->name);
6162 $flag = $this->config_read($this->name.'_flag');
6164 if (is_null($value) or is_null($flag)) {
6165 return NULL;
6168 $flag = (int)$flag;
6169 $forced = (boolean)(1 & $flag); // first bit
6170 $adv = (boolean)(2 & $flag); // second bit
6172 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6176 * Save the new settings passed in $data
6178 * @todo Add vartype handling to ensure $data is array
6179 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6180 * @return string empty or error message
6182 public function write_setting($data) {
6183 global $CFG;
6185 $value = $data['value'];
6186 $forced = empty($data['forced']) ? 0 : 1;
6187 $adv = empty($data['adv']) ? 0 : 2;
6188 $flag = ($forced | $adv); //bitwise or
6190 if (!in_array($value, array_keys($this->choices))) {
6191 return 'Error setting ';
6194 $oldvalue = $this->config_read($this->name);
6195 $oldflag = (int)$this->config_read($this->name.'_flag');
6196 $oldforced = (1 & $oldflag); // first bit
6198 $result1 = $this->config_write($this->name, $value);
6199 $result2 = $this->config_write($this->name.'_flag', $flag);
6201 // force regrade if needed
6202 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6203 require_once($CFG->libdir.'/gradelib.php');
6204 grade_category::updated_forced_settings();
6207 if ($result1 and $result2) {
6208 return '';
6209 } else {
6210 return get_string('errorsetting', 'admin');
6215 * Return XHTML to display the field and wrapping div
6217 * @todo Add vartype handling to ensure $data is array
6218 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6219 * @param string $query
6220 * @return string XHTML to display control
6222 public function output_html($data, $query='') {
6223 global $OUTPUT;
6225 $value = $data['value'];
6227 $default = $this->get_defaultsetting();
6228 if (!is_null($default)) {
6229 $defaultinfo = array();
6230 if (isset($this->choices[$default['value']])) {
6231 $defaultinfo[] = $this->choices[$default['value']];
6233 if (!empty($default['forced'])) {
6234 $defaultinfo[] = get_string('force');
6236 if (!empty($default['adv'])) {
6237 $defaultinfo[] = get_string('advanced');
6239 $defaultinfo = implode(', ', $defaultinfo);
6241 } else {
6242 $defaultinfo = NULL;
6245 $options = $this->choices;
6246 $context = (object) [
6247 'id' => $this->get_id(),
6248 'name' => $this->get_full_name(),
6249 'forced' => !empty($data['forced']),
6250 'advanced' => !empty($data['adv']),
6251 'options' => array_map(function($option) use ($options, $value) {
6252 return [
6253 'value' => $option,
6254 'name' => $options[$option],
6255 'selected' => $option == $value
6257 }, array_keys($options)),
6260 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6262 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
6268 * Selection of grade report in user profiles
6270 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6272 class admin_setting_grade_profilereport extends admin_setting_configselect {
6274 * Calls parent::__construct with specific arguments
6276 public function __construct() {
6277 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6281 * Loads an array of choices for the configselect control
6283 * @return bool always return true
6285 public function load_choices() {
6286 if (is_array($this->choices)) {
6287 return true;
6289 $this->choices = array();
6291 global $CFG;
6292 require_once($CFG->libdir.'/gradelib.php');
6294 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6295 if (file_exists($plugindir.'/lib.php')) {
6296 require_once($plugindir.'/lib.php');
6297 $functionname = 'grade_report_'.$plugin.'_profilereport';
6298 if (function_exists($functionname)) {
6299 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6303 return true;
6308 * Provides a selection of grade reports to be used for "grades".
6310 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6313 class admin_setting_my_grades_report extends admin_setting_configselect {
6316 * Calls parent::__construct with specific arguments.
6318 public function __construct() {
6319 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6320 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6324 * Loads an array of choices for the configselect control.
6326 * @return bool always returns true.
6328 public function load_choices() {
6329 global $CFG; // Remove this line and behold the horror of behat test failures!
6330 $this->choices = array();
6331 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
6332 if (file_exists($plugindir . '/lib.php')) {
6333 require_once($plugindir . '/lib.php');
6334 // Check to see if the class exists. Check the correct plugin convention first.
6335 if (class_exists('gradereport_' . $plugin)) {
6336 $classname = 'gradereport_' . $plugin;
6337 } else if (class_exists('grade_report_' . $plugin)) {
6338 // We are using the old plugin naming convention.
6339 $classname = 'grade_report_' . $plugin;
6340 } else {
6341 continue;
6343 if ($classname::supports_mygrades()) {
6344 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6348 // Add an option to specify an external url.
6349 $this->choices['external'] = get_string('externalurl', 'grades');
6350 return true;
6355 * Special class for register auth selection
6357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6359 class admin_setting_special_registerauth extends admin_setting_configselect {
6361 * Calls parent::__construct with specific arguments
6363 public function __construct() {
6364 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6368 * Returns the default option
6370 * @return string empty or default option
6372 public function get_defaultsetting() {
6373 $this->load_choices();
6374 $defaultsetting = parent::get_defaultsetting();
6375 if (array_key_exists($defaultsetting, $this->choices)) {
6376 return $defaultsetting;
6377 } else {
6378 return '';
6383 * Loads the possible choices for the array
6385 * @return bool always returns true
6387 public function load_choices() {
6388 global $CFG;
6390 if (is_array($this->choices)) {
6391 return true;
6393 $this->choices = array();
6394 $this->choices[''] = get_string('disable');
6396 $authsenabled = get_enabled_auth_plugins();
6398 foreach ($authsenabled as $auth) {
6399 $authplugin = get_auth_plugin($auth);
6400 if (!$authplugin->can_signup()) {
6401 continue;
6403 // Get the auth title (from core or own auth lang files)
6404 $authtitle = $authplugin->get_title();
6405 $this->choices[$auth] = $authtitle;
6407 return true;
6413 * General plugins manager
6415 class admin_page_pluginsoverview extends admin_externalpage {
6418 * Sets basic information about the external page
6420 public function __construct() {
6421 global $CFG;
6422 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6423 "$CFG->wwwroot/$CFG->admin/plugins.php");
6428 * Module manage page
6430 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6432 class admin_page_managemods extends admin_externalpage {
6434 * Calls parent::__construct with specific arguments
6436 public function __construct() {
6437 global $CFG;
6438 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6442 * Try to find the specified module
6444 * @param string $query The module to search for
6445 * @return array
6447 public function search($query) {
6448 global $CFG, $DB;
6449 if ($result = parent::search($query)) {
6450 return $result;
6453 $found = false;
6454 if ($modules = $DB->get_records('modules')) {
6455 foreach ($modules as $module) {
6456 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6457 continue;
6459 if (strpos($module->name, $query) !== false) {
6460 $found = true;
6461 break;
6463 $strmodulename = get_string('modulename', $module->name);
6464 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6465 $found = true;
6466 break;
6470 if ($found) {
6471 $result = new stdClass();
6472 $result->page = $this;
6473 $result->settings = array();
6474 return array($this->name => $result);
6475 } else {
6476 return array();
6483 * Special class for enrol plugins management.
6485 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6488 class admin_setting_manageenrols extends admin_setting {
6490 * Calls parent::__construct with specific arguments
6492 public function __construct() {
6493 $this->nosave = true;
6494 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6498 * Always returns true, does nothing
6500 * @return true
6502 public function get_setting() {
6503 return true;
6507 * Always returns true, does nothing
6509 * @return true
6511 public function get_defaultsetting() {
6512 return true;
6516 * Always returns '', does not write anything
6518 * @return string Always returns ''
6520 public function write_setting($data) {
6521 // do not write any setting
6522 return '';
6526 * Checks if $query is one of the available enrol plugins
6528 * @param string $query The string to search for
6529 * @return bool Returns true if found, false if not
6531 public function is_related($query) {
6532 if (parent::is_related($query)) {
6533 return true;
6536 $query = core_text::strtolower($query);
6537 $enrols = enrol_get_plugins(false);
6538 foreach ($enrols as $name=>$enrol) {
6539 $localised = get_string('pluginname', 'enrol_'.$name);
6540 if (strpos(core_text::strtolower($name), $query) !== false) {
6541 return true;
6543 if (strpos(core_text::strtolower($localised), $query) !== false) {
6544 return true;
6547 return false;
6551 * Builds the XHTML to display the control
6553 * @param string $data Unused
6554 * @param string $query
6555 * @return string
6557 public function output_html($data, $query='') {
6558 global $CFG, $OUTPUT, $DB, $PAGE;
6560 // Display strings.
6561 $strup = get_string('up');
6562 $strdown = get_string('down');
6563 $strsettings = get_string('settings');
6564 $strenable = get_string('enable');
6565 $strdisable = get_string('disable');
6566 $struninstall = get_string('uninstallplugin', 'core_admin');
6567 $strusage = get_string('enrolusage', 'enrol');
6568 $strversion = get_string('version');
6569 $strtest = get_string('testsettings', 'core_enrol');
6571 $pluginmanager = core_plugin_manager::instance();
6573 $enrols_available = enrol_get_plugins(false);
6574 $active_enrols = enrol_get_plugins(true);
6576 $allenrols = array();
6577 foreach ($active_enrols as $key=>$enrol) {
6578 $allenrols[$key] = true;
6580 foreach ($enrols_available as $key=>$enrol) {
6581 $allenrols[$key] = true;
6583 // Now find all borked plugins and at least allow then to uninstall.
6584 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6585 foreach ($condidates as $candidate) {
6586 if (empty($allenrols[$candidate])) {
6587 $allenrols[$candidate] = true;
6591 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6592 $return .= $OUTPUT->box_start('generalbox enrolsui');
6594 $table = new html_table();
6595 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6596 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6597 $table->id = 'courseenrolmentplugins';
6598 $table->attributes['class'] = 'admintable generaltable';
6599 $table->data = array();
6601 // Iterate through enrol plugins and add to the display table.
6602 $updowncount = 1;
6603 $enrolcount = count($active_enrols);
6604 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6605 $printed = array();
6606 foreach($allenrols as $enrol => $unused) {
6607 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6608 $version = get_config('enrol_'.$enrol, 'version');
6609 if ($version === false) {
6610 $version = '';
6613 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6614 $name = get_string('pluginname', 'enrol_'.$enrol);
6615 } else {
6616 $name = $enrol;
6618 // Usage.
6619 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6620 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6621 $usage = "$ci / $cp";
6623 // Hide/show links.
6624 $class = '';
6625 if (isset($active_enrols[$enrol])) {
6626 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6627 $hideshow = "<a href=\"$aurl\">";
6628 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6629 $enabled = true;
6630 $displayname = $name;
6631 } else if (isset($enrols_available[$enrol])) {
6632 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6633 $hideshow = "<a href=\"$aurl\">";
6634 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6635 $enabled = false;
6636 $displayname = $name;
6637 $class = 'dimmed_text';
6638 } else {
6639 $hideshow = '';
6640 $enabled = false;
6641 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6643 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6644 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6645 } else {
6646 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6649 // Up/down link (only if enrol is enabled).
6650 $updown = '';
6651 if ($enabled) {
6652 if ($updowncount > 1) {
6653 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6654 $updown .= "<a href=\"$aurl\">";
6655 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6656 } else {
6657 $updown .= $OUTPUT->spacer() . '&nbsp;';
6659 if ($updowncount < $enrolcount) {
6660 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6661 $updown .= "<a href=\"$aurl\">";
6662 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6663 } else {
6664 $updown .= $OUTPUT->spacer() . '&nbsp;';
6666 ++$updowncount;
6669 // Add settings link.
6670 if (!$version) {
6671 $settings = '';
6672 } else if ($surl = $plugininfo->get_settings_url()) {
6673 $settings = html_writer::link($surl, $strsettings);
6674 } else {
6675 $settings = '';
6678 // Add uninstall info.
6679 $uninstall = '';
6680 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6681 $uninstall = html_writer::link($uninstallurl, $struninstall);
6684 $test = '';
6685 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6686 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6687 $test = html_writer::link($testsettingsurl, $strtest);
6690 // Add a row to the table.
6691 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6692 if ($class) {
6693 $row->attributes['class'] = $class;
6695 $table->data[] = $row;
6697 $printed[$enrol] = true;
6700 $return .= html_writer::table($table);
6701 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6702 $return .= $OUTPUT->box_end();
6703 return highlight($query, $return);
6709 * Blocks manage page
6711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6713 class admin_page_manageblocks extends admin_externalpage {
6715 * Calls parent::__construct with specific arguments
6717 public function __construct() {
6718 global $CFG;
6719 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6723 * Search for a specific block
6725 * @param string $query The string to search for
6726 * @return array
6728 public function search($query) {
6729 global $CFG, $DB;
6730 if ($result = parent::search($query)) {
6731 return $result;
6734 $found = false;
6735 if ($blocks = $DB->get_records('block')) {
6736 foreach ($blocks as $block) {
6737 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6738 continue;
6740 if (strpos($block->name, $query) !== false) {
6741 $found = true;
6742 break;
6744 $strblockname = get_string('pluginname', 'block_'.$block->name);
6745 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6746 $found = true;
6747 break;
6751 if ($found) {
6752 $result = new stdClass();
6753 $result->page = $this;
6754 $result->settings = array();
6755 return array($this->name => $result);
6756 } else {
6757 return array();
6763 * Message outputs configuration
6765 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6767 class admin_page_managemessageoutputs extends admin_externalpage {
6769 * Calls parent::__construct with specific arguments
6771 public function __construct() {
6772 global $CFG;
6773 parent::__construct('managemessageoutputs',
6774 get_string('defaultmessageoutputs', 'message'),
6775 new moodle_url('/admin/message.php')
6780 * Search for a specific message processor
6782 * @param string $query The string to search for
6783 * @return array
6785 public function search($query) {
6786 global $CFG, $DB;
6787 if ($result = parent::search($query)) {
6788 return $result;
6791 $found = false;
6792 if ($processors = get_message_processors()) {
6793 foreach ($processors as $processor) {
6794 if (!$processor->available) {
6795 continue;
6797 if (strpos($processor->name, $query) !== false) {
6798 $found = true;
6799 break;
6801 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6802 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6803 $found = true;
6804 break;
6808 if ($found) {
6809 $result = new stdClass();
6810 $result->page = $this;
6811 $result->settings = array();
6812 return array($this->name => $result);
6813 } else {
6814 return array();
6820 * Manage question behaviours page
6822 * @copyright 2011 The Open University
6823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6825 class admin_page_manageqbehaviours extends admin_externalpage {
6827 * Constructor
6829 public function __construct() {
6830 global $CFG;
6831 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6832 new moodle_url('/admin/qbehaviours.php'));
6836 * Search question behaviours for the specified string
6838 * @param string $query The string to search for in question behaviours
6839 * @return array
6841 public function search($query) {
6842 global $CFG;
6843 if ($result = parent::search($query)) {
6844 return $result;
6847 $found = false;
6848 require_once($CFG->dirroot . '/question/engine/lib.php');
6849 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6850 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6851 $query) !== false) {
6852 $found = true;
6853 break;
6856 if ($found) {
6857 $result = new stdClass();
6858 $result->page = $this;
6859 $result->settings = array();
6860 return array($this->name => $result);
6861 } else {
6862 return array();
6869 * Question type manage page
6871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6873 class admin_page_manageqtypes extends admin_externalpage {
6875 * Calls parent::__construct with specific arguments
6877 public function __construct() {
6878 global $CFG;
6879 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6880 new moodle_url('/admin/qtypes.php'));
6884 * Search question types for the specified string
6886 * @param string $query The string to search for in question types
6887 * @return array
6889 public function search($query) {
6890 global $CFG;
6891 if ($result = parent::search($query)) {
6892 return $result;
6895 $found = false;
6896 require_once($CFG->dirroot . '/question/engine/bank.php');
6897 foreach (question_bank::get_all_qtypes() as $qtype) {
6898 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6899 $found = true;
6900 break;
6903 if ($found) {
6904 $result = new stdClass();
6905 $result->page = $this;
6906 $result->settings = array();
6907 return array($this->name => $result);
6908 } else {
6909 return array();
6915 class admin_page_manageportfolios extends admin_externalpage {
6917 * Calls parent::__construct with specific arguments
6919 public function __construct() {
6920 global $CFG;
6921 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6922 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6926 * Searches page for the specified string.
6927 * @param string $query The string to search for
6928 * @return bool True if it is found on this page
6930 public function search($query) {
6931 global $CFG;
6932 if ($result = parent::search($query)) {
6933 return $result;
6936 $found = false;
6937 $portfolios = core_component::get_plugin_list('portfolio');
6938 foreach ($portfolios as $p => $dir) {
6939 if (strpos($p, $query) !== false) {
6940 $found = true;
6941 break;
6944 if (!$found) {
6945 foreach (portfolio_instances(false, false) as $instance) {
6946 $title = $instance->get('name');
6947 if (strpos(core_text::strtolower($title), $query) !== false) {
6948 $found = true;
6949 break;
6954 if ($found) {
6955 $result = new stdClass();
6956 $result->page = $this;
6957 $result->settings = array();
6958 return array($this->name => $result);
6959 } else {
6960 return array();
6966 class admin_page_managerepositories extends admin_externalpage {
6968 * Calls parent::__construct with specific arguments
6970 public function __construct() {
6971 global $CFG;
6972 parent::__construct('managerepositories', get_string('manage',
6973 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6977 * Searches page for the specified string.
6978 * @param string $query The string to search for
6979 * @return bool True if it is found on this page
6981 public function search($query) {
6982 global $CFG;
6983 if ($result = parent::search($query)) {
6984 return $result;
6987 $found = false;
6988 $repositories= core_component::get_plugin_list('repository');
6989 foreach ($repositories as $p => $dir) {
6990 if (strpos($p, $query) !== false) {
6991 $found = true;
6992 break;
6995 if (!$found) {
6996 foreach (repository::get_types() as $instance) {
6997 $title = $instance->get_typename();
6998 if (strpos(core_text::strtolower($title), $query) !== false) {
6999 $found = true;
7000 break;
7005 if ($found) {
7006 $result = new stdClass();
7007 $result->page = $this;
7008 $result->settings = array();
7009 return array($this->name => $result);
7010 } else {
7011 return array();
7018 * Special class for authentication administration.
7020 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7022 class admin_setting_manageauths extends admin_setting {
7024 * Calls parent::__construct with specific arguments
7026 public function __construct() {
7027 $this->nosave = true;
7028 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
7032 * Always returns true
7034 * @return true
7036 public function get_setting() {
7037 return true;
7041 * Always returns true
7043 * @return true
7045 public function get_defaultsetting() {
7046 return true;
7050 * Always returns '' and doesn't write anything
7052 * @return string Always returns ''
7054 public function write_setting($data) {
7055 // do not write any setting
7056 return '';
7060 * Search to find if Query is related to auth plugin
7062 * @param string $query The string to search for
7063 * @return bool true for related false for not
7065 public function is_related($query) {
7066 if (parent::is_related($query)) {
7067 return true;
7070 $authsavailable = core_component::get_plugin_list('auth');
7071 foreach ($authsavailable as $auth => $dir) {
7072 if (strpos($auth, $query) !== false) {
7073 return true;
7075 $authplugin = get_auth_plugin($auth);
7076 $authtitle = $authplugin->get_title();
7077 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
7078 return true;
7081 return false;
7085 * Return XHTML to display control
7087 * @param mixed $data Unused
7088 * @param string $query
7089 * @return string highlight
7091 public function output_html($data, $query='') {
7092 global $CFG, $OUTPUT, $DB;
7094 // display strings
7095 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7096 'settings', 'edit', 'name', 'enable', 'disable',
7097 'up', 'down', 'none', 'users'));
7098 $txt->updown = "$txt->up/$txt->down";
7099 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7100 $txt->testsettings = get_string('testsettings', 'core_auth');
7102 $authsavailable = core_component::get_plugin_list('auth');
7103 get_enabled_auth_plugins(true); // fix the list of enabled auths
7104 if (empty($CFG->auth)) {
7105 $authsenabled = array();
7106 } else {
7107 $authsenabled = explode(',', $CFG->auth);
7110 // construct the display array, with enabled auth plugins at the top, in order
7111 $displayauths = array();
7112 $registrationauths = array();
7113 $registrationauths[''] = $txt->disable;
7114 $authplugins = array();
7115 foreach ($authsenabled as $auth) {
7116 $authplugin = get_auth_plugin($auth);
7117 $authplugins[$auth] = $authplugin;
7118 /// Get the auth title (from core or own auth lang files)
7119 $authtitle = $authplugin->get_title();
7120 /// Apply titles
7121 $displayauths[$auth] = $authtitle;
7122 if ($authplugin->can_signup()) {
7123 $registrationauths[$auth] = $authtitle;
7127 foreach ($authsavailable as $auth => $dir) {
7128 if (array_key_exists($auth, $displayauths)) {
7129 continue; //already in the list
7131 $authplugin = get_auth_plugin($auth);
7132 $authplugins[$auth] = $authplugin;
7133 /// Get the auth title (from core or own auth lang files)
7134 $authtitle = $authplugin->get_title();
7135 /// Apply titles
7136 $displayauths[$auth] = $authtitle;
7137 if ($authplugin->can_signup()) {
7138 $registrationauths[$auth] = $authtitle;
7142 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7143 $return .= $OUTPUT->box_start('generalbox authsui');
7145 $table = new html_table();
7146 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
7147 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7148 $table->data = array();
7149 $table->attributes['class'] = 'admintable generaltable';
7150 $table->id = 'manageauthtable';
7152 //add always enabled plugins first
7153 $displayname = $displayauths['manual'];
7154 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7155 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7156 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
7157 $displayname = $displayauths['nologin'];
7158 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7159 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
7162 // iterate through auth plugins and add to the display table
7163 $updowncount = 1;
7164 $authcount = count($authsenabled);
7165 $url = "auth.php?sesskey=" . sesskey();
7166 foreach ($displayauths as $auth => $name) {
7167 if ($auth == 'manual' or $auth == 'nologin') {
7168 continue;
7170 $class = '';
7171 // hide/show link
7172 if (in_array($auth, $authsenabled)) {
7173 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
7174 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7175 $enabled = true;
7176 $displayname = $name;
7178 else {
7179 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
7180 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7181 $enabled = false;
7182 $displayname = $name;
7183 $class = 'dimmed_text';
7186 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7188 // up/down link (only if auth is enabled)
7189 $updown = '';
7190 if ($enabled) {
7191 if ($updowncount > 1) {
7192 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
7193 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7195 else {
7196 $updown .= $OUTPUT->spacer() . '&nbsp;';
7198 if ($updowncount < $authcount) {
7199 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
7200 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7202 else {
7203 $updown .= $OUTPUT->spacer() . '&nbsp;';
7205 ++ $updowncount;
7208 // settings link
7209 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
7210 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7211 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
7212 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
7213 } else {
7214 $settings = '';
7217 // Uninstall link.
7218 $uninstall = '';
7219 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7220 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7223 $test = '';
7224 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7225 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
7226 $test = html_writer::link($testurl, $txt->testsettings);
7229 // Add a row to the table.
7230 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7231 if ($class) {
7232 $row->attributes['class'] = $class;
7234 $table->data[] = $row;
7236 $return .= html_writer::table($table);
7237 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7238 $return .= $OUTPUT->box_end();
7239 return highlight($query, $return);
7245 * Special class for authentication administration.
7247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7249 class admin_setting_manageeditors extends admin_setting {
7251 * Calls parent::__construct with specific arguments
7253 public function __construct() {
7254 $this->nosave = true;
7255 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
7259 * Always returns true, does nothing
7261 * @return true
7263 public function get_setting() {
7264 return true;
7268 * Always returns true, does nothing
7270 * @return true
7272 public function get_defaultsetting() {
7273 return true;
7277 * Always returns '', does not write anything
7279 * @return string Always returns ''
7281 public function write_setting($data) {
7282 // do not write any setting
7283 return '';
7287 * Checks if $query is one of the available editors
7289 * @param string $query The string to search for
7290 * @return bool Returns true if found, false if not
7292 public function is_related($query) {
7293 if (parent::is_related($query)) {
7294 return true;
7297 $editors_available = editors_get_available();
7298 foreach ($editors_available as $editor=>$editorstr) {
7299 if (strpos($editor, $query) !== false) {
7300 return true;
7302 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
7303 return true;
7306 return false;
7310 * Builds the XHTML to display the control
7312 * @param string $data Unused
7313 * @param string $query
7314 * @return string
7316 public function output_html($data, $query='') {
7317 global $CFG, $OUTPUT;
7319 // display strings
7320 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7321 'up', 'down', 'none'));
7322 $struninstall = get_string('uninstallplugin', 'core_admin');
7324 $txt->updown = "$txt->up/$txt->down";
7326 $editors_available = editors_get_available();
7327 $active_editors = explode(',', $CFG->texteditors);
7329 $active_editors = array_reverse($active_editors);
7330 foreach ($active_editors as $key=>$editor) {
7331 if (empty($editors_available[$editor])) {
7332 unset($active_editors[$key]);
7333 } else {
7334 $name = $editors_available[$editor];
7335 unset($editors_available[$editor]);
7336 $editors_available[$editor] = $name;
7339 if (empty($active_editors)) {
7340 //$active_editors = array('textarea');
7342 $editors_available = array_reverse($editors_available, true);
7343 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
7344 $return .= $OUTPUT->box_start('generalbox editorsui');
7346 $table = new html_table();
7347 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7348 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7349 $table->id = 'editormanagement';
7350 $table->attributes['class'] = 'admintable generaltable';
7351 $table->data = array();
7353 // iterate through auth plugins and add to the display table
7354 $updowncount = 1;
7355 $editorcount = count($active_editors);
7356 $url = "editors.php?sesskey=" . sesskey();
7357 foreach ($editors_available as $editor => $name) {
7358 // hide/show link
7359 $class = '';
7360 if (in_array($editor, $active_editors)) {
7361 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
7362 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7363 $enabled = true;
7364 $displayname = $name;
7366 else {
7367 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
7368 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7369 $enabled = false;
7370 $displayname = $name;
7371 $class = 'dimmed_text';
7374 // up/down link (only if auth is enabled)
7375 $updown = '';
7376 if ($enabled) {
7377 if ($updowncount > 1) {
7378 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
7379 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7381 else {
7382 $updown .= $OUTPUT->spacer() . '&nbsp;';
7384 if ($updowncount < $editorcount) {
7385 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
7386 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7388 else {
7389 $updown .= $OUTPUT->spacer() . '&nbsp;';
7391 ++ $updowncount;
7394 // settings link
7395 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
7396 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7397 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7398 } else {
7399 $settings = '';
7402 $uninstall = '';
7403 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7404 $uninstall = html_writer::link($uninstallurl, $struninstall);
7407 // Add a row to the table.
7408 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7409 if ($class) {
7410 $row->attributes['class'] = $class;
7412 $table->data[] = $row;
7414 $return .= html_writer::table($table);
7415 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7416 $return .= $OUTPUT->box_end();
7417 return highlight($query, $return);
7422 * Special class for antiviruses administration.
7424 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7427 class admin_setting_manageantiviruses extends admin_setting {
7429 * Calls parent::__construct with specific arguments
7431 public function __construct() {
7432 $this->nosave = true;
7433 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7437 * Always returns true, does nothing
7439 * @return true
7441 public function get_setting() {
7442 return true;
7446 * Always returns true, does nothing
7448 * @return true
7450 public function get_defaultsetting() {
7451 return true;
7455 * Always returns '', does not write anything
7457 * @param string $data Unused
7458 * @return string Always returns ''
7460 public function write_setting($data) {
7461 // Do not write any setting.
7462 return '';
7466 * Checks if $query is one of the available editors
7468 * @param string $query The string to search for
7469 * @return bool Returns true if found, false if not
7471 public function is_related($query) {
7472 if (parent::is_related($query)) {
7473 return true;
7476 $antivirusesavailable = \core\antivirus\manager::get_available();
7477 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7478 if (strpos($antivirus, $query) !== false) {
7479 return true;
7481 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7482 return true;
7485 return false;
7489 * Builds the XHTML to display the control
7491 * @param string $data Unused
7492 * @param string $query
7493 * @return string
7495 public function output_html($data, $query='') {
7496 global $CFG, $OUTPUT;
7498 // Display strings.
7499 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7500 'up', 'down', 'none'));
7501 $struninstall = get_string('uninstallplugin', 'core_admin');
7503 $txt->updown = "$txt->up/$txt->down";
7505 $antivirusesavailable = \core\antivirus\manager::get_available();
7506 $activeantiviruses = explode(',', $CFG->antiviruses);
7508 $activeantiviruses = array_reverse($activeantiviruses);
7509 foreach ($activeantiviruses as $key => $antivirus) {
7510 if (empty($antivirusesavailable[$antivirus])) {
7511 unset($activeantiviruses[$key]);
7512 } else {
7513 $name = $antivirusesavailable[$antivirus];
7514 unset($antivirusesavailable[$antivirus]);
7515 $antivirusesavailable[$antivirus] = $name;
7518 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7519 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7520 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7522 $table = new html_table();
7523 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7524 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7525 $table->id = 'antivirusmanagement';
7526 $table->attributes['class'] = 'admintable generaltable';
7527 $table->data = array();
7529 // Iterate through auth plugins and add to the display table.
7530 $updowncount = 1;
7531 $antiviruscount = count($activeantiviruses);
7532 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7533 foreach ($antivirusesavailable as $antivirus => $name) {
7534 // Hide/show link.
7535 $class = '';
7536 if (in_array($antivirus, $activeantiviruses)) {
7537 $hideshowurl = $baseurl;
7538 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7539 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7540 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7541 $enabled = true;
7542 $displayname = $name;
7543 } else {
7544 $hideshowurl = $baseurl;
7545 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7546 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7547 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7548 $enabled = false;
7549 $displayname = $name;
7550 $class = 'dimmed_text';
7553 // Up/down link.
7554 $updown = '';
7555 if ($enabled) {
7556 if ($updowncount > 1) {
7557 $updownurl = $baseurl;
7558 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7559 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7560 $updown = html_writer::link($updownurl, $updownimg);
7561 } else {
7562 $updownimg = $OUTPUT->spacer();
7564 if ($updowncount < $antiviruscount) {
7565 $updownurl = $baseurl;
7566 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7567 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7568 $updown = html_writer::link($updownurl, $updownimg);
7569 } else {
7570 $updownimg = $OUTPUT->spacer();
7572 ++ $updowncount;
7575 // Settings link.
7576 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7577 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7578 $settings = html_writer::link($eurl, $txt->settings);
7579 } else {
7580 $settings = '';
7583 $uninstall = '';
7584 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7585 $uninstall = html_writer::link($uninstallurl, $struninstall);
7588 // Add a row to the table.
7589 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7590 if ($class) {
7591 $row->attributes['class'] = $class;
7593 $table->data[] = $row;
7595 $return .= html_writer::table($table);
7596 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7597 $return .= $OUTPUT->box_end();
7598 return highlight($query, $return);
7603 * Course formats manager. Allows to enable/disable formats and jump to settings
7605 class admin_setting_manageformats extends admin_setting {
7608 * Calls parent::__construct with specific arguments
7610 public function __construct() {
7611 $this->nosave = true;
7612 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7616 * Always returns true
7618 * @return true
7620 public function get_setting() {
7621 return true;
7625 * Always returns true
7627 * @return true
7629 public function get_defaultsetting() {
7630 return true;
7634 * Always returns '' and doesn't write anything
7636 * @param mixed $data string or array, must not be NULL
7637 * @return string Always returns ''
7639 public function write_setting($data) {
7640 // do not write any setting
7641 return '';
7645 * Search to find if Query is related to format plugin
7647 * @param string $query The string to search for
7648 * @return bool true for related false for not
7650 public function is_related($query) {
7651 if (parent::is_related($query)) {
7652 return true;
7654 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7655 foreach ($formats as $format) {
7656 if (strpos($format->component, $query) !== false ||
7657 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7658 return true;
7661 return false;
7665 * Return XHTML to display control
7667 * @param mixed $data Unused
7668 * @param string $query
7669 * @return string highlight
7671 public function output_html($data, $query='') {
7672 global $CFG, $OUTPUT;
7673 $return = '';
7674 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7675 $return .= $OUTPUT->box_start('generalbox formatsui');
7677 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7679 // display strings
7680 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7681 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7682 $txt->updown = "$txt->up/$txt->down";
7684 $table = new html_table();
7685 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7686 $table->align = array('left', 'center', 'center', 'center', 'center');
7687 $table->attributes['class'] = 'manageformattable generaltable admintable';
7688 $table->data = array();
7690 $cnt = 0;
7691 $defaultformat = get_config('moodlecourse', 'format');
7692 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7693 foreach ($formats as $format) {
7694 $url = new moodle_url('/admin/courseformats.php',
7695 array('sesskey' => sesskey(), 'format' => $format->name));
7696 $isdefault = '';
7697 $class = '';
7698 if ($format->is_enabled()) {
7699 $strformatname = $format->displayname;
7700 if ($defaultformat === $format->name) {
7701 $hideshow = $txt->default;
7702 } else {
7703 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7704 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7706 } else {
7707 $strformatname = $format->displayname;
7708 $class = 'dimmed_text';
7709 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7710 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7712 $updown = '';
7713 if ($cnt) {
7714 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7715 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7716 } else {
7717 $updown .= $spacer;
7719 if ($cnt < count($formats) - 1) {
7720 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7721 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7722 } else {
7723 $updown .= $spacer;
7725 $cnt++;
7726 $settings = '';
7727 if ($format->get_settings_url()) {
7728 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7730 $uninstall = '';
7731 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7732 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7734 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7735 if ($class) {
7736 $row->attributes['class'] = $class;
7738 $table->data[] = $row;
7740 $return .= html_writer::table($table);
7741 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7742 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7743 $return .= $OUTPUT->box_end();
7744 return highlight($query, $return);
7749 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7751 * @package core
7752 * @copyright 2018 Toni Barbera
7753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7755 class admin_setting_managecustomfields extends admin_setting {
7758 * Calls parent::__construct with specific arguments
7760 public function __construct() {
7761 $this->nosave = true;
7762 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7766 * Always returns true
7768 * @return true
7770 public function get_setting() {
7771 return true;
7775 * Always returns true
7777 * @return true
7779 public function get_defaultsetting() {
7780 return true;
7784 * Always returns '' and doesn't write anything
7786 * @param mixed $data string or array, must not be NULL
7787 * @return string Always returns ''
7789 public function write_setting($data) {
7790 // Do not write any setting.
7791 return '';
7795 * Search to find if Query is related to format plugin
7797 * @param string $query The string to search for
7798 * @return bool true for related false for not
7800 public function is_related($query) {
7801 if (parent::is_related($query)) {
7802 return true;
7804 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7805 foreach ($formats as $format) {
7806 if (strpos($format->component, $query) !== false ||
7807 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7808 return true;
7811 return false;
7815 * Return XHTML to display control
7817 * @param mixed $data Unused
7818 * @param string $query
7819 * @return string highlight
7821 public function output_html($data, $query='') {
7822 global $CFG, $OUTPUT;
7823 $return = '';
7824 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7825 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7827 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7829 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7830 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7831 $txt->updown = "$txt->up/$txt->down";
7833 $table = new html_table();
7834 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7835 $table->align = array('left', 'center', 'center', 'center');
7836 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7837 $table->data = array();
7839 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7840 foreach ($fields as $field) {
7841 $url = new moodle_url('/admin/customfields.php',
7842 array('sesskey' => sesskey(), 'field' => $field->name));
7844 if ($field->is_enabled()) {
7845 $strfieldname = $field->displayname;
7846 $class = '';
7847 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7848 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7849 } else {
7850 $strfieldname = $field->displayname;
7851 $class = 'dimmed_text';
7852 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7853 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7855 $settings = '';
7856 if ($field->get_settings_url()) {
7857 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7859 $uninstall = '';
7860 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7861 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7863 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7864 $row->attributes['class'] = $class;
7865 $table->data[] = $row;
7867 $return .= html_writer::table($table);
7868 $return .= $OUTPUT->box_end();
7869 return highlight($query, $return);
7874 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7876 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7877 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7879 class admin_setting_managedataformats extends admin_setting {
7882 * Calls parent::__construct with specific arguments
7884 public function __construct() {
7885 $this->nosave = true;
7886 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7890 * Always returns true
7892 * @return true
7894 public function get_setting() {
7895 return true;
7899 * Always returns true
7901 * @return true
7903 public function get_defaultsetting() {
7904 return true;
7908 * Always returns '' and doesn't write anything
7910 * @param mixed $data string or array, must not be NULL
7911 * @return string Always returns ''
7913 public function write_setting($data) {
7914 // Do not write any setting.
7915 return '';
7919 * Search to find if Query is related to format plugin
7921 * @param string $query The string to search for
7922 * @return bool true for related false for not
7924 public function is_related($query) {
7925 if (parent::is_related($query)) {
7926 return true;
7928 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7929 foreach ($formats as $format) {
7930 if (strpos($format->component, $query) !== false ||
7931 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7932 return true;
7935 return false;
7939 * Return XHTML to display control
7941 * @param mixed $data Unused
7942 * @param string $query
7943 * @return string highlight
7945 public function output_html($data, $query='') {
7946 global $CFG, $OUTPUT;
7947 $return = '';
7949 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7951 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7952 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7953 $txt->updown = "$txt->up/$txt->down";
7955 $table = new html_table();
7956 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7957 $table->align = array('left', 'center', 'center', 'center', 'center');
7958 $table->attributes['class'] = 'manageformattable generaltable admintable';
7959 $table->data = array();
7961 $cnt = 0;
7962 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7963 $totalenabled = 0;
7964 foreach ($formats as $format) {
7965 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7966 $totalenabled++;
7969 foreach ($formats as $format) {
7970 $status = $format->get_status();
7971 $url = new moodle_url('/admin/dataformats.php',
7972 array('sesskey' => sesskey(), 'name' => $format->name));
7974 $class = '';
7975 if ($format->is_enabled()) {
7976 $strformatname = $format->displayname;
7977 if ($totalenabled == 1&& $format->is_enabled()) {
7978 $hideshow = '';
7979 } else {
7980 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7981 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7983 } else {
7984 $class = 'dimmed_text';
7985 $strformatname = $format->displayname;
7986 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7987 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7990 $updown = '';
7991 if ($cnt) {
7992 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7993 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7994 } else {
7995 $updown .= $spacer;
7997 if ($cnt < count($formats) - 1) {
7998 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7999 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8000 } else {
8001 $updown .= $spacer;
8004 $uninstall = '';
8005 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8006 $uninstall = get_string('status_missing', 'core_plugin');
8007 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8008 $uninstall = get_string('status_new', 'core_plugin');
8009 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
8010 if ($totalenabled != 1 || !$format->is_enabled()) {
8011 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8015 $settings = '';
8016 if ($format->get_settings_url()) {
8017 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
8020 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
8021 if ($class) {
8022 $row->attributes['class'] = $class;
8024 $table->data[] = $row;
8025 $cnt++;
8027 $return .= html_writer::table($table);
8028 return highlight($query, $return);
8033 * Special class for filter administration.
8035 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8037 class admin_page_managefilters extends admin_externalpage {
8039 * Calls parent::__construct with specific arguments
8041 public function __construct() {
8042 global $CFG;
8043 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
8047 * Searches all installed filters for specified filter
8049 * @param string $query The filter(string) to search for
8050 * @param string $query
8052 public function search($query) {
8053 global $CFG;
8054 if ($result = parent::search($query)) {
8055 return $result;
8058 $found = false;
8059 $filternames = filter_get_all_installed();
8060 foreach ($filternames as $path => $strfiltername) {
8061 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
8062 $found = true;
8063 break;
8065 if (strpos($path, $query) !== false) {
8066 $found = true;
8067 break;
8071 if ($found) {
8072 $result = new stdClass;
8073 $result->page = $this;
8074 $result->settings = array();
8075 return array($this->name => $result);
8076 } else {
8077 return array();
8083 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8084 * Requires a get_rank method on the plugininfo class for sorting.
8086 * @copyright 2017 Damyon Wiese
8087 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8089 abstract class admin_setting_manage_plugins extends admin_setting {
8092 * Get the admin settings section name (just a unique string)
8094 * @return string
8096 public function get_section_name() {
8097 return 'manage' . $this->get_plugin_type() . 'plugins';
8101 * Get the admin settings section title (use get_string).
8103 * @return string
8105 abstract public function get_section_title();
8108 * Get the type of plugin to manage.
8110 * @return string
8112 abstract public function get_plugin_type();
8115 * Get the name of the second column.
8117 * @return string
8119 public function get_info_column_name() {
8120 return '';
8124 * Get the type of plugin to manage.
8126 * @param plugininfo The plugin info class.
8127 * @return string
8129 abstract public function get_info_column($plugininfo);
8132 * Calls parent::__construct with specific arguments
8134 public function __construct() {
8135 $this->nosave = true;
8136 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8140 * Always returns true, does nothing
8142 * @return true
8144 public function get_setting() {
8145 return true;
8149 * Always returns true, does nothing
8151 * @return true
8153 public function get_defaultsetting() {
8154 return true;
8158 * Always returns '', does not write anything
8160 * @param mixed $data
8161 * @return string Always returns ''
8163 public function write_setting($data) {
8164 // Do not write any setting.
8165 return '';
8169 * Checks if $query is one of the available plugins of this type
8171 * @param string $query The string to search for
8172 * @return bool Returns true if found, false if not
8174 public function is_related($query) {
8175 if (parent::is_related($query)) {
8176 return true;
8179 $query = core_text::strtolower($query);
8180 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
8181 foreach ($plugins as $name => $plugin) {
8182 $localised = $plugin->displayname;
8183 if (strpos(core_text::strtolower($name), $query) !== false) {
8184 return true;
8186 if (strpos(core_text::strtolower($localised), $query) !== false) {
8187 return true;
8190 return false;
8194 * The URL for the management page for this plugintype.
8196 * @return moodle_url
8198 protected function get_manage_url() {
8199 return new moodle_url('/admin/updatesetting.php');
8203 * Builds the HTML to display the control.
8205 * @param string $data Unused
8206 * @param string $query
8207 * @return string
8209 public function output_html($data, $query = '') {
8210 global $CFG, $OUTPUT, $DB, $PAGE;
8212 $context = (object) [
8213 'manageurl' => new moodle_url($this->get_manage_url(), [
8214 'type' => $this->get_plugin_type(),
8215 'sesskey' => sesskey(),
8217 'infocolumnname' => $this->get_info_column_name(),
8218 'plugins' => [],
8221 $pluginmanager = core_plugin_manager::instance();
8222 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8223 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8224 $plugins = array_merge($enabled, $allplugins);
8225 foreach ($plugins as $key => $plugin) {
8226 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
8228 $pluginkey = (object) [
8229 'plugin' => $plugin->displayname,
8230 'enabled' => $plugin->is_enabled(),
8231 'togglelink' => '',
8232 'moveuplink' => '',
8233 'movedownlink' => '',
8234 'settingslink' => $plugin->get_settings_url(),
8235 'uninstalllink' => '',
8236 'info' => '',
8239 // Enable/Disable link.
8240 $togglelink = new moodle_url($pluginlink);
8241 if ($plugin->is_enabled()) {
8242 $toggletarget = false;
8243 $togglelink->param('action', 'disable');
8245 if (count($context->plugins)) {
8246 // This is not the first plugin.
8247 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
8250 if (count($enabled) > count($context->plugins) + 1) {
8251 // This is not the last plugin.
8252 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
8255 $pluginkey->info = $this->get_info_column($plugin);
8256 } else {
8257 $toggletarget = true;
8258 $togglelink->param('action', 'enable');
8261 $pluginkey->toggletarget = $toggletarget;
8262 $pluginkey->togglelink = $togglelink;
8264 $frankenstyle = $plugin->type . '_' . $plugin->name;
8265 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8266 // This plugin supports uninstallation.
8267 $pluginkey->uninstalllink = $uninstalllink;
8270 if (!empty($this->get_info_column_name())) {
8271 // This plugintype has an info column.
8272 $pluginkey->info = $this->get_info_column($plugin);
8275 $context->plugins[] = $pluginkey;
8278 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8279 return highlight($query, $str);
8284 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8285 * Requires a get_rank method on the plugininfo class for sorting.
8287 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8290 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8291 public function get_section_title() {
8292 return get_string('type_fileconverter_plural', 'plugin');
8295 public function get_plugin_type() {
8296 return 'fileconverter';
8299 public function get_info_column_name() {
8300 return get_string('supportedconversions', 'plugin');
8303 public function get_info_column($plugininfo) {
8304 return $plugininfo->get_supported_conversions();
8309 * Special class for media player plugins management.
8311 * @copyright 2016 Marina Glancy
8312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8314 class admin_setting_managemediaplayers extends admin_setting {
8316 * Calls parent::__construct with specific arguments
8318 public function __construct() {
8319 $this->nosave = true;
8320 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8324 * Always returns true, does nothing
8326 * @return true
8328 public function get_setting() {
8329 return true;
8333 * Always returns true, does nothing
8335 * @return true
8337 public function get_defaultsetting() {
8338 return true;
8342 * Always returns '', does not write anything
8344 * @param mixed $data
8345 * @return string Always returns ''
8347 public function write_setting($data) {
8348 // Do not write any setting.
8349 return '';
8353 * Checks if $query is one of the available enrol plugins
8355 * @param string $query The string to search for
8356 * @return bool Returns true if found, false if not
8358 public function is_related($query) {
8359 if (parent::is_related($query)) {
8360 return true;
8363 $query = core_text::strtolower($query);
8364 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8365 foreach ($plugins as $name => $plugin) {
8366 $localised = $plugin->displayname;
8367 if (strpos(core_text::strtolower($name), $query) !== false) {
8368 return true;
8370 if (strpos(core_text::strtolower($localised), $query) !== false) {
8371 return true;
8374 return false;
8378 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8379 * @return \core\plugininfo\media[]
8381 protected function get_sorted_plugins() {
8382 $pluginmanager = core_plugin_manager::instance();
8384 $plugins = $pluginmanager->get_plugins_of_type('media');
8385 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8387 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8388 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8390 $order = array_values($enabledplugins);
8391 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8393 $sortedplugins = array();
8394 foreach ($order as $name) {
8395 $sortedplugins[$name] = $plugins[$name];
8398 return $sortedplugins;
8402 * Builds the XHTML to display the control
8404 * @param string $data Unused
8405 * @param string $query
8406 * @return string
8408 public function output_html($data, $query='') {
8409 global $CFG, $OUTPUT, $DB, $PAGE;
8411 // Display strings.
8412 $strup = get_string('up');
8413 $strdown = get_string('down');
8414 $strsettings = get_string('settings');
8415 $strenable = get_string('enable');
8416 $strdisable = get_string('disable');
8417 $struninstall = get_string('uninstallplugin', 'core_admin');
8418 $strversion = get_string('version');
8419 $strname = get_string('name');
8420 $strsupports = get_string('supports', 'core_media');
8422 $pluginmanager = core_plugin_manager::instance();
8424 $plugins = $this->get_sorted_plugins();
8425 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8427 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8429 $table = new html_table();
8430 $table->head = array($strname, $strsupports, $strversion,
8431 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8432 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8433 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8434 $table->id = 'mediaplayerplugins';
8435 $table->attributes['class'] = 'admintable generaltable';
8436 $table->data = array();
8438 // Iterate through media plugins and add to the display table.
8439 $updowncount = 1;
8440 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8441 $printed = array();
8442 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8444 $usedextensions = [];
8445 foreach ($plugins as $name => $plugin) {
8446 $url->param('media', $name);
8447 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8448 $version = $plugininfo->versiondb;
8449 $supports = $plugininfo->supports($usedextensions);
8451 // Hide/show links.
8452 $class = '';
8453 if (!$plugininfo->is_installed_and_upgraded()) {
8454 $hideshow = '';
8455 $enabled = false;
8456 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8457 } else {
8458 $enabled = $plugininfo->is_enabled();
8459 if ($enabled) {
8460 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8461 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8462 } else {
8463 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8464 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8465 $class = 'dimmed_text';
8467 $displayname = $plugin->displayname;
8468 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8469 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8472 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8473 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8474 } else {
8475 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8478 // Up/down link (only if enrol is enabled).
8479 $updown = '';
8480 if ($enabled) {
8481 if ($updowncount > 1) {
8482 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8483 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8484 } else {
8485 $updown = $spacer;
8487 if ($updowncount < count($enabledplugins)) {
8488 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8489 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8490 } else {
8491 $updown .= $spacer;
8493 ++$updowncount;
8496 $uninstall = '';
8497 $status = $plugininfo->get_status();
8498 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8499 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8501 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8502 $uninstall = get_string('status_new', 'core_plugin');
8503 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8504 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8507 $settings = '';
8508 if ($plugininfo->get_settings_url()) {
8509 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8512 // Add a row to the table.
8513 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8514 if ($class) {
8515 $row->attributes['class'] = $class;
8517 $table->data[] = $row;
8519 $printed[$name] = true;
8522 $return .= html_writer::table($table);
8523 $return .= $OUTPUT->box_end();
8524 return highlight($query, $return);
8530 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8532 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8533 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8535 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8538 * Calls parent::__construct with specific arguments
8540 public function __construct() {
8541 $this->nosave = true;
8542 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8546 * Always returns true
8548 * @return true
8550 public function get_setting() {
8551 return true;
8555 * Always returns true
8557 * @return true
8559 public function get_defaultsetting() {
8560 return true;
8564 * Always returns '' and doesn't write anything
8566 * @param mixed $data string or array, must not be NULL
8567 * @return string Always returns ''
8569 public function write_setting($data) {
8570 // Do not write any setting.
8571 return '';
8575 * Search to find if Query is related to content bank plugin
8577 * @param string $query The string to search for
8578 * @return bool true for related false for not
8580 public function is_related($query) {
8581 if (parent::is_related($query)) {
8582 return true;
8584 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8585 foreach ($types as $type) {
8586 if (strpos($type->component, $query) !== false ||
8587 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8588 return true;
8591 return false;
8595 * Return XHTML to display control
8597 * @param mixed $data Unused
8598 * @param string $query
8599 * @return string highlight
8601 public function output_html($data, $query='') {
8602 global $CFG, $OUTPUT;
8603 $return = '';
8605 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8606 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8607 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8609 $table = new html_table();
8610 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8611 $table->align = array('left', 'center', 'center', 'center', 'center');
8612 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8613 $table->data = array();
8614 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8616 $totalenabled = 0;
8617 $count = 0;
8618 foreach ($types as $type) {
8619 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8620 $totalenabled++;
8624 foreach ($types as $type) {
8625 $url = new moodle_url('/admin/contentbank.php',
8626 array('sesskey' => sesskey(), 'name' => $type->name));
8628 $class = '';
8629 $strtypename = $type->displayname;
8630 if ($type->is_enabled()) {
8631 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8632 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8633 } else {
8634 $class = 'dimmed_text';
8635 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8636 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8639 $updown = '';
8640 if ($count) {
8641 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8642 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8643 } else {
8644 $updown .= $spacer;
8646 if ($count < count($types) - 1) {
8647 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8648 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8649 } else {
8650 $updown .= $spacer;
8653 $settings = '';
8654 if ($type->get_settings_url()) {
8655 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8658 $uninstall = '';
8659 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8660 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8663 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8664 if ($class) {
8665 $row->attributes['class'] = $class;
8667 $table->data[] = $row;
8668 $count++;
8670 $return .= html_writer::table($table);
8671 return highlight($query, $return);
8676 * Initialise admin page - this function does require login and permission
8677 * checks specified in page definition.
8679 * This function must be called on each admin page before other code.
8681 * @global moodle_page $PAGE
8683 * @param string $section name of page
8684 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8685 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8686 * added to the turn blocks editing on/off form, so this page reloads correctly.
8687 * @param string $actualurl if the actual page being viewed is not the normal one for this
8688 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8689 * @param array $options Additional options that can be specified for page setup.
8690 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8691 * nosearch - Do not display search bar
8693 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8694 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8696 $PAGE->set_context(null); // hack - set context to something, by default to system context
8698 $site = get_site();
8699 require_login(null, false);
8701 if (!empty($options['pagelayout'])) {
8702 // A specific page layout has been requested.
8703 $PAGE->set_pagelayout($options['pagelayout']);
8704 } else if ($section === 'upgradesettings') {
8705 $PAGE->set_pagelayout('maintenance');
8706 } else {
8707 $PAGE->set_pagelayout('admin');
8710 $adminroot = admin_get_root(false, false); // settings not required for external pages
8711 $extpage = $adminroot->locate($section, true);
8713 $hassiteconfig = has_capability('moodle/site:config', context_system::instance());
8714 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8715 // The requested section isn't in the admin tree
8716 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8717 if (!$hassiteconfig) {
8718 // The requested section could depend on a different capability
8719 // but most likely the user has inadequate capabilities
8720 throw new \moodle_exception('accessdenied', 'admin');
8721 } else {
8722 throw new \moodle_exception('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8726 // this eliminates our need to authenticate on the actual pages
8727 if (!$extpage->check_access()) {
8728 throw new \moodle_exception('accessdenied', 'admin');
8729 die;
8732 navigation_node::require_admin_tree();
8734 // $PAGE->set_extra_button($extrabutton); TODO
8736 if (!$actualurl) {
8737 $actualurl = $extpage->url;
8740 $PAGE->set_url($actualurl, $extraurlparams);
8741 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8742 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8745 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8746 // During initial install.
8747 $strinstallation = get_string('installation', 'install');
8748 $strsettings = get_string('settings');
8749 $PAGE->navbar->add($strsettings);
8750 $PAGE->set_title($strinstallation);
8751 $PAGE->set_heading($strinstallation);
8752 $PAGE->set_cacheable(false);
8753 return;
8756 // Locate the current item on the navigation and make it active when found.
8757 $path = $extpage->path;
8758 $node = $PAGE->settingsnav;
8759 while ($node && count($path) > 0) {
8760 $node = $node->get(array_pop($path));
8762 if ($node) {
8763 $node->make_active();
8766 // Normal case.
8767 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8768 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8769 $USER->editing = $adminediting;
8772 $visiblepathtosection = array_reverse($extpage->visiblepath);
8774 if ($PAGE->user_allowed_editing() && !$PAGE->theme->haseditswitch) {
8775 if ($PAGE->user_is_editing()) {
8776 $caption = get_string('blockseditoff');
8777 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8778 } else {
8779 $caption = get_string('blocksediton');
8780 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8782 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8785 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8786 $PAGE->set_heading($SITE->fullname);
8788 if ($hassiteconfig && empty($options['nosearch'])) {
8789 $PAGE->add_header_action($OUTPUT->render_from_template('core_admin/header_search_input', [
8790 'action' => new moodle_url('/admin/search.php'),
8791 'query' => $PAGE->url->get_param('query'),
8792 ]));
8795 // prevent caching in nav block
8796 $PAGE->navigation->clear_cache();
8800 * Returns the reference to admin tree root
8802 * @return object admin_root object
8804 function admin_get_root($reload=false, $requirefulltree=true) {
8805 global $CFG, $DB, $OUTPUT, $ADMIN;
8807 if (is_null($ADMIN)) {
8808 // create the admin tree!
8809 $ADMIN = new admin_root($requirefulltree);
8812 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8813 $ADMIN->purge_children($requirefulltree);
8816 if (!$ADMIN->loaded) {
8817 // we process this file first to create categories first and in correct order
8818 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8820 // now we process all other files in admin/settings to build the admin tree
8821 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8822 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8823 continue;
8825 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8826 // plugins are loaded last - they may insert pages anywhere
8827 continue;
8829 require($file);
8831 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8833 $ADMIN->loaded = true;
8836 return $ADMIN;
8839 /// settings utility functions
8842 * This function applies default settings.
8843 * Because setting the defaults of some settings can enable other settings,
8844 * this function is called recursively until no more new settings are found.
8846 * @param object $node, NULL means complete tree, null by default
8847 * @param bool $unconditional if true overrides all values with defaults, true by default
8848 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8849 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8850 * @return array $settingsoutput The names and values of the changed settings
8852 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8853 $counter = 0;
8855 if (is_null($node)) {
8856 core_plugin_manager::reset_caches();
8857 $node = admin_get_root(true, true);
8858 $counter = count($settingsoutput);
8861 if ($node instanceof admin_category) {
8862 $entries = array_keys($node->children);
8863 foreach ($entries as $entry) {
8864 $settingsoutput = admin_apply_default_settings(
8865 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8869 } else if ($node instanceof admin_settingpage) {
8870 foreach ($node->settings as $setting) {
8871 if (!$unconditional && !is_null($setting->get_setting())) {
8872 // Do not override existing defaults.
8873 continue;
8875 $defaultsetting = $setting->get_defaultsetting();
8876 if (is_null($defaultsetting)) {
8877 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8878 continue;
8881 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8883 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8884 $admindefaultsettings[$settingname] = $settingname;
8885 $settingsoutput[$settingname] = $defaultsetting;
8887 // Set the default for this setting.
8888 $setting->write_setting($defaultsetting);
8889 $setting->write_setting_flags(null);
8890 } else {
8891 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8896 // Call this function recursively until all settings are processed.
8897 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8898 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8900 // Just in case somebody modifies the list of active plugins directly.
8901 core_plugin_manager::reset_caches();
8903 return $settingsoutput;
8907 * Store changed settings, this function updates the errors variable in $ADMIN
8909 * @param object $formdata from form
8910 * @return int number of changed settings
8912 function admin_write_settings($formdata) {
8913 global $CFG, $SITE, $DB;
8915 $olddbsessions = !empty($CFG->dbsessions);
8916 $formdata = (array)$formdata;
8918 $data = array();
8919 foreach ($formdata as $fullname=>$value) {
8920 if (strpos($fullname, 's_') !== 0) {
8921 continue; // not a config value
8923 $data[$fullname] = $value;
8926 $adminroot = admin_get_root();
8927 $settings = admin_find_write_settings($adminroot, $data);
8929 $count = 0;
8930 foreach ($settings as $fullname=>$setting) {
8931 /** @var $setting admin_setting */
8932 $original = $setting->get_setting();
8933 $error = $setting->write_setting($data[$fullname]);
8934 if ($error !== '') {
8935 $adminroot->errors[$fullname] = new stdClass();
8936 $adminroot->errors[$fullname]->data = $data[$fullname];
8937 $adminroot->errors[$fullname]->id = $setting->get_id();
8938 $adminroot->errors[$fullname]->error = $error;
8939 } else {
8940 $setting->write_setting_flags($data);
8942 if ($setting->post_write_settings($original)) {
8943 $count++;
8947 if ($olddbsessions != !empty($CFG->dbsessions)) {
8948 require_logout();
8951 // Now update $SITE - just update the fields, in case other people have a
8952 // a reference to it (e.g. $PAGE, $COURSE).
8953 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8954 foreach (get_object_vars($newsite) as $field => $value) {
8955 $SITE->$field = $value;
8958 // now reload all settings - some of them might depend on the changed
8959 admin_get_root(true);
8960 return $count;
8964 * Internal recursive function - finds all settings from submitted form
8966 * @param object $node Instance of admin_category, or admin_settingpage
8967 * @param array $data
8968 * @return array
8970 function admin_find_write_settings($node, $data) {
8971 $return = array();
8973 if (empty($data)) {
8974 return $return;
8977 if ($node instanceof admin_category) {
8978 if ($node->check_access()) {
8979 $entries = array_keys($node->children);
8980 foreach ($entries as $entry) {
8981 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8985 } else if ($node instanceof admin_settingpage) {
8986 if ($node->check_access()) {
8987 foreach ($node->settings as $setting) {
8988 $fullname = $setting->get_full_name();
8989 if (array_key_exists($fullname, $data)) {
8990 $return[$fullname] = $setting;
8997 return $return;
9001 * Internal function - prints the search results
9003 * @param string $query String to search for
9004 * @return string empty or XHTML
9006 function admin_search_settings_html($query) {
9007 global $CFG, $OUTPUT, $PAGE;
9009 if (core_text::strlen($query) < 2) {
9010 return '';
9012 $query = core_text::strtolower($query);
9014 $adminroot = admin_get_root();
9015 $findings = $adminroot->search($query);
9016 $savebutton = false;
9018 $tpldata = (object) [
9019 'actionurl' => $PAGE->url->out(false),
9020 'results' => [],
9021 'sesskey' => sesskey(),
9024 foreach ($findings as $found) {
9025 $page = $found->page;
9026 $settings = $found->settings;
9027 if ($page->is_hidden()) {
9028 // hidden pages are not displayed in search results
9029 continue;
9032 $heading = highlight($query, $page->visiblename);
9033 $headingurl = null;
9034 if ($page instanceof admin_externalpage) {
9035 $headingurl = new moodle_url($page->url);
9036 } else if ($page instanceof admin_settingpage) {
9037 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
9038 } else {
9039 continue;
9042 // Locate the page in the admin root and populate its visiblepath attribute.
9043 $path = array();
9044 $located = $adminroot->locate($page->name, true);
9045 if ($located) {
9046 foreach ($located->visiblepath as $pathitem) {
9047 array_unshift($path, (string) $pathitem);
9051 $sectionsettings = [];
9052 if (!empty($settings)) {
9053 foreach ($settings as $setting) {
9054 if (empty($setting->nosave)) {
9055 $savebutton = true;
9057 $fullname = $setting->get_full_name();
9058 if (array_key_exists($fullname, $adminroot->errors)) {
9059 $data = $adminroot->errors[$fullname]->data;
9060 } else {
9061 $data = $setting->get_setting();
9062 // do not use defaults if settings not available - upgradesettings handles the defaults!
9064 $sectionsettings[] = $setting->output_html($data, $query);
9068 $tpldata->results[] = (object) [
9069 'title' => $heading,
9070 'path' => $path,
9071 'url' => $headingurl->out(false),
9072 'settings' => $sectionsettings
9076 $tpldata->showsave = $savebutton;
9077 $tpldata->hasresults = !empty($tpldata->results);
9079 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
9083 * Internal function - returns arrays of html pages with uninitialised settings
9085 * @param object $node Instance of admin_category or admin_settingpage
9086 * @return array
9088 function admin_output_new_settings_by_page($node) {
9089 global $OUTPUT;
9090 $return = array();
9092 if ($node instanceof admin_category) {
9093 $entries = array_keys($node->children);
9094 foreach ($entries as $entry) {
9095 $return += admin_output_new_settings_by_page($node->children[$entry]);
9098 } else if ($node instanceof admin_settingpage) {
9099 $newsettings = array();
9100 foreach ($node->settings as $setting) {
9101 if (is_null($setting->get_setting())) {
9102 $newsettings[] = $setting;
9105 if (count($newsettings) > 0) {
9106 $adminroot = admin_get_root();
9107 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
9108 $page .= '<fieldset class="adminsettings">'."\n";
9109 foreach ($newsettings as $setting) {
9110 $fullname = $setting->get_full_name();
9111 if (array_key_exists($fullname, $adminroot->errors)) {
9112 $data = $adminroot->errors[$fullname]->data;
9113 } else {
9114 $data = $setting->get_setting();
9115 if (is_null($data)) {
9116 $data = $setting->get_defaultsetting();
9119 $page .= '<div class="clearer"><!-- --></div>'."\n";
9120 $page .= $setting->output_html($data);
9122 $page .= '</fieldset>';
9123 $return[$node->name] = $page;
9127 return $return;
9131 * Format admin settings
9133 * @param object $setting
9134 * @param string $title label element
9135 * @param string $form form fragment, html code - not highlighted automatically
9136 * @param string $description
9137 * @param mixed $label link label to id, true by default or string being the label to connect it to
9138 * @param string $warning warning text
9139 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9140 * @param string $query search query to be highlighted
9141 * @return string XHTML
9143 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9144 global $CFG, $OUTPUT;
9146 $context = (object) [
9147 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
9148 'fullname' => $setting->get_full_name(),
9151 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9152 if ($label === true) {
9153 $context->labelfor = $setting->get_id();
9154 } else if ($label === false) {
9155 $context->labelfor = '';
9156 } else {
9157 $context->labelfor = $label;
9160 $form .= $setting->output_setting_flags();
9162 $context->warning = $warning;
9163 $context->override = '';
9164 if (empty($setting->plugin)) {
9165 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
9166 $context->override = get_string('configoverride', 'admin');
9168 } else {
9169 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
9170 $context->override = get_string('configoverride', 'admin');
9174 $defaults = array();
9175 if (!is_null($defaultinfo)) {
9176 if ($defaultinfo === '') {
9177 $defaultinfo = get_string('emptysettingvalue', 'admin');
9179 $defaults[] = $defaultinfo;
9182 $context->default = null;
9183 $setting->get_setting_flag_defaults($defaults);
9184 if (!empty($defaults)) {
9185 $defaultinfo = implode(', ', $defaults);
9186 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9187 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9191 $context->error = '';
9192 $adminroot = admin_get_root();
9193 if (array_key_exists($context->fullname, $adminroot->errors)) {
9194 $context->error = $adminroot->errors[$context->fullname]->error;
9197 if ($dependenton = $setting->get_dependent_on()) {
9198 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9201 $context->id = 'admin-' . $setting->name;
9202 $context->title = highlightfast($query, $title);
9203 $context->name = highlightfast($query, $context->name);
9204 $context->description = highlight($query, markdown_to_html($description));
9205 $context->element = $form;
9206 $context->forceltr = $setting->get_force_ltr();
9207 $context->customcontrol = $setting->has_custom_form_control();
9209 return $OUTPUT->render_from_template('core_admin/setting', $context);
9213 * Based on find_new_settings{@link ()} in upgradesettings.php
9214 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9216 * @param object $node Instance of admin_category, or admin_settingpage
9217 * @return boolean true if any settings haven't been initialised, false if they all have
9219 function any_new_admin_settings($node) {
9221 if ($node instanceof admin_category) {
9222 $entries = array_keys($node->children);
9223 foreach ($entries as $entry) {
9224 if (any_new_admin_settings($node->children[$entry])) {
9225 return true;
9229 } else if ($node instanceof admin_settingpage) {
9230 foreach ($node->settings as $setting) {
9231 if ($setting->get_setting() === NULL) {
9232 return true;
9237 return false;
9241 * Given a table and optionally a column name should replaces be done?
9243 * @param string $table name
9244 * @param string $column name
9245 * @return bool success or fail
9247 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9249 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9250 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9251 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9253 // Additional skip tables.
9254 if (!empty($additionalskiptables)) {
9255 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9258 // Don't process these.
9259 if (in_array($table, $skiptables)) {
9260 return false;
9263 // To be safe never replace inside a table that looks related to logging.
9264 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9265 return false;
9268 // Do column based exclusions.
9269 if (!empty($column)) {
9270 // Don't touch anything that looks like a hash.
9271 if (preg_match('/hash$/', $column)) {
9272 return false;
9276 return true;
9280 * Moved from admin/replace.php so that we can use this in cron
9282 * @param string $search string to look for
9283 * @param string $replace string to replace
9284 * @return bool success or fail
9286 function db_replace($search, $replace, $additionalskiptables = '') {
9287 global $DB, $CFG, $OUTPUT;
9289 // Turn off time limits, sometimes upgrades can be slow.
9290 core_php_time_limit::raise();
9292 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9293 return false;
9295 foreach ($tables as $table) {
9297 if (!db_should_replace($table, '', $additionalskiptables)) {
9298 continue;
9301 if ($columns = $DB->get_columns($table)) {
9302 $DB->set_debug(true);
9303 foreach ($columns as $column) {
9304 if (!db_should_replace($table, $column->name)) {
9305 continue;
9307 $DB->replace_all_text($table, $column, $search, $replace);
9309 $DB->set_debug(false);
9313 // delete modinfo caches
9314 rebuild_course_cache(0, true);
9316 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9317 $blocks = core_component::get_plugin_list('block');
9318 foreach ($blocks as $blockname=>$fullblock) {
9319 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9320 continue;
9323 if (!is_readable($fullblock.'/lib.php')) {
9324 continue;
9327 $function = 'block_'.$blockname.'_global_db_replace';
9328 include_once($fullblock.'/lib.php');
9329 if (!function_exists($function)) {
9330 continue;
9333 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9334 $function($search, $replace);
9335 echo $OUTPUT->notification("...finished", 'notifysuccess');
9338 // Trigger an event.
9339 $eventargs = [
9340 'context' => context_system::instance(),
9341 'other' => [
9342 'search' => $search,
9343 'replace' => $replace
9346 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9347 $event->trigger();
9349 purge_all_caches();
9351 return true;
9355 * Manage repository settings
9357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9359 class admin_setting_managerepository extends admin_setting {
9360 /** @var string */
9361 private $baseurl;
9364 * calls parent::__construct with specific arguments
9366 public function __construct() {
9367 global $CFG;
9368 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9369 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9373 * Always returns true, does nothing
9375 * @return true
9377 public function get_setting() {
9378 return true;
9382 * Always returns true does nothing
9384 * @return true
9386 public function get_defaultsetting() {
9387 return true;
9391 * Always returns s_managerepository
9393 * @return string Always return 's_managerepository'
9395 public function get_full_name() {
9396 return 's_managerepository';
9400 * Always returns '' doesn't do anything
9402 public function write_setting($data) {
9403 $url = $this->baseurl . '&amp;new=' . $data;
9404 return '';
9405 // TODO
9406 // Should not use redirect and exit here
9407 // Find a better way to do this.
9408 // redirect($url);
9409 // exit;
9413 * Searches repository plugins for one that matches $query
9415 * @param string $query The string to search for
9416 * @return bool true if found, false if not
9418 public function is_related($query) {
9419 if (parent::is_related($query)) {
9420 return true;
9423 $repositories= core_component::get_plugin_list('repository');
9424 foreach ($repositories as $p => $dir) {
9425 if (strpos($p, $query) !== false) {
9426 return true;
9429 foreach (repository::get_types() as $instance) {
9430 $title = $instance->get_typename();
9431 if (strpos(core_text::strtolower($title), $query) !== false) {
9432 return true;
9435 return false;
9439 * Helper function that generates a moodle_url object
9440 * relevant to the repository
9443 function repository_action_url($repository) {
9444 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9448 * Builds XHTML to display the control
9450 * @param string $data Unused
9451 * @param string $query
9452 * @return string XHTML
9454 public function output_html($data, $query='') {
9455 global $CFG, $USER, $OUTPUT;
9457 // Get strings that are used
9458 $strshow = get_string('on', 'repository');
9459 $strhide = get_string('off', 'repository');
9460 $strdelete = get_string('disabled', 'repository');
9462 $actionchoicesforexisting = array(
9463 'show' => $strshow,
9464 'hide' => $strhide,
9465 'delete' => $strdelete
9468 $actionchoicesfornew = array(
9469 'newon' => $strshow,
9470 'newoff' => $strhide,
9471 'delete' => $strdelete
9474 $return = '';
9475 $return .= $OUTPUT->box_start('generalbox');
9477 // Set strings that are used multiple times
9478 $settingsstr = get_string('settings');
9479 $disablestr = get_string('disable');
9481 // Table to list plug-ins
9482 $table = new html_table();
9483 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9484 $table->align = array('left', 'center', 'center', 'center', 'center');
9485 $table->data = array();
9487 // Get list of used plug-ins
9488 $repositorytypes = repository::get_types();
9489 if (!empty($repositorytypes)) {
9490 // Array to store plugins being used
9491 $alreadyplugins = array();
9492 $totalrepositorytypes = count($repositorytypes);
9493 $updowncount = 1;
9494 foreach ($repositorytypes as $i) {
9495 $settings = '';
9496 $typename = $i->get_typename();
9497 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9498 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9499 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9501 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9502 // Calculate number of instances in order to display them for the Moodle administrator
9503 if (!empty($instanceoptionnames)) {
9504 $params = array();
9505 $params['context'] = array(context_system::instance());
9506 $params['onlyvisible'] = false;
9507 $params['type'] = $typename;
9508 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9509 // site instances
9510 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9511 $params['context'] = array();
9512 $instances = repository::static_function($typename, 'get_instances', $params);
9513 $courseinstances = array();
9514 $userinstances = array();
9516 foreach ($instances as $instance) {
9517 $repocontext = context::instance_by_id($instance->instance->contextid);
9518 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9519 $courseinstances[] = $instance;
9520 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9521 $userinstances[] = $instance;
9524 // course instances
9525 $instancenumber = count($courseinstances);
9526 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9528 // user private instances
9529 $instancenumber = count($userinstances);
9530 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9531 } else {
9532 $admininstancenumbertext = "";
9533 $courseinstancenumbertext = "";
9534 $userinstancenumbertext = "";
9537 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9539 $settings .= $OUTPUT->container_start('mdl-left');
9540 $settings .= '<br/>';
9541 $settings .= $admininstancenumbertext;
9542 $settings .= '<br/>';
9543 $settings .= $courseinstancenumbertext;
9544 $settings .= '<br/>';
9545 $settings .= $userinstancenumbertext;
9546 $settings .= $OUTPUT->container_end();
9548 // Get the current visibility
9549 if ($i->get_visible()) {
9550 $currentaction = 'show';
9551 } else {
9552 $currentaction = 'hide';
9555 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9557 // Display up/down link
9558 $updown = '';
9559 // Should be done with CSS instead.
9560 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9562 if ($updowncount > 1) {
9563 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9564 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9566 else {
9567 $updown .= $spacer;
9569 if ($updowncount < $totalrepositorytypes) {
9570 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9571 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9573 else {
9574 $updown .= $spacer;
9577 $updowncount++;
9579 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9581 if (!in_array($typename, $alreadyplugins)) {
9582 $alreadyplugins[] = $typename;
9587 // Get all the plugins that exist on disk
9588 $plugins = core_component::get_plugin_list('repository');
9589 if (!empty($plugins)) {
9590 foreach ($plugins as $plugin => $dir) {
9591 // Check that it has not already been listed
9592 if (!in_array($plugin, $alreadyplugins)) {
9593 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9594 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9599 $return .= html_writer::table($table);
9600 $return .= $OUTPUT->box_end();
9601 return highlight($query, $return);
9606 * Special checkbox for enable mobile web service
9607 * If enable then we store the service id of the mobile service into config table
9608 * If disable then we unstore the service id from the config table
9610 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9612 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9613 private $restuse;
9616 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9618 * @return boolean
9620 private function is_protocol_cap_allowed() {
9621 global $DB, $CFG;
9623 // If the $this->restuse variable is not set, it needs to be set.
9624 if (empty($this->restuse) and $this->restuse!==false) {
9625 $params = array();
9626 $params['permission'] = CAP_ALLOW;
9627 $params['roleid'] = $CFG->defaultuserroleid;
9628 $params['capability'] = 'webservice/rest:use';
9629 $this->restuse = $DB->record_exists('role_capabilities', $params);
9632 return $this->restuse;
9636 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9637 * @param type $status true to allow, false to not set
9639 private function set_protocol_cap($status) {
9640 global $CFG;
9641 if ($status and !$this->is_protocol_cap_allowed()) {
9642 //need to allow the cap
9643 $permission = CAP_ALLOW;
9644 $assign = true;
9645 } else if (!$status and $this->is_protocol_cap_allowed()){
9646 //need to disallow the cap
9647 $permission = CAP_INHERIT;
9648 $assign = true;
9650 if (!empty($assign)) {
9651 $systemcontext = context_system::instance();
9652 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9657 * Builds XHTML to display the control.
9658 * The main purpose of this overloading is to display a warning when https
9659 * is not supported by the server
9660 * @param string $data Unused
9661 * @param string $query
9662 * @return string XHTML
9664 public function output_html($data, $query='') {
9665 global $OUTPUT;
9666 $html = parent::output_html($data, $query);
9668 if ((string)$data === $this->yes) {
9669 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9670 foreach ($notifications as $notification) {
9671 $message = get_string($notification[0], $notification[1]);
9672 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9676 return $html;
9680 * Retrieves the current setting using the objects name
9682 * @return string
9684 public function get_setting() {
9685 global $CFG;
9687 // First check if is not set.
9688 $result = $this->config_read($this->name);
9689 if (is_null($result)) {
9690 return null;
9693 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9694 // Or if web services aren't enabled this can't be,
9695 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9696 return 0;
9699 require_once($CFG->dirroot . '/webservice/lib.php');
9700 $webservicemanager = new webservice();
9701 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9702 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9703 return $result;
9704 } else {
9705 return 0;
9710 * Save the selected setting
9712 * @param string $data The selected site
9713 * @return string empty string or error message
9715 public function write_setting($data) {
9716 global $DB, $CFG;
9718 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9719 if (empty($CFG->defaultuserroleid)) {
9720 return '';
9723 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9725 require_once($CFG->dirroot . '/webservice/lib.php');
9726 $webservicemanager = new webservice();
9728 $updateprotocol = false;
9729 if ((string)$data === $this->yes) {
9730 //code run when enable mobile web service
9731 //enable web service systeme if necessary
9732 set_config('enablewebservices', true);
9734 //enable mobile service
9735 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9736 $mobileservice->enabled = 1;
9737 $webservicemanager->update_external_service($mobileservice);
9739 // Enable REST server.
9740 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9742 if (!in_array('rest', $activeprotocols)) {
9743 $activeprotocols[] = 'rest';
9744 $updateprotocol = true;
9747 if ($updateprotocol) {
9748 set_config('webserviceprotocols', implode(',', $activeprotocols));
9751 // Allow rest:use capability for authenticated user.
9752 $this->set_protocol_cap(true);
9753 } else {
9754 // Disable the mobile service.
9755 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9756 $mobileservice->enabled = 0;
9757 $webservicemanager->update_external_service($mobileservice);
9760 return (parent::write_setting($data));
9765 * Special class for management of external services
9767 * @author Petr Skoda (skodak)
9769 class admin_setting_manageexternalservices extends admin_setting {
9771 * Calls parent::__construct with specific arguments
9773 public function __construct() {
9774 $this->nosave = true;
9775 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9779 * Always returns true, does nothing
9781 * @return true
9783 public function get_setting() {
9784 return true;
9788 * Always returns true, does nothing
9790 * @return true
9792 public function get_defaultsetting() {
9793 return true;
9797 * Always returns '', does not write anything
9799 * @return string Always returns ''
9801 public function write_setting($data) {
9802 // do not write any setting
9803 return '';
9807 * Checks if $query is one of the available external services
9809 * @param string $query The string to search for
9810 * @return bool Returns true if found, false if not
9812 public function is_related($query) {
9813 global $DB;
9815 if (parent::is_related($query)) {
9816 return true;
9819 $services = $DB->get_records('external_services', array(), 'id, name');
9820 foreach ($services as $service) {
9821 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9822 return true;
9825 return false;
9829 * Builds the XHTML to display the control
9831 * @param string $data Unused
9832 * @param string $query
9833 * @return string
9835 public function output_html($data, $query='') {
9836 global $CFG, $OUTPUT, $DB;
9838 // display strings
9839 $stradministration = get_string('administration');
9840 $stredit = get_string('edit');
9841 $strservice = get_string('externalservice', 'webservice');
9842 $strdelete = get_string('delete');
9843 $strplugin = get_string('plugin', 'admin');
9844 $stradd = get_string('add');
9845 $strfunctions = get_string('functions', 'webservice');
9846 $strusers = get_string('users');
9847 $strserviceusers = get_string('serviceusers', 'webservice');
9849 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9850 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9851 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9853 // built in services
9854 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9855 $return = "";
9856 if (!empty($services)) {
9857 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9861 $table = new html_table();
9862 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9863 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9864 $table->id = 'builtinservices';
9865 $table->attributes['class'] = 'admintable externalservices generaltable';
9866 $table->data = array();
9868 // iterate through auth plugins and add to the display table
9869 foreach ($services as $service) {
9870 $name = $service->name;
9872 // hide/show link
9873 if ($service->enabled) {
9874 $displayname = "<span>$name</span>";
9875 } else {
9876 $displayname = "<span class=\"dimmed_text\">$name</span>";
9879 $plugin = $service->component;
9881 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9883 if ($service->restrictedusers) {
9884 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9885 } else {
9886 $users = get_string('allusers', 'webservice');
9889 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9891 // add a row to the table
9892 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9894 $return .= html_writer::table($table);
9897 // Custom services
9898 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9899 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9901 $table = new html_table();
9902 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9903 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9904 $table->id = 'customservices';
9905 $table->attributes['class'] = 'admintable externalservices generaltable';
9906 $table->data = array();
9908 // iterate through auth plugins and add to the display table
9909 foreach ($services as $service) {
9910 $name = $service->name;
9912 // hide/show link
9913 if ($service->enabled) {
9914 $displayname = "<span>$name</span>";
9915 } else {
9916 $displayname = "<span class=\"dimmed_text\">$name</span>";
9919 // delete link
9920 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9922 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9924 if ($service->restrictedusers) {
9925 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9926 } else {
9927 $users = get_string('allusers', 'webservice');
9930 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9932 // add a row to the table
9933 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9935 // add new custom service option
9936 $return .= html_writer::table($table);
9938 $return .= '<br />';
9939 // add a token to the table
9940 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9942 return highlight($query, $return);
9947 * Special class for overview of external services
9949 * @author Jerome Mouneyrac
9951 class admin_setting_webservicesoverview extends admin_setting {
9954 * Calls parent::__construct with specific arguments
9956 public function __construct() {
9957 $this->nosave = true;
9958 parent::__construct('webservicesoverviewui',
9959 get_string('webservicesoverview', 'webservice'), '', '');
9963 * Always returns true, does nothing
9965 * @return true
9967 public function get_setting() {
9968 return true;
9972 * Always returns true, does nothing
9974 * @return true
9976 public function get_defaultsetting() {
9977 return true;
9981 * Always returns '', does not write anything
9983 * @return string Always returns ''
9985 public function write_setting($data) {
9986 // do not write any setting
9987 return '';
9991 * Builds the XHTML to display the control
9993 * @param string $data Unused
9994 * @param string $query
9995 * @return string
9997 public function output_html($data, $query='') {
9998 global $CFG, $OUTPUT;
10000 $return = "";
10001 $brtag = html_writer::empty_tag('br');
10003 /// One system controlling Moodle with Token
10004 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
10005 $table = new html_table();
10006 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10007 get_string('description'));
10008 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10009 $table->id = 'onesystemcontrol';
10010 $table->attributes['class'] = 'admintable wsoverview generaltable';
10011 $table->data = array();
10013 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
10014 . $brtag . $brtag;
10016 /// 1. Enable Web Services
10017 $row = array();
10018 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10019 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10020 array('href' => $url));
10021 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10022 if ($CFG->enablewebservices) {
10023 $status = get_string('yes');
10025 $row[1] = $status;
10026 $row[2] = get_string('enablewsdescription', 'webservice');
10027 $table->data[] = $row;
10029 /// 2. Enable protocols
10030 $row = array();
10031 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10032 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10033 array('href' => $url));
10034 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10035 //retrieve activated protocol
10036 $active_protocols = empty($CFG->webserviceprotocols) ?
10037 array() : explode(',', $CFG->webserviceprotocols);
10038 if (!empty($active_protocols)) {
10039 $status = "";
10040 foreach ($active_protocols as $protocol) {
10041 $status .= $protocol . $brtag;
10044 $row[1] = $status;
10045 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10046 $table->data[] = $row;
10048 /// 3. Create user account
10049 $row = array();
10050 $url = new moodle_url("/user/editadvanced.php?id=-1");
10051 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
10052 array('href' => $url));
10053 $row[1] = "";
10054 $row[2] = get_string('createuserdescription', 'webservice');
10055 $table->data[] = $row;
10057 /// 4. Add capability to users
10058 $row = array();
10059 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10060 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
10061 array('href' => $url));
10062 $row[1] = "";
10063 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
10064 $table->data[] = $row;
10066 /// 5. Select a web service
10067 $row = array();
10068 $url = new moodle_url("/admin/settings.php?section=externalservices");
10069 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10070 array('href' => $url));
10071 $row[1] = "";
10072 $row[2] = get_string('createservicedescription', 'webservice');
10073 $table->data[] = $row;
10075 /// 6. Add functions
10076 $row = array();
10077 $url = new moodle_url("/admin/settings.php?section=externalservices");
10078 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10079 array('href' => $url));
10080 $row[1] = "";
10081 $row[2] = get_string('addfunctionsdescription', 'webservice');
10082 $table->data[] = $row;
10084 /// 7. Add the specific user
10085 $row = array();
10086 $url = new moodle_url("/admin/settings.php?section=externalservices");
10087 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
10088 array('href' => $url));
10089 $row[1] = "";
10090 $row[2] = get_string('selectspecificuserdescription', 'webservice');
10091 $table->data[] = $row;
10093 /// 8. Create token for the specific user
10094 $row = array();
10095 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
10096 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
10097 array('href' => $url));
10098 $row[1] = "";
10099 $row[2] = get_string('createtokenforuserdescription', 'webservice');
10100 $table->data[] = $row;
10102 /// 9. Enable the documentation
10103 $row = array();
10104 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
10105 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
10106 array('href' => $url));
10107 $status = '<span class="warning">' . get_string('no') . '</span>';
10108 if ($CFG->enablewsdocumentation) {
10109 $status = get_string('yes');
10111 $row[1] = $status;
10112 $row[2] = get_string('enabledocumentationdescription', 'webservice');
10113 $table->data[] = $row;
10115 /// 10. Test the service
10116 $row = array();
10117 $url = new moodle_url("/admin/webservice/testclient.php");
10118 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10119 array('href' => $url));
10120 $row[1] = "";
10121 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10122 $table->data[] = $row;
10124 $return .= html_writer::table($table);
10126 /// Users as clients with token
10127 $return .= $brtag . $brtag . $brtag;
10128 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10129 $table = new html_table();
10130 $table->head = array(get_string('step', 'webservice'), get_string('status'),
10131 get_string('description'));
10132 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
10133 $table->id = 'userasclients';
10134 $table->attributes['class'] = 'admintable wsoverview generaltable';
10135 $table->data = array();
10137 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10138 $brtag . $brtag;
10140 /// 1. Enable Web Services
10141 $row = array();
10142 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10143 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
10144 array('href' => $url));
10145 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10146 if ($CFG->enablewebservices) {
10147 $status = get_string('yes');
10149 $row[1] = $status;
10150 $row[2] = get_string('enablewsdescription', 'webservice');
10151 $table->data[] = $row;
10153 /// 2. Enable protocols
10154 $row = array();
10155 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10156 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
10157 array('href' => $url));
10158 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10159 //retrieve activated protocol
10160 $active_protocols = empty($CFG->webserviceprotocols) ?
10161 array() : explode(',', $CFG->webserviceprotocols);
10162 if (!empty($active_protocols)) {
10163 $status = "";
10164 foreach ($active_protocols as $protocol) {
10165 $status .= $protocol . $brtag;
10168 $row[1] = $status;
10169 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10170 $table->data[] = $row;
10173 /// 3. Select a web service
10174 $row = array();
10175 $url = new moodle_url("/admin/settings.php?section=externalservices");
10176 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
10177 array('href' => $url));
10178 $row[1] = "";
10179 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10180 $table->data[] = $row;
10182 /// 4. Add functions
10183 $row = array();
10184 $url = new moodle_url("/admin/settings.php?section=externalservices");
10185 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
10186 array('href' => $url));
10187 $row[1] = "";
10188 $row[2] = get_string('addfunctionsdescription', 'webservice');
10189 $table->data[] = $row;
10191 /// 5. Add capability to users
10192 $row = array();
10193 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10194 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
10195 array('href' => $url));
10196 $row[1] = "";
10197 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10198 $table->data[] = $row;
10200 /// 6. Test the service
10201 $row = array();
10202 $url = new moodle_url("/admin/webservice/testclient.php");
10203 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
10204 array('href' => $url));
10205 $row[1] = "";
10206 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10207 $table->data[] = $row;
10209 $return .= html_writer::table($table);
10211 return highlight($query, $return);
10218 * Special class for web service protocol administration.
10220 * @author Petr Skoda (skodak)
10222 class admin_setting_managewebserviceprotocols extends admin_setting {
10225 * Calls parent::__construct with specific arguments
10227 public function __construct() {
10228 $this->nosave = true;
10229 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10233 * Always returns true, does nothing
10235 * @return true
10237 public function get_setting() {
10238 return true;
10242 * Always returns true, does nothing
10244 * @return true
10246 public function get_defaultsetting() {
10247 return true;
10251 * Always returns '', does not write anything
10253 * @return string Always returns ''
10255 public function write_setting($data) {
10256 // do not write any setting
10257 return '';
10261 * Checks if $query is one of the available webservices
10263 * @param string $query The string to search for
10264 * @return bool Returns true if found, false if not
10266 public function is_related($query) {
10267 if (parent::is_related($query)) {
10268 return true;
10271 $protocols = core_component::get_plugin_list('webservice');
10272 foreach ($protocols as $protocol=>$location) {
10273 if (strpos($protocol, $query) !== false) {
10274 return true;
10276 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10277 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10278 return true;
10281 return false;
10285 * Builds the XHTML to display the control
10287 * @param string $data Unused
10288 * @param string $query
10289 * @return string
10291 public function output_html($data, $query='') {
10292 global $CFG, $OUTPUT;
10294 // display strings
10295 $stradministration = get_string('administration');
10296 $strsettings = get_string('settings');
10297 $stredit = get_string('edit');
10298 $strprotocol = get_string('protocol', 'webservice');
10299 $strenable = get_string('enable');
10300 $strdisable = get_string('disable');
10301 $strversion = get_string('version');
10303 $protocols_available = core_component::get_plugin_list('webservice');
10304 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10305 ksort($protocols_available);
10307 foreach ($activeprotocols as $key => $protocol) {
10308 if (empty($protocols_available[$protocol])) {
10309 unset($activeprotocols[$key]);
10313 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10314 if (in_array('xmlrpc', $activeprotocols)) {
10315 $notify = new \core\output\notification(get_string('xmlrpcwebserviceenabled', 'admin'),
10316 \core\output\notification::NOTIFY_WARNING);
10317 $return .= $OUTPUT->render($notify);
10319 $return .= $OUTPUT->box_start('generalbox webservicesui');
10321 $table = new html_table();
10322 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10323 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10324 $table->id = 'webserviceprotocols';
10325 $table->attributes['class'] = 'admintable generaltable';
10326 $table->data = array();
10328 // iterate through auth plugins and add to the display table
10329 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10330 foreach ($protocols_available as $protocol => $location) {
10331 $name = get_string('pluginname', 'webservice_'.$protocol);
10333 $plugin = new stdClass();
10334 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10335 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10337 $version = isset($plugin->version) ? $plugin->version : '';
10339 // hide/show link
10340 if (in_array($protocol, $activeprotocols)) {
10341 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10342 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10343 $displayname = "<span>$name</span>";
10344 } else {
10345 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10346 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10347 $displayname = "<span class=\"dimmed_text\">$name</span>";
10350 // settings link
10351 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10352 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10353 } else {
10354 $settings = '';
10357 // add a row to the table
10358 $table->data[] = array($displayname, $version, $hideshow, $settings);
10360 $return .= html_writer::table($table);
10361 $return .= get_string('configwebserviceplugins', 'webservice');
10362 $return .= $OUTPUT->box_end();
10364 return highlight($query, $return);
10369 * Colour picker
10371 * @copyright 2010 Sam Hemelryk
10372 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10374 class admin_setting_configcolourpicker extends admin_setting {
10377 * Information for previewing the colour
10379 * @var array|null
10381 protected $previewconfig = null;
10384 * Use default when empty.
10386 protected $usedefaultwhenempty = true;
10390 * @param string $name
10391 * @param string $visiblename
10392 * @param string $description
10393 * @param string $defaultsetting
10394 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10396 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10397 $usedefaultwhenempty = true) {
10398 $this->previewconfig = $previewconfig;
10399 $this->usedefaultwhenempty = $usedefaultwhenempty;
10400 parent::__construct($name, $visiblename, $description, $defaultsetting);
10401 $this->set_force_ltr(true);
10405 * Return the setting
10407 * @return mixed returns config if successful else null
10409 public function get_setting() {
10410 return $this->config_read($this->name);
10414 * Saves the setting
10416 * @param string $data
10417 * @return bool
10419 public function write_setting($data) {
10420 $data = $this->validate($data);
10421 if ($data === false) {
10422 return get_string('validateerror', 'admin');
10424 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10428 * Validates the colour that was entered by the user
10430 * @param string $data
10431 * @return string|false
10433 protected function validate($data) {
10435 * List of valid HTML colour names
10437 * @var array
10439 $colornames = array(
10440 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10441 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10442 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10443 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10444 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10445 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10446 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10447 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10448 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10449 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10450 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10451 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10452 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10453 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10454 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10455 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10456 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10457 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10458 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10459 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10460 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10461 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10462 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10463 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10464 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10465 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10466 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10467 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10468 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10469 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10470 'whitesmoke', 'yellow', 'yellowgreen'
10473 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10474 if (strpos($data, '#')!==0) {
10475 $data = '#'.$data;
10477 return $data;
10478 } else if (in_array(strtolower($data), $colornames)) {
10479 return $data;
10480 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10481 return $data;
10482 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10483 return $data;
10484 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10485 return $data;
10486 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10487 return $data;
10488 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10489 return $data;
10490 } else if (empty($data)) {
10491 if ($this->usedefaultwhenempty){
10492 return $this->defaultsetting;
10493 } else {
10494 return '';
10496 } else {
10497 return false;
10502 * Generates the HTML for the setting
10504 * @global moodle_page $PAGE
10505 * @global core_renderer $OUTPUT
10506 * @param string $data
10507 * @param string $query
10509 public function output_html($data, $query = '') {
10510 global $PAGE, $OUTPUT;
10512 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10513 $context = (object) [
10514 'id' => $this->get_id(),
10515 'name' => $this->get_full_name(),
10516 'value' => $data,
10517 'icon' => $icon->export_for_template($OUTPUT),
10518 'haspreviewconfig' => !empty($this->previewconfig),
10519 'forceltr' => $this->get_force_ltr(),
10520 'readonly' => $this->is_readonly(),
10523 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10524 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10526 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10527 $this->get_defaultsetting(), $query);
10534 * Class used for uploading of one file into file storage,
10535 * the file name is stored in config table.
10537 * Please note you need to implement your own '_pluginfile' callback function,
10538 * this setting only stores the file, it does not deal with file serving.
10540 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10543 class admin_setting_configstoredfile extends admin_setting {
10544 /** @var array file area options - should be one file only */
10545 protected $options;
10546 /** @var string name of the file area */
10547 protected $filearea;
10548 /** @var int intemid */
10549 protected $itemid;
10550 /** @var string used for detection of changes */
10551 protected $oldhashes;
10554 * Create new stored file setting.
10556 * @param string $name low level setting name
10557 * @param string $visiblename human readable setting name
10558 * @param string $description description of setting
10559 * @param mixed $filearea file area for file storage
10560 * @param int $itemid itemid for file storage
10561 * @param array $options file area options
10563 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10564 parent::__construct($name, $visiblename, $description, '');
10565 $this->filearea = $filearea;
10566 $this->itemid = $itemid;
10567 $this->options = (array)$options;
10568 $this->customcontrol = true;
10572 * Applies defaults and returns all options.
10573 * @return array
10575 protected function get_options() {
10576 global $CFG;
10578 require_once("$CFG->libdir/filelib.php");
10579 require_once("$CFG->dirroot/repository/lib.php");
10580 $defaults = array(
10581 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10582 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10583 'context' => context_system::instance());
10584 foreach($this->options as $k => $v) {
10585 $defaults[$k] = $v;
10588 return $defaults;
10591 public function get_setting() {
10592 return $this->config_read($this->name);
10595 public function write_setting($data) {
10596 global $USER;
10598 // Let's not deal with validation here, this is for admins only.
10599 $current = $this->get_setting();
10600 if (empty($data) && $current === null) {
10601 // This will be the case when applying default settings (installation).
10602 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10603 } else if (!is_number($data)) {
10604 // Draft item id is expected here!
10605 return get_string('errorsetting', 'admin');
10608 $options = $this->get_options();
10609 $fs = get_file_storage();
10610 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10612 $this->oldhashes = null;
10613 if ($current) {
10614 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10615 if ($file = $fs->get_file_by_hash($hash)) {
10616 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10618 unset($file);
10621 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10622 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10623 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10624 // with an error because the draft area does not exist, as he did not use it.
10625 $usercontext = context_user::instance($USER->id);
10626 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10627 return get_string('errorsetting', 'admin');
10631 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10632 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10634 $filepath = '';
10635 if ($files) {
10636 /** @var stored_file $file */
10637 $file = reset($files);
10638 $filepath = $file->get_filepath().$file->get_filename();
10641 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10644 public function post_write_settings($original) {
10645 $options = $this->get_options();
10646 $fs = get_file_storage();
10647 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10649 $current = $this->get_setting();
10650 $newhashes = null;
10651 if ($current) {
10652 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10653 if ($file = $fs->get_file_by_hash($hash)) {
10654 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10656 unset($file);
10659 if ($this->oldhashes === $newhashes) {
10660 $this->oldhashes = null;
10661 return false;
10663 $this->oldhashes = null;
10665 $callbackfunction = $this->updatedcallback;
10666 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10667 $callbackfunction($this->get_full_name());
10669 return true;
10672 public function output_html($data, $query = '') {
10673 global $CFG;
10675 $options = $this->get_options();
10676 $id = $this->get_id();
10677 $elname = $this->get_full_name();
10678 $draftitemid = file_get_submitted_draft_itemid($elname);
10679 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10680 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10682 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10683 require_once("$CFG->dirroot/lib/form/filemanager.php");
10685 $fmoptions = new stdClass();
10686 $fmoptions->mainfile = $options['mainfile'];
10687 $fmoptions->maxbytes = $options['maxbytes'];
10688 $fmoptions->maxfiles = $options['maxfiles'];
10689 $fmoptions->subdirs = $options['subdirs'];
10690 $fmoptions->accepted_types = $options['accepted_types'];
10691 $fmoptions->return_types = $options['return_types'];
10692 $fmoptions->context = $options['context'];
10693 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10695 $fm = new MoodleQuickForm_filemanager($elname, $this->visiblename, ['id' => $id], $fmoptions);
10696 $fm->setValue($draftitemid);
10698 return format_admin_setting($this, $this->visiblename,
10699 '<div class="form-filemanager" data-fieldtype="filemanager">' . $fm->toHtml() . '</div>',
10700 $this->description, true, '', '', $query);
10706 * Administration interface for user specified regular expressions for device detection.
10708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10710 class admin_setting_devicedetectregex extends admin_setting {
10713 * Calls parent::__construct with specific args
10715 * @param string $name
10716 * @param string $visiblename
10717 * @param string $description
10718 * @param mixed $defaultsetting
10720 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10721 global $CFG;
10722 parent::__construct($name, $visiblename, $description, $defaultsetting);
10726 * Return the current setting(s)
10728 * @return array Current settings array
10730 public function get_setting() {
10731 global $CFG;
10733 $config = $this->config_read($this->name);
10734 if (is_null($config)) {
10735 return null;
10738 return $this->prepare_form_data($config);
10742 * Save selected settings
10744 * @param array $data Array of settings to save
10745 * @return bool
10747 public function write_setting($data) {
10748 if (empty($data)) {
10749 $data = array();
10752 if ($this->config_write($this->name, $this->process_form_data($data))) {
10753 return ''; // success
10754 } else {
10755 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10760 * Return XHTML field(s) for regexes
10762 * @param array $data Array of options to set in HTML
10763 * @return string XHTML string for the fields and wrapping div(s)
10765 public function output_html($data, $query='') {
10766 global $OUTPUT;
10768 $context = (object) [
10769 'expressions' => [],
10770 'name' => $this->get_full_name()
10773 if (empty($data)) {
10774 $looplimit = 1;
10775 } else {
10776 $looplimit = (count($data)/2)+1;
10779 for ($i=0; $i<$looplimit; $i++) {
10781 $expressionname = 'expression'.$i;
10783 if (!empty($data[$expressionname])){
10784 $expression = $data[$expressionname];
10785 } else {
10786 $expression = '';
10789 $valuename = 'value'.$i;
10791 if (!empty($data[$valuename])){
10792 $value = $data[$valuename];
10793 } else {
10794 $value= '';
10797 $context->expressions[] = [
10798 'index' => $i,
10799 'expression' => $expression,
10800 'value' => $value
10804 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10806 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10810 * Converts the string of regexes
10812 * @see self::process_form_data()
10813 * @param $regexes string of regexes
10814 * @return array of form fields and their values
10816 protected function prepare_form_data($regexes) {
10818 $regexes = json_decode($regexes);
10820 $form = array();
10822 $i = 0;
10824 foreach ($regexes as $value => $regex) {
10825 $expressionname = 'expression'.$i;
10826 $valuename = 'value'.$i;
10828 $form[$expressionname] = $regex;
10829 $form[$valuename] = $value;
10830 $i++;
10833 return $form;
10837 * Converts the data from admin settings form into a string of regexes
10839 * @see self::prepare_form_data()
10840 * @param array $data array of admin form fields and values
10841 * @return false|string of regexes
10843 protected function process_form_data(array $form) {
10845 $count = count($form); // number of form field values
10847 if ($count % 2) {
10848 // we must get five fields per expression
10849 return false;
10852 $regexes = array();
10853 for ($i = 0; $i < $count / 2; $i++) {
10854 $expressionname = "expression".$i;
10855 $valuename = "value".$i;
10857 $expression = trim($form['expression'.$i]);
10858 $value = trim($form['value'.$i]);
10860 if (empty($expression)){
10861 continue;
10864 $regexes[$value] = $expression;
10867 $regexes = json_encode($regexes);
10869 return $regexes;
10875 * Multiselect for current modules
10877 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10879 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10880 private $excludesystem;
10883 * Calls parent::__construct - note array $choices is not required
10885 * @param string $name setting name
10886 * @param string $visiblename localised setting name
10887 * @param string $description setting description
10888 * @param array $defaultsetting a plain array of default module ids
10889 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10891 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10892 $excludesystem = true) {
10893 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10894 $this->excludesystem = $excludesystem;
10898 * Loads an array of current module choices
10900 * @return bool always return true
10902 public function load_choices() {
10903 if (is_array($this->choices)) {
10904 return true;
10906 $this->choices = array();
10908 global $CFG, $DB;
10909 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10910 foreach ($records as $record) {
10911 // Exclude modules if the code doesn't exist
10912 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10913 // Also exclude system modules (if specified)
10914 if (!($this->excludesystem &&
10915 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10916 MOD_ARCHETYPE_SYSTEM)) {
10917 $this->choices[$record->id] = $record->name;
10921 return true;
10926 * Admin setting to show if a php extension is enabled or not.
10928 * @copyright 2013 Damyon Wiese
10929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10931 class admin_setting_php_extension_enabled extends admin_setting {
10933 /** @var string The name of the extension to check for */
10934 private $extension;
10937 * Calls parent::__construct with specific arguments
10939 public function __construct($name, $visiblename, $description, $extension) {
10940 $this->extension = $extension;
10941 $this->nosave = true;
10942 parent::__construct($name, $visiblename, $description, '');
10946 * Always returns true, does nothing
10948 * @return true
10950 public function get_setting() {
10951 return true;
10955 * Always returns true, does nothing
10957 * @return true
10959 public function get_defaultsetting() {
10960 return true;
10964 * Always returns '', does not write anything
10966 * @return string Always returns ''
10968 public function write_setting($data) {
10969 // Do not write any setting.
10970 return '';
10974 * Outputs the html for this setting.
10975 * @return string Returns an XHTML string
10977 public function output_html($data, $query='') {
10978 global $OUTPUT;
10980 $o = '';
10981 if (!extension_loaded($this->extension)) {
10982 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10984 $o .= format_admin_setting($this, $this->visiblename, $warning);
10986 return $o;
10991 * Server timezone setting.
10993 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10994 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10995 * @author Petr Skoda <petr.skoda@totaralms.com>
10997 class admin_setting_servertimezone extends admin_setting_configselect {
10999 * Constructor.
11001 public function __construct() {
11002 $default = core_date::get_default_php_timezone();
11003 if ($default === 'UTC') {
11004 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
11005 $default = 'Europe/London';
11008 parent::__construct('timezone',
11009 new lang_string('timezone', 'core_admin'),
11010 new lang_string('configtimezone', 'core_admin'), $default, null);
11014 * Lazy load timezone options.
11015 * @return bool true if loaded, false if error
11017 public function load_choices() {
11018 global $CFG;
11019 if (is_array($this->choices)) {
11020 return true;
11023 $current = isset($CFG->timezone) ? $CFG->timezone : null;
11024 $this->choices = core_date::get_list_of_timezones($current, false);
11025 if ($current == 99) {
11026 // Do not show 99 unless it is current value, we want to get rid of it over time.
11027 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
11028 core_date::get_default_php_timezone());
11031 return true;
11036 * Forced user timezone setting.
11038 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11040 * @author Petr Skoda <petr.skoda@totaralms.com>
11042 class admin_setting_forcetimezone extends admin_setting_configselect {
11044 * Constructor.
11046 public function __construct() {
11047 parent::__construct('forcetimezone',
11048 new lang_string('forcetimezone', 'core_admin'),
11049 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
11053 * Lazy load timezone options.
11054 * @return bool true if loaded, false if error
11056 public function load_choices() {
11057 global $CFG;
11058 if (is_array($this->choices)) {
11059 return true;
11062 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
11063 $this->choices = core_date::get_list_of_timezones($current, true);
11064 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
11066 return true;
11072 * Search setup steps info.
11074 * @package core
11075 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
11076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11078 class admin_setting_searchsetupinfo extends admin_setting {
11081 * Calls parent::__construct with specific arguments
11083 public function __construct() {
11084 $this->nosave = true;
11085 parent::__construct('searchsetupinfo', '', '', '');
11089 * Always returns true, does nothing
11091 * @return true
11093 public function get_setting() {
11094 return true;
11098 * Always returns true, does nothing
11100 * @return true
11102 public function get_defaultsetting() {
11103 return true;
11107 * Always returns '', does not write anything
11109 * @param array $data
11110 * @return string Always returns ''
11112 public function write_setting($data) {
11113 // Do not write any setting.
11114 return '';
11118 * Builds the HTML to display the control
11120 * @param string $data Unused
11121 * @param string $query
11122 * @return string
11124 public function output_html($data, $query='') {
11125 global $CFG, $OUTPUT, $ADMIN;
11127 $return = '';
11128 $brtag = html_writer::empty_tag('br');
11130 $searchareas = \core_search\manager::get_search_areas_list();
11131 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
11132 $anyindexed = false;
11133 foreach ($searchareas as $areaid => $searcharea) {
11134 list($componentname, $varname) = $searcharea->get_config_var_name();
11135 if (get_config($componentname, $varname . '_indexingstart')) {
11136 $anyindexed = true;
11137 break;
11141 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11143 $table = new html_table();
11144 $table->head = array(get_string('step', 'search'), get_string('status'));
11145 $table->colclasses = array('leftalign step', 'leftalign status');
11146 $table->id = 'searchsetup';
11147 $table->attributes['class'] = 'admintable generaltable';
11148 $table->data = array();
11150 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11152 // Select a search engine.
11153 $row = array();
11154 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11155 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
11156 array('href' => $url));
11158 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11159 if (!empty($CFG->searchengine)) {
11160 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11161 array('class' => 'badge badge-success'));
11164 $row[1] = $status;
11165 $table->data[] = $row;
11167 // Available areas.
11168 $row = array();
11169 $url = new moodle_url('/admin/searchareas.php');
11170 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11171 array('href' => $url));
11173 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11174 if ($anyenabled) {
11175 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11178 $row[1] = $status;
11179 $table->data[] = $row;
11181 // Setup search engine.
11182 $row = array();
11183 if (empty($CFG->searchengine)) {
11184 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11185 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11186 } else {
11187 if ($ADMIN->locate('search' . $CFG->searchengine)) {
11188 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11189 $row[0] = '3. ' . html_writer::link($url, get_string('setupsearchengine', 'core_admin'));
11190 } else {
11191 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11194 // Check the engine status.
11195 $searchengine = \core_search\manager::search_engine_instance();
11196 try {
11197 $serverstatus = $searchengine->is_server_ready();
11198 } catch (\moodle_exception $e) {
11199 $serverstatus = $e->getMessage();
11201 if ($serverstatus === true) {
11202 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11203 } else {
11204 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11206 $row[1] = $status;
11208 $table->data[] = $row;
11210 // Indexed data.
11211 $row = array();
11212 $url = new moodle_url('/admin/searchareas.php');
11213 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11214 if ($anyindexed) {
11215 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11216 } else {
11217 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11219 $row[1] = $status;
11220 $table->data[] = $row;
11222 // Enable global search.
11223 $row = array();
11224 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11225 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11226 array('href' => $url));
11227 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11228 if (\core_search\manager::is_global_search_enabled()) {
11229 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11231 $row[1] = $status;
11232 $table->data[] = $row;
11234 // Replace front page search.
11235 $row = array();
11236 $url = new moodle_url("/admin/search.php?query=searchincludeallcourses");
11237 $row[0] = '6. ' . html_writer::tag('a', get_string('replacefrontsearch', 'admin'),
11238 array('href' => $url));
11239 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11240 if (\core_search\manager::can_replace_course_search()) {
11241 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11243 $row[1] = $status;
11244 $table->data[] = $row;
11246 $return .= html_writer::table($table);
11248 return highlight($query, $return);
11254 * Used to validate the contents of SCSS code and ensuring they are parsable.
11256 * It does not attempt to detect undefined SCSS variables because it is designed
11257 * to be used without knowledge of other config/scss included.
11259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11260 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11262 class admin_setting_scsscode extends admin_setting_configtextarea {
11265 * Validate the contents of the SCSS to ensure its parsable. Does not
11266 * attempt to detect undefined scss variables.
11268 * @param string $data The scss code from text field.
11269 * @return mixed bool true for success or string:error on failure.
11271 public function validate($data) {
11272 if (empty($data)) {
11273 return true;
11276 $scss = new core_scss();
11277 try {
11278 $scss->compile($data);
11279 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11280 return get_string('scssinvalid', 'admin', $e->getMessage());
11281 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11282 // Silently ignore this - it could be a scss variable defined from somewhere
11283 // else which we are not examining here.
11284 return true;
11287 return true;
11293 * Administration setting to define a list of file types.
11295 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11296 * @copyright 2017 David Mudrák <david@moodle.com>
11297 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11299 class admin_setting_filetypes extends admin_setting_configtext {
11301 /** @var array Allow selection from these file types only. */
11302 protected $onlytypes = [];
11304 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11305 protected $allowall = true;
11307 /** @var core_form\filetypes_util instance to use as a helper. */
11308 protected $util = null;
11311 * Constructor.
11313 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11314 * @param string $visiblename Localised label of the setting
11315 * @param string $description Localised description of the setting
11316 * @param string $defaultsetting Default setting value.
11317 * @param array $options Setting widget options, an array with optional keys:
11318 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11319 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11321 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11323 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11325 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11326 $this->onlytypes = $options['onlytypes'];
11329 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11330 $this->allowall = (bool)$options['allowall'];
11333 $this->util = new \core_form\filetypes_util();
11337 * Normalize the user's input and write it to the database as comma separated list.
11339 * Comma separated list as a text representation of the array was chosen to
11340 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11342 * @param string $data Value submitted by the admin.
11343 * @return string Epty string if all good, error message otherwise.
11345 public function write_setting($data) {
11346 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11350 * Validate data before storage
11352 * @param string $data The setting values provided by the admin
11353 * @return bool|string True if ok, the string if error found
11355 public function validate($data) {
11356 $parentcheck = parent::validate($data);
11357 if ($parentcheck !== true) {
11358 return $parentcheck;
11361 // Check for unknown file types.
11362 if ($unknown = $this->util->get_unknown_file_types($data)) {
11363 return get_string('filetypesunknown', 'core_form', implode(', ', $unknown));
11366 // Check for disallowed file types.
11367 if ($notlisted = $this->util->get_not_listed($data, $this->onlytypes)) {
11368 return get_string('filetypesnotallowed', 'core_form', implode(', ', $notlisted));
11371 return true;
11375 * Return an HTML string for the setting element.
11377 * @param string $data The current setting value
11378 * @param string $query Admin search query to be highlighted
11379 * @return string HTML to be displayed
11381 public function output_html($data, $query='') {
11382 global $OUTPUT, $PAGE;
11384 $default = $this->get_defaultsetting();
11385 $context = (object) [
11386 'id' => $this->get_id(),
11387 'name' => $this->get_full_name(),
11388 'value' => $data,
11389 'descriptions' => $this->util->describe_file_types($data),
11391 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11393 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11394 $this->get_id(),
11395 $this->visiblename->out(),
11396 $this->onlytypes,
11397 $this->allowall,
11400 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11404 * Should the values be always displayed in LTR mode?
11406 * We always return true here because these values are not RTL compatible.
11408 * @return bool True because these values are not RTL compatible.
11410 public function get_force_ltr() {
11411 return true;
11416 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11419 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11421 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11424 * Constructor.
11426 * @param string $name
11427 * @param string $visiblename
11428 * @param string $description
11429 * @param mixed $defaultsetting string or array
11430 * @param mixed $paramtype
11431 * @param string $cols
11432 * @param string $rows
11434 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11435 $cols = '60', $rows = '8') {
11436 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11437 // Pre-set force LTR to false.
11438 $this->set_force_ltr(false);
11442 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11444 * @param string $data The age of digital consent map from text field.
11445 * @return mixed bool true for success or string:error on failure.
11447 public function validate($data) {
11448 if (empty($data)) {
11449 return true;
11452 try {
11453 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11454 } catch (\moodle_exception $e) {
11455 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11458 return true;
11463 * Selection of plugins that can work as site policy handlers
11465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11466 * @copyright 2018 Marina Glancy
11468 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11471 * Constructor
11472 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11473 * for ones in config_plugins.
11474 * @param string $visiblename localised
11475 * @param string $description long localised info
11476 * @param string $defaultsetting
11478 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11479 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11483 * Lazy-load the available choices for the select box
11485 public function load_choices() {
11486 if (during_initial_install()) {
11487 return false;
11489 if (is_array($this->choices)) {
11490 return true;
11493 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11494 $manager = new \core_privacy\local\sitepolicy\manager();
11495 $plugins = $manager->get_all_handlers();
11496 foreach ($plugins as $pname => $unused) {
11497 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11498 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11501 return true;
11506 * Used to validate theme presets code and ensuring they compile well.
11508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11509 * @copyright 2019 Bas Brands <bas@moodle.com>
11511 class admin_setting_configthemepreset extends admin_setting_configselect {
11513 /** @var string The name of the theme to check for */
11514 private $themename;
11517 * Constructor
11518 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11519 * or 'myplugin/mysetting' for ones in config_plugins.
11520 * @param string $visiblename localised
11521 * @param string $description long localised info
11522 * @param string|int $defaultsetting
11523 * @param array $choices array of $value=>$label for each selection
11524 * @param string $themename name of theme to check presets for.
11526 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11527 $this->themename = $themename;
11528 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11532 * Write settings if validated
11534 * @param string $data
11535 * @return string
11537 public function write_setting($data) {
11538 $validated = $this->validate($data);
11539 if ($validated !== true) {
11540 return $validated;
11542 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11546 * Validate the preset file to ensure its parsable.
11548 * @param string $data The preset file chosen.
11549 * @return mixed bool true for success or string:error on failure.
11551 public function validate($data) {
11553 if (in_array($data, ['default.scss', 'plain.scss'])) {
11554 return true;
11557 $fs = get_file_storage();
11558 $theme = theme_config::load($this->themename);
11559 $context = context_system::instance();
11561 // If the preset has not changed there is no need to validate it.
11562 if ($theme->settings->preset == $data) {
11563 return true;
11566 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11567 // This operation uses a lot of resources.
11568 raise_memory_limit(MEMORY_EXTRA);
11569 core_php_time_limit::raise(300);
11571 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11572 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11574 $compiler = new core_scss();
11575 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11576 $compiler->append_raw_scss($presetfile->get_content());
11577 if ($scssproperties = $theme->get_scss_property()) {
11578 $compiler->setImportPaths($scssproperties[0]);
11580 $compiler->append_raw_scss($theme->get_extra_scss_code());
11582 try {
11583 $compiler->to_css();
11584 } catch (Exception $e) {
11585 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11588 // Try to save memory.
11589 $compiler = null;
11590 unset($compiler);
11593 return true;
11598 * Selection of plugins that can work as H5P libraries handlers
11600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11601 * @copyright 2020 Sara Arjona <sara@moodle.com>
11603 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11606 * Constructor
11607 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11608 * for ones in config_plugins.
11609 * @param string $visiblename localised
11610 * @param string $description long localised info
11611 * @param string $defaultsetting
11613 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11614 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11618 * Lazy-load the available choices for the select box
11620 public function load_choices() {
11621 if (during_initial_install()) {
11622 return false;
11624 if (is_array($this->choices)) {
11625 return true;
11628 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11629 foreach ($this->choices as $name => $class) {
11630 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11631 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11634 return true;