Merge branch 'MDL-45849-selfenrol' of https://github.com/Peterburnett/moodle
[moodle.git] / lib / adminlib.php
blob1a0235c1da97993794a76feb18c31e168558fb48
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 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
136 $subpluginsfile = "{$base}/db/subplugins.json";
137 if (file_exists($subpluginsfile)) {
138 $subplugins = (array) json_decode(file_get_contents($subpluginsfile))->plugintypes;
139 } else if (file_exists("{$base}/db/subplugins.php")) {
140 debugging('Use of subplugins.php has been deprecated. ' .
141 'Please update your plugin to provide a subplugins.json file instead.',
142 DEBUG_DEVELOPER);
143 $subplugins = [];
144 include("{$base}/db/subplugins.php");
147 if (!empty($subplugins)) {
148 foreach (array_keys($subplugins) as $subplugintype) {
149 $instances = core_component::get_plugin_list($subplugintype);
150 foreach ($instances as $subpluginname => $notusedpluginpath) {
151 uninstall_plugin($subplugintype, $subpluginname);
157 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
159 if ($type === 'mod') {
160 $pluginname = $name; // eg. 'forum'
161 if (get_string_manager()->string_exists('modulename', $component)) {
162 $strpluginname = get_string('modulename', $component);
163 } else {
164 $strpluginname = $component;
167 } else {
168 $pluginname = $component;
169 if (get_string_manager()->string_exists('pluginname', $component)) {
170 $strpluginname = get_string('pluginname', $component);
171 } else {
172 $strpluginname = $component;
176 echo $OUTPUT->heading($pluginname);
178 // Delete all tag areas, collections and instances associated with this plugin.
179 core_tag_area::uninstall($component);
181 // Custom plugin uninstall.
182 $plugindirectory = core_component::get_plugin_directory($type, $name);
183 $uninstalllib = $plugindirectory . '/db/uninstall.php';
184 if (file_exists($uninstalllib)) {
185 require_once($uninstalllib);
186 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
187 if (function_exists($uninstallfunction)) {
188 // Do not verify result, let plugin complain if necessary.
189 $uninstallfunction();
193 // Specific plugin type cleanup.
194 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
195 if ($plugininfo) {
196 $plugininfo->uninstall_cleanup();
197 core_plugin_manager::reset_caches();
199 $plugininfo = null;
201 // perform clean-up task common for all the plugin/subplugin types
203 //delete the web service functions and pre-built services
204 require_once($CFG->dirroot.'/lib/externallib.php');
205 external_delete_descriptions($component);
207 // delete calendar events
208 $DB->delete_records('event', array('modulename' => $pluginname));
209 $DB->delete_records('event', ['component' => $component]);
211 // Delete scheduled tasks.
212 $DB->delete_records('task_scheduled', array('component' => $component));
214 // Delete Inbound Message datakeys.
215 $DB->delete_records_select('messageinbound_datakeys',
216 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
218 // Delete Inbound Message handlers.
219 $DB->delete_records('messageinbound_handlers', array('component' => $component));
221 // delete all the logs
222 $DB->delete_records('log', array('module' => $pluginname));
224 // delete log_display information
225 $DB->delete_records('log_display', array('component' => $component));
227 // delete the module configuration records
228 unset_all_config_for_plugin($component);
229 if ($type === 'mod') {
230 unset_all_config_for_plugin($pluginname);
233 // delete message provider
234 message_provider_uninstall($component);
236 // delete the plugin tables
237 $xmldbfilepath = $plugindirectory . '/db/install.xml';
238 drop_plugin_tables($component, $xmldbfilepath, false);
239 if ($type === 'mod' or $type === 'block') {
240 // non-frankenstyle table prefixes
241 drop_plugin_tables($name, $xmldbfilepath, false);
244 // delete the capabilities that were defined by this module
245 capabilities_cleanup($component);
247 // Delete all remaining files in the filepool owned by the component.
248 $fs = get_file_storage();
249 $fs->delete_component_files($component);
251 // Finally purge all caches.
252 purge_all_caches();
254 // Invalidate the hash used for upgrade detections.
255 set_config('allversionshash', '');
257 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
261 * Returns the version of installed component
263 * @param string $component component name
264 * @param string $source either 'disk' or 'installed' - where to get the version information from
265 * @return string|bool version number or false if the component is not found
267 function get_component_version($component, $source='installed') {
268 global $CFG, $DB;
270 list($type, $name) = core_component::normalize_component($component);
272 // moodle core or a core subsystem
273 if ($type === 'core') {
274 if ($source === 'installed') {
275 if (empty($CFG->version)) {
276 return false;
277 } else {
278 return $CFG->version;
280 } else {
281 if (!is_readable($CFG->dirroot.'/version.php')) {
282 return false;
283 } else {
284 $version = null; //initialize variable for IDEs
285 include($CFG->dirroot.'/version.php');
286 return $version;
291 // activity module
292 if ($type === 'mod') {
293 if ($source === 'installed') {
294 if ($CFG->version < 2013092001.02) {
295 return $DB->get_field('modules', 'version', array('name'=>$name));
296 } else {
297 return get_config('mod_'.$name, 'version');
300 } else {
301 $mods = core_component::get_plugin_list('mod');
302 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
303 return false;
304 } else {
305 $plugin = new stdClass();
306 $plugin->version = null;
307 $module = $plugin;
308 include($mods[$name].'/version.php');
309 return $plugin->version;
314 // block
315 if ($type === 'block') {
316 if ($source === 'installed') {
317 if ($CFG->version < 2013092001.02) {
318 return $DB->get_field('block', 'version', array('name'=>$name));
319 } else {
320 return get_config('block_'.$name, 'version');
322 } else {
323 $blocks = core_component::get_plugin_list('block');
324 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
325 return false;
326 } else {
327 $plugin = new stdclass();
328 include($blocks[$name].'/version.php');
329 return $plugin->version;
334 // all other plugin types
335 if ($source === 'installed') {
336 return get_config($type.'_'.$name, 'version');
337 } else {
338 $plugins = core_component::get_plugin_list($type);
339 if (empty($plugins[$name])) {
340 return false;
341 } else {
342 $plugin = new stdclass();
343 include($plugins[$name].'/version.php');
344 return $plugin->version;
350 * Delete all plugin tables
352 * @param string $name Name of plugin, used as table prefix
353 * @param string $file Path to install.xml file
354 * @param bool $feedback defaults to true
355 * @return bool Always returns true
357 function drop_plugin_tables($name, $file, $feedback=true) {
358 global $CFG, $DB;
360 // first try normal delete
361 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
362 return true;
365 // then try to find all tables that start with name and are not in any xml file
366 $used_tables = get_used_table_names();
368 $tables = $DB->get_tables();
370 /// Iterate over, fixing id fields as necessary
371 foreach ($tables as $table) {
372 if (in_array($table, $used_tables)) {
373 continue;
376 if (strpos($table, $name) !== 0) {
377 continue;
380 // found orphan table --> delete it
381 if ($DB->get_manager()->table_exists($table)) {
382 $xmldb_table = new xmldb_table($table);
383 $DB->get_manager()->drop_table($xmldb_table);
387 return true;
391 * Returns names of all known tables == tables that moodle knows about.
393 * @return array Array of lowercase table names
395 function get_used_table_names() {
396 $table_names = array();
397 $dbdirs = get_db_directories();
399 foreach ($dbdirs as $dbdir) {
400 $file = $dbdir.'/install.xml';
402 $xmldb_file = new xmldb_file($file);
404 if (!$xmldb_file->fileExists()) {
405 continue;
408 $loaded = $xmldb_file->loadXMLStructure();
409 $structure = $xmldb_file->getStructure();
411 if ($loaded and $tables = $structure->getTables()) {
412 foreach($tables as $table) {
413 $table_names[] = strtolower($table->getName());
418 return $table_names;
422 * Returns list of all directories where we expect install.xml files
423 * @return array Array of paths
425 function get_db_directories() {
426 global $CFG;
428 $dbdirs = array();
430 /// First, the main one (lib/db)
431 $dbdirs[] = $CFG->libdir.'/db';
433 /// Then, all the ones defined by core_component::get_plugin_types()
434 $plugintypes = core_component::get_plugin_types();
435 foreach ($plugintypes as $plugintype => $pluginbasedir) {
436 if ($plugins = core_component::get_plugin_list($plugintype)) {
437 foreach ($plugins as $plugin => $plugindir) {
438 $dbdirs[] = $plugindir.'/db';
443 return $dbdirs;
447 * Try to obtain or release the cron lock.
448 * @param string $name name of lock
449 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
450 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
451 * @return bool true if lock obtained
453 function set_cron_lock($name, $until, $ignorecurrent=false) {
454 global $DB;
455 if (empty($name)) {
456 debugging("Tried to get a cron lock for a null fieldname");
457 return false;
460 // remove lock by force == remove from config table
461 if (is_null($until)) {
462 set_config($name, null);
463 return true;
466 if (!$ignorecurrent) {
467 // read value from db - other processes might have changed it
468 $value = $DB->get_field('config', 'value', array('name'=>$name));
470 if ($value and $value > time()) {
471 //lock active
472 return false;
476 set_config($name, $until);
477 return true;
481 * Test if and critical warnings are present
482 * @return bool
484 function admin_critical_warnings_present() {
485 global $SESSION;
487 if (!has_capability('moodle/site:config', context_system::instance())) {
488 return 0;
491 if (!isset($SESSION->admin_critical_warning)) {
492 $SESSION->admin_critical_warning = 0;
493 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
494 $SESSION->admin_critical_warning = 1;
498 return $SESSION->admin_critical_warning;
502 * Detects if float supports at least 10 decimal digits
504 * Detects if float supports at least 10 decimal digits
505 * and also if float-->string conversion works as expected.
507 * @return bool true if problem found
509 function is_float_problem() {
510 $num1 = 2009010200.01;
511 $num2 = 2009010200.02;
513 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
517 * Try to verify that dataroot is not accessible from web.
519 * Try to verify that dataroot is not accessible from web.
520 * It is not 100% correct but might help to reduce number of vulnerable sites.
521 * Protection from httpd.conf and .htaccess is not detected properly.
523 * @uses INSECURE_DATAROOT_WARNING
524 * @uses INSECURE_DATAROOT_ERROR
525 * @param bool $fetchtest try to test public access by fetching file, default false
526 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
528 function is_dataroot_insecure($fetchtest=false) {
529 global $CFG;
531 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
533 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
534 $rp = strrev(trim($rp, '/'));
535 $rp = explode('/', $rp);
536 foreach($rp as $r) {
537 if (strpos($siteroot, '/'.$r.'/') === 0) {
538 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
539 } else {
540 break; // probably alias root
544 $siteroot = strrev($siteroot);
545 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
547 if (strpos($dataroot, $siteroot) !== 0) {
548 return false;
551 if (!$fetchtest) {
552 return INSECURE_DATAROOT_WARNING;
555 // now try all methods to fetch a test file using http protocol
557 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
558 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
559 $httpdocroot = $matches[1];
560 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
561 make_upload_directory('diag');
562 $testfile = $CFG->dataroot.'/diag/public.txt';
563 if (!file_exists($testfile)) {
564 file_put_contents($testfile, 'test file, do not delete');
565 @chmod($testfile, $CFG->filepermissions);
567 $teststr = trim(file_get_contents($testfile));
568 if (empty($teststr)) {
569 // hmm, strange
570 return INSECURE_DATAROOT_WARNING;
573 $testurl = $datarooturl.'/diag/public.txt';
574 if (extension_loaded('curl') and
575 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
576 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
577 ($ch = @curl_init($testurl)) !== false) {
578 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
579 curl_setopt($ch, CURLOPT_HEADER, false);
580 $data = curl_exec($ch);
581 if (!curl_errno($ch)) {
582 $data = trim($data);
583 if ($data === $teststr) {
584 curl_close($ch);
585 return INSECURE_DATAROOT_ERROR;
588 curl_close($ch);
591 if ($data = @file_get_contents($testurl)) {
592 $data = trim($data);
593 if ($data === $teststr) {
594 return INSECURE_DATAROOT_ERROR;
598 preg_match('|https?://([^/]+)|i', $testurl, $matches);
599 $sitename = $matches[1];
600 $error = 0;
601 if ($fp = @fsockopen($sitename, 80, $error)) {
602 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
603 $localurl = $matches[1];
604 $out = "GET $localurl HTTP/1.1\r\n";
605 $out .= "Host: $sitename\r\n";
606 $out .= "Connection: Close\r\n\r\n";
607 fwrite($fp, $out);
608 $data = '';
609 $incoming = false;
610 while (!feof($fp)) {
611 if ($incoming) {
612 $data .= fgets($fp, 1024);
613 } else if (@fgets($fp, 1024) === "\r\n") {
614 $incoming = true;
617 fclose($fp);
618 $data = trim($data);
619 if ($data === $teststr) {
620 return INSECURE_DATAROOT_ERROR;
624 return INSECURE_DATAROOT_WARNING;
628 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
630 function enable_cli_maintenance_mode() {
631 global $CFG, $SITE;
633 if (file_exists("$CFG->dataroot/climaintenance.html")) {
634 unlink("$CFG->dataroot/climaintenance.html");
637 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
638 $data = $CFG->maintenance_message;
639 $data = bootstrap_renderer::early_error_content($data, null, null, null);
640 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
642 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
643 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
645 } else {
646 $data = get_string('sitemaintenance', 'admin');
647 $data = bootstrap_renderer::early_error_content($data, null, null, null);
648 $data = bootstrap_renderer::plain_page(get_string('sitemaintenancetitle', 'admin', $SITE->fullname), $data);
651 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
652 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
655 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
659 * Interface for anything appearing in the admin tree
661 * The interface that is implemented by anything that appears in the admin tree
662 * block. It forces inheriting classes to define a method for checking user permissions
663 * and methods for finding something in the admin tree.
665 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
667 interface part_of_admin_tree {
670 * Finds a named part_of_admin_tree.
672 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
673 * and not parentable_part_of_admin_tree, then this function should only check if
674 * $this->name matches $name. If it does, it should return a reference to $this,
675 * otherwise, it should return a reference to NULL.
677 * If a class inherits parentable_part_of_admin_tree, this method should be called
678 * recursively on all child objects (assuming, of course, the parent object's name
679 * doesn't match the search criterion).
681 * @param string $name The internal name of the part_of_admin_tree we're searching for.
682 * @return mixed An object reference or a NULL reference.
684 public function locate($name);
687 * Removes named part_of_admin_tree.
689 * @param string $name The internal name of the part_of_admin_tree we want to remove.
690 * @return bool success.
692 public function prune($name);
695 * Search using query
696 * @param string $query
697 * @return mixed array-object structure of found settings and pages
699 public function search($query);
702 * Verifies current user's access to this part_of_admin_tree.
704 * Used to check if the current user has access to this part of the admin tree or
705 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
706 * then this method is usually just a call to has_capability() in the site context.
708 * If a class inherits parentable_part_of_admin_tree, this method should return the
709 * logical OR of the return of check_access() on all child objects.
711 * @return bool True if the user has access, false if she doesn't.
713 public function check_access();
716 * Mostly useful for removing of some parts of the tree in admin tree block.
718 * @return True is hidden from normal list view
720 public function is_hidden();
723 * Show we display Save button at the page bottom?
724 * @return bool
726 public function show_save();
731 * Interface implemented by any part_of_admin_tree that has children.
733 * The interface implemented by any part_of_admin_tree that can be a parent
734 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
735 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
736 * include an add method for adding other part_of_admin_tree objects as children.
738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
740 interface parentable_part_of_admin_tree extends part_of_admin_tree {
743 * Adds a part_of_admin_tree object to the admin tree.
745 * Used to add a part_of_admin_tree object to this object or a child of this
746 * object. $something should only be added if $destinationname matches
747 * $this->name. If it doesn't, add should be called on child objects that are
748 * also parentable_part_of_admin_tree's.
750 * $something should be appended as the last child in the $destinationname. If the
751 * $beforesibling is specified, $something should be prepended to it. If the given
752 * sibling is not found, $something should be appended to the end of $destinationname
753 * and a developer debugging message should be displayed.
755 * @param string $destinationname The internal name of the new parent for $something.
756 * @param part_of_admin_tree $something The object to be added.
757 * @return bool True on success, false on failure.
759 public function add($destinationname, $something, $beforesibling = null);
765 * The object used to represent folders (a.k.a. categories) in the admin tree block.
767 * Each admin_category object contains a number of part_of_admin_tree objects.
769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
771 class admin_category implements parentable_part_of_admin_tree {
773 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
774 protected $children;
775 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
776 public $name;
777 /** @var string The displayed name for this category. Usually obtained through get_string() */
778 public $visiblename;
779 /** @var bool Should this category be hidden in admin tree block? */
780 public $hidden;
781 /** @var mixed Either a string or an array or strings */
782 public $path;
783 /** @var mixed Either a string or an array or strings */
784 public $visiblepath;
786 /** @var array fast lookup category cache, all categories of one tree point to one cache */
787 protected $category_cache;
789 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
790 protected $sort = false;
791 /** @var bool If set to true children will be sorted in ascending order. */
792 protected $sortasc = true;
793 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
794 protected $sortsplit = true;
795 /** @var bool $sorted True if the children have been sorted and don't need resorting */
796 protected $sorted = false;
799 * Constructor for an empty admin category
801 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
802 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
803 * @param bool $hidden hide category in admin tree block, defaults to false
805 public function __construct($name, $visiblename, $hidden=false) {
806 $this->children = array();
807 $this->name = $name;
808 $this->visiblename = $visiblename;
809 $this->hidden = $hidden;
813 * Returns a reference to the part_of_admin_tree object with internal name $name.
815 * @param string $name The internal name of the object we want.
816 * @param bool $findpath initialize path and visiblepath arrays
817 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
818 * defaults to false
820 public function locate($name, $findpath=false) {
821 if (!isset($this->category_cache[$this->name])) {
822 // somebody much have purged the cache
823 $this->category_cache[$this->name] = $this;
826 if ($this->name == $name) {
827 if ($findpath) {
828 $this->visiblepath[] = $this->visiblename;
829 $this->path[] = $this->name;
831 return $this;
834 // quick category lookup
835 if (!$findpath and isset($this->category_cache[$name])) {
836 return $this->category_cache[$name];
839 $return = NULL;
840 foreach($this->children as $childid=>$unused) {
841 if ($return = $this->children[$childid]->locate($name, $findpath)) {
842 break;
846 if (!is_null($return) and $findpath) {
847 $return->visiblepath[] = $this->visiblename;
848 $return->path[] = $this->name;
851 return $return;
855 * Search using query
857 * @param string query
858 * @return mixed array-object structure of found settings and pages
860 public function search($query) {
861 $result = array();
862 foreach ($this->get_children() as $child) {
863 $subsearch = $child->search($query);
864 if (!is_array($subsearch)) {
865 debugging('Incorrect search result from '.$child->name);
866 continue;
868 $result = array_merge($result, $subsearch);
870 return $result;
874 * Removes part_of_admin_tree object with internal name $name.
876 * @param string $name The internal name of the object we want to remove.
877 * @return bool success
879 public function prune($name) {
881 if ($this->name == $name) {
882 return false; //can not remove itself
885 foreach($this->children as $precedence => $child) {
886 if ($child->name == $name) {
887 // clear cache and delete self
888 while($this->category_cache) {
889 // delete the cache, but keep the original array address
890 array_pop($this->category_cache);
892 unset($this->children[$precedence]);
893 return true;
894 } else if ($this->children[$precedence]->prune($name)) {
895 return true;
898 return false;
902 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
904 * By default the new part of the tree is appended as the last child of the parent. You
905 * can specify a sibling node that the new part should be prepended to. If the given
906 * sibling is not found, the part is appended to the end (as it would be by default) and
907 * a developer debugging message is displayed.
909 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
910 * @param string $destinationame The internal name of the immediate parent that we want for $something.
911 * @param mixed $something A part_of_admin_tree or setting instance to be added.
912 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
913 * @return bool True if successfully added, false if $something can not be added.
915 public function add($parentname, $something, $beforesibling = null) {
916 global $CFG;
918 $parent = $this->locate($parentname);
919 if (is_null($parent)) {
920 debugging('parent does not exist!');
921 return false;
924 if ($something instanceof part_of_admin_tree) {
925 if (!($parent instanceof parentable_part_of_admin_tree)) {
926 debugging('error - parts of tree can be inserted only into parentable parts');
927 return false;
929 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
930 // The name of the node is already used, simply warn the developer that this should not happen.
931 // It is intentional to check for the debug level before performing the check.
932 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
934 if (is_null($beforesibling)) {
935 // Append $something as the parent's last child.
936 $parent->children[] = $something;
937 } else {
938 if (!is_string($beforesibling) or trim($beforesibling) === '') {
939 throw new coding_exception('Unexpected value of the beforesibling parameter');
941 // Try to find the position of the sibling.
942 $siblingposition = null;
943 foreach ($parent->children as $childposition => $child) {
944 if ($child->name === $beforesibling) {
945 $siblingposition = $childposition;
946 break;
949 if (is_null($siblingposition)) {
950 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
951 $parent->children[] = $something;
952 } else {
953 $parent->children = array_merge(
954 array_slice($parent->children, 0, $siblingposition),
955 array($something),
956 array_slice($parent->children, $siblingposition)
960 if ($something instanceof admin_category) {
961 if (isset($this->category_cache[$something->name])) {
962 debugging('Duplicate admin category name: '.$something->name);
963 } else {
964 $this->category_cache[$something->name] = $something;
965 $something->category_cache =& $this->category_cache;
966 foreach ($something->children as $child) {
967 // just in case somebody already added subcategories
968 if ($child instanceof admin_category) {
969 if (isset($this->category_cache[$child->name])) {
970 debugging('Duplicate admin category name: '.$child->name);
971 } else {
972 $this->category_cache[$child->name] = $child;
973 $child->category_cache =& $this->category_cache;
979 return true;
981 } else {
982 debugging('error - can not add this element');
983 return false;
989 * Checks if the user has access to anything in this category.
991 * @return bool True if the user has access to at least one child in this category, false otherwise.
993 public function check_access() {
994 foreach ($this->children as $child) {
995 if ($child->check_access()) {
996 return true;
999 return false;
1003 * Is this category hidden in admin tree block?
1005 * @return bool True if hidden
1007 public function is_hidden() {
1008 return $this->hidden;
1012 * Show we display Save button at the page bottom?
1013 * @return bool
1015 public function show_save() {
1016 foreach ($this->children as $child) {
1017 if ($child->show_save()) {
1018 return true;
1021 return false;
1025 * Sets sorting on this category.
1027 * Please note this function doesn't actually do the sorting.
1028 * It can be called anytime.
1029 * Sorting occurs when the user calls get_children.
1030 * Code using the children array directly won't see the sorted results.
1032 * @param bool $sort If set to true children will be sorted, if false they won't be.
1033 * @param bool $asc If true sorting will be ascending, otherwise descending.
1034 * @param bool $split If true we sort pages and sub categories separately.
1036 public function set_sorting($sort, $asc = true, $split = true) {
1037 $this->sort = (bool)$sort;
1038 $this->sortasc = (bool)$asc;
1039 $this->sortsplit = (bool)$split;
1043 * Returns the children associated with this category.
1045 * @return part_of_admin_tree[]
1047 public function get_children() {
1048 // If we should sort and it hasn't already been sorted.
1049 if ($this->sort && !$this->sorted) {
1050 if ($this->sortsplit) {
1051 $categories = array();
1052 $pages = array();
1053 foreach ($this->children as $child) {
1054 if ($child instanceof admin_category) {
1055 $categories[] = $child;
1056 } else {
1057 $pages[] = $child;
1060 core_collator::asort_objects_by_property($categories, 'visiblename');
1061 core_collator::asort_objects_by_property($pages, 'visiblename');
1062 if (!$this->sortasc) {
1063 $categories = array_reverse($categories);
1064 $pages = array_reverse($pages);
1066 $this->children = array_merge($pages, $categories);
1067 } else {
1068 core_collator::asort_objects_by_property($this->children, 'visiblename');
1069 if (!$this->sortasc) {
1070 $this->children = array_reverse($this->children);
1073 $this->sorted = true;
1075 return $this->children;
1079 * Magically gets a property from this object.
1081 * @param $property
1082 * @return part_of_admin_tree[]
1083 * @throws coding_exception
1085 public function __get($property) {
1086 if ($property === 'children') {
1087 return $this->get_children();
1089 throw new coding_exception('Invalid property requested.');
1093 * Magically sets a property against this object.
1095 * @param string $property
1096 * @param mixed $value
1097 * @throws coding_exception
1099 public function __set($property, $value) {
1100 if ($property === 'children') {
1101 $this->sorted = false;
1102 $this->children = $value;
1103 } else {
1104 throw new coding_exception('Invalid property requested.');
1109 * Checks if an inaccessible property is set.
1111 * @param string $property
1112 * @return bool
1113 * @throws coding_exception
1115 public function __isset($property) {
1116 if ($property === 'children') {
1117 return isset($this->children);
1119 throw new coding_exception('Invalid property requested.');
1125 * Root of admin settings tree, does not have any parent.
1127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1129 class admin_root extends admin_category {
1130 /** @var array List of errors */
1131 public $errors;
1132 /** @var string search query */
1133 public $search;
1134 /** @var bool full tree flag - true means all settings required, false only pages required */
1135 public $fulltree;
1136 /** @var bool flag indicating loaded tree */
1137 public $loaded;
1138 /** @var mixed site custom defaults overriding defaults in settings files*/
1139 public $custom_defaults;
1142 * @param bool $fulltree true means all settings required,
1143 * false only pages required
1145 public function __construct($fulltree) {
1146 global $CFG;
1148 parent::__construct('root', get_string('administration'), false);
1149 $this->errors = array();
1150 $this->search = '';
1151 $this->fulltree = $fulltree;
1152 $this->loaded = false;
1154 $this->category_cache = array();
1156 // load custom defaults if found
1157 $this->custom_defaults = null;
1158 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1159 if (is_readable($defaultsfile)) {
1160 $defaults = array();
1161 include($defaultsfile);
1162 if (is_array($defaults) and count($defaults)) {
1163 $this->custom_defaults = $defaults;
1169 * Empties children array, and sets loaded to false
1171 * @param bool $requirefulltree
1173 public function purge_children($requirefulltree) {
1174 $this->children = array();
1175 $this->fulltree = ($requirefulltree || $this->fulltree);
1176 $this->loaded = false;
1177 //break circular dependencies - this helps PHP 5.2
1178 while($this->category_cache) {
1179 array_pop($this->category_cache);
1181 $this->category_cache = array();
1187 * Links external PHP pages into the admin tree.
1189 * See detailed usage example at the top of this document (adminlib.php)
1191 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1193 class admin_externalpage implements part_of_admin_tree {
1195 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1196 public $name;
1198 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1199 public $visiblename;
1201 /** @var string The external URL that we should link to when someone requests this external page. */
1202 public $url;
1204 /** @var string The role capability/permission a user must have to access this external page. */
1205 public $req_capability;
1207 /** @var object The context in which capability/permission should be checked, default is site context. */
1208 public $context;
1210 /** @var bool hidden in admin tree block. */
1211 public $hidden;
1213 /** @var mixed either string or array of string */
1214 public $path;
1216 /** @var array list of visible names of page parents */
1217 public $visiblepath;
1220 * Constructor for adding an external page into the admin tree.
1222 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1223 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1224 * @param string $url The external URL that we should link to when someone requests this external page.
1225 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1226 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1227 * @param stdClass $context The context the page relates to. Not sure what happens
1228 * if you specify something other than system or front page. Defaults to system.
1230 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1231 $this->name = $name;
1232 $this->visiblename = $visiblename;
1233 $this->url = $url;
1234 if (is_array($req_capability)) {
1235 $this->req_capability = $req_capability;
1236 } else {
1237 $this->req_capability = array($req_capability);
1239 $this->hidden = $hidden;
1240 $this->context = $context;
1244 * Returns a reference to the part_of_admin_tree object with internal name $name.
1246 * @param string $name The internal name of the object we want.
1247 * @param bool $findpath defaults to false
1248 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1250 public function locate($name, $findpath=false) {
1251 if ($this->name == $name) {
1252 if ($findpath) {
1253 $this->visiblepath = array($this->visiblename);
1254 $this->path = array($this->name);
1256 return $this;
1257 } else {
1258 $return = NULL;
1259 return $return;
1264 * This function always returns false, required function by interface
1266 * @param string $name
1267 * @return false
1269 public function prune($name) {
1270 return false;
1274 * Search using query
1276 * @param string $query
1277 * @return mixed array-object structure of found settings and pages
1279 public function search($query) {
1280 $found = false;
1281 if (strpos(strtolower($this->name), $query) !== false) {
1282 $found = true;
1283 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1284 $found = true;
1286 if ($found) {
1287 $result = new stdClass();
1288 $result->page = $this;
1289 $result->settings = array();
1290 return array($this->name => $result);
1291 } else {
1292 return array();
1297 * Determines if the current user has access to this external page based on $this->req_capability.
1299 * @return bool True if user has access, false otherwise.
1301 public function check_access() {
1302 global $CFG;
1303 $context = empty($this->context) ? context_system::instance() : $this->context;
1304 foreach($this->req_capability as $cap) {
1305 if (has_capability($cap, $context)) {
1306 return true;
1309 return false;
1313 * Is this external page hidden in admin tree block?
1315 * @return bool True if hidden
1317 public function is_hidden() {
1318 return $this->hidden;
1322 * Show we display Save button at the page bottom?
1323 * @return bool
1325 public function show_save() {
1326 return false;
1331 * Used to store details of the dependency between two settings elements.
1333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1334 * @copyright 2017 Davo Smith, Synergy Learning
1336 class admin_settingdependency {
1337 /** @var string the name of the setting to be shown/hidden */
1338 public $settingname;
1339 /** @var string the setting this is dependent on */
1340 public $dependenton;
1341 /** @var string the condition to show/hide the element */
1342 public $condition;
1343 /** @var string the value to compare against */
1344 public $value;
1346 /** @var string[] list of valid conditions */
1347 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1350 * admin_settingdependency constructor.
1351 * @param string $settingname
1352 * @param string $dependenton
1353 * @param string $condition
1354 * @param string $value
1355 * @throws \coding_exception
1357 public function __construct($settingname, $dependenton, $condition, $value) {
1358 $this->settingname = $this->parse_name($settingname);
1359 $this->dependenton = $this->parse_name($dependenton);
1360 $this->condition = $condition;
1361 $this->value = $value;
1363 if (!in_array($this->condition, self::$validconditions)) {
1364 throw new coding_exception("Invalid condition '$condition'");
1369 * Convert the setting name into the form field name.
1370 * @param string $name
1371 * @return string
1373 private function parse_name($name) {
1374 $bits = explode('/', $name);
1375 $name = array_pop($bits);
1376 $plugin = '';
1377 if ($bits) {
1378 $plugin = array_pop($bits);
1379 if ($plugin === 'moodle') {
1380 $plugin = '';
1383 return 's_'.$plugin.'_'.$name;
1387 * Gather together all the dependencies in a format suitable for initialising javascript
1388 * @param admin_settingdependency[] $dependencies
1389 * @return array
1391 public static function prepare_for_javascript($dependencies) {
1392 $result = [];
1393 foreach ($dependencies as $d) {
1394 if (!isset($result[$d->dependenton])) {
1395 $result[$d->dependenton] = [];
1397 if (!isset($result[$d->dependenton][$d->condition])) {
1398 $result[$d->dependenton][$d->condition] = [];
1400 if (!isset($result[$d->dependenton][$d->condition][$d->value])) {
1401 $result[$d->dependenton][$d->condition][$d->value] = [];
1403 $result[$d->dependenton][$d->condition][$d->value][] = $d->settingname;
1405 return $result;
1410 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1414 class admin_settingpage implements part_of_admin_tree {
1416 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1417 public $name;
1419 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1420 public $visiblename;
1422 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1423 public $settings;
1425 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1426 protected $dependencies = [];
1428 /** @var string The role capability/permission a user must have to access this external page. */
1429 public $req_capability;
1431 /** @var object The context in which capability/permission should be checked, default is site context. */
1432 public $context;
1434 /** @var bool hidden in admin tree block. */
1435 public $hidden;
1437 /** @var mixed string of paths or array of strings of paths */
1438 public $path;
1440 /** @var array list of visible names of page parents */
1441 public $visiblepath;
1444 * see admin_settingpage for details of this function
1446 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1447 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1448 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1449 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1450 * @param stdClass $context The context the page relates to. Not sure what happens
1451 * if you specify something other than system or front page. Defaults to system.
1453 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1454 $this->settings = new stdClass();
1455 $this->name = $name;
1456 $this->visiblename = $visiblename;
1457 if (is_array($req_capability)) {
1458 $this->req_capability = $req_capability;
1459 } else {
1460 $this->req_capability = array($req_capability);
1462 $this->hidden = $hidden;
1463 $this->context = $context;
1467 * see admin_category
1469 * @param string $name
1470 * @param bool $findpath
1471 * @return mixed Object (this) if name == this->name, else returns null
1473 public function locate($name, $findpath=false) {
1474 if ($this->name == $name) {
1475 if ($findpath) {
1476 $this->visiblepath = array($this->visiblename);
1477 $this->path = array($this->name);
1479 return $this;
1480 } else {
1481 $return = NULL;
1482 return $return;
1487 * Search string in settings page.
1489 * @param string $query
1490 * @return array
1492 public function search($query) {
1493 $found = array();
1495 foreach ($this->settings as $setting) {
1496 if ($setting->is_related($query)) {
1497 $found[] = $setting;
1501 if ($found) {
1502 $result = new stdClass();
1503 $result->page = $this;
1504 $result->settings = $found;
1505 return array($this->name => $result);
1508 $found = false;
1509 if (strpos(strtolower($this->name), $query) !== false) {
1510 $found = true;
1511 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1512 $found = true;
1514 if ($found) {
1515 $result = new stdClass();
1516 $result->page = $this;
1517 $result->settings = array();
1518 return array($this->name => $result);
1519 } else {
1520 return array();
1525 * This function always returns false, required by interface
1527 * @param string $name
1528 * @return bool Always false
1530 public function prune($name) {
1531 return false;
1535 * adds an admin_setting to this admin_settingpage
1537 * 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
1538 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1540 * @param object $setting is the admin_setting object you want to add
1541 * @return bool true if successful, false if not
1543 public function add($setting) {
1544 if (!($setting instanceof admin_setting)) {
1545 debugging('error - not a setting instance');
1546 return false;
1549 $name = $setting->name;
1550 if ($setting->plugin) {
1551 $name = $setting->plugin . $name;
1553 $this->settings->{$name} = $setting;
1554 return true;
1558 * Hide the named setting if the specified condition is matched.
1560 * @param string $settingname
1561 * @param string $dependenton
1562 * @param string $condition
1563 * @param string $value
1565 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1566 $this->dependencies[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1568 // Reformat the dependency name to the plugin | name format used in the display.
1569 $dependenton = str_replace('/', ' | ', $dependenton);
1571 // Let the setting know, so it can be displayed underneath.
1572 $findname = str_replace('/', '', $settingname);
1573 foreach ($this->settings as $name => $setting) {
1574 if ($name === $findname) {
1575 $setting->add_dependent_on($dependenton);
1581 * see admin_externalpage
1583 * @return bool Returns true for yes false for no
1585 public function check_access() {
1586 global $CFG;
1587 $context = empty($this->context) ? context_system::instance() : $this->context;
1588 foreach($this->req_capability as $cap) {
1589 if (has_capability($cap, $context)) {
1590 return true;
1593 return false;
1597 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1598 * @return string Returns an XHTML string
1600 public function output_html() {
1601 $adminroot = admin_get_root();
1602 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1603 foreach($this->settings as $setting) {
1604 $fullname = $setting->get_full_name();
1605 if (array_key_exists($fullname, $adminroot->errors)) {
1606 $data = $adminroot->errors[$fullname]->data;
1607 } else {
1608 $data = $setting->get_setting();
1609 // do not use defaults if settings not available - upgrade settings handles the defaults!
1611 $return .= $setting->output_html($data);
1613 $return .= '</fieldset>';
1614 return $return;
1618 * Is this settings page hidden in admin tree block?
1620 * @return bool True if hidden
1622 public function is_hidden() {
1623 return $this->hidden;
1627 * Show we display Save button at the page bottom?
1628 * @return bool
1630 public function show_save() {
1631 foreach($this->settings as $setting) {
1632 if (empty($setting->nosave)) {
1633 return true;
1636 return false;
1640 * Should any of the settings on this page be shown / hidden based on conditions?
1641 * @return bool
1643 public function has_dependencies() {
1644 return (bool)$this->dependencies;
1648 * Format the setting show/hide conditions ready to initialise the page javascript
1649 * @return array
1651 public function get_dependencies_for_javascript() {
1652 if (!$this->has_dependencies()) {
1653 return [];
1655 return admin_settingdependency::prepare_for_javascript($this->dependencies);
1661 * Admin settings class. Only exists on setting pages.
1662 * Read & write happens at this level; no authentication.
1664 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1666 abstract class admin_setting {
1667 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1668 public $name;
1669 /** @var string localised name */
1670 public $visiblename;
1671 /** @var string localised long description in Markdown format */
1672 public $description;
1673 /** @var mixed Can be string or array of string */
1674 public $defaultsetting;
1675 /** @var string */
1676 public $updatedcallback;
1677 /** @var mixed can be String or Null. Null means main config table */
1678 public $plugin; // null means main config table
1679 /** @var bool true indicates this setting does not actually save anything, just information */
1680 public $nosave = false;
1681 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1682 public $affectsmodinfo = false;
1683 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1684 private $flags = array();
1685 /** @var bool Whether this field must be forced LTR. */
1686 private $forceltr = null;
1687 /** @var array list of other settings that may cause this setting to be hidden */
1688 private $dependenton = [];
1689 /** @var bool Whether this setting uses a custom form control */
1690 protected $customcontrol = false;
1693 * Constructor
1694 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1695 * or 'myplugin/mysetting' for ones in config_plugins.
1696 * @param string $visiblename localised name
1697 * @param string $description localised long description
1698 * @param mixed $defaultsetting string or array depending on implementation
1700 public function __construct($name, $visiblename, $description, $defaultsetting) {
1701 $this->parse_setting_name($name);
1702 $this->visiblename = $visiblename;
1703 $this->description = $description;
1704 $this->defaultsetting = $defaultsetting;
1708 * Generic function to add a flag to this admin setting.
1710 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1711 * @param bool $default - The default for the flag
1712 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1713 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1715 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1716 if (empty($this->flags[$shortname])) {
1717 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1718 } else {
1719 $this->flags[$shortname]->set_options($enabled, $default);
1724 * Set the enabled options flag on this admin setting.
1726 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1727 * @param bool $default - The default for the flag
1729 public function set_enabled_flag_options($enabled, $default) {
1730 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1734 * Set the advanced options flag on this admin setting.
1736 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1737 * @param bool $default - The default for the flag
1739 public function set_advanced_flag_options($enabled, $default) {
1740 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1745 * Set the locked options flag on this admin setting.
1747 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1748 * @param bool $default - The default for the flag
1750 public function set_locked_flag_options($enabled, $default) {
1751 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1755 * Set the required options flag on this admin setting.
1757 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1758 * @param bool $default - The default for the flag.
1760 public function set_required_flag_options($enabled, $default) {
1761 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1765 * Get the currently saved value for a setting flag
1767 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1768 * @return bool
1770 public function get_setting_flag_value(admin_setting_flag $flag) {
1771 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1772 if (!isset($value)) {
1773 $value = $flag->get_default();
1776 return !empty($value);
1780 * Get the list of defaults for the flags on this setting.
1782 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1784 public function get_setting_flag_defaults(& $defaults) {
1785 foreach ($this->flags as $flag) {
1786 if ($flag->is_enabled() && $flag->get_default()) {
1787 $defaults[] = $flag->get_displayname();
1793 * Output the input fields for the advanced and locked flags on this setting.
1795 * @param bool $adv - The current value of the advanced flag.
1796 * @param bool $locked - The current value of the locked flag.
1797 * @return string $output - The html for the flags.
1799 public function output_setting_flags() {
1800 $output = '';
1802 foreach ($this->flags as $flag) {
1803 if ($flag->is_enabled()) {
1804 $output .= $flag->output_setting_flag($this);
1808 if (!empty($output)) {
1809 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1811 return $output;
1815 * Write the values of the flags for this admin setting.
1817 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1818 * @return bool - true if successful.
1820 public function write_setting_flags($data) {
1821 $result = true;
1822 foreach ($this->flags as $flag) {
1823 $result = $result && $flag->write_setting_flag($this, $data);
1825 return $result;
1829 * Set up $this->name and potentially $this->plugin
1831 * Set up $this->name and possibly $this->plugin based on whether $name looks
1832 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1833 * on the names, that is, output a developer debug warning if the name
1834 * contains anything other than [a-zA-Z0-9_]+.
1836 * @param string $name the setting name passed in to the constructor.
1838 private function parse_setting_name($name) {
1839 $bits = explode('/', $name);
1840 if (count($bits) > 2) {
1841 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1843 $this->name = array_pop($bits);
1844 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1845 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1847 if (!empty($bits)) {
1848 $this->plugin = array_pop($bits);
1849 if ($this->plugin === 'moodle') {
1850 $this->plugin = null;
1851 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1852 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1858 * Returns the fullname prefixed by the plugin
1859 * @return string
1861 public function get_full_name() {
1862 return 's_'.$this->plugin.'_'.$this->name;
1866 * Returns the ID string based on plugin and name
1867 * @return string
1869 public function get_id() {
1870 return 'id_s_'.$this->plugin.'_'.$this->name;
1874 * @param bool $affectsmodinfo If true, changes to this setting will
1875 * cause the course cache to be rebuilt
1877 public function set_affects_modinfo($affectsmodinfo) {
1878 $this->affectsmodinfo = $affectsmodinfo;
1882 * Returns the config if possible
1884 * @return mixed returns config if successful else null
1886 public function config_read($name) {
1887 global $CFG;
1888 if (!empty($this->plugin)) {
1889 $value = get_config($this->plugin, $name);
1890 return $value === false ? NULL : $value;
1892 } else {
1893 if (isset($CFG->$name)) {
1894 return $CFG->$name;
1895 } else {
1896 return NULL;
1902 * Used to set a config pair and log change
1904 * @param string $name
1905 * @param mixed $value Gets converted to string if not null
1906 * @return bool Write setting to config table
1908 public function config_write($name, $value) {
1909 global $DB, $USER, $CFG;
1911 if ($this->nosave) {
1912 return true;
1915 // make sure it is a real change
1916 $oldvalue = get_config($this->plugin, $name);
1917 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1918 $value = is_null($value) ? null : (string)$value;
1920 if ($oldvalue === $value) {
1921 return true;
1924 // store change
1925 set_config($name, $value, $this->plugin);
1927 // Some admin settings affect course modinfo
1928 if ($this->affectsmodinfo) {
1929 // Clear course cache for all courses
1930 rebuild_course_cache(0, true);
1933 $this->add_to_config_log($name, $oldvalue, $value);
1935 return true; // BC only
1939 * Log config changes if necessary.
1940 * @param string $name
1941 * @param string $oldvalue
1942 * @param string $value
1944 protected function add_to_config_log($name, $oldvalue, $value) {
1945 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1949 * Returns current value of this setting
1950 * @return mixed array or string depending on instance, NULL means not set yet
1952 public abstract function get_setting();
1955 * Returns default setting if exists
1956 * @return mixed array or string depending on instance; NULL means no default, user must supply
1958 public function get_defaultsetting() {
1959 $adminroot = admin_get_root(false, false);
1960 if (!empty($adminroot->custom_defaults)) {
1961 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1962 if (isset($adminroot->custom_defaults[$plugin])) {
1963 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1964 return $adminroot->custom_defaults[$plugin][$this->name];
1968 return $this->defaultsetting;
1972 * Store new setting
1974 * @param mixed $data string or array, must not be NULL
1975 * @return string empty string if ok, string error message otherwise
1977 public abstract function write_setting($data);
1980 * Return part of form with setting
1981 * This function should always be overwritten
1983 * @param mixed $data array or string depending on setting
1984 * @param string $query
1985 * @return string
1987 public function output_html($data, $query='') {
1988 // should be overridden
1989 return;
1993 * Function called if setting updated - cleanup, cache reset, etc.
1994 * @param string $functionname Sets the function name
1995 * @return void
1997 public function set_updatedcallback($functionname) {
1998 $this->updatedcallback = $functionname;
2002 * Execute postupdatecallback if necessary.
2003 * @param mixed $original original value before write_setting()
2004 * @return bool true if changed, false if not.
2006 public function post_write_settings($original) {
2007 // Comparison must work for arrays too.
2008 if (serialize($original) === serialize($this->get_setting())) {
2009 return false;
2012 $callbackfunction = $this->updatedcallback;
2013 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2014 $callbackfunction($this->get_full_name());
2016 return true;
2020 * Is setting related to query text - used when searching
2021 * @param string $query
2022 * @return bool
2024 public function is_related($query) {
2025 if (strpos(strtolower($this->name), $query) !== false) {
2026 return true;
2028 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
2029 return true;
2031 if (strpos(core_text::strtolower($this->description), $query) !== false) {
2032 return true;
2034 $current = $this->get_setting();
2035 if (!is_null($current)) {
2036 if (is_string($current)) {
2037 if (strpos(core_text::strtolower($current), $query) !== false) {
2038 return true;
2042 $default = $this->get_defaultsetting();
2043 if (!is_null($default)) {
2044 if (is_string($default)) {
2045 if (strpos(core_text::strtolower($default), $query) !== false) {
2046 return true;
2050 return false;
2054 * Get whether this should be displayed in LTR mode.
2056 * @return bool|null
2058 public function get_force_ltr() {
2059 return $this->forceltr;
2063 * Set whether to force LTR or not.
2065 * @param bool $value True when forced, false when not force, null when unknown.
2067 public function set_force_ltr($value) {
2068 $this->forceltr = $value;
2072 * Add a setting to the list of those that could cause this one to be hidden
2073 * @param string $dependenton
2075 public function add_dependent_on($dependenton) {
2076 $this->dependenton[] = $dependenton;
2080 * Get a list of the settings that could cause this one to be hidden.
2081 * @return array
2083 public function get_dependent_on() {
2084 return $this->dependenton;
2088 * Whether this setting uses a custom form control.
2089 * This function is especially useful to decide if we should render a label element for this setting or not.
2091 * @return bool
2093 public function has_custom_form_control(): bool {
2094 return $this->customcontrol;
2099 * An additional option that can be applied to an admin setting.
2100 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2104 class admin_setting_flag {
2105 /** @var bool Flag to indicate if this option can be toggled for this setting */
2106 private $enabled = false;
2107 /** @var bool Flag to indicate if this option defaults to true or false */
2108 private $default = false;
2109 /** @var string Short string used to create setting name - e.g. 'adv' */
2110 private $shortname = '';
2111 /** @var string String used as the label for this flag */
2112 private $displayname = '';
2113 /** @const Checkbox for this flag is displayed in admin page */
2114 const ENABLED = true;
2115 /** @const Checkbox for this flag is not displayed in admin page */
2116 const DISABLED = false;
2119 * Constructor
2121 * @param bool $enabled Can this option can be toggled.
2122 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2123 * @param bool $default The default checked state for this setting option.
2124 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2125 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2127 public function __construct($enabled, $default, $shortname, $displayname) {
2128 $this->shortname = $shortname;
2129 $this->displayname = $displayname;
2130 $this->set_options($enabled, $default);
2134 * Update the values of this setting options class
2136 * @param bool $enabled Can this option can be toggled.
2137 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2138 * @param bool $default The default checked state for this setting option.
2140 public function set_options($enabled, $default) {
2141 $this->enabled = $enabled;
2142 $this->default = $default;
2146 * Should this option appear in the interface and be toggleable?
2148 * @return bool Is it enabled?
2150 public function is_enabled() {
2151 return $this->enabled;
2155 * Should this option be checked by default?
2157 * @return bool Is it on by default?
2159 public function get_default() {
2160 return $this->default;
2164 * Return the short name for this flag. e.g. 'adv' or 'locked'
2166 * @return string
2168 public function get_shortname() {
2169 return $this->shortname;
2173 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2175 * @return string
2177 public function get_displayname() {
2178 return $this->displayname;
2182 * Save the submitted data for this flag - or set it to the default if $data is null.
2184 * @param admin_setting $setting - The admin setting for this flag
2185 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2186 * @return bool
2188 public function write_setting_flag(admin_setting $setting, $data) {
2189 $result = true;
2190 if ($this->is_enabled()) {
2191 if (!isset($data)) {
2192 $value = $this->get_default();
2193 } else {
2194 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2196 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2199 return $result;
2204 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2206 * @param admin_setting $setting - The admin setting for this flag
2207 * @return string - The html for the checkbox.
2209 public function output_setting_flag(admin_setting $setting) {
2210 global $OUTPUT;
2212 $value = $setting->get_setting_flag_value($this);
2214 $context = new stdClass();
2215 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2216 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2217 $context->value = 1;
2218 $context->checked = $value ? true : false;
2219 $context->label = $this->get_displayname();
2221 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2227 * No setting - just heading and text.
2229 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2231 class admin_setting_heading extends admin_setting {
2234 * not a setting, just text
2235 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2236 * @param string $heading heading
2237 * @param string $information text in box
2239 public function __construct($name, $heading, $information) {
2240 $this->nosave = true;
2241 parent::__construct($name, $heading, $information, '');
2245 * Always returns true
2246 * @return bool Always returns true
2248 public function get_setting() {
2249 return true;
2253 * Always returns true
2254 * @return bool Always returns true
2256 public function get_defaultsetting() {
2257 return true;
2261 * Never write settings
2262 * @return string Always returns an empty string
2264 public function write_setting($data) {
2265 // do not write any setting
2266 return '';
2270 * Returns an HTML string
2271 * @return string Returns an HTML string
2273 public function output_html($data, $query='') {
2274 global $OUTPUT;
2275 $context = new stdClass();
2276 $context->title = $this->visiblename;
2277 $context->description = $this->description;
2278 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2279 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2284 * No setting - just name and description in same row.
2286 * @copyright 2018 onwards Amaia Anabitarte
2287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2289 class admin_setting_description extends admin_setting {
2292 * Not a setting, just text
2294 * @param string $name
2295 * @param string $visiblename
2296 * @param string $description
2298 public function __construct($name, $visiblename, $description) {
2299 $this->nosave = true;
2300 parent::__construct($name, $visiblename, $description, '');
2304 * Always returns true
2306 * @return bool Always returns true
2308 public function get_setting() {
2309 return true;
2313 * Always returns true
2315 * @return bool Always returns true
2317 public function get_defaultsetting() {
2318 return true;
2322 * Never write settings
2324 * @param mixed $data Gets converted to str for comparison against yes value
2325 * @return string Always returns an empty string
2327 public function write_setting($data) {
2328 // Do not write any setting.
2329 return '';
2333 * Returns an HTML string
2335 * @param string $data
2336 * @param string $query
2337 * @return string Returns an HTML string
2339 public function output_html($data, $query='') {
2340 global $OUTPUT;
2342 $context = new stdClass();
2343 $context->title = $this->visiblename;
2344 $context->description = $this->description;
2346 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2353 * The most flexible setting, the user enters text.
2355 * This type of field should be used for config settings which are using
2356 * English words and are not localised (passwords, database name, list of values, ...).
2358 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2360 class admin_setting_configtext extends admin_setting {
2362 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2363 public $paramtype;
2364 /** @var int default field size */
2365 public $size;
2368 * Config text constructor
2370 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2371 * @param string $visiblename localised
2372 * @param string $description long localised info
2373 * @param string $defaultsetting
2374 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2375 * @param int $size default field size
2377 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2378 $this->paramtype = $paramtype;
2379 if (!is_null($size)) {
2380 $this->size = $size;
2381 } else {
2382 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2384 parent::__construct($name, $visiblename, $description, $defaultsetting);
2388 * Get whether this should be displayed in LTR mode.
2390 * Try to guess from the PARAM type unless specifically set.
2392 public function get_force_ltr() {
2393 $forceltr = parent::get_force_ltr();
2394 if ($forceltr === null) {
2395 return !is_rtl_compatible($this->paramtype);
2397 return $forceltr;
2401 * Return the setting
2403 * @return mixed returns config if successful else null
2405 public function get_setting() {
2406 return $this->config_read($this->name);
2409 public function write_setting($data) {
2410 if ($this->paramtype === PARAM_INT and $data === '') {
2411 // do not complain if '' used instead of 0
2412 $data = 0;
2414 // $data is a string
2415 $validated = $this->validate($data);
2416 if ($validated !== true) {
2417 return $validated;
2419 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2423 * Validate data before storage
2424 * @param string data
2425 * @return mixed true if ok string if error found
2427 public function validate($data) {
2428 // allow paramtype to be a custom regex if it is the form of /pattern/
2429 if (preg_match('#^/.*/$#', $this->paramtype)) {
2430 if (preg_match($this->paramtype, $data)) {
2431 return true;
2432 } else {
2433 return get_string('validateerror', 'admin');
2436 } else if ($this->paramtype === PARAM_RAW) {
2437 return true;
2439 } else {
2440 $cleaned = clean_param($data, $this->paramtype);
2441 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2442 return true;
2443 } else {
2444 return get_string('validateerror', 'admin');
2450 * Return an XHTML string for the setting
2451 * @return string Returns an XHTML string
2453 public function output_html($data, $query='') {
2454 global $OUTPUT;
2456 $default = $this->get_defaultsetting();
2457 $context = (object) [
2458 'size' => $this->size,
2459 'id' => $this->get_id(),
2460 'name' => $this->get_full_name(),
2461 'value' => $data,
2462 'forceltr' => $this->get_force_ltr(),
2464 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2466 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2471 * Text input with a maximum length constraint.
2473 * @copyright 2015 onwards Ankit Agarwal
2474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2476 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2478 /** @var int maximum number of chars allowed. */
2479 protected $maxlength;
2482 * Config text constructor
2484 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2485 * or 'myplugin/mysetting' for ones in config_plugins.
2486 * @param string $visiblename localised
2487 * @param string $description long localised info
2488 * @param string $defaultsetting
2489 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2490 * @param int $size default field size
2491 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2493 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2494 $size=null, $maxlength = 0) {
2495 $this->maxlength = $maxlength;
2496 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2500 * Validate data before storage
2502 * @param string $data data
2503 * @return mixed true if ok string if error found
2505 public function validate($data) {
2506 $parentvalidation = parent::validate($data);
2507 if ($parentvalidation === true) {
2508 if ($this->maxlength > 0) {
2509 // Max length check.
2510 $length = core_text::strlen($data);
2511 if ($length > $this->maxlength) {
2512 return get_string('maximumchars', 'moodle', $this->maxlength);
2514 return true;
2515 } else {
2516 return true; // No max length check needed.
2518 } else {
2519 return $parentvalidation;
2525 * General text area without html editor.
2527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2529 class admin_setting_configtextarea extends admin_setting_configtext {
2530 private $rows;
2531 private $cols;
2534 * @param string $name
2535 * @param string $visiblename
2536 * @param string $description
2537 * @param mixed $defaultsetting string or array
2538 * @param mixed $paramtype
2539 * @param string $cols The number of columns to make the editor
2540 * @param string $rows The number of rows to make the editor
2542 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2543 $this->rows = $rows;
2544 $this->cols = $cols;
2545 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2549 * Returns an XHTML string for the editor
2551 * @param string $data
2552 * @param string $query
2553 * @return string XHTML string for the editor
2555 public function output_html($data, $query='') {
2556 global $OUTPUT;
2558 $default = $this->get_defaultsetting();
2559 $defaultinfo = $default;
2560 if (!is_null($default) and $default !== '') {
2561 $defaultinfo = "\n".$default;
2564 $context = (object) [
2565 'cols' => $this->cols,
2566 'rows' => $this->rows,
2567 'id' => $this->get_id(),
2568 'name' => $this->get_full_name(),
2569 'value' => $data,
2570 'forceltr' => $this->get_force_ltr(),
2572 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2574 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2579 * General text area with html editor.
2581 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2584 * @param string $name
2585 * @param string $visiblename
2586 * @param string $description
2587 * @param mixed $defaultsetting string or array
2588 * @param mixed $paramtype
2590 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2591 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2592 $this->set_force_ltr(false);
2593 editors_head_setup();
2597 * Returns an XHTML string for the editor
2599 * @param string $data
2600 * @param string $query
2601 * @return string XHTML string for the editor
2603 public function output_html($data, $query='') {
2604 $editor = editors_get_preferred_editor(FORMAT_HTML);
2605 $editor->set_text($data);
2606 $editor->use_editor($this->get_id(), array('noclean'=>true));
2607 return parent::output_html($data, $query);
2611 * Checks if data has empty html.
2613 * @param string $data
2614 * @return string Empty when no errors.
2616 public function write_setting($data) {
2617 if (trim(html_to_text($data)) === '') {
2618 $data = '';
2620 return parent::write_setting($data);
2626 * Password field, allows unmasking of password
2628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2630 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2633 * Constructor
2634 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2635 * @param string $visiblename localised
2636 * @param string $description long localised info
2637 * @param string $defaultsetting default password
2639 public function __construct($name, $visiblename, $description, $defaultsetting) {
2640 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2644 * Log config changes if necessary.
2645 * @param string $name
2646 * @param string $oldvalue
2647 * @param string $value
2649 protected function add_to_config_log($name, $oldvalue, $value) {
2650 if ($value !== '') {
2651 $value = '********';
2653 if ($oldvalue !== '' and $oldvalue !== null) {
2654 $oldvalue = '********';
2656 parent::add_to_config_log($name, $oldvalue, $value);
2660 * Returns HTML for the field.
2662 * @param string $data Value for the field
2663 * @param string $query Passed as final argument for format_admin_setting
2664 * @return string Rendered HTML
2666 public function output_html($data, $query='') {
2667 global $OUTPUT, $CFG;
2668 $forced = false;
2669 if (empty($this->plugin)) {
2670 if (array_key_exists($this->name, $CFG->config_php_settings)) {
2671 $forced = true;
2673 } else {
2674 if (array_key_exists($this->plugin, $CFG->forced_plugin_settings)
2675 and array_key_exists($this->name, $CFG->forced_plugin_settings[$this->plugin])) {
2676 $forced = true;
2679 $context = (object) [
2680 'id' => $this->get_id(),
2681 'name' => $this->get_full_name(),
2682 'size' => $this->size,
2683 'value' => $forced ? null : $data,
2684 'forceltr' => $this->get_force_ltr(),
2685 'forced' => $forced
2687 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2688 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2693 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2696 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2698 class admin_setting_configpasswordunmask_with_advanced extends admin_setting_configpasswordunmask {
2701 * 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 array $defaultsetting ('value'=>string, 'adv'=>bool)
2708 public function __construct($name, $visiblename, $description, $defaultsetting) {
2709 parent::__construct($name, $visiblename, $description, $defaultsetting['value']);
2710 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
2715 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2716 * Note: Only advanced makes sense right now - locked does not.
2718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2720 class admin_setting_configempty extends admin_setting_configtext {
2723 * @param string $name
2724 * @param string $visiblename
2725 * @param string $description
2727 public function __construct($name, $visiblename, $description) {
2728 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2732 * Returns an XHTML string for the hidden field
2734 * @param string $data
2735 * @param string $query
2736 * @return string XHTML string for the editor
2738 public function output_html($data, $query='') {
2739 global $OUTPUT;
2741 $context = (object) [
2742 'id' => $this->get_id(),
2743 'name' => $this->get_full_name()
2745 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2747 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2753 * Path to directory
2755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2757 class admin_setting_configfile extends admin_setting_configtext {
2759 * Constructor
2760 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2761 * @param string $visiblename localised
2762 * @param string $description long localised info
2763 * @param string $defaultdirectory default directory location
2765 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2766 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2770 * Returns XHTML for the field
2772 * Returns XHTML for the field and also checks whether the file
2773 * specified in $data exists using file_exists()
2775 * @param string $data File name and path to use in value attr
2776 * @param string $query
2777 * @return string XHTML field
2779 public function output_html($data, $query='') {
2780 global $CFG, $OUTPUT;
2782 $default = $this->get_defaultsetting();
2783 $context = (object) [
2784 'id' => $this->get_id(),
2785 'name' => $this->get_full_name(),
2786 'size' => $this->size,
2787 'value' => $data,
2788 'showvalidity' => !empty($data),
2789 'valid' => $data && file_exists($data),
2790 'readonly' => !empty($CFG->preventexecpath),
2791 'forceltr' => $this->get_force_ltr(),
2794 if ($context->readonly) {
2795 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2798 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2800 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2804 * Checks if execpatch has been disabled in config.php
2806 public function write_setting($data) {
2807 global $CFG;
2808 if (!empty($CFG->preventexecpath)) {
2809 if ($this->get_setting() === null) {
2810 // Use default during installation.
2811 $data = $this->get_defaultsetting();
2812 if ($data === null) {
2813 $data = '';
2815 } else {
2816 return '';
2819 return parent::write_setting($data);
2826 * Path to executable file
2828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2830 class admin_setting_configexecutable extends admin_setting_configfile {
2833 * Returns an XHTML field
2835 * @param string $data This is the value for the field
2836 * @param string $query
2837 * @return string XHTML field
2839 public function output_html($data, $query='') {
2840 global $CFG, $OUTPUT;
2841 $default = $this->get_defaultsetting();
2842 require_once("$CFG->libdir/filelib.php");
2844 $context = (object) [
2845 'id' => $this->get_id(),
2846 'name' => $this->get_full_name(),
2847 'size' => $this->size,
2848 'value' => $data,
2849 'showvalidity' => !empty($data),
2850 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2851 'readonly' => !empty($CFG->preventexecpath),
2852 'forceltr' => $this->get_force_ltr()
2855 if (!empty($CFG->preventexecpath)) {
2856 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2859 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2861 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2867 * Path to directory
2869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2871 class admin_setting_configdirectory extends admin_setting_configfile {
2874 * Returns an XHTML field
2876 * @param string $data This is the value for the field
2877 * @param string $query
2878 * @return string XHTML
2880 public function output_html($data, $query='') {
2881 global $CFG, $OUTPUT;
2882 $default = $this->get_defaultsetting();
2884 $context = (object) [
2885 'id' => $this->get_id(),
2886 'name' => $this->get_full_name(),
2887 'size' => $this->size,
2888 'value' => $data,
2889 'showvalidity' => !empty($data),
2890 'valid' => $data && file_exists($data) && is_dir($data),
2891 'readonly' => !empty($CFG->preventexecpath),
2892 'forceltr' => $this->get_force_ltr()
2895 if (!empty($CFG->preventexecpath)) {
2896 $this->visiblename .= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2899 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2901 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2907 * Checkbox
2909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2911 class admin_setting_configcheckbox extends admin_setting {
2912 /** @var string Value used when checked */
2913 public $yes;
2914 /** @var string Value used when not checked */
2915 public $no;
2918 * Constructor
2919 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2920 * @param string $visiblename localised
2921 * @param string $description long localised info
2922 * @param string $defaultsetting
2923 * @param string $yes value used when checked
2924 * @param string $no value used when not checked
2926 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2927 parent::__construct($name, $visiblename, $description, $defaultsetting);
2928 $this->yes = (string)$yes;
2929 $this->no = (string)$no;
2933 * Retrieves the current setting using the objects name
2935 * @return string
2937 public function get_setting() {
2938 return $this->config_read($this->name);
2942 * Sets the value for the setting
2944 * Sets the value for the setting to either the yes or no values
2945 * of the object by comparing $data to yes
2947 * @param mixed $data Gets converted to str for comparison against yes value
2948 * @return string empty string or error
2950 public function write_setting($data) {
2951 if ((string)$data === $this->yes) { // convert to strings before comparison
2952 $data = $this->yes;
2953 } else {
2954 $data = $this->no;
2956 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2960 * Returns an XHTML checkbox field
2962 * @param string $data If $data matches yes then checkbox is checked
2963 * @param string $query
2964 * @return string XHTML field
2966 public function output_html($data, $query='') {
2967 global $OUTPUT;
2969 $context = (object) [
2970 'id' => $this->get_id(),
2971 'name' => $this->get_full_name(),
2972 'no' => $this->no,
2973 'value' => $this->yes,
2974 'checked' => (string) $data === $this->yes,
2977 $default = $this->get_defaultsetting();
2978 if (!is_null($default)) {
2979 if ((string)$default === $this->yes) {
2980 $defaultinfo = get_string('checkboxyes', 'admin');
2981 } else {
2982 $defaultinfo = get_string('checkboxno', 'admin');
2984 } else {
2985 $defaultinfo = NULL;
2988 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2990 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2996 * Multiple checkboxes, each represents different value, stored in csv format
2998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3000 class admin_setting_configmulticheckbox extends admin_setting {
3001 /** @var array Array of choices value=>label */
3002 public $choices;
3005 * Constructor: uses parent::__construct
3007 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3008 * @param string $visiblename localised
3009 * @param string $description long localised info
3010 * @param array $defaultsetting array of selected
3011 * @param array $choices array of $value=>$label for each checkbox
3013 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3014 $this->choices = $choices;
3015 parent::__construct($name, $visiblename, $description, $defaultsetting);
3019 * This public function may be used in ancestors for lazy loading of choices
3021 * @todo Check if this function is still required content commented out only returns true
3022 * @return bool true if loaded, false if error
3024 public function load_choices() {
3026 if (is_array($this->choices)) {
3027 return true;
3029 .... load choices here
3031 return true;
3035 * Is setting related to query text - used when searching
3037 * @param string $query
3038 * @return bool true on related, false on not or failure
3040 public function is_related($query) {
3041 if (!$this->load_choices() or empty($this->choices)) {
3042 return false;
3044 if (parent::is_related($query)) {
3045 return true;
3048 foreach ($this->choices as $desc) {
3049 if (strpos(core_text::strtolower($desc), $query) !== false) {
3050 return true;
3053 return false;
3057 * Returns the current setting if it is set
3059 * @return mixed null if null, else an array
3061 public function get_setting() {
3062 $result = $this->config_read($this->name);
3064 if (is_null($result)) {
3065 return NULL;
3067 if ($result === '') {
3068 return array();
3070 $enabled = explode(',', $result);
3071 $setting = array();
3072 foreach ($enabled as $option) {
3073 $setting[$option] = 1;
3075 return $setting;
3079 * Saves the setting(s) provided in $data
3081 * @param array $data An array of data, if not array returns empty str
3082 * @return mixed empty string on useless data or bool true=success, false=failed
3084 public function write_setting($data) {
3085 if (!is_array($data)) {
3086 return ''; // ignore it
3088 if (!$this->load_choices() or empty($this->choices)) {
3089 return '';
3091 unset($data['xxxxx']);
3092 $result = array();
3093 foreach ($data as $key => $value) {
3094 if ($value and array_key_exists($key, $this->choices)) {
3095 $result[] = $key;
3098 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
3102 * Returns XHTML field(s) as required by choices
3104 * Relies on data being an array should data ever be another valid vartype with
3105 * acceptable value this may cause a warning/error
3106 * if (!is_array($data)) would fix the problem
3108 * @todo Add vartype handling to ensure $data is an array
3110 * @param array $data An array of checked values
3111 * @param string $query
3112 * @return string XHTML field
3114 public function output_html($data, $query='') {
3115 global $OUTPUT;
3117 if (!$this->load_choices() or empty($this->choices)) {
3118 return '';
3121 $default = $this->get_defaultsetting();
3122 if (is_null($default)) {
3123 $default = array();
3125 if (is_null($data)) {
3126 $data = array();
3129 $context = (object) [
3130 'id' => $this->get_id(),
3131 'name' => $this->get_full_name(),
3134 $options = array();
3135 $defaults = array();
3136 foreach ($this->choices as $key => $description) {
3137 if (!empty($default[$key])) {
3138 $defaults[] = $description;
3141 $options[] = [
3142 'key' => $key,
3143 'checked' => !empty($data[$key]),
3144 'label' => highlightfast($query, $description)
3148 if (is_null($default)) {
3149 $defaultinfo = null;
3150 } else if (!empty($defaults)) {
3151 $defaultinfo = implode(', ', $defaults);
3152 } else {
3153 $defaultinfo = get_string('none');
3156 $context->options = $options;
3157 $context->hasoptions = !empty($options);
3159 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3161 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
3168 * Multiple checkboxes 2, value stored as string 00101011
3170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3172 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
3175 * Returns the setting if set
3177 * @return mixed null if not set, else an array of set settings
3179 public function get_setting() {
3180 $result = $this->config_read($this->name);
3181 if (is_null($result)) {
3182 return NULL;
3184 if (!$this->load_choices()) {
3185 return NULL;
3187 $result = str_pad($result, count($this->choices), '0');
3188 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
3189 $setting = array();
3190 foreach ($this->choices as $key=>$unused) {
3191 $value = array_shift($result);
3192 if ($value) {
3193 $setting[$key] = 1;
3196 return $setting;
3200 * Save setting(s) provided in $data param
3202 * @param array $data An array of settings to save
3203 * @return mixed empty string for bad data or bool true=>success, false=>error
3205 public function write_setting($data) {
3206 if (!is_array($data)) {
3207 return ''; // ignore it
3209 if (!$this->load_choices() or empty($this->choices)) {
3210 return '';
3212 $result = '';
3213 foreach ($this->choices as $key=>$unused) {
3214 if (!empty($data[$key])) {
3215 $result .= '1';
3216 } else {
3217 $result .= '0';
3220 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
3226 * Select one value from list
3228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3230 class admin_setting_configselect extends admin_setting {
3231 /** @var array Array of choices value=>label */
3232 public $choices;
3233 /** @var array Array of choices grouped using optgroups */
3234 public $optgroups;
3237 * Constructor
3238 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3239 * @param string $visiblename localised
3240 * @param string $description long localised info
3241 * @param string|int $defaultsetting
3242 * @param array $choices array of $value=>$label for each selection
3244 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3245 // Look for optgroup and single options.
3246 if (is_array($choices)) {
3247 $this->choices = [];
3248 foreach ($choices as $key => $val) {
3249 if (is_array($val)) {
3250 $this->optgroups[$key] = $val;
3251 $this->choices = array_merge($this->choices, $val);
3252 } else {
3253 $this->choices[$key] = $val;
3258 parent::__construct($name, $visiblename, $description, $defaultsetting);
3262 * This function may be used in ancestors for lazy loading of choices
3264 * Override this method if loading of choices is expensive, such
3265 * as when it requires multiple db requests.
3267 * @return bool true if loaded, false if error
3269 public function load_choices() {
3271 if (is_array($this->choices)) {
3272 return true;
3274 .... load choices here
3276 return true;
3280 * Check if this is $query is related to a choice
3282 * @param string $query
3283 * @return bool true if related, false if not
3285 public function is_related($query) {
3286 if (parent::is_related($query)) {
3287 return true;
3289 if (!$this->load_choices()) {
3290 return false;
3292 foreach ($this->choices as $key=>$value) {
3293 if (strpos(core_text::strtolower($key), $query) !== false) {
3294 return true;
3296 if (strpos(core_text::strtolower($value), $query) !== false) {
3297 return true;
3300 return false;
3304 * Return the setting
3306 * @return mixed returns config if successful else null
3308 public function get_setting() {
3309 return $this->config_read($this->name);
3313 * Save a setting
3315 * @param string $data
3316 * @return string empty of error string
3318 public function write_setting($data) {
3319 if (!$this->load_choices() or empty($this->choices)) {
3320 return '';
3322 if (!array_key_exists($data, $this->choices)) {
3323 return ''; // ignore it
3326 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3330 * Returns XHTML select field
3332 * Ensure the options are loaded, and generate the XHTML for the select
3333 * element and any warning message. Separating this out from output_html
3334 * makes it easier to subclass this class.
3336 * @param string $data the option to show as selected.
3337 * @param string $current the currently selected option in the database, null if none.
3338 * @param string $default the default selected option.
3339 * @return array the HTML for the select element, and a warning message.
3340 * @deprecated since Moodle 3.2
3342 public function output_select_html($data, $current, $default, $extraname = '') {
3343 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3347 * Returns XHTML select field and wrapping div(s)
3349 * @see output_select_html()
3351 * @param string $data the option to show as selected
3352 * @param string $query
3353 * @return string XHTML field and wrapping div
3355 public function output_html($data, $query='') {
3356 global $OUTPUT;
3358 $default = $this->get_defaultsetting();
3359 $current = $this->get_setting();
3361 if (!$this->load_choices() || empty($this->choices)) {
3362 return '';
3365 $context = (object) [
3366 'id' => $this->get_id(),
3367 'name' => $this->get_full_name(),
3370 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3371 $defaultinfo = $this->choices[$default];
3372 } else {
3373 $defaultinfo = NULL;
3376 // Warnings.
3377 $warning = '';
3378 if ($current === null) {
3379 // First run.
3380 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3381 // No warning.
3382 } else if (!array_key_exists($current, $this->choices)) {
3383 $warning = get_string('warningcurrentsetting', 'admin', $current);
3384 if (!is_null($default) && $data == $current) {
3385 $data = $default; // Use default instead of first value when showing the form.
3389 $options = [];
3390 $template = 'core_admin/setting_configselect';
3392 if (!empty($this->optgroups)) {
3393 $optgroups = [];
3394 foreach ($this->optgroups as $label => $choices) {
3395 $optgroup = array('label' => $label, 'options' => []);
3396 foreach ($choices as $value => $name) {
3397 $optgroup['options'][] = [
3398 'value' => $value,
3399 'name' => $name,
3400 'selected' => (string) $value == $data
3402 unset($this->choices[$value]);
3404 $optgroups[] = $optgroup;
3406 $context->options = $options;
3407 $context->optgroups = $optgroups;
3408 $template = 'core_admin/setting_configselect_optgroup';
3411 foreach ($this->choices as $value => $name) {
3412 $options[] = [
3413 'value' => $value,
3414 'name' => $name,
3415 'selected' => (string) $value == $data
3418 $context->options = $options;
3420 $element = $OUTPUT->render_from_template($template, $context);
3422 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3428 * Select multiple items from list
3430 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3432 class admin_setting_configmultiselect extends admin_setting_configselect {
3434 * Constructor
3435 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3436 * @param string $visiblename localised
3437 * @param string $description long localised info
3438 * @param array $defaultsetting array of selected items
3439 * @param array $choices array of $value=>$label for each list item
3441 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3442 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3446 * Returns the select setting(s)
3448 * @return mixed null or array. Null if no settings else array of setting(s)
3450 public function get_setting() {
3451 $result = $this->config_read($this->name);
3452 if (is_null($result)) {
3453 return NULL;
3455 if ($result === '') {
3456 return array();
3458 return explode(',', $result);
3462 * Saves setting(s) provided through $data
3464 * Potential bug in the works should anyone call with this function
3465 * using a vartype that is not an array
3467 * @param array $data
3469 public function write_setting($data) {
3470 if (!is_array($data)) {
3471 return ''; //ignore it
3473 if (!$this->load_choices() or empty($this->choices)) {
3474 return '';
3477 unset($data['xxxxx']);
3479 $save = array();
3480 foreach ($data as $value) {
3481 if (!array_key_exists($value, $this->choices)) {
3482 continue; // ignore it
3484 $save[] = $value;
3487 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3491 * Is setting related to query text - used when searching
3493 * @param string $query
3494 * @return bool true if related, false if not
3496 public function is_related($query) {
3497 if (!$this->load_choices() or empty($this->choices)) {
3498 return false;
3500 if (parent::is_related($query)) {
3501 return true;
3504 foreach ($this->choices as $desc) {
3505 if (strpos(core_text::strtolower($desc), $query) !== false) {
3506 return true;
3509 return false;
3513 * Returns XHTML multi-select field
3515 * @todo Add vartype handling to ensure $data is an array
3516 * @param array $data Array of values to select by default
3517 * @param string $query
3518 * @return string XHTML multi-select field
3520 public function output_html($data, $query='') {
3521 global $OUTPUT;
3523 if (!$this->load_choices() or empty($this->choices)) {
3524 return '';
3527 $default = $this->get_defaultsetting();
3528 if (is_null($default)) {
3529 $default = array();
3531 if (is_null($data)) {
3532 $data = array();
3535 $context = (object) [
3536 'id' => $this->get_id(),
3537 'name' => $this->get_full_name(),
3538 'size' => min(10, count($this->choices))
3541 $defaults = [];
3542 $options = [];
3543 $template = 'core_admin/setting_configmultiselect';
3545 if (!empty($this->optgroups)) {
3546 $optgroups = [];
3547 foreach ($this->optgroups as $label => $choices) {
3548 $optgroup = array('label' => $label, 'options' => []);
3549 foreach ($choices as $value => $name) {
3550 if (in_array($value, $default)) {
3551 $defaults[] = $name;
3553 $optgroup['options'][] = [
3554 'value' => $value,
3555 'name' => $name,
3556 'selected' => in_array($value, $data)
3558 unset($this->choices[$value]);
3560 $optgroups[] = $optgroup;
3562 $context->optgroups = $optgroups;
3563 $template = 'core_admin/setting_configmultiselect_optgroup';
3566 foreach ($this->choices as $value => $name) {
3567 if (in_array($value, $default)) {
3568 $defaults[] = $name;
3570 $options[] = [
3571 'value' => $value,
3572 'name' => $name,
3573 'selected' => in_array($value, $data)
3576 $context->options = $options;
3578 if (is_null($default)) {
3579 $defaultinfo = NULL;
3580 } if (!empty($defaults)) {
3581 $defaultinfo = implode(', ', $defaults);
3582 } else {
3583 $defaultinfo = get_string('none');
3586 $element = $OUTPUT->render_from_template($template, $context);
3588 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3593 * Time selector
3595 * This is a liiitle bit messy. we're using two selects, but we're returning
3596 * them as an array named after $name (so we only use $name2 internally for the setting)
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 class admin_setting_configtime extends admin_setting {
3601 /** @var string Used for setting second select (minutes) */
3602 public $name2;
3605 * Constructor
3606 * @param string $hoursname setting for hours
3607 * @param string $minutesname setting for hours
3608 * @param string $visiblename localised
3609 * @param string $description long localised info
3610 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3612 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3613 $this->name2 = $minutesname;
3614 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3618 * Get the selected time
3620 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3622 public function get_setting() {
3623 $result1 = $this->config_read($this->name);
3624 $result2 = $this->config_read($this->name2);
3625 if (is_null($result1) or is_null($result2)) {
3626 return NULL;
3629 return array('h' => $result1, 'm' => $result2);
3633 * Store the time (hours and minutes)
3635 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3636 * @return bool true if success, false if not
3638 public function write_setting($data) {
3639 if (!is_array($data)) {
3640 return '';
3643 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3644 return ($result ? '' : get_string('errorsetting', 'admin'));
3648 * Returns XHTML time select fields
3650 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3651 * @param string $query
3652 * @return string XHTML time select fields and wrapping div(s)
3654 public function output_html($data, $query='') {
3655 global $OUTPUT;
3657 $default = $this->get_defaultsetting();
3658 if (is_array($default)) {
3659 $defaultinfo = $default['h'].':'.$default['m'];
3660 } else {
3661 $defaultinfo = NULL;
3664 $context = (object) [
3665 'id' => $this->get_id(),
3666 'name' => $this->get_full_name(),
3667 'hours' => array_map(function($i) use ($data) {
3668 return [
3669 'value' => $i,
3670 'name' => $i,
3671 'selected' => $i == $data['h']
3673 }, range(0, 23)),
3674 'minutes' => array_map(function($i) use ($data) {
3675 return [
3676 'value' => $i,
3677 'name' => $i,
3678 'selected' => $i == $data['m']
3680 }, range(0, 59, 5))
3683 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3685 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3686 $this->get_id() . 'h', '', $defaultinfo, $query);
3693 * Seconds duration setting.
3695 * @copyright 2012 Petr Skoda (http://skodak.org)
3696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3698 class admin_setting_configduration extends admin_setting {
3700 /** @var int default duration unit */
3701 protected $defaultunit;
3704 * Constructor
3705 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3706 * or 'myplugin/mysetting' for ones in config_plugins.
3707 * @param string $visiblename localised name
3708 * @param string $description localised long description
3709 * @param mixed $defaultsetting string or array depending on implementation
3710 * @param int $defaultunit - day, week, etc. (in seconds)
3712 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3713 if (is_number($defaultsetting)) {
3714 $defaultsetting = self::parse_seconds($defaultsetting);
3716 $units = self::get_units();
3717 if (isset($units[$defaultunit])) {
3718 $this->defaultunit = $defaultunit;
3719 } else {
3720 $this->defaultunit = 86400;
3722 parent::__construct($name, $visiblename, $description, $defaultsetting);
3726 * Returns selectable units.
3727 * @static
3728 * @return array
3730 protected static function get_units() {
3731 return array(
3732 604800 => get_string('weeks'),
3733 86400 => get_string('days'),
3734 3600 => get_string('hours'),
3735 60 => get_string('minutes'),
3736 1 => get_string('seconds'),
3741 * Converts seconds to some more user friendly string.
3742 * @static
3743 * @param int $seconds
3744 * @return string
3746 protected static function get_duration_text($seconds) {
3747 if (empty($seconds)) {
3748 return get_string('none');
3750 $data = self::parse_seconds($seconds);
3751 switch ($data['u']) {
3752 case (60*60*24*7):
3753 return get_string('numweeks', '', $data['v']);
3754 case (60*60*24):
3755 return get_string('numdays', '', $data['v']);
3756 case (60*60):
3757 return get_string('numhours', '', $data['v']);
3758 case (60):
3759 return get_string('numminutes', '', $data['v']);
3760 default:
3761 return get_string('numseconds', '', $data['v']*$data['u']);
3766 * Finds suitable units for given duration.
3767 * @static
3768 * @param int $seconds
3769 * @return array
3771 protected static function parse_seconds($seconds) {
3772 foreach (self::get_units() as $unit => $unused) {
3773 if ($seconds % $unit === 0) {
3774 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3777 return array('v'=>(int)$seconds, 'u'=>1);
3781 * Get the selected duration as array.
3783 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3785 public function get_setting() {
3786 $seconds = $this->config_read($this->name);
3787 if (is_null($seconds)) {
3788 return null;
3791 return self::parse_seconds($seconds);
3795 * Store the duration as seconds.
3797 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3798 * @return bool true if success, false if not
3800 public function write_setting($data) {
3801 if (!is_array($data)) {
3802 return '';
3805 $seconds = (int)($data['v']*$data['u']);
3806 if ($seconds < 0) {
3807 return get_string('errorsetting', 'admin');
3810 $result = $this->config_write($this->name, $seconds);
3811 return ($result ? '' : get_string('errorsetting', 'admin'));
3815 * Returns duration text+select fields.
3817 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3818 * @param string $query
3819 * @return string duration text+select fields and wrapping div(s)
3821 public function output_html($data, $query='') {
3822 global $OUTPUT;
3824 $default = $this->get_defaultsetting();
3825 if (is_number($default)) {
3826 $defaultinfo = self::get_duration_text($default);
3827 } else if (is_array($default)) {
3828 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3829 } else {
3830 $defaultinfo = null;
3833 $inputid = $this->get_id() . 'v';
3834 $units = self::get_units();
3835 $defaultunit = $this->defaultunit;
3837 $context = (object) [
3838 'id' => $this->get_id(),
3839 'name' => $this->get_full_name(),
3840 'value' => $data['v'],
3841 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3842 return [
3843 'value' => $unit,
3844 'name' => $units[$unit],
3845 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3847 }, array_keys($units))
3850 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3852 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3858 * Seconds duration setting with an advanced checkbox, that controls a additional
3859 * $name.'_adv' setting.
3861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3862 * @copyright 2014 The Open University
3864 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3866 * Constructor
3867 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3868 * or 'myplugin/mysetting' for ones in config_plugins.
3869 * @param string $visiblename localised name
3870 * @param string $description localised long description
3871 * @param array $defaultsetting array of int value, and bool whether it is
3872 * is advanced by default.
3873 * @param int $defaultunit - day, week, etc. (in seconds)
3875 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3876 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3877 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3883 * Used to validate a textarea used for ip addresses
3885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3886 * @copyright 2011 Petr Skoda (http://skodak.org)
3888 class admin_setting_configiplist extends admin_setting_configtextarea {
3891 * Validate the contents of the textarea as IP addresses
3893 * Used to validate a new line separated list of IP addresses collected from
3894 * a textarea control
3896 * @param string $data A list of IP Addresses separated by new lines
3897 * @return mixed bool true for success or string:error on failure
3899 public function validate($data) {
3900 if(!empty($data)) {
3901 $lines = explode("\n", $data);
3902 } else {
3903 return true;
3905 $result = true;
3906 $badips = array();
3907 foreach ($lines as $line) {
3908 $tokens = explode('#', $line);
3909 $ip = trim($tokens[0]);
3910 if (empty($ip)) {
3911 continue;
3913 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3914 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3915 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3916 } else {
3917 $result = false;
3918 $badips[] = $ip;
3921 if($result) {
3922 return true;
3923 } else {
3924 return get_string('validateiperror', 'admin', join(', ', $badips));
3930 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3933 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3935 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3938 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3939 * Used to validate a new line separated list of entries collected from a textarea control.
3941 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3942 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3943 * via the get_setting() method, which has been overriden.
3945 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3946 * @return mixed bool true for success or string:error on failure
3948 public function validate($data) {
3949 if (empty($data)) {
3950 return true;
3952 $entries = explode("\n", $data);
3953 $badentries = [];
3955 foreach ($entries as $key => $entry) {
3956 $entry = trim($entry);
3957 if (empty($entry)) {
3958 return get_string('validateemptylineerror', 'admin');
3961 // Validate each string entry against the supported formats.
3962 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3963 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3964 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3965 continue;
3968 // Otherwise, the entry is invalid.
3969 $badentries[] = $entry;
3972 if ($badentries) {
3973 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3975 return true;
3979 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3981 * @param string $data the setting data, as sent from the web form.
3982 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3984 protected function ace_encode($data) {
3985 if (empty($data)) {
3986 return $data;
3988 $entries = explode("\n", $data);
3989 foreach ($entries as $key => $entry) {
3990 $entry = trim($entry);
3991 // This regex matches any string that has non-ascii character.
3992 if (preg_match('/[^\x00-\x7f]/', $entry)) {
3993 // If we can convert the unicode string to an idn, do so.
3994 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3995 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3996 $entries[$key] = $val ? $val : $entry;
3999 return implode("\n", $entries);
4003 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4005 * @param string $data the setting data, as found in the database.
4006 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4008 protected function ace_decode($data) {
4009 $entries = explode("\n", $data);
4010 foreach ($entries as $key => $entry) {
4011 $entry = trim($entry);
4012 if (strpos($entry, 'xn--') !== false) {
4013 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
4016 return implode("\n", $entries);
4020 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4022 * @return mixed returns punycode-converted setting string if successful, else null.
4024 public function get_setting() {
4025 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4026 $data = $this->config_read($this->name);
4027 if (function_exists('idn_to_utf8') && !is_null($data)) {
4028 $data = $this->ace_decode($data);
4030 return $data;
4034 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4036 * @param string $data
4037 * @return string
4039 public function write_setting($data) {
4040 if ($this->paramtype === PARAM_INT and $data === '') {
4041 // Do not complain if '' used instead of 0.
4042 $data = 0;
4045 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4046 if (function_exists('idn_to_ascii')) {
4047 $data = $this->ace_encode($data);
4050 $validated = $this->validate($data);
4051 if ($validated !== true) {
4052 return $validated;
4054 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4059 * Used to validate a textarea used for port numbers.
4061 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4062 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4064 class admin_setting_configportlist extends admin_setting_configtextarea {
4067 * Validate the contents of the textarea as port numbers.
4068 * Used to validate a new line separated list of ports collected from a textarea control.
4070 * @param string $data A list of ports separated by new lines
4071 * @return mixed bool true for success or string:error on failure
4073 public function validate($data) {
4074 if (empty($data)) {
4075 return true;
4077 $ports = explode("\n", $data);
4078 $badentries = [];
4079 foreach ($ports as $port) {
4080 $port = trim($port);
4081 if (empty($port)) {
4082 return get_string('validateemptylineerror', 'admin');
4085 // Is the string a valid integer number?
4086 if (strval(intval($port)) !== $port || intval($port) <= 0) {
4087 $badentries[] = $port;
4090 if ($badentries) {
4091 return get_string('validateerrorlist', 'admin', $badentries);
4093 return true;
4099 * An admin setting for selecting one or more users who have a capability
4100 * in the system context
4102 * An admin setting for selecting one or more users, who have a particular capability
4103 * in the system context. Warning, make sure the list will never be too long. There is
4104 * no paging or searching of this list.
4106 * To correctly get a list of users from this config setting, you need to call the
4107 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4111 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
4112 /** @var string The capabilities name */
4113 protected $capability;
4114 /** @var int include admin users too */
4115 protected $includeadmins;
4118 * Constructor.
4120 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4121 * @param string $visiblename localised name
4122 * @param string $description localised long description
4123 * @param array $defaultsetting array of usernames
4124 * @param string $capability string capability name.
4125 * @param bool $includeadmins include administrators
4127 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4128 $this->capability = $capability;
4129 $this->includeadmins = $includeadmins;
4130 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4134 * Load all of the uses who have the capability into choice array
4136 * @return bool Always returns true
4138 function load_choices() {
4139 if (is_array($this->choices)) {
4140 return true;
4142 list($sort, $sortparams) = users_order_by_sql('u');
4143 if (!empty($sortparams)) {
4144 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4145 'This is unexpected, and a problem because there is no way to pass these ' .
4146 'parameters to get_users_by_capability. See MDL-34657.');
4148 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
4149 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
4150 $this->choices = array(
4151 '$@NONE@$' => get_string('nobody'),
4152 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
4154 if ($this->includeadmins) {
4155 $admins = get_admins();
4156 foreach ($admins as $user) {
4157 $this->choices[$user->id] = fullname($user);
4160 if (is_array($users)) {
4161 foreach ($users as $user) {
4162 $this->choices[$user->id] = fullname($user);
4165 return true;
4169 * Returns the default setting for class
4171 * @return mixed Array, or string. Empty string if no default
4173 public function get_defaultsetting() {
4174 $this->load_choices();
4175 $defaultsetting = parent::get_defaultsetting();
4176 if (empty($defaultsetting)) {
4177 return array('$@NONE@$');
4178 } else if (array_key_exists($defaultsetting, $this->choices)) {
4179 return $defaultsetting;
4180 } else {
4181 return '';
4186 * Returns the current setting
4188 * @return mixed array or string
4190 public function get_setting() {
4191 $result = parent::get_setting();
4192 if ($result === null) {
4193 // this is necessary for settings upgrade
4194 return null;
4196 if (empty($result)) {
4197 $result = array('$@NONE@$');
4199 return $result;
4203 * Save the chosen setting provided as $data
4205 * @param array $data
4206 * @return mixed string or array
4208 public function write_setting($data) {
4209 // If all is selected, remove any explicit options.
4210 if (in_array('$@ALL@$', $data)) {
4211 $data = array('$@ALL@$');
4213 // None never needs to be written to the DB.
4214 if (in_array('$@NONE@$', $data)) {
4215 unset($data[array_search('$@NONE@$', $data)]);
4217 return parent::write_setting($data);
4223 * Special checkbox for calendar - resets SESSION vars.
4225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4227 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
4229 * Calls the parent::__construct with default values
4231 * name => calendar_adminseesall
4232 * visiblename => get_string('adminseesall', 'admin')
4233 * description => get_string('helpadminseesall', 'admin')
4234 * defaultsetting => 0
4236 public function __construct() {
4237 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4238 get_string('helpadminseesall', 'admin'), '0');
4242 * Stores the setting passed in $data
4244 * @param mixed gets converted to string for comparison
4245 * @return string empty string or error message
4247 public function write_setting($data) {
4248 global $SESSION;
4249 return parent::write_setting($data);
4254 * Special select for settings that are altered in setup.php and can not be altered on the fly
4256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4258 class admin_setting_special_selectsetup extends admin_setting_configselect {
4260 * Reads the setting directly from the database
4262 * @return mixed
4264 public function get_setting() {
4265 // read directly from db!
4266 return get_config(NULL, $this->name);
4270 * Save the setting passed in $data
4272 * @param string $data The setting to save
4273 * @return string empty or error message
4275 public function write_setting($data) {
4276 global $CFG;
4277 // do not change active CFG setting!
4278 $current = $CFG->{$this->name};
4279 $result = parent::write_setting($data);
4280 $CFG->{$this->name} = $current;
4281 return $result;
4287 * Special select for frontpage - stores data in course table
4289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4291 class admin_setting_sitesetselect extends admin_setting_configselect {
4293 * Returns the site name for the selected site
4295 * @see get_site()
4296 * @return string The site name of the selected site
4298 public function get_setting() {
4299 $site = course_get_format(get_site())->get_course();
4300 return $site->{$this->name};
4304 * Updates the database and save the setting
4306 * @param string data
4307 * @return string empty or error message
4309 public function write_setting($data) {
4310 global $DB, $SITE, $COURSE;
4311 if (!in_array($data, array_keys($this->choices))) {
4312 return get_string('errorsetting', 'admin');
4314 $record = new stdClass();
4315 $record->id = SITEID;
4316 $temp = $this->name;
4317 $record->$temp = $data;
4318 $record->timemodified = time();
4320 course_get_format($SITE)->update_course_format_options($record);
4321 $DB->update_record('course', $record);
4323 // Reset caches.
4324 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4325 if ($SITE->id == $COURSE->id) {
4326 $COURSE = $SITE;
4328 format_base::reset_course_cache($SITE->id);
4330 return '';
4337 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4338 * block to hidden.
4340 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4342 class admin_setting_bloglevel extends admin_setting_configselect {
4344 * Updates the database and save the setting
4346 * @param string data
4347 * @return string empty or error message
4349 public function write_setting($data) {
4350 global $DB, $CFG;
4351 if ($data == 0) {
4352 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4353 foreach ($blogblocks as $block) {
4354 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4356 } else {
4357 // reenable all blocks only when switching from disabled blogs
4358 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4359 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4360 foreach ($blogblocks as $block) {
4361 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4365 return parent::write_setting($data);
4371 * Special select - lists on the frontpage - hacky
4373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4375 class admin_setting_courselist_frontpage extends admin_setting {
4376 /** @var array Array of choices value=>label */
4377 public $choices;
4380 * Construct override, requires one param
4382 * @param bool $loggedin Is the user logged in
4384 public function __construct($loggedin) {
4385 global $CFG;
4386 require_once($CFG->dirroot.'/course/lib.php');
4387 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4388 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4389 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4390 $defaults = array(FRONTPAGEALLCOURSELIST);
4391 parent::__construct($name, $visiblename, $description, $defaults);
4395 * Loads the choices available
4397 * @return bool always returns true
4399 public function load_choices() {
4400 if (is_array($this->choices)) {
4401 return true;
4403 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4404 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4405 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4406 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4407 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4408 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4409 'none' => get_string('none'));
4410 if ($this->name === 'frontpage') {
4411 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4413 return true;
4417 * Returns the selected settings
4419 * @param mixed array or setting or null
4421 public function get_setting() {
4422 $result = $this->config_read($this->name);
4423 if (is_null($result)) {
4424 return NULL;
4426 if ($result === '') {
4427 return array();
4429 return explode(',', $result);
4433 * Save the selected options
4435 * @param array $data
4436 * @return mixed empty string (data is not an array) or bool true=success false=failure
4438 public function write_setting($data) {
4439 if (!is_array($data)) {
4440 return '';
4442 $this->load_choices();
4443 $save = array();
4444 foreach($data as $datum) {
4445 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4446 continue;
4448 $save[$datum] = $datum; // no duplicates
4450 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4454 * Return XHTML select field and wrapping div
4456 * @todo Add vartype handling to make sure $data is an array
4457 * @param array $data Array of elements to select by default
4458 * @return string XHTML select field and wrapping div
4460 public function output_html($data, $query='') {
4461 global $OUTPUT;
4463 $this->load_choices();
4464 $currentsetting = array();
4465 foreach ($data as $key) {
4466 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4467 $currentsetting[] = $key; // already selected first
4471 $context = (object) [
4472 'id' => $this->get_id(),
4473 'name' => $this->get_full_name(),
4476 $options = $this->choices;
4477 $selects = [];
4478 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4479 if (!array_key_exists($i, $currentsetting)) {
4480 $currentsetting[$i] = 'none';
4482 $selects[] = [
4483 'key' => $i,
4484 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4485 return [
4486 'name' => $options[$option],
4487 'value' => $option,
4488 'selected' => $currentsetting[$i] == $option
4490 }, array_keys($options))
4493 $context->selects = $selects;
4495 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4497 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4503 * Special checkbox for frontpage - stores data in course table
4505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4507 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4509 * Returns the current sites name
4511 * @return string
4513 public function get_setting() {
4514 $site = course_get_format(get_site())->get_course();
4515 return $site->{$this->name};
4519 * Save the selected setting
4521 * @param string $data The selected site
4522 * @return string empty string or error message
4524 public function write_setting($data) {
4525 global $DB, $SITE, $COURSE;
4526 $record = new stdClass();
4527 $record->id = $SITE->id;
4528 $record->{$this->name} = ($data == '1' ? 1 : 0);
4529 $record->timemodified = time();
4531 course_get_format($SITE)->update_course_format_options($record);
4532 $DB->update_record('course', $record);
4534 // Reset caches.
4535 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4536 if ($SITE->id == $COURSE->id) {
4537 $COURSE = $SITE;
4539 format_base::reset_course_cache($SITE->id);
4541 return '';
4546 * Special text for frontpage - stores data in course table.
4547 * Empty string means not set here. Manual setting is required.
4549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4551 class admin_setting_sitesettext extends admin_setting_configtext {
4554 * Constructor.
4556 public function __construct() {
4557 call_user_func_array(['parent', '__construct'], func_get_args());
4558 $this->set_force_ltr(false);
4562 * Return the current setting
4564 * @return mixed string or null
4566 public function get_setting() {
4567 $site = course_get_format(get_site())->get_course();
4568 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4572 * Validate the selected data
4574 * @param string $data The selected value to validate
4575 * @return mixed true or message string
4577 public function validate($data) {
4578 global $DB, $SITE;
4579 $cleaned = clean_param($data, PARAM_TEXT);
4580 if ($cleaned === '') {
4581 return get_string('required');
4583 if ($this->name ==='shortname' &&
4584 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4585 return get_string('shortnametaken', 'error', $data);
4587 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4588 return true;
4589 } else {
4590 return get_string('validateerror', 'admin');
4595 * Save the selected setting
4597 * @param string $data The selected value
4598 * @return string empty or error message
4600 public function write_setting($data) {
4601 global $DB, $SITE, $COURSE;
4602 $data = trim($data);
4603 $validated = $this->validate($data);
4604 if ($validated !== true) {
4605 return $validated;
4608 $record = new stdClass();
4609 $record->id = $SITE->id;
4610 $record->{$this->name} = $data;
4611 $record->timemodified = time();
4613 course_get_format($SITE)->update_course_format_options($record);
4614 $DB->update_record('course', $record);
4616 // Reset caches.
4617 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4618 if ($SITE->id == $COURSE->id) {
4619 $COURSE = $SITE;
4621 format_base::reset_course_cache($SITE->id);
4623 return '';
4629 * Special text editor for site description.
4631 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4633 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4636 * Calls parent::__construct with specific arguments
4638 public function __construct() {
4639 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4640 PARAM_RAW, 60, 15);
4644 * Return the current setting
4645 * @return string The current setting
4647 public function get_setting() {
4648 $site = course_get_format(get_site())->get_course();
4649 return $site->{$this->name};
4653 * Save the new setting
4655 * @param string $data The new value to save
4656 * @return string empty or error message
4658 public function write_setting($data) {
4659 global $DB, $SITE, $COURSE;
4660 $record = new stdClass();
4661 $record->id = $SITE->id;
4662 $record->{$this->name} = $data;
4663 $record->timemodified = time();
4665 course_get_format($SITE)->update_course_format_options($record);
4666 $DB->update_record('course', $record);
4668 // Reset caches.
4669 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4670 if ($SITE->id == $COURSE->id) {
4671 $COURSE = $SITE;
4673 format_base::reset_course_cache($SITE->id);
4675 return '';
4681 * Administration interface for emoticon_manager settings.
4683 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4685 class admin_setting_emoticons extends admin_setting {
4688 * Calls parent::__construct with specific args
4690 public function __construct() {
4691 global $CFG;
4693 $manager = get_emoticon_manager();
4694 $defaults = $this->prepare_form_data($manager->default_emoticons());
4695 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4699 * Return the current setting(s)
4701 * @return array Current settings array
4703 public function get_setting() {
4704 global $CFG;
4706 $manager = get_emoticon_manager();
4708 $config = $this->config_read($this->name);
4709 if (is_null($config)) {
4710 return null;
4713 $config = $manager->decode_stored_config($config);
4714 if (is_null($config)) {
4715 return null;
4718 return $this->prepare_form_data($config);
4722 * Save selected settings
4724 * @param array $data Array of settings to save
4725 * @return bool
4727 public function write_setting($data) {
4729 $manager = get_emoticon_manager();
4730 $emoticons = $this->process_form_data($data);
4732 if ($emoticons === false) {
4733 return false;
4736 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4737 return ''; // success
4738 } else {
4739 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4744 * Return XHTML field(s) for options
4746 * @param array $data Array of options to set in HTML
4747 * @return string XHTML string for the fields and wrapping div(s)
4749 public function output_html($data, $query='') {
4750 global $OUTPUT;
4752 $context = (object) [
4753 'name' => $this->get_full_name(),
4754 'emoticons' => [],
4755 'forceltr' => true,
4758 $i = 0;
4759 foreach ($data as $field => $value) {
4761 // When $i == 0: text.
4762 // When $i == 1: imagename.
4763 // When $i == 2: imagecomponent.
4764 // When $i == 3: altidentifier.
4765 // When $i == 4: altcomponent.
4766 $fields[$i] = (object) [
4767 'field' => $field,
4768 'value' => $value,
4769 'index' => $i
4771 $i++;
4773 if ($i > 4) {
4774 $icon = null;
4775 if (!empty($fields[1]->value)) {
4776 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4777 $alt = get_string($fields[3]->value, $fields[4]->value);
4778 } else {
4779 $alt = $fields[0]->value;
4781 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4783 $context->emoticons[] = [
4784 'fields' => $fields,
4785 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4787 $fields = [];
4788 $i = 0;
4792 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4793 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4794 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4798 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4800 * @see self::process_form_data()
4801 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4802 * @return array of form fields and their values
4804 protected function prepare_form_data(array $emoticons) {
4806 $form = array();
4807 $i = 0;
4808 foreach ($emoticons as $emoticon) {
4809 $form['text'.$i] = $emoticon->text;
4810 $form['imagename'.$i] = $emoticon->imagename;
4811 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4812 $form['altidentifier'.$i] = $emoticon->altidentifier;
4813 $form['altcomponent'.$i] = $emoticon->altcomponent;
4814 $i++;
4816 // add one more blank field set for new object
4817 $form['text'.$i] = '';
4818 $form['imagename'.$i] = '';
4819 $form['imagecomponent'.$i] = '';
4820 $form['altidentifier'.$i] = '';
4821 $form['altcomponent'.$i] = '';
4823 return $form;
4827 * Converts the data from admin settings form into an array of emoticon objects
4829 * @see self::prepare_form_data()
4830 * @param array $data array of admin form fields and values
4831 * @return false|array of emoticon objects
4833 protected function process_form_data(array $form) {
4835 $count = count($form); // number of form field values
4837 if ($count % 5) {
4838 // we must get five fields per emoticon object
4839 return false;
4842 $emoticons = array();
4843 for ($i = 0; $i < $count / 5; $i++) {
4844 $emoticon = new stdClass();
4845 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4846 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4847 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4848 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4849 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4851 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4852 // prevent from breaking http://url.addresses by accident
4853 $emoticon->text = '';
4856 if (strlen($emoticon->text) < 2) {
4857 // do not allow single character emoticons
4858 $emoticon->text = '';
4861 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4862 // emoticon text must contain some non-alphanumeric character to prevent
4863 // breaking HTML tags
4864 $emoticon->text = '';
4867 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4868 $emoticons[] = $emoticon;
4871 return $emoticons;
4878 * Special setting for limiting of the list of available languages.
4880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4882 class admin_setting_langlist extends admin_setting_configtext {
4884 * Calls parent::__construct with specific arguments
4886 public function __construct() {
4887 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4891 * Save the new setting
4893 * @param string $data The new setting
4894 * @return bool
4896 public function write_setting($data) {
4897 $return = parent::write_setting($data);
4898 get_string_manager()->reset_caches();
4899 return $return;
4905 * Selection of one of the recognised countries using the list
4906 * returned by {@link get_list_of_countries()}.
4908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4910 class admin_settings_country_select extends admin_setting_configselect {
4911 protected $includeall;
4912 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4913 $this->includeall = $includeall;
4914 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4918 * Lazy-load the available choices for the select box
4920 public function load_choices() {
4921 global $CFG;
4922 if (is_array($this->choices)) {
4923 return true;
4925 $this->choices = array_merge(
4926 array('0' => get_string('choosedots')),
4927 get_string_manager()->get_list_of_countries($this->includeall));
4928 return true;
4934 * admin_setting_configselect for the default number of sections in a course,
4935 * simply so we can lazy-load the choices.
4937 * @copyright 2011 The Open University
4938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4940 class admin_settings_num_course_sections extends admin_setting_configselect {
4941 public function __construct($name, $visiblename, $description, $defaultsetting) {
4942 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4945 /** Lazy-load the available choices for the select box */
4946 public function load_choices() {
4947 $max = get_config('moodlecourse', 'maxsections');
4948 if (!isset($max) || !is_numeric($max)) {
4949 $max = 52;
4951 for ($i = 0; $i <= $max; $i++) {
4952 $this->choices[$i] = "$i";
4954 return true;
4960 * Course category selection
4962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4964 class admin_settings_coursecat_select extends admin_setting_configselect {
4966 * Calls parent::__construct with specific arguments
4968 public function __construct($name, $visiblename, $description, $defaultsetting) {
4969 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4973 * Load the available choices for the select box
4975 * @return bool
4977 public function load_choices() {
4978 global $CFG;
4979 require_once($CFG->dirroot.'/course/lib.php');
4980 if (is_array($this->choices)) {
4981 return true;
4983 $this->choices = core_course_category::make_categories_list('', 0, ' / ');
4984 return true;
4990 * Special control for selecting days to backup
4992 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4994 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4996 * Calls parent::__construct with specific arguments
4998 public function __construct() {
4999 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5000 $this->plugin = 'backup';
5004 * Load the available choices for the select box
5006 * @return bool Always returns true
5008 public function load_choices() {
5009 if (is_array($this->choices)) {
5010 return true;
5012 $this->choices = array();
5013 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5014 foreach ($days as $day) {
5015 $this->choices[$day] = get_string($day, 'calendar');
5017 return true;
5022 * Special setting for backup auto destination.
5024 * @package core
5025 * @subpackage admin
5026 * @copyright 2014 Frédéric Massart - FMCorz.net
5027 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5029 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
5032 * Calls parent::__construct with specific arguments.
5034 public function __construct() {
5035 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5039 * Check if the directory must be set, depending on backup/backup_auto_storage.
5041 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5042 * there will be conflicts if this validation happens before the other one.
5044 * @param string $data Form data.
5045 * @return string Empty when no errors.
5047 public function write_setting($data) {
5048 $storage = (int) get_config('backup', 'backup_auto_storage');
5049 if ($storage !== 0) {
5050 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
5051 // The directory must exist and be writable.
5052 return get_string('backuperrorinvaliddestination');
5055 return parent::write_setting($data);
5061 * Special debug setting
5063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 class admin_setting_special_debug extends admin_setting_configselect {
5067 * Calls parent::__construct with specific arguments
5069 public function __construct() {
5070 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
5074 * Load the available choices for the select box
5076 * @return bool
5078 public function load_choices() {
5079 if (is_array($this->choices)) {
5080 return true;
5082 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
5083 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
5084 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
5085 DEBUG_ALL => get_string('debugall', 'admin'),
5086 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
5087 return true;
5093 * Special admin control
5095 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5097 class admin_setting_special_calendar_weekend extends admin_setting {
5099 * Calls parent::__construct with specific arguments
5101 public function __construct() {
5102 $name = 'calendar_weekend';
5103 $visiblename = get_string('calendar_weekend', 'admin');
5104 $description = get_string('helpweekenddays', 'admin');
5105 $default = array ('0', '6'); // Saturdays and Sundays
5106 parent::__construct($name, $visiblename, $description, $default);
5110 * Gets the current settings as an array
5112 * @return mixed Null if none, else array of settings
5114 public function get_setting() {
5115 $result = $this->config_read($this->name);
5116 if (is_null($result)) {
5117 return NULL;
5119 if ($result === '') {
5120 return array();
5122 $settings = array();
5123 for ($i=0; $i<7; $i++) {
5124 if ($result & (1 << $i)) {
5125 $settings[] = $i;
5128 return $settings;
5132 * Save the new settings
5134 * @param array $data Array of new settings
5135 * @return bool
5137 public function write_setting($data) {
5138 if (!is_array($data)) {
5139 return '';
5141 unset($data['xxxxx']);
5142 $result = 0;
5143 foreach($data as $index) {
5144 $result |= 1 << $index;
5146 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
5150 * Return XHTML to display the control
5152 * @param array $data array of selected days
5153 * @param string $query
5154 * @return string XHTML for display (field + wrapping div(s)
5156 public function output_html($data, $query='') {
5157 global $OUTPUT;
5159 // The order matters very much because of the implied numeric keys.
5160 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5161 $context = (object) [
5162 'name' => $this->get_full_name(),
5163 'id' => $this->get_id(),
5164 'days' => array_map(function($index) use ($days, $data) {
5165 return [
5166 'index' => $index,
5167 'label' => get_string($days[$index], 'calendar'),
5168 'checked' => in_array($index, $data)
5170 }, array_keys($days))
5173 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5175 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
5182 * Admin setting that allows a user to pick a behaviour.
5184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5186 class admin_setting_question_behaviour extends admin_setting_configselect {
5188 * @param string $name name of config variable
5189 * @param string $visiblename display name
5190 * @param string $description description
5191 * @param string $default default.
5193 public function __construct($name, $visiblename, $description, $default) {
5194 parent::__construct($name, $visiblename, $description, $default, null);
5198 * Load list of behaviours as choices
5199 * @return bool true => success, false => error.
5201 public function load_choices() {
5202 global $CFG;
5203 require_once($CFG->dirroot . '/question/engine/lib.php');
5204 $this->choices = question_engine::get_behaviour_options('');
5205 return true;
5211 * Admin setting that allows a user to pick appropriate roles for something.
5213 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5215 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
5216 /** @var array Array of capabilities which identify roles */
5217 private $types;
5220 * @param string $name Name of config variable
5221 * @param string $visiblename Display name
5222 * @param string $description Description
5223 * @param array $types Array of archetypes which identify
5224 * roles that will be enabled by default.
5226 public function __construct($name, $visiblename, $description, $types) {
5227 parent::__construct($name, $visiblename, $description, NULL, NULL);
5228 $this->types = $types;
5232 * Load roles as choices
5234 * @return bool true=>success, false=>error
5236 public function load_choices() {
5237 global $CFG, $DB;
5238 if (during_initial_install()) {
5239 return false;
5241 if (is_array($this->choices)) {
5242 return true;
5244 if ($roles = get_all_roles()) {
5245 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
5246 return true;
5247 } else {
5248 return false;
5253 * Return the default setting for this control
5255 * @return array Array of default settings
5257 public function get_defaultsetting() {
5258 global $CFG;
5260 if (during_initial_install()) {
5261 return null;
5263 $result = array();
5264 foreach($this->types as $archetype) {
5265 if ($caproles = get_archetype_roles($archetype)) {
5266 foreach ($caproles as $caprole) {
5267 $result[$caprole->id] = 1;
5271 return $result;
5277 * Admin setting that is a list of installed filter plugins.
5279 * @copyright 2015 The Open University
5280 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5282 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5285 * Constructor
5287 * @param string $name unique ascii name, either 'mysetting' for settings
5288 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5289 * @param string $visiblename localised name
5290 * @param string $description localised long description
5291 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5293 public function __construct($name, $visiblename, $description, $default) {
5294 if (empty($default)) {
5295 $default = array();
5297 $this->load_choices();
5298 foreach ($default as $plugin) {
5299 if (!isset($this->choices[$plugin])) {
5300 unset($default[$plugin]);
5303 parent::__construct($name, $visiblename, $description, $default, null);
5306 public function load_choices() {
5307 if (is_array($this->choices)) {
5308 return true;
5310 $this->choices = array();
5312 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5313 $this->choices[$plugin] = filter_get_name($plugin);
5315 return true;
5321 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5325 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5327 * Constructor
5328 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5329 * @param string $visiblename localised
5330 * @param string $description long localised info
5331 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5332 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5333 * @param int $size default field size
5335 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5336 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5337 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5343 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5345 * @copyright 2009 Petr Skoda (http://skodak.org)
5346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5348 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5351 * Constructor
5352 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5353 * @param string $visiblename localised
5354 * @param string $description long localised info
5355 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5356 * @param string $yes value used when checked
5357 * @param string $no value used when not checked
5359 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5360 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5361 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5368 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5370 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5372 * @copyright 2010 Sam Hemelryk
5373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5375 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5377 * Constructor
5378 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5379 * @param string $visiblename localised
5380 * @param string $description long localised info
5381 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5382 * @param string $yes value used when checked
5383 * @param string $no value used when not checked
5385 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5386 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5387 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5394 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5398 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5400 * Calls parent::__construct with specific arguments
5402 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5403 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5404 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5410 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5412 * @copyright 2017 Marina Glancy
5413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5415 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5417 * Constructor
5418 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5419 * or 'myplugin/mysetting' for ones in config_plugins.
5420 * @param string $visiblename localised
5421 * @param string $description long localised info
5422 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5423 * @param array $choices array of $value=>$label for each selection
5425 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5426 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5427 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5433 * Graded roles in gradebook
5435 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5437 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5439 * Calls parent::__construct with specific arguments
5441 public function __construct() {
5442 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5443 get_string('configgradebookroles', 'admin'),
5444 array('student'));
5451 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5453 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5455 * Saves the new settings passed in $data
5457 * @param string $data
5458 * @return mixed string or Array
5460 public function write_setting($data) {
5461 global $CFG, $DB;
5463 $oldvalue = $this->config_read($this->name);
5464 $return = parent::write_setting($data);
5465 $newvalue = $this->config_read($this->name);
5467 if ($oldvalue !== $newvalue) {
5468 // force full regrading
5469 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5472 return $return;
5478 * Which roles to show on course description page
5480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5482 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5484 * Calls parent::__construct with specific arguments
5486 public function __construct() {
5487 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5488 get_string('coursecontact_desc', 'admin'),
5489 array('editingteacher'));
5490 $this->set_updatedcallback(function (){
5491 cache::make('core', 'coursecontacts')->purge();
5499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5501 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5503 * Calls parent::__construct with specific arguments
5505 public function __construct() {
5506 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5507 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5511 * Old syntax of class constructor. Deprecated in PHP7.
5513 * @deprecated since Moodle 3.1
5515 public function admin_setting_special_gradelimiting() {
5516 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5517 self::__construct();
5521 * Force site regrading
5523 function regrade_all() {
5524 global $CFG;
5525 require_once("$CFG->libdir/gradelib.php");
5526 grade_force_site_regrading();
5530 * Saves the new settings
5532 * @param mixed $data
5533 * @return string empty string or error message
5535 function write_setting($data) {
5536 $previous = $this->get_setting();
5538 if ($previous === null) {
5539 if ($data) {
5540 $this->regrade_all();
5542 } else {
5543 if ($data != $previous) {
5544 $this->regrade_all();
5547 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5553 * Special setting for $CFG->grade_minmaxtouse.
5555 * @package core
5556 * @copyright 2015 Frédéric Massart - FMCorz.net
5557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5559 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5562 * Constructor.
5564 public function __construct() {
5565 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5566 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5567 array(
5568 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5569 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5575 * Saves the new setting.
5577 * @param mixed $data
5578 * @return string empty string or error message
5580 function write_setting($data) {
5581 global $CFG;
5583 $previous = $this->get_setting();
5584 $result = parent::write_setting($data);
5586 // If saved and the value has changed.
5587 if (empty($result) && $previous != $data) {
5588 require_once($CFG->libdir . '/gradelib.php');
5589 grade_force_site_regrading();
5592 return $result;
5599 * Primary grade export plugin - has state tracking.
5601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5603 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5605 * Calls parent::__construct with specific arguments
5607 public function __construct() {
5608 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5609 get_string('configgradeexport', 'admin'), array(), NULL);
5613 * Load the available choices for the multicheckbox
5615 * @return bool always returns true
5617 public function load_choices() {
5618 if (is_array($this->choices)) {
5619 return true;
5621 $this->choices = array();
5623 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5624 foreach($plugins as $plugin => $unused) {
5625 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5628 return true;
5634 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5636 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5638 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5640 * Config gradepointmax constructor
5642 * @param string $name Overidden by "gradepointmax"
5643 * @param string $visiblename Overridden by "gradepointmax" language string.
5644 * @param string $description Overridden by "gradepointmax_help" language string.
5645 * @param string $defaultsetting Not used, overridden by 100.
5646 * @param mixed $paramtype Overridden by PARAM_INT.
5647 * @param int $size Overridden by 5.
5649 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5650 $name = 'gradepointdefault';
5651 $visiblename = get_string('gradepointdefault', 'grades');
5652 $description = get_string('gradepointdefault_help', 'grades');
5653 $defaultsetting = 100;
5654 $paramtype = PARAM_INT;
5655 $size = 5;
5656 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5660 * Validate data before storage
5661 * @param string $data The submitted data
5662 * @return bool|string true if ok, string if error found
5664 public function validate($data) {
5665 global $CFG;
5666 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5667 return true;
5668 } else {
5669 return get_string('gradepointdefault_validateerror', 'grades');
5676 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5680 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5683 * Config gradepointmax constructor
5685 * @param string $name Overidden by "gradepointmax"
5686 * @param string $visiblename Overridden by "gradepointmax" language string.
5687 * @param string $description Overridden by "gradepointmax_help" language string.
5688 * @param string $defaultsetting Not used, overridden by 100.
5689 * @param mixed $paramtype Overridden by PARAM_INT.
5690 * @param int $size Overridden by 5.
5692 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5693 $name = 'gradepointmax';
5694 $visiblename = get_string('gradepointmax', 'grades');
5695 $description = get_string('gradepointmax_help', 'grades');
5696 $defaultsetting = 100;
5697 $paramtype = PARAM_INT;
5698 $size = 5;
5699 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5703 * Save the selected setting
5705 * @param string $data The selected site
5706 * @return string empty string or error message
5708 public function write_setting($data) {
5709 if ($data === '') {
5710 $data = (int)$this->defaultsetting;
5711 } else {
5712 $data = $data;
5714 return parent::write_setting($data);
5718 * Validate data before storage
5719 * @param string $data The submitted data
5720 * @return bool|string true if ok, string if error found
5722 public function validate($data) {
5723 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5724 return true;
5725 } else {
5726 return get_string('gradepointmax_validateerror', 'grades');
5731 * Return an XHTML string for the setting
5732 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5733 * @param string $query search query to be highlighted
5734 * @return string XHTML to display control
5736 public function output_html($data, $query = '') {
5737 global $OUTPUT;
5739 $default = $this->get_defaultsetting();
5740 $context = (object) [
5741 'size' => $this->size,
5742 'id' => $this->get_id(),
5743 'name' => $this->get_full_name(),
5744 'value' => $data,
5745 'attributes' => [
5746 'maxlength' => 5
5748 'forceltr' => $this->get_force_ltr()
5750 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5752 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5758 * Grade category settings
5760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5762 class admin_setting_gradecat_combo extends admin_setting {
5763 /** @var array Array of choices */
5764 public $choices;
5767 * Sets choices and calls parent::__construct with passed arguments
5768 * @param string $name
5769 * @param string $visiblename
5770 * @param string $description
5771 * @param mixed $defaultsetting string or array depending on implementation
5772 * @param array $choices An array of choices for the control
5774 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5775 $this->choices = $choices;
5776 parent::__construct($name, $visiblename, $description, $defaultsetting);
5780 * Return the current setting(s) array
5782 * @return array Array of value=>xx, forced=>xx, adv=>xx
5784 public function get_setting() {
5785 global $CFG;
5787 $value = $this->config_read($this->name);
5788 $flag = $this->config_read($this->name.'_flag');
5790 if (is_null($value) or is_null($flag)) {
5791 return NULL;
5794 $flag = (int)$flag;
5795 $forced = (boolean)(1 & $flag); // first bit
5796 $adv = (boolean)(2 & $flag); // second bit
5798 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5802 * Save the new settings passed in $data
5804 * @todo Add vartype handling to ensure $data is array
5805 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5806 * @return string empty or error message
5808 public function write_setting($data) {
5809 global $CFG;
5811 $value = $data['value'];
5812 $forced = empty($data['forced']) ? 0 : 1;
5813 $adv = empty($data['adv']) ? 0 : 2;
5814 $flag = ($forced | $adv); //bitwise or
5816 if (!in_array($value, array_keys($this->choices))) {
5817 return 'Error setting ';
5820 $oldvalue = $this->config_read($this->name);
5821 $oldflag = (int)$this->config_read($this->name.'_flag');
5822 $oldforced = (1 & $oldflag); // first bit
5824 $result1 = $this->config_write($this->name, $value);
5825 $result2 = $this->config_write($this->name.'_flag', $flag);
5827 // force regrade if needed
5828 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5829 require_once($CFG->libdir.'/gradelib.php');
5830 grade_category::updated_forced_settings();
5833 if ($result1 and $result2) {
5834 return '';
5835 } else {
5836 return get_string('errorsetting', 'admin');
5841 * Return XHTML to display the field and wrapping div
5843 * @todo Add vartype handling to ensure $data is array
5844 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5845 * @param string $query
5846 * @return string XHTML to display control
5848 public function output_html($data, $query='') {
5849 global $OUTPUT;
5851 $value = $data['value'];
5853 $default = $this->get_defaultsetting();
5854 if (!is_null($default)) {
5855 $defaultinfo = array();
5856 if (isset($this->choices[$default['value']])) {
5857 $defaultinfo[] = $this->choices[$default['value']];
5859 if (!empty($default['forced'])) {
5860 $defaultinfo[] = get_string('force');
5862 if (!empty($default['adv'])) {
5863 $defaultinfo[] = get_string('advanced');
5865 $defaultinfo = implode(', ', $defaultinfo);
5867 } else {
5868 $defaultinfo = NULL;
5871 $options = $this->choices;
5872 $context = (object) [
5873 'id' => $this->get_id(),
5874 'name' => $this->get_full_name(),
5875 'forced' => !empty($data['forced']),
5876 'advanced' => !empty($data['adv']),
5877 'options' => array_map(function($option) use ($options, $value) {
5878 return [
5879 'value' => $option,
5880 'name' => $options[$option],
5881 'selected' => $option == $value
5883 }, array_keys($options)),
5886 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5888 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5894 * Selection of grade report in user profiles
5896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5898 class admin_setting_grade_profilereport extends admin_setting_configselect {
5900 * Calls parent::__construct with specific arguments
5902 public function __construct() {
5903 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5907 * Loads an array of choices for the configselect control
5909 * @return bool always return true
5911 public function load_choices() {
5912 if (is_array($this->choices)) {
5913 return true;
5915 $this->choices = array();
5917 global $CFG;
5918 require_once($CFG->libdir.'/gradelib.php');
5920 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5921 if (file_exists($plugindir.'/lib.php')) {
5922 require_once($plugindir.'/lib.php');
5923 $functionname = 'grade_report_'.$plugin.'_profilereport';
5924 if (function_exists($functionname)) {
5925 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5929 return true;
5934 * Provides a selection of grade reports to be used for "grades".
5936 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5939 class admin_setting_my_grades_report extends admin_setting_configselect {
5942 * Calls parent::__construct with specific arguments.
5944 public function __construct() {
5945 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5946 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5950 * Loads an array of choices for the configselect control.
5952 * @return bool always returns true.
5954 public function load_choices() {
5955 global $CFG; // Remove this line and behold the horror of behat test failures!
5956 $this->choices = array();
5957 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5958 if (file_exists($plugindir . '/lib.php')) {
5959 require_once($plugindir . '/lib.php');
5960 // Check to see if the class exists. Check the correct plugin convention first.
5961 if (class_exists('gradereport_' . $plugin)) {
5962 $classname = 'gradereport_' . $plugin;
5963 } else if (class_exists('grade_report_' . $plugin)) {
5964 // We are using the old plugin naming convention.
5965 $classname = 'grade_report_' . $plugin;
5966 } else {
5967 continue;
5969 if ($classname::supports_mygrades()) {
5970 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5974 // Add an option to specify an external url.
5975 $this->choices['external'] = get_string('externalurl', 'grades');
5976 return true;
5981 * Special class for register auth selection
5983 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5985 class admin_setting_special_registerauth extends admin_setting_configselect {
5987 * Calls parent::__construct with specific arguments
5989 public function __construct() {
5990 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5994 * Returns the default option
5996 * @return string empty or default option
5998 public function get_defaultsetting() {
5999 $this->load_choices();
6000 $defaultsetting = parent::get_defaultsetting();
6001 if (array_key_exists($defaultsetting, $this->choices)) {
6002 return $defaultsetting;
6003 } else {
6004 return '';
6009 * Loads the possible choices for the array
6011 * @return bool always returns true
6013 public function load_choices() {
6014 global $CFG;
6016 if (is_array($this->choices)) {
6017 return true;
6019 $this->choices = array();
6020 $this->choices[''] = get_string('disable');
6022 $authsenabled = get_enabled_auth_plugins(true);
6024 foreach ($authsenabled as $auth) {
6025 $authplugin = get_auth_plugin($auth);
6026 if (!$authplugin->can_signup()) {
6027 continue;
6029 // Get the auth title (from core or own auth lang files)
6030 $authtitle = $authplugin->get_title();
6031 $this->choices[$auth] = $authtitle;
6033 return true;
6039 * General plugins manager
6041 class admin_page_pluginsoverview extends admin_externalpage {
6044 * Sets basic information about the external page
6046 public function __construct() {
6047 global $CFG;
6048 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6049 "$CFG->wwwroot/$CFG->admin/plugins.php");
6054 * Module manage page
6056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6058 class admin_page_managemods extends admin_externalpage {
6060 * Calls parent::__construct with specific arguments
6062 public function __construct() {
6063 global $CFG;
6064 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6068 * Try to find the specified module
6070 * @param string $query The module to search for
6071 * @return array
6073 public function search($query) {
6074 global $CFG, $DB;
6075 if ($result = parent::search($query)) {
6076 return $result;
6079 $found = false;
6080 if ($modules = $DB->get_records('modules')) {
6081 foreach ($modules as $module) {
6082 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6083 continue;
6085 if (strpos($module->name, $query) !== false) {
6086 $found = true;
6087 break;
6089 $strmodulename = get_string('modulename', $module->name);
6090 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
6091 $found = true;
6092 break;
6096 if ($found) {
6097 $result = new stdClass();
6098 $result->page = $this;
6099 $result->settings = array();
6100 return array($this->name => $result);
6101 } else {
6102 return array();
6109 * Special class for enrol plugins management.
6111 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6114 class admin_setting_manageenrols extends admin_setting {
6116 * Calls parent::__construct with specific arguments
6118 public function __construct() {
6119 $this->nosave = true;
6120 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6124 * Always returns true, does nothing
6126 * @return true
6128 public function get_setting() {
6129 return true;
6133 * Always returns true, does nothing
6135 * @return true
6137 public function get_defaultsetting() {
6138 return true;
6142 * Always returns '', does not write anything
6144 * @return string Always returns ''
6146 public function write_setting($data) {
6147 // do not write any setting
6148 return '';
6152 * Checks if $query is one of the available enrol plugins
6154 * @param string $query The string to search for
6155 * @return bool Returns true if found, false if not
6157 public function is_related($query) {
6158 if (parent::is_related($query)) {
6159 return true;
6162 $query = core_text::strtolower($query);
6163 $enrols = enrol_get_plugins(false);
6164 foreach ($enrols as $name=>$enrol) {
6165 $localised = get_string('pluginname', 'enrol_'.$name);
6166 if (strpos(core_text::strtolower($name), $query) !== false) {
6167 return true;
6169 if (strpos(core_text::strtolower($localised), $query) !== false) {
6170 return true;
6173 return false;
6177 * Builds the XHTML to display the control
6179 * @param string $data Unused
6180 * @param string $query
6181 * @return string
6183 public function output_html($data, $query='') {
6184 global $CFG, $OUTPUT, $DB, $PAGE;
6186 // Display strings.
6187 $strup = get_string('up');
6188 $strdown = get_string('down');
6189 $strsettings = get_string('settings');
6190 $strenable = get_string('enable');
6191 $strdisable = get_string('disable');
6192 $struninstall = get_string('uninstallplugin', 'core_admin');
6193 $strusage = get_string('enrolusage', 'enrol');
6194 $strversion = get_string('version');
6195 $strtest = get_string('testsettings', 'core_enrol');
6197 $pluginmanager = core_plugin_manager::instance();
6199 $enrols_available = enrol_get_plugins(false);
6200 $active_enrols = enrol_get_plugins(true);
6202 $allenrols = array();
6203 foreach ($active_enrols as $key=>$enrol) {
6204 $allenrols[$key] = true;
6206 foreach ($enrols_available as $key=>$enrol) {
6207 $allenrols[$key] = true;
6209 // Now find all borked plugins and at least allow then to uninstall.
6210 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6211 foreach ($condidates as $candidate) {
6212 if (empty($allenrols[$candidate])) {
6213 $allenrols[$candidate] = true;
6217 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6218 $return .= $OUTPUT->box_start('generalbox enrolsui');
6220 $table = new html_table();
6221 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6222 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6223 $table->id = 'courseenrolmentplugins';
6224 $table->attributes['class'] = 'admintable generaltable';
6225 $table->data = array();
6227 // Iterate through enrol plugins and add to the display table.
6228 $updowncount = 1;
6229 $enrolcount = count($active_enrols);
6230 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6231 $printed = array();
6232 foreach($allenrols as $enrol => $unused) {
6233 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6234 $version = get_config('enrol_'.$enrol, 'version');
6235 if ($version === false) {
6236 $version = '';
6239 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6240 $name = get_string('pluginname', 'enrol_'.$enrol);
6241 } else {
6242 $name = $enrol;
6244 // Usage.
6245 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6246 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6247 $usage = "$ci / $cp";
6249 // Hide/show links.
6250 $class = '';
6251 if (isset($active_enrols[$enrol])) {
6252 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6253 $hideshow = "<a href=\"$aurl\">";
6254 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6255 $enabled = true;
6256 $displayname = $name;
6257 } else if (isset($enrols_available[$enrol])) {
6258 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6259 $hideshow = "<a href=\"$aurl\">";
6260 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6261 $enabled = false;
6262 $displayname = $name;
6263 $class = 'dimmed_text';
6264 } else {
6265 $hideshow = '';
6266 $enabled = false;
6267 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6269 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
6270 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6271 } else {
6272 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6275 // Up/down link (only if enrol is enabled).
6276 $updown = '';
6277 if ($enabled) {
6278 if ($updowncount > 1) {
6279 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6280 $updown .= "<a href=\"$aurl\">";
6281 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6282 } else {
6283 $updown .= $OUTPUT->spacer() . '&nbsp;';
6285 if ($updowncount < $enrolcount) {
6286 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6287 $updown .= "<a href=\"$aurl\">";
6288 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6289 } else {
6290 $updown .= $OUTPUT->spacer() . '&nbsp;';
6292 ++$updowncount;
6295 // Add settings link.
6296 if (!$version) {
6297 $settings = '';
6298 } else if ($surl = $plugininfo->get_settings_url()) {
6299 $settings = html_writer::link($surl, $strsettings);
6300 } else {
6301 $settings = '';
6304 // Add uninstall info.
6305 $uninstall = '';
6306 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6307 $uninstall = html_writer::link($uninstallurl, $struninstall);
6310 $test = '';
6311 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6312 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6313 $test = html_writer::link($testsettingsurl, $strtest);
6316 // Add a row to the table.
6317 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6318 if ($class) {
6319 $row->attributes['class'] = $class;
6321 $table->data[] = $row;
6323 $printed[$enrol] = true;
6326 $return .= html_writer::table($table);
6327 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6328 $return .= $OUTPUT->box_end();
6329 return highlight($query, $return);
6335 * Blocks manage page
6337 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6339 class admin_page_manageblocks extends admin_externalpage {
6341 * Calls parent::__construct with specific arguments
6343 public function __construct() {
6344 global $CFG;
6345 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6349 * Search for a specific block
6351 * @param string $query The string to search for
6352 * @return array
6354 public function search($query) {
6355 global $CFG, $DB;
6356 if ($result = parent::search($query)) {
6357 return $result;
6360 $found = false;
6361 if ($blocks = $DB->get_records('block')) {
6362 foreach ($blocks as $block) {
6363 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6364 continue;
6366 if (strpos($block->name, $query) !== false) {
6367 $found = true;
6368 break;
6370 $strblockname = get_string('pluginname', 'block_'.$block->name);
6371 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6372 $found = true;
6373 break;
6377 if ($found) {
6378 $result = new stdClass();
6379 $result->page = $this;
6380 $result->settings = array();
6381 return array($this->name => $result);
6382 } else {
6383 return array();
6389 * Message outputs configuration
6391 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6393 class admin_page_managemessageoutputs extends admin_externalpage {
6395 * Calls parent::__construct with specific arguments
6397 public function __construct() {
6398 global $CFG;
6399 parent::__construct('managemessageoutputs',
6400 get_string('defaultmessageoutputs', 'message'),
6401 new moodle_url('/admin/message.php')
6406 * Search for a specific message processor
6408 * @param string $query The string to search for
6409 * @return array
6411 public function search($query) {
6412 global $CFG, $DB;
6413 if ($result = parent::search($query)) {
6414 return $result;
6417 $found = false;
6418 if ($processors = get_message_processors()) {
6419 foreach ($processors as $processor) {
6420 if (!$processor->available) {
6421 continue;
6423 if (strpos($processor->name, $query) !== false) {
6424 $found = true;
6425 break;
6427 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6428 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6429 $found = true;
6430 break;
6434 if ($found) {
6435 $result = new stdClass();
6436 $result->page = $this;
6437 $result->settings = array();
6438 return array($this->name => $result);
6439 } else {
6440 return array();
6446 * Default message outputs configuration
6448 * @deprecated since Moodle 3.7 MDL-64495. Please use admin_page_managemessageoutputs instead.
6449 * @todo MDL-64866 This will be deleted in Moodle 4.1.
6451 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6453 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6455 * Calls parent::__construct with specific arguments
6457 * @deprecated since Moodle 3.7 MDL-64495. Please use admin_page_managemessageoutputs instead.
6458 * @todo MDL-64866 This will be deleted in Moodle 4.1.
6460 public function __construct() {
6461 global $CFG;
6463 debugging('admin_page_defaultmessageoutputs class is deprecated. Please use admin_page_managemessageoutputs instead.',
6464 DEBUG_DEVELOPER);
6466 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6472 * Manage question behaviours page
6474 * @copyright 2011 The Open University
6475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6477 class admin_page_manageqbehaviours extends admin_externalpage {
6479 * Constructor
6481 public function __construct() {
6482 global $CFG;
6483 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6484 new moodle_url('/admin/qbehaviours.php'));
6488 * Search question behaviours for the specified string
6490 * @param string $query The string to search for in question behaviours
6491 * @return array
6493 public function search($query) {
6494 global $CFG;
6495 if ($result = parent::search($query)) {
6496 return $result;
6499 $found = false;
6500 require_once($CFG->dirroot . '/question/engine/lib.php');
6501 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6502 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6503 $query) !== false) {
6504 $found = true;
6505 break;
6508 if ($found) {
6509 $result = new stdClass();
6510 $result->page = $this;
6511 $result->settings = array();
6512 return array($this->name => $result);
6513 } else {
6514 return array();
6521 * Question type manage page
6523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6525 class admin_page_manageqtypes extends admin_externalpage {
6527 * Calls parent::__construct with specific arguments
6529 public function __construct() {
6530 global $CFG;
6531 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6532 new moodle_url('/admin/qtypes.php'));
6536 * Search question types for the specified string
6538 * @param string $query The string to search for in question types
6539 * @return array
6541 public function search($query) {
6542 global $CFG;
6543 if ($result = parent::search($query)) {
6544 return $result;
6547 $found = false;
6548 require_once($CFG->dirroot . '/question/engine/bank.php');
6549 foreach (question_bank::get_all_qtypes() as $qtype) {
6550 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6551 $found = true;
6552 break;
6555 if ($found) {
6556 $result = new stdClass();
6557 $result->page = $this;
6558 $result->settings = array();
6559 return array($this->name => $result);
6560 } else {
6561 return array();
6567 class admin_page_manageportfolios extends admin_externalpage {
6569 * Calls parent::__construct with specific arguments
6571 public function __construct() {
6572 global $CFG;
6573 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6574 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6578 * Searches page for the specified string.
6579 * @param string $query The string to search for
6580 * @return bool True if it is found on this page
6582 public function search($query) {
6583 global $CFG;
6584 if ($result = parent::search($query)) {
6585 return $result;
6588 $found = false;
6589 $portfolios = core_component::get_plugin_list('portfolio');
6590 foreach ($portfolios as $p => $dir) {
6591 if (strpos($p, $query) !== false) {
6592 $found = true;
6593 break;
6596 if (!$found) {
6597 foreach (portfolio_instances(false, false) as $instance) {
6598 $title = $instance->get('name');
6599 if (strpos(core_text::strtolower($title), $query) !== false) {
6600 $found = true;
6601 break;
6606 if ($found) {
6607 $result = new stdClass();
6608 $result->page = $this;
6609 $result->settings = array();
6610 return array($this->name => $result);
6611 } else {
6612 return array();
6618 class admin_page_managerepositories extends admin_externalpage {
6620 * Calls parent::__construct with specific arguments
6622 public function __construct() {
6623 global $CFG;
6624 parent::__construct('managerepositories', get_string('manage',
6625 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6629 * Searches page for the specified string.
6630 * @param string $query The string to search for
6631 * @return bool True if it is found on this page
6633 public function search($query) {
6634 global $CFG;
6635 if ($result = parent::search($query)) {
6636 return $result;
6639 $found = false;
6640 $repositories= core_component::get_plugin_list('repository');
6641 foreach ($repositories as $p => $dir) {
6642 if (strpos($p, $query) !== false) {
6643 $found = true;
6644 break;
6647 if (!$found) {
6648 foreach (repository::get_types() as $instance) {
6649 $title = $instance->get_typename();
6650 if (strpos(core_text::strtolower($title), $query) !== false) {
6651 $found = true;
6652 break;
6657 if ($found) {
6658 $result = new stdClass();
6659 $result->page = $this;
6660 $result->settings = array();
6661 return array($this->name => $result);
6662 } else {
6663 return array();
6670 * Special class for authentication administration.
6672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6674 class admin_setting_manageauths extends admin_setting {
6676 * Calls parent::__construct with specific arguments
6678 public function __construct() {
6679 $this->nosave = true;
6680 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6684 * Always returns true
6686 * @return true
6688 public function get_setting() {
6689 return true;
6693 * Always returns true
6695 * @return true
6697 public function get_defaultsetting() {
6698 return true;
6702 * Always returns '' and doesn't write anything
6704 * @return string Always returns ''
6706 public function write_setting($data) {
6707 // do not write any setting
6708 return '';
6712 * Search to find if Query is related to auth plugin
6714 * @param string $query The string to search for
6715 * @return bool true for related false for not
6717 public function is_related($query) {
6718 if (parent::is_related($query)) {
6719 return true;
6722 $authsavailable = core_component::get_plugin_list('auth');
6723 foreach ($authsavailable as $auth => $dir) {
6724 if (strpos($auth, $query) !== false) {
6725 return true;
6727 $authplugin = get_auth_plugin($auth);
6728 $authtitle = $authplugin->get_title();
6729 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6730 return true;
6733 return false;
6737 * Return XHTML to display control
6739 * @param mixed $data Unused
6740 * @param string $query
6741 * @return string highlight
6743 public function output_html($data, $query='') {
6744 global $CFG, $OUTPUT, $DB;
6746 // display strings
6747 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6748 'settings', 'edit', 'name', 'enable', 'disable',
6749 'up', 'down', 'none', 'users'));
6750 $txt->updown = "$txt->up/$txt->down";
6751 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6752 $txt->testsettings = get_string('testsettings', 'core_auth');
6754 $authsavailable = core_component::get_plugin_list('auth');
6755 get_enabled_auth_plugins(true); // fix the list of enabled auths
6756 if (empty($CFG->auth)) {
6757 $authsenabled = array();
6758 } else {
6759 $authsenabled = explode(',', $CFG->auth);
6762 // construct the display array, with enabled auth plugins at the top, in order
6763 $displayauths = array();
6764 $registrationauths = array();
6765 $registrationauths[''] = $txt->disable;
6766 $authplugins = array();
6767 foreach ($authsenabled as $auth) {
6768 $authplugin = get_auth_plugin($auth);
6769 $authplugins[$auth] = $authplugin;
6770 /// Get the auth title (from core or own auth lang files)
6771 $authtitle = $authplugin->get_title();
6772 /// Apply titles
6773 $displayauths[$auth] = $authtitle;
6774 if ($authplugin->can_signup()) {
6775 $registrationauths[$auth] = $authtitle;
6779 foreach ($authsavailable as $auth => $dir) {
6780 if (array_key_exists($auth, $displayauths)) {
6781 continue; //already in the list
6783 $authplugin = get_auth_plugin($auth);
6784 $authplugins[$auth] = $authplugin;
6785 /// Get the auth title (from core or own auth lang files)
6786 $authtitle = $authplugin->get_title();
6787 /// Apply titles
6788 $displayauths[$auth] = $authtitle;
6789 if ($authplugin->can_signup()) {
6790 $registrationauths[$auth] = $authtitle;
6794 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6795 $return .= $OUTPUT->box_start('generalbox authsui');
6797 $table = new html_table();
6798 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6799 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6800 $table->data = array();
6801 $table->attributes['class'] = 'admintable generaltable';
6802 $table->id = 'manageauthtable';
6804 //add always enabled plugins first
6805 $displayname = $displayauths['manual'];
6806 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6807 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6808 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6809 $displayname = $displayauths['nologin'];
6810 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6811 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6814 // iterate through auth plugins and add to the display table
6815 $updowncount = 1;
6816 $authcount = count($authsenabled);
6817 $url = "auth.php?sesskey=" . sesskey();
6818 foreach ($displayauths as $auth => $name) {
6819 if ($auth == 'manual' or $auth == 'nologin') {
6820 continue;
6822 $class = '';
6823 // hide/show link
6824 if (in_array($auth, $authsenabled)) {
6825 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6826 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6827 $enabled = true;
6828 $displayname = $name;
6830 else {
6831 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6832 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6833 $enabled = false;
6834 $displayname = $name;
6835 $class = 'dimmed_text';
6838 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6840 // up/down link (only if auth is enabled)
6841 $updown = '';
6842 if ($enabled) {
6843 if ($updowncount > 1) {
6844 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6845 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6847 else {
6848 $updown .= $OUTPUT->spacer() . '&nbsp;';
6850 if ($updowncount < $authcount) {
6851 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6852 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6854 else {
6855 $updown .= $OUTPUT->spacer() . '&nbsp;';
6857 ++ $updowncount;
6860 // settings link
6861 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6862 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6863 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6864 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6865 } else {
6866 $settings = '';
6869 // Uninstall link.
6870 $uninstall = '';
6871 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6872 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6875 $test = '';
6876 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6877 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6878 $test = html_writer::link($testurl, $txt->testsettings);
6881 // Add a row to the table.
6882 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6883 if ($class) {
6884 $row->attributes['class'] = $class;
6886 $table->data[] = $row;
6888 $return .= html_writer::table($table);
6889 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6890 $return .= $OUTPUT->box_end();
6891 return highlight($query, $return);
6897 * Special class for authentication administration.
6899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6901 class admin_setting_manageeditors extends admin_setting {
6903 * Calls parent::__construct with specific arguments
6905 public function __construct() {
6906 $this->nosave = true;
6907 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6911 * Always returns true, does nothing
6913 * @return true
6915 public function get_setting() {
6916 return true;
6920 * Always returns true, does nothing
6922 * @return true
6924 public function get_defaultsetting() {
6925 return true;
6929 * Always returns '', does not write anything
6931 * @return string Always returns ''
6933 public function write_setting($data) {
6934 // do not write any setting
6935 return '';
6939 * Checks if $query is one of the available editors
6941 * @param string $query The string to search for
6942 * @return bool Returns true if found, false if not
6944 public function is_related($query) {
6945 if (parent::is_related($query)) {
6946 return true;
6949 $editors_available = editors_get_available();
6950 foreach ($editors_available as $editor=>$editorstr) {
6951 if (strpos($editor, $query) !== false) {
6952 return true;
6954 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6955 return true;
6958 return false;
6962 * Builds the XHTML to display the control
6964 * @param string $data Unused
6965 * @param string $query
6966 * @return string
6968 public function output_html($data, $query='') {
6969 global $CFG, $OUTPUT;
6971 // display strings
6972 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6973 'up', 'down', 'none'));
6974 $struninstall = get_string('uninstallplugin', 'core_admin');
6976 $txt->updown = "$txt->up/$txt->down";
6978 $editors_available = editors_get_available();
6979 $active_editors = explode(',', $CFG->texteditors);
6981 $active_editors = array_reverse($active_editors);
6982 foreach ($active_editors as $key=>$editor) {
6983 if (empty($editors_available[$editor])) {
6984 unset($active_editors[$key]);
6985 } else {
6986 $name = $editors_available[$editor];
6987 unset($editors_available[$editor]);
6988 $editors_available[$editor] = $name;
6991 if (empty($active_editors)) {
6992 //$active_editors = array('textarea');
6994 $editors_available = array_reverse($editors_available, true);
6995 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6996 $return .= $OUTPUT->box_start('generalbox editorsui');
6998 $table = new html_table();
6999 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7000 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7001 $table->id = 'editormanagement';
7002 $table->attributes['class'] = 'admintable generaltable';
7003 $table->data = array();
7005 // iterate through auth plugins and add to the display table
7006 $updowncount = 1;
7007 $editorcount = count($active_editors);
7008 $url = "editors.php?sesskey=" . sesskey();
7009 foreach ($editors_available as $editor => $name) {
7010 // hide/show link
7011 $class = '';
7012 if (in_array($editor, $active_editors)) {
7013 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
7014 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7015 $enabled = true;
7016 $displayname = $name;
7018 else {
7019 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
7020 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7021 $enabled = false;
7022 $displayname = $name;
7023 $class = 'dimmed_text';
7026 // up/down link (only if auth is enabled)
7027 $updown = '';
7028 if ($enabled) {
7029 if ($updowncount > 1) {
7030 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
7031 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
7033 else {
7034 $updown .= $OUTPUT->spacer() . '&nbsp;';
7036 if ($updowncount < $editorcount) {
7037 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
7038 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
7040 else {
7041 $updown .= $OUTPUT->spacer() . '&nbsp;';
7043 ++ $updowncount;
7046 // settings link
7047 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
7048 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7049 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7050 } else {
7051 $settings = '';
7054 $uninstall = '';
7055 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7056 $uninstall = html_writer::link($uninstallurl, $struninstall);
7059 // Add a row to the table.
7060 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7061 if ($class) {
7062 $row->attributes['class'] = $class;
7064 $table->data[] = $row;
7066 $return .= html_writer::table($table);
7067 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7068 $return .= $OUTPUT->box_end();
7069 return highlight($query, $return);
7074 * Special class for antiviruses administration.
7076 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7079 class admin_setting_manageantiviruses extends admin_setting {
7081 * Calls parent::__construct with specific arguments
7083 public function __construct() {
7084 $this->nosave = true;
7085 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7089 * Always returns true, does nothing
7091 * @return true
7093 public function get_setting() {
7094 return true;
7098 * Always returns true, does nothing
7100 * @return true
7102 public function get_defaultsetting() {
7103 return true;
7107 * Always returns '', does not write anything
7109 * @param string $data Unused
7110 * @return string Always returns ''
7112 public function write_setting($data) {
7113 // Do not write any setting.
7114 return '';
7118 * Checks if $query is one of the available editors
7120 * @param string $query The string to search for
7121 * @return bool Returns true if found, false if not
7123 public function is_related($query) {
7124 if (parent::is_related($query)) {
7125 return true;
7128 $antivirusesavailable = \core\antivirus\manager::get_available();
7129 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7130 if (strpos($antivirus, $query) !== false) {
7131 return true;
7133 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
7134 return true;
7137 return false;
7141 * Builds the XHTML to display the control
7143 * @param string $data Unused
7144 * @param string $query
7145 * @return string
7147 public function output_html($data, $query='') {
7148 global $CFG, $OUTPUT;
7150 // Display strings.
7151 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7152 'up', 'down', 'none'));
7153 $struninstall = get_string('uninstallplugin', 'core_admin');
7155 $txt->updown = "$txt->up/$txt->down";
7157 $antivirusesavailable = \core\antivirus\manager::get_available();
7158 $activeantiviruses = explode(',', $CFG->antiviruses);
7160 $activeantiviruses = array_reverse($activeantiviruses);
7161 foreach ($activeantiviruses as $key => $antivirus) {
7162 if (empty($antivirusesavailable[$antivirus])) {
7163 unset($activeantiviruses[$key]);
7164 } else {
7165 $name = $antivirusesavailable[$antivirus];
7166 unset($antivirusesavailable[$antivirus]);
7167 $antivirusesavailable[$antivirus] = $name;
7170 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7171 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7172 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7174 $table = new html_table();
7175 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
7176 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7177 $table->id = 'antivirusmanagement';
7178 $table->attributes['class'] = 'admintable generaltable';
7179 $table->data = array();
7181 // Iterate through auth plugins and add to the display table.
7182 $updowncount = 1;
7183 $antiviruscount = count($activeantiviruses);
7184 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7185 foreach ($antivirusesavailable as $antivirus => $name) {
7186 // Hide/show link.
7187 $class = '';
7188 if (in_array($antivirus, $activeantiviruses)) {
7189 $hideshowurl = $baseurl;
7190 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7191 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7192 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7193 $enabled = true;
7194 $displayname = $name;
7195 } else {
7196 $hideshowurl = $baseurl;
7197 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7198 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7199 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
7200 $enabled = false;
7201 $displayname = $name;
7202 $class = 'dimmed_text';
7205 // Up/down link.
7206 $updown = '';
7207 if ($enabled) {
7208 if ($updowncount > 1) {
7209 $updownurl = $baseurl;
7210 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7211 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7212 $updown = html_writer::link($updownurl, $updownimg);
7213 } else {
7214 $updownimg = $OUTPUT->spacer();
7216 if ($updowncount < $antiviruscount) {
7217 $updownurl = $baseurl;
7218 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7219 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7220 $updown = html_writer::link($updownurl, $updownimg);
7221 } else {
7222 $updownimg = $OUTPUT->spacer();
7224 ++ $updowncount;
7227 // Settings link.
7228 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7229 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7230 $settings = html_writer::link($eurl, $txt->settings);
7231 } else {
7232 $settings = '';
7235 $uninstall = '';
7236 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7237 $uninstall = html_writer::link($uninstallurl, $struninstall);
7240 // Add a row to the table.
7241 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7242 if ($class) {
7243 $row->attributes['class'] = $class;
7245 $table->data[] = $row;
7247 $return .= html_writer::table($table);
7248 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
7249 $return .= $OUTPUT->box_end();
7250 return highlight($query, $return);
7255 * Special class for license administration.
7257 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7258 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7259 * @todo MDL-45184 This class will be deleted in Moodle 4.3.
7261 class admin_setting_managelicenses extends admin_setting {
7263 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7264 * @todo MDL-45184 This class will be deleted in Moodle 4.3
7266 public function __construct() {
7267 global $ADMIN;
7269 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7270 DEBUG_DEVELOPER);
7272 // Replace admin setting load with new external page load for tool_licensemanager, if not loaded already.
7273 if (!is_null($ADMIN->locate('licensemanager'))) {
7274 $temp = new admin_externalpage('licensemanager',
7275 get_string('licensemanager', 'tool_licensemanager'),
7276 \tool_licensemanager\helper::get_licensemanager_url());
7278 $ADMIN->add('license', $temp);
7283 * Always returns true, does nothing
7285 * @deprecated since Moodle 3.9 MDL-45184.
7286 * @todo MDL-45184 This method will be deleted in Moodle 4.3
7288 * @return true
7290 public function get_setting() {
7291 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7292 DEBUG_DEVELOPER);
7294 return true;
7298 * Always returns true, does nothing
7300 * @deprecated since Moodle 3.9 MDL-45184.
7301 * @todo MDL-45184 This method will be deleted in Moodle 4.3
7303 * @return true
7305 public function get_defaultsetting() {
7306 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7307 DEBUG_DEVELOPER);
7309 return true;
7313 * Always returns '', does not write anything
7315 * @deprecated since Moodle 3.9 MDL-45184.
7316 * @todo MDL-45184 This method will be deleted in Moodle 4.3
7318 * @return string Always returns ''
7320 public function write_setting($data) {
7321 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7322 DEBUG_DEVELOPER);
7324 // do not write any setting
7325 return '';
7329 * Builds the XHTML to display the control
7331 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7332 * @todo MDL-45184 This method will be deleted in Moodle 4.3
7334 * @param string $data Unused
7335 * @param string $query
7336 * @return string
7338 public function output_html($data, $query='') {
7339 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7340 DEBUG_DEVELOPER);
7342 redirect(\tool_licensemanager\helper::get_licensemanager_url());
7347 * Course formats manager. Allows to enable/disable formats and jump to settings
7349 class admin_setting_manageformats extends admin_setting {
7352 * Calls parent::__construct with specific arguments
7354 public function __construct() {
7355 $this->nosave = true;
7356 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7360 * Always returns true
7362 * @return true
7364 public function get_setting() {
7365 return true;
7369 * Always returns true
7371 * @return true
7373 public function get_defaultsetting() {
7374 return true;
7378 * Always returns '' and doesn't write anything
7380 * @param mixed $data string or array, must not be NULL
7381 * @return string Always returns ''
7383 public function write_setting($data) {
7384 // do not write any setting
7385 return '';
7389 * Search to find if Query is related to format plugin
7391 * @param string $query The string to search for
7392 * @return bool true for related false for not
7394 public function is_related($query) {
7395 if (parent::is_related($query)) {
7396 return true;
7398 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7399 foreach ($formats as $format) {
7400 if (strpos($format->component, $query) !== false ||
7401 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7402 return true;
7405 return false;
7409 * Return XHTML to display control
7411 * @param mixed $data Unused
7412 * @param string $query
7413 * @return string highlight
7415 public function output_html($data, $query='') {
7416 global $CFG, $OUTPUT;
7417 $return = '';
7418 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7419 $return .= $OUTPUT->box_start('generalbox formatsui');
7421 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7423 // display strings
7424 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7425 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7426 $txt->updown = "$txt->up/$txt->down";
7428 $table = new html_table();
7429 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7430 $table->align = array('left', 'center', 'center', 'center', 'center');
7431 $table->attributes['class'] = 'manageformattable generaltable admintable';
7432 $table->data = array();
7434 $cnt = 0;
7435 $defaultformat = get_config('moodlecourse', 'format');
7436 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7437 foreach ($formats as $format) {
7438 $url = new moodle_url('/admin/courseformats.php',
7439 array('sesskey' => sesskey(), 'format' => $format->name));
7440 $isdefault = '';
7441 $class = '';
7442 if ($format->is_enabled()) {
7443 $strformatname = $format->displayname;
7444 if ($defaultformat === $format->name) {
7445 $hideshow = $txt->default;
7446 } else {
7447 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7448 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7450 } else {
7451 $strformatname = $format->displayname;
7452 $class = 'dimmed_text';
7453 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7454 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7456 $updown = '';
7457 if ($cnt) {
7458 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7459 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7460 } else {
7461 $updown .= $spacer;
7463 if ($cnt < count($formats) - 1) {
7464 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7465 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7466 } else {
7467 $updown .= $spacer;
7469 $cnt++;
7470 $settings = '';
7471 if ($format->get_settings_url()) {
7472 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7474 $uninstall = '';
7475 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7476 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7478 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7479 if ($class) {
7480 $row->attributes['class'] = $class;
7482 $table->data[] = $row;
7484 $return .= html_writer::table($table);
7485 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7486 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7487 $return .= $OUTPUT->box_end();
7488 return highlight($query, $return);
7493 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7495 * @package core
7496 * @copyright 2018 Toni Barbera
7497 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7499 class admin_setting_managecustomfields extends admin_setting {
7502 * Calls parent::__construct with specific arguments
7504 public function __construct() {
7505 $this->nosave = true;
7506 parent::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7510 * Always returns true
7512 * @return true
7514 public function get_setting() {
7515 return true;
7519 * Always returns true
7521 * @return true
7523 public function get_defaultsetting() {
7524 return true;
7528 * Always returns '' and doesn't write anything
7530 * @param mixed $data string or array, must not be NULL
7531 * @return string Always returns ''
7533 public function write_setting($data) {
7534 // Do not write any setting.
7535 return '';
7539 * Search to find if Query is related to format plugin
7541 * @param string $query The string to search for
7542 * @return bool true for related false for not
7544 public function is_related($query) {
7545 if (parent::is_related($query)) {
7546 return true;
7548 $formats = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7549 foreach ($formats as $format) {
7550 if (strpos($format->component, $query) !== false ||
7551 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7552 return true;
7555 return false;
7559 * Return XHTML to display control
7561 * @param mixed $data Unused
7562 * @param string $query
7563 * @return string highlight
7565 public function output_html($data, $query='') {
7566 global $CFG, $OUTPUT;
7567 $return = '';
7568 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7569 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7571 $fields = core_plugin_manager::instance()->get_plugins_of_type('customfield');
7573 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7574 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7575 $txt->updown = "$txt->up/$txt->down";
7577 $table = new html_table();
7578 $table->head = array($txt->name, $txt->enable, $txt->uninstall, $txt->settings);
7579 $table->align = array('left', 'center', 'center', 'center');
7580 $table->attributes['class'] = 'managecustomfieldtable generaltable admintable';
7581 $table->data = array();
7583 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7584 foreach ($fields as $field) {
7585 $url = new moodle_url('/admin/customfields.php',
7586 array('sesskey' => sesskey(), 'field' => $field->name));
7588 if ($field->is_enabled()) {
7589 $strfieldname = $field->displayname;
7590 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7591 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7592 } else {
7593 $strfieldname = $field->displayname;
7594 $class = 'dimmed_text';
7595 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7596 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7598 $settings = '';
7599 if ($field->get_settings_url()) {
7600 $settings = html_writer::link($field->get_settings_url(), $txt->settings);
7602 $uninstall = '';
7603 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('customfield_'.$field->name, 'manage')) {
7604 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7606 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7607 $table->data[] = $row;
7609 $return .= html_writer::table($table);
7610 $return .= $OUTPUT->box_end();
7611 return highlight($query, $return);
7616 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7618 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7621 class admin_setting_managedataformats extends admin_setting {
7624 * Calls parent::__construct with specific arguments
7626 public function __construct() {
7627 $this->nosave = true;
7628 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7632 * Always returns true
7634 * @return true
7636 public function get_setting() {
7637 return true;
7641 * Always returns true
7643 * @return true
7645 public function get_defaultsetting() {
7646 return true;
7650 * Always returns '' and doesn't write anything
7652 * @param mixed $data string or array, must not be NULL
7653 * @return string Always returns ''
7655 public function write_setting($data) {
7656 // Do not write any setting.
7657 return '';
7661 * Search to find if Query is related to format plugin
7663 * @param string $query The string to search for
7664 * @return bool true for related false for not
7666 public function is_related($query) {
7667 if (parent::is_related($query)) {
7668 return true;
7670 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7671 foreach ($formats as $format) {
7672 if (strpos($format->component, $query) !== false ||
7673 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7674 return true;
7677 return false;
7681 * Return XHTML to display control
7683 * @param mixed $data Unused
7684 * @param string $query
7685 * @return string highlight
7687 public function output_html($data, $query='') {
7688 global $CFG, $OUTPUT;
7689 $return = '';
7691 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7693 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7694 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7695 $txt->updown = "$txt->up/$txt->down";
7697 $table = new html_table();
7698 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7699 $table->align = array('left', 'center', 'center', 'center', 'center');
7700 $table->attributes['class'] = 'manageformattable generaltable admintable';
7701 $table->data = array();
7703 $cnt = 0;
7704 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7705 $totalenabled = 0;
7706 foreach ($formats as $format) {
7707 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7708 $totalenabled++;
7711 foreach ($formats as $format) {
7712 $status = $format->get_status();
7713 $url = new moodle_url('/admin/dataformats.php',
7714 array('sesskey' => sesskey(), 'name' => $format->name));
7716 $class = '';
7717 if ($format->is_enabled()) {
7718 $strformatname = $format->displayname;
7719 if ($totalenabled == 1&& $format->is_enabled()) {
7720 $hideshow = '';
7721 } else {
7722 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7723 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7725 } else {
7726 $class = 'dimmed_text';
7727 $strformatname = $format->displayname;
7728 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7729 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7732 $updown = '';
7733 if ($cnt) {
7734 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7735 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7736 } else {
7737 $updown .= $spacer;
7739 if ($cnt < count($formats) - 1) {
7740 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7741 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7742 } else {
7743 $updown .= $spacer;
7746 $uninstall = '';
7747 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7748 $uninstall = get_string('status_missing', 'core_plugin');
7749 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7750 $uninstall = get_string('status_new', 'core_plugin');
7751 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7752 if ($totalenabled != 1 || !$format->is_enabled()) {
7753 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7757 $settings = '';
7758 if ($format->get_settings_url()) {
7759 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7762 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7763 if ($class) {
7764 $row->attributes['class'] = $class;
7766 $table->data[] = $row;
7767 $cnt++;
7769 $return .= html_writer::table($table);
7770 return highlight($query, $return);
7775 * Special class for filter administration.
7777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7779 class admin_page_managefilters extends admin_externalpage {
7781 * Calls parent::__construct with specific arguments
7783 public function __construct() {
7784 global $CFG;
7785 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7789 * Searches all installed filters for specified filter
7791 * @param string $query The filter(string) to search for
7792 * @param string $query
7794 public function search($query) {
7795 global $CFG;
7796 if ($result = parent::search($query)) {
7797 return $result;
7800 $found = false;
7801 $filternames = filter_get_all_installed();
7802 foreach ($filternames as $path => $strfiltername) {
7803 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7804 $found = true;
7805 break;
7807 if (strpos($path, $query) !== false) {
7808 $found = true;
7809 break;
7813 if ($found) {
7814 $result = new stdClass;
7815 $result->page = $this;
7816 $result->settings = array();
7817 return array($this->name => $result);
7818 } else {
7819 return array();
7825 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7826 * Requires a get_rank method on the plugininfo class for sorting.
7828 * @copyright 2017 Damyon Wiese
7829 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7831 abstract class admin_setting_manage_plugins extends admin_setting {
7834 * Get the admin settings section name (just a unique string)
7836 * @return string
7838 public function get_section_name() {
7839 return 'manage' . $this->get_plugin_type() . 'plugins';
7843 * Get the admin settings section title (use get_string).
7845 * @return string
7847 abstract public function get_section_title();
7850 * Get the type of plugin to manage.
7852 * @return string
7854 abstract public function get_plugin_type();
7857 * Get the name of the second column.
7859 * @return string
7861 public function get_info_column_name() {
7862 return '';
7866 * Get the type of plugin to manage.
7868 * @param plugininfo The plugin info class.
7869 * @return string
7871 abstract public function get_info_column($plugininfo);
7874 * Calls parent::__construct with specific arguments
7876 public function __construct() {
7877 $this->nosave = true;
7878 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7882 * Always returns true, does nothing
7884 * @return true
7886 public function get_setting() {
7887 return true;
7891 * Always returns true, does nothing
7893 * @return true
7895 public function get_defaultsetting() {
7896 return true;
7900 * Always returns '', does not write anything
7902 * @param mixed $data
7903 * @return string Always returns ''
7905 public function write_setting($data) {
7906 // Do not write any setting.
7907 return '';
7911 * Checks if $query is one of the available plugins of this type
7913 * @param string $query The string to search for
7914 * @return bool Returns true if found, false if not
7916 public function is_related($query) {
7917 if (parent::is_related($query)) {
7918 return true;
7921 $query = core_text::strtolower($query);
7922 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7923 foreach ($plugins as $name => $plugin) {
7924 $localised = $plugin->displayname;
7925 if (strpos(core_text::strtolower($name), $query) !== false) {
7926 return true;
7928 if (strpos(core_text::strtolower($localised), $query) !== false) {
7929 return true;
7932 return false;
7936 * The URL for the management page for this plugintype.
7938 * @return moodle_url
7940 protected function get_manage_url() {
7941 return new moodle_url('/admin/updatesetting.php');
7945 * Builds the HTML to display the control.
7947 * @param string $data Unused
7948 * @param string $query
7949 * @return string
7951 public function output_html($data, $query = '') {
7952 global $CFG, $OUTPUT, $DB, $PAGE;
7954 $context = (object) [
7955 'manageurl' => new moodle_url($this->get_manage_url(), [
7956 'type' => $this->get_plugin_type(),
7957 'sesskey' => sesskey(),
7959 'infocolumnname' => $this->get_info_column_name(),
7960 'plugins' => [],
7963 $pluginmanager = core_plugin_manager::instance();
7964 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7965 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7966 $plugins = array_merge($enabled, $allplugins);
7967 foreach ($plugins as $key => $plugin) {
7968 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7970 $pluginkey = (object) [
7971 'plugin' => $plugin->displayname,
7972 'enabled' => $plugin->is_enabled(),
7973 'togglelink' => '',
7974 'moveuplink' => '',
7975 'movedownlink' => '',
7976 'settingslink' => $plugin->get_settings_url(),
7977 'uninstalllink' => '',
7978 'info' => '',
7981 // Enable/Disable link.
7982 $togglelink = new moodle_url($pluginlink);
7983 if ($plugin->is_enabled()) {
7984 $toggletarget = false;
7985 $togglelink->param('action', 'disable');
7987 if (count($context->plugins)) {
7988 // This is not the first plugin.
7989 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7992 if (count($enabled) > count($context->plugins) + 1) {
7993 // This is not the last plugin.
7994 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7997 $pluginkey->info = $this->get_info_column($plugin);
7998 } else {
7999 $toggletarget = true;
8000 $togglelink->param('action', 'enable');
8003 $pluginkey->toggletarget = $toggletarget;
8004 $pluginkey->togglelink = $togglelink;
8006 $frankenstyle = $plugin->type . '_' . $plugin->name;
8007 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8008 // This plugin supports uninstallation.
8009 $pluginkey->uninstalllink = $uninstalllink;
8012 if (!empty($this->get_info_column_name())) {
8013 // This plugintype has an info column.
8014 $pluginkey->info = $this->get_info_column($plugin);
8017 $context->plugins[] = $pluginkey;
8020 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8021 return highlight($query, $str);
8026 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8027 * Requires a get_rank method on the plugininfo class for sorting.
8029 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8032 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
8033 public function get_section_title() {
8034 return get_string('type_fileconverter_plural', 'plugin');
8037 public function get_plugin_type() {
8038 return 'fileconverter';
8041 public function get_info_column_name() {
8042 return get_string('supportedconversions', 'plugin');
8045 public function get_info_column($plugininfo) {
8046 return $plugininfo->get_supported_conversions();
8051 * Special class for media player plugins management.
8053 * @copyright 2016 Marina Glancy
8054 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8056 class admin_setting_managemediaplayers extends admin_setting {
8058 * Calls parent::__construct with specific arguments
8060 public function __construct() {
8061 $this->nosave = true;
8062 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8066 * Always returns true, does nothing
8068 * @return true
8070 public function get_setting() {
8071 return true;
8075 * Always returns true, does nothing
8077 * @return true
8079 public function get_defaultsetting() {
8080 return true;
8084 * Always returns '', does not write anything
8086 * @param mixed $data
8087 * @return string Always returns ''
8089 public function write_setting($data) {
8090 // Do not write any setting.
8091 return '';
8095 * Checks if $query is one of the available enrol plugins
8097 * @param string $query The string to search for
8098 * @return bool Returns true if found, false if not
8100 public function is_related($query) {
8101 if (parent::is_related($query)) {
8102 return true;
8105 $query = core_text::strtolower($query);
8106 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
8107 foreach ($plugins as $name => $plugin) {
8108 $localised = $plugin->displayname;
8109 if (strpos(core_text::strtolower($name), $query) !== false) {
8110 return true;
8112 if (strpos(core_text::strtolower($localised), $query) !== false) {
8113 return true;
8116 return false;
8120 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8121 * @return \core\plugininfo\media[]
8123 protected function get_sorted_plugins() {
8124 $pluginmanager = core_plugin_manager::instance();
8126 $plugins = $pluginmanager->get_plugins_of_type('media');
8127 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8129 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8130 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
8132 $order = array_values($enabledplugins);
8133 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8135 $sortedplugins = array();
8136 foreach ($order as $name) {
8137 $sortedplugins[$name] = $plugins[$name];
8140 return $sortedplugins;
8144 * Builds the XHTML to display the control
8146 * @param string $data Unused
8147 * @param string $query
8148 * @return string
8150 public function output_html($data, $query='') {
8151 global $CFG, $OUTPUT, $DB, $PAGE;
8153 // Display strings.
8154 $strup = get_string('up');
8155 $strdown = get_string('down');
8156 $strsettings = get_string('settings');
8157 $strenable = get_string('enable');
8158 $strdisable = get_string('disable');
8159 $struninstall = get_string('uninstallplugin', 'core_admin');
8160 $strversion = get_string('version');
8161 $strname = get_string('name');
8162 $strsupports = get_string('supports', 'core_media');
8164 $pluginmanager = core_plugin_manager::instance();
8166 $plugins = $this->get_sorted_plugins();
8167 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8169 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8171 $table = new html_table();
8172 $table->head = array($strname, $strsupports, $strversion,
8173 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8174 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
8175 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8176 $table->id = 'mediaplayerplugins';
8177 $table->attributes['class'] = 'admintable generaltable';
8178 $table->data = array();
8180 // Iterate through media plugins and add to the display table.
8181 $updowncount = 1;
8182 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8183 $printed = array();
8184 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8186 $usedextensions = [];
8187 foreach ($plugins as $name => $plugin) {
8188 $url->param('media', $name);
8189 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8190 $version = $plugininfo->versiondb;
8191 $supports = $plugininfo->supports($usedextensions);
8193 // Hide/show links.
8194 $class = '';
8195 if (!$plugininfo->is_installed_and_upgraded()) {
8196 $hideshow = '';
8197 $enabled = false;
8198 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8199 } else {
8200 $enabled = $plugininfo->is_enabled();
8201 if ($enabled) {
8202 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
8203 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8204 } else {
8205 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
8206 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8207 $class = 'dimmed_text';
8209 $displayname = $plugin->displayname;
8210 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8211 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8214 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
8215 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8216 } else {
8217 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8220 // Up/down link (only if enrol is enabled).
8221 $updown = '';
8222 if ($enabled) {
8223 if ($updowncount > 1) {
8224 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
8225 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8226 } else {
8227 $updown = $spacer;
8229 if ($updowncount < count($enabledplugins)) {
8230 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
8231 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8232 } else {
8233 $updown .= $spacer;
8235 ++$updowncount;
8238 $uninstall = '';
8239 $status = $plugininfo->get_status();
8240 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
8241 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8243 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
8244 $uninstall = get_string('status_new', 'core_plugin');
8245 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8246 $uninstall .= html_writer::link($uninstallurl, $struninstall);
8249 $settings = '';
8250 if ($plugininfo->get_settings_url()) {
8251 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
8254 // Add a row to the table.
8255 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8256 if ($class) {
8257 $row->attributes['class'] = $class;
8259 $table->data[] = $row;
8261 $printed[$name] = true;
8264 $return .= html_writer::table($table);
8265 $return .= $OUTPUT->box_end();
8266 return highlight($query, $return);
8272 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8274 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8277 class admin_setting_managecontentbankcontenttypes extends admin_setting {
8280 * Calls parent::__construct with specific arguments
8282 public function __construct() {
8283 $this->nosave = true;
8284 parent::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8288 * Always returns true
8290 * @return true
8292 public function get_setting() {
8293 return true;
8297 * Always returns true
8299 * @return true
8301 public function get_defaultsetting() {
8302 return true;
8306 * Always returns '' and doesn't write anything
8308 * @param mixed $data string or array, must not be NULL
8309 * @return string Always returns ''
8311 public function write_setting($data) {
8312 // Do not write any setting.
8313 return '';
8317 * Search to find if Query is related to content bank plugin
8319 * @param string $query The string to search for
8320 * @return bool true for related false for not
8322 public function is_related($query) {
8323 if (parent::is_related($query)) {
8324 return true;
8326 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8327 foreach ($types as $type) {
8328 if (strpos($type->component, $query) !== false ||
8329 strpos(core_text::strtolower($type->displayname), $query) !== false) {
8330 return true;
8333 return false;
8337 * Return XHTML to display control
8339 * @param mixed $data Unused
8340 * @param string $query
8341 * @return string highlight
8343 public function output_html($data, $query='') {
8344 global $CFG, $OUTPUT;
8345 $return = '';
8347 $types = core_plugin_manager::instance()->get_plugins_of_type('contenttype');
8348 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8349 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
8351 $table = new html_table();
8352 $table->head = array($txt->name, $txt->enable, $txt->order, $txt->settings, $txt->uninstall);
8353 $table->align = array('left', 'center', 'center', 'center', 'center');
8354 $table->attributes['class'] = 'managecontentbanktable generaltable admintable';
8355 $table->data = array();
8356 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8358 $totalenabled = 0;
8359 $count = 0;
8360 foreach ($types as $type) {
8361 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8362 $totalenabled++;
8366 foreach ($types as $type) {
8367 $url = new moodle_url('/admin/contentbank.php',
8368 array('sesskey' => sesskey(), 'name' => $type->name));
8370 $class = '';
8371 $strtypename = $type->displayname;
8372 if ($type->is_enabled()) {
8373 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
8374 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
8375 } else {
8376 $class = 'dimmed_text';
8377 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
8378 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
8381 $updown = '';
8382 if ($count) {
8383 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
8384 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
8385 } else {
8386 $updown .= $spacer;
8388 if ($count < count($types) - 1) {
8389 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
8390 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
8391 } else {
8392 $updown .= $spacer;
8395 $settings = '';
8396 if ($type->get_settings_url()) {
8397 $settings = html_writer::link($type->get_settings_url(), $txt->settings);
8400 $uninstall = '';
8401 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('contenttype_'.$type->name, 'manage')) {
8402 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
8405 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8406 if ($class) {
8407 $row->attributes['class'] = $class;
8409 $table->data[] = $row;
8410 $count++;
8412 $return .= html_writer::table($table);
8413 return highlight($query, $return);
8418 * Initialise admin page - this function does require login and permission
8419 * checks specified in page definition.
8421 * This function must be called on each admin page before other code.
8423 * @global moodle_page $PAGE
8425 * @param string $section name of page
8426 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8427 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8428 * added to the turn blocks editing on/off form, so this page reloads correctly.
8429 * @param string $actualurl if the actual page being viewed is not the normal one for this
8430 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8431 * @param array $options Additional options that can be specified for page setup.
8432 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8434 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8435 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8437 $PAGE->set_context(null); // hack - set context to something, by default to system context
8439 $site = get_site();
8440 require_login(null, false);
8442 if (!empty($options['pagelayout'])) {
8443 // A specific page layout has been requested.
8444 $PAGE->set_pagelayout($options['pagelayout']);
8445 } else if ($section === 'upgradesettings') {
8446 $PAGE->set_pagelayout('maintenance');
8447 } else {
8448 $PAGE->set_pagelayout('admin');
8451 $adminroot = admin_get_root(false, false); // settings not required for external pages
8452 $extpage = $adminroot->locate($section, true);
8454 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
8455 // The requested section isn't in the admin tree
8456 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8457 if (!has_capability('moodle/site:config', context_system::instance())) {
8458 // The requested section could depend on a different capability
8459 // but most likely the user has inadequate capabilities
8460 print_error('accessdenied', 'admin');
8461 } else {
8462 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8466 // this eliminates our need to authenticate on the actual pages
8467 if (!$extpage->check_access()) {
8468 print_error('accessdenied', 'admin');
8469 die;
8472 navigation_node::require_admin_tree();
8474 // $PAGE->set_extra_button($extrabutton); TODO
8476 if (!$actualurl) {
8477 $actualurl = $extpage->url;
8480 $PAGE->set_url($actualurl, $extraurlparams);
8481 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
8482 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
8485 if (empty($SITE->fullname) || empty($SITE->shortname)) {
8486 // During initial install.
8487 $strinstallation = get_string('installation', 'install');
8488 $strsettings = get_string('settings');
8489 $PAGE->navbar->add($strsettings);
8490 $PAGE->set_title($strinstallation);
8491 $PAGE->set_heading($strinstallation);
8492 $PAGE->set_cacheable(false);
8493 return;
8496 // Locate the current item on the navigation and make it active when found.
8497 $path = $extpage->path;
8498 $node = $PAGE->settingsnav;
8499 while ($node && count($path) > 0) {
8500 $node = $node->get(array_pop($path));
8502 if ($node) {
8503 $node->make_active();
8506 // Normal case.
8507 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
8508 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8509 $USER->editing = $adminediting;
8512 $visiblepathtosection = array_reverse($extpage->visiblepath);
8514 if ($PAGE->user_allowed_editing()) {
8515 if ($PAGE->user_is_editing()) {
8516 $caption = get_string('blockseditoff');
8517 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8518 } else {
8519 $caption = get_string('blocksediton');
8520 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8522 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8525 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8526 $PAGE->set_heading($SITE->fullname);
8528 // prevent caching in nav block
8529 $PAGE->navigation->clear_cache();
8533 * Returns the reference to admin tree root
8535 * @return object admin_root object
8537 function admin_get_root($reload=false, $requirefulltree=true) {
8538 global $CFG, $DB, $OUTPUT, $ADMIN;
8540 if (is_null($ADMIN)) {
8541 // create the admin tree!
8542 $ADMIN = new admin_root($requirefulltree);
8545 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
8546 $ADMIN->purge_children($requirefulltree);
8549 if (!$ADMIN->loaded) {
8550 // we process this file first to create categories first and in correct order
8551 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
8553 // now we process all other files in admin/settings to build the admin tree
8554 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
8555 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
8556 continue;
8558 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
8559 // plugins are loaded last - they may insert pages anywhere
8560 continue;
8562 require($file);
8564 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8566 $ADMIN->loaded = true;
8569 return $ADMIN;
8572 /// settings utility functions
8575 * This function applies default settings.
8576 * Because setting the defaults of some settings can enable other settings,
8577 * this function is called recursively until no more new settings are found.
8579 * @param object $node, NULL means complete tree, null by default
8580 * @param bool $unconditional if true overrides all values with defaults, true by default
8581 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8582 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8583 * @return array $settingsoutput The names and values of the changed settings
8585 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8586 $counter = 0;
8588 if (is_null($node)) {
8589 core_plugin_manager::reset_caches();
8590 $node = admin_get_root(true, true);
8591 $counter = count($settingsoutput);
8594 if ($node instanceof admin_category) {
8595 $entries = array_keys($node->children);
8596 foreach ($entries as $entry) {
8597 $settingsoutput = admin_apply_default_settings(
8598 $node->children[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8602 } else if ($node instanceof admin_settingpage) {
8603 foreach ($node->settings as $setting) {
8604 if (!$unconditional && !is_null($setting->get_setting())) {
8605 // Do not override existing defaults.
8606 continue;
8608 $defaultsetting = $setting->get_defaultsetting();
8609 if (is_null($defaultsetting)) {
8610 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8611 continue;
8614 $settingname = $node->name . '_' . $setting->name; // Get a unique name for the setting.
8616 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8617 $admindefaultsettings[$settingname] = $settingname;
8618 $settingsoutput[$settingname] = $defaultsetting;
8620 // Set the default for this setting.
8621 $setting->write_setting($defaultsetting);
8622 $setting->write_setting_flags(null);
8623 } else {
8624 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8629 // Call this function recursively until all settings are processed.
8630 if (($node instanceof admin_root) && ($counter != count($settingsoutput))) {
8631 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8633 // Just in case somebody modifies the list of active plugins directly.
8634 core_plugin_manager::reset_caches();
8636 return $settingsoutput;
8640 * Store changed settings, this function updates the errors variable in $ADMIN
8642 * @param object $formdata from form
8643 * @return int number of changed settings
8645 function admin_write_settings($formdata) {
8646 global $CFG, $SITE, $DB;
8648 $olddbsessions = !empty($CFG->dbsessions);
8649 $formdata = (array)$formdata;
8651 $data = array();
8652 foreach ($formdata as $fullname=>$value) {
8653 if (strpos($fullname, 's_') !== 0) {
8654 continue; // not a config value
8656 $data[$fullname] = $value;
8659 $adminroot = admin_get_root();
8660 $settings = admin_find_write_settings($adminroot, $data);
8662 $count = 0;
8663 foreach ($settings as $fullname=>$setting) {
8664 /** @var $setting admin_setting */
8665 $original = $setting->get_setting();
8666 $error = $setting->write_setting($data[$fullname]);
8667 if ($error !== '') {
8668 $adminroot->errors[$fullname] = new stdClass();
8669 $adminroot->errors[$fullname]->data = $data[$fullname];
8670 $adminroot->errors[$fullname]->id = $setting->get_id();
8671 $adminroot->errors[$fullname]->error = $error;
8672 } else {
8673 $setting->write_setting_flags($data);
8675 if ($setting->post_write_settings($original)) {
8676 $count++;
8680 if ($olddbsessions != !empty($CFG->dbsessions)) {
8681 require_logout();
8684 // Now update $SITE - just update the fields, in case other people have a
8685 // a reference to it (e.g. $PAGE, $COURSE).
8686 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8687 foreach (get_object_vars($newsite) as $field => $value) {
8688 $SITE->$field = $value;
8691 // now reload all settings - some of them might depend on the changed
8692 admin_get_root(true);
8693 return $count;
8697 * Internal recursive function - finds all settings from submitted form
8699 * @param object $node Instance of admin_category, or admin_settingpage
8700 * @param array $data
8701 * @return array
8703 function admin_find_write_settings($node, $data) {
8704 $return = array();
8706 if (empty($data)) {
8707 return $return;
8710 if ($node instanceof admin_category) {
8711 if ($node->check_access()) {
8712 $entries = array_keys($node->children);
8713 foreach ($entries as $entry) {
8714 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8718 } else if ($node instanceof admin_settingpage) {
8719 if ($node->check_access()) {
8720 foreach ($node->settings as $setting) {
8721 $fullname = $setting->get_full_name();
8722 if (array_key_exists($fullname, $data)) {
8723 $return[$fullname] = $setting;
8730 return $return;
8734 * Internal function - prints the search results
8736 * @param string $query String to search for
8737 * @return string empty or XHTML
8739 function admin_search_settings_html($query) {
8740 global $CFG, $OUTPUT, $PAGE;
8742 if (core_text::strlen($query) < 2) {
8743 return '';
8745 $query = core_text::strtolower($query);
8747 $adminroot = admin_get_root();
8748 $findings = $adminroot->search($query);
8749 $savebutton = false;
8751 $tpldata = (object) [
8752 'actionurl' => $PAGE->url->out(false),
8753 'results' => [],
8754 'sesskey' => sesskey(),
8757 foreach ($findings as $found) {
8758 $page = $found->page;
8759 $settings = $found->settings;
8760 if ($page->is_hidden()) {
8761 // hidden pages are not displayed in search results
8762 continue;
8765 $heading = highlight($query, $page->visiblename);
8766 $headingurl = null;
8767 if ($page instanceof admin_externalpage) {
8768 $headingurl = new moodle_url($page->url);
8769 } else if ($page instanceof admin_settingpage) {
8770 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8771 } else {
8772 continue;
8775 // Locate the page in the admin root and populate its visiblepath attribute.
8776 $path = array();
8777 $located = $adminroot->locate($page->name, true);
8778 if ($located) {
8779 foreach ($located->visiblepath as $pathitem) {
8780 array_unshift($path, (string) $pathitem);
8784 $sectionsettings = [];
8785 if (!empty($settings)) {
8786 foreach ($settings as $setting) {
8787 if (empty($setting->nosave)) {
8788 $savebutton = true;
8790 $fullname = $setting->get_full_name();
8791 if (array_key_exists($fullname, $adminroot->errors)) {
8792 $data = $adminroot->errors[$fullname]->data;
8793 } else {
8794 $data = $setting->get_setting();
8795 // do not use defaults if settings not available - upgradesettings handles the defaults!
8797 $sectionsettings[] = $setting->output_html($data, $query);
8801 $tpldata->results[] = (object) [
8802 'title' => $heading,
8803 'path' => $path,
8804 'url' => $headingurl->out(false),
8805 'settings' => $sectionsettings
8809 $tpldata->showsave = $savebutton;
8810 $tpldata->hasresults = !empty($tpldata->results);
8812 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8816 * Internal function - returns arrays of html pages with uninitialised settings
8818 * @param object $node Instance of admin_category or admin_settingpage
8819 * @return array
8821 function admin_output_new_settings_by_page($node) {
8822 global $OUTPUT;
8823 $return = array();
8825 if ($node instanceof admin_category) {
8826 $entries = array_keys($node->children);
8827 foreach ($entries as $entry) {
8828 $return += admin_output_new_settings_by_page($node->children[$entry]);
8831 } else if ($node instanceof admin_settingpage) {
8832 $newsettings = array();
8833 foreach ($node->settings as $setting) {
8834 if (is_null($setting->get_setting())) {
8835 $newsettings[] = $setting;
8838 if (count($newsettings) > 0) {
8839 $adminroot = admin_get_root();
8840 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8841 $page .= '<fieldset class="adminsettings">'."\n";
8842 foreach ($newsettings as $setting) {
8843 $fullname = $setting->get_full_name();
8844 if (array_key_exists($fullname, $adminroot->errors)) {
8845 $data = $adminroot->errors[$fullname]->data;
8846 } else {
8847 $data = $setting->get_setting();
8848 if (is_null($data)) {
8849 $data = $setting->get_defaultsetting();
8852 $page .= '<div class="clearer"><!-- --></div>'."\n";
8853 $page .= $setting->output_html($data);
8855 $page .= '</fieldset>';
8856 $return[$node->name] = $page;
8860 return $return;
8864 * Format admin settings
8866 * @param object $setting
8867 * @param string $title label element
8868 * @param string $form form fragment, html code - not highlighted automatically
8869 * @param string $description
8870 * @param mixed $label link label to id, true by default or string being the label to connect it to
8871 * @param string $warning warning text
8872 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8873 * @param string $query search query to be highlighted
8874 * @return string XHTML
8876 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8877 global $CFG, $OUTPUT;
8879 $context = (object) [
8880 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8881 'fullname' => $setting->get_full_name(),
8884 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8885 if ($label === true) {
8886 $context->labelfor = $setting->get_id();
8887 } else if ($label === false) {
8888 $context->labelfor = '';
8889 } else {
8890 $context->labelfor = $label;
8893 $form .= $setting->output_setting_flags();
8895 $context->warning = $warning;
8896 $context->override = '';
8897 if (empty($setting->plugin)) {
8898 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8899 $context->override = get_string('configoverride', 'admin');
8901 } else {
8902 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8903 $context->override = get_string('configoverride', 'admin');
8907 $defaults = array();
8908 if (!is_null($defaultinfo)) {
8909 if ($defaultinfo === '') {
8910 $defaultinfo = get_string('emptysettingvalue', 'admin');
8912 $defaults[] = $defaultinfo;
8915 $context->default = null;
8916 $setting->get_setting_flag_defaults($defaults);
8917 if (!empty($defaults)) {
8918 $defaultinfo = implode(', ', $defaults);
8919 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8920 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8924 $context->error = '';
8925 $adminroot = admin_get_root();
8926 if (array_key_exists($context->fullname, $adminroot->errors)) {
8927 $context->error = $adminroot->errors[$context->fullname]->error;
8930 if ($dependenton = $setting->get_dependent_on()) {
8931 $context->dependenton = get_string('settingdependenton', 'admin', implode(', ', $dependenton));
8934 $context->id = 'admin-' . $setting->name;
8935 $context->title = highlightfast($query, $title);
8936 $context->name = highlightfast($query, $context->name);
8937 $context->description = highlight($query, markdown_to_html($description));
8938 $context->element = $form;
8939 $context->forceltr = $setting->get_force_ltr();
8940 $context->customcontrol = $setting->has_custom_form_control();
8942 return $OUTPUT->render_from_template('core_admin/setting', $context);
8946 * Based on find_new_settings{@link ()} in upgradesettings.php
8947 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8949 * @param object $node Instance of admin_category, or admin_settingpage
8950 * @return boolean true if any settings haven't been initialised, false if they all have
8952 function any_new_admin_settings($node) {
8954 if ($node instanceof admin_category) {
8955 $entries = array_keys($node->children);
8956 foreach ($entries as $entry) {
8957 if (any_new_admin_settings($node->children[$entry])) {
8958 return true;
8962 } else if ($node instanceof admin_settingpage) {
8963 foreach ($node->settings as $setting) {
8964 if ($setting->get_setting() === NULL) {
8965 return true;
8970 return false;
8974 * Given a table and optionally a column name should replaces be done?
8976 * @param string $table name
8977 * @param string $column name
8978 * @return bool success or fail
8980 function db_should_replace($table, $column = ''): bool {
8982 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8983 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
8984 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
8986 // Don't process these.
8987 if (in_array($table, $skiptables)) {
8988 return false;
8991 // To be safe never replace inside a table that looks related to logging.
8992 if (preg_match('/(^|_)logs?($|_)/', $table)) {
8993 return false;
8996 // Do column based exclusions.
8997 if (!empty($column)) {
8998 // Don't touch anything that looks like a hash.
8999 if (preg_match('/hash$/', $column)) {
9000 return false;
9004 return true;
9008 * Moved from admin/replace.php so that we can use this in cron
9010 * @param string $search string to look for
9011 * @param string $replace string to replace
9012 * @return bool success or fail
9014 function db_replace($search, $replace) {
9015 global $DB, $CFG, $OUTPUT;
9017 // Turn off time limits, sometimes upgrades can be slow.
9018 core_php_time_limit::raise();
9020 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9021 return false;
9023 foreach ($tables as $table) {
9025 if (!db_should_replace($table)) {
9026 continue;
9029 if ($columns = $DB->get_columns($table)) {
9030 $DB->set_debug(true);
9031 foreach ($columns as $column) {
9032 if (!db_should_replace($table, $column->name)) {
9033 continue;
9035 $DB->replace_all_text($table, $column, $search, $replace);
9037 $DB->set_debug(false);
9041 // delete modinfo caches
9042 rebuild_course_cache(0, true);
9044 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9045 $blocks = core_component::get_plugin_list('block');
9046 foreach ($blocks as $blockname=>$fullblock) {
9047 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9048 continue;
9051 if (!is_readable($fullblock.'/lib.php')) {
9052 continue;
9055 $function = 'block_'.$blockname.'_global_db_replace';
9056 include_once($fullblock.'/lib.php');
9057 if (!function_exists($function)) {
9058 continue;
9061 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9062 $function($search, $replace);
9063 echo $OUTPUT->notification("...finished", 'notifysuccess');
9066 // Trigger an event.
9067 $eventargs = [
9068 'context' => context_system::instance(),
9069 'other' => [
9070 'search' => $search,
9071 'replace' => $replace
9074 $event = \core\event\database_text_field_content_replaced::create($eventargs);
9075 $event->trigger();
9077 purge_all_caches();
9079 return true;
9083 * Manage repository settings
9085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9087 class admin_setting_managerepository extends admin_setting {
9088 /** @var string */
9089 private $baseurl;
9092 * calls parent::__construct with specific arguments
9094 public function __construct() {
9095 global $CFG;
9096 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
9097 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
9101 * Always returns true, does nothing
9103 * @return true
9105 public function get_setting() {
9106 return true;
9110 * Always returns true does nothing
9112 * @return true
9114 public function get_defaultsetting() {
9115 return true;
9119 * Always returns s_managerepository
9121 * @return string Always return 's_managerepository'
9123 public function get_full_name() {
9124 return 's_managerepository';
9128 * Always returns '' doesn't do anything
9130 public function write_setting($data) {
9131 $url = $this->baseurl . '&amp;new=' . $data;
9132 return '';
9133 // TODO
9134 // Should not use redirect and exit here
9135 // Find a better way to do this.
9136 // redirect($url);
9137 // exit;
9141 * Searches repository plugins for one that matches $query
9143 * @param string $query The string to search for
9144 * @return bool true if found, false if not
9146 public function is_related($query) {
9147 if (parent::is_related($query)) {
9148 return true;
9151 $repositories= core_component::get_plugin_list('repository');
9152 foreach ($repositories as $p => $dir) {
9153 if (strpos($p, $query) !== false) {
9154 return true;
9157 foreach (repository::get_types() as $instance) {
9158 $title = $instance->get_typename();
9159 if (strpos(core_text::strtolower($title), $query) !== false) {
9160 return true;
9163 return false;
9167 * Helper function that generates a moodle_url object
9168 * relevant to the repository
9171 function repository_action_url($repository) {
9172 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
9176 * Builds XHTML to display the control
9178 * @param string $data Unused
9179 * @param string $query
9180 * @return string XHTML
9182 public function output_html($data, $query='') {
9183 global $CFG, $USER, $OUTPUT;
9185 // Get strings that are used
9186 $strshow = get_string('on', 'repository');
9187 $strhide = get_string('off', 'repository');
9188 $strdelete = get_string('disabled', 'repository');
9190 $actionchoicesforexisting = array(
9191 'show' => $strshow,
9192 'hide' => $strhide,
9193 'delete' => $strdelete
9196 $actionchoicesfornew = array(
9197 'newon' => $strshow,
9198 'newoff' => $strhide,
9199 'delete' => $strdelete
9202 $return = '';
9203 $return .= $OUTPUT->box_start('generalbox');
9205 // Set strings that are used multiple times
9206 $settingsstr = get_string('settings');
9207 $disablestr = get_string('disable');
9209 // Table to list plug-ins
9210 $table = new html_table();
9211 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9212 $table->align = array('left', 'center', 'center', 'center', 'center');
9213 $table->data = array();
9215 // Get list of used plug-ins
9216 $repositorytypes = repository::get_types();
9217 if (!empty($repositorytypes)) {
9218 // Array to store plugins being used
9219 $alreadyplugins = array();
9220 $totalrepositorytypes = count($repositorytypes);
9221 $updowncount = 1;
9222 foreach ($repositorytypes as $i) {
9223 $settings = '';
9224 $typename = $i->get_typename();
9225 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9226 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
9227 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
9229 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
9230 // Calculate number of instances in order to display them for the Moodle administrator
9231 if (!empty($instanceoptionnames)) {
9232 $params = array();
9233 $params['context'] = array(context_system::instance());
9234 $params['onlyvisible'] = false;
9235 $params['type'] = $typename;
9236 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
9237 // site instances
9238 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9239 $params['context'] = array();
9240 $instances = repository::static_function($typename, 'get_instances', $params);
9241 $courseinstances = array();
9242 $userinstances = array();
9244 foreach ($instances as $instance) {
9245 $repocontext = context::instance_by_id($instance->instance->contextid);
9246 if ($repocontext->contextlevel == CONTEXT_COURSE) {
9247 $courseinstances[] = $instance;
9248 } else if ($repocontext->contextlevel == CONTEXT_USER) {
9249 $userinstances[] = $instance;
9252 // course instances
9253 $instancenumber = count($courseinstances);
9254 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9256 // user private instances
9257 $instancenumber = count($userinstances);
9258 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9259 } else {
9260 $admininstancenumbertext = "";
9261 $courseinstancenumbertext = "";
9262 $userinstancenumbertext = "";
9265 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
9267 $settings .= $OUTPUT->container_start('mdl-left');
9268 $settings .= '<br/>';
9269 $settings .= $admininstancenumbertext;
9270 $settings .= '<br/>';
9271 $settings .= $courseinstancenumbertext;
9272 $settings .= '<br/>';
9273 $settings .= $userinstancenumbertext;
9274 $settings .= $OUTPUT->container_end();
9276 // Get the current visibility
9277 if ($i->get_visible()) {
9278 $currentaction = 'show';
9279 } else {
9280 $currentaction = 'hide';
9283 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9285 // Display up/down link
9286 $updown = '';
9287 // Should be done with CSS instead.
9288 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9290 if ($updowncount > 1) {
9291 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
9292 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
9294 else {
9295 $updown .= $spacer;
9297 if ($updowncount < $totalrepositorytypes) {
9298 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
9299 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
9301 else {
9302 $updown .= $spacer;
9305 $updowncount++;
9307 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9309 if (!in_array($typename, $alreadyplugins)) {
9310 $alreadyplugins[] = $typename;
9315 // Get all the plugins that exist on disk
9316 $plugins = core_component::get_plugin_list('repository');
9317 if (!empty($plugins)) {
9318 foreach ($plugins as $plugin => $dir) {
9319 // Check that it has not already been listed
9320 if (!in_array($plugin, $alreadyplugins)) {
9321 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9322 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9327 $return .= html_writer::table($table);
9328 $return .= $OUTPUT->box_end();
9329 return highlight($query, $return);
9334 * Special checkbox for enable mobile web service
9335 * If enable then we store the service id of the mobile service into config table
9336 * If disable then we unstore the service id from the config table
9338 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
9340 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9341 private $restuse;
9344 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9346 * @return boolean
9348 private function is_protocol_cap_allowed() {
9349 global $DB, $CFG;
9351 // If the $this->restuse variable is not set, it needs to be set.
9352 if (empty($this->restuse) and $this->restuse!==false) {
9353 $params = array();
9354 $params['permission'] = CAP_ALLOW;
9355 $params['roleid'] = $CFG->defaultuserroleid;
9356 $params['capability'] = 'webservice/rest:use';
9357 $this->restuse = $DB->record_exists('role_capabilities', $params);
9360 return $this->restuse;
9364 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9365 * @param type $status true to allow, false to not set
9367 private function set_protocol_cap($status) {
9368 global $CFG;
9369 if ($status and !$this->is_protocol_cap_allowed()) {
9370 //need to allow the cap
9371 $permission = CAP_ALLOW;
9372 $assign = true;
9373 } else if (!$status and $this->is_protocol_cap_allowed()){
9374 //need to disallow the cap
9375 $permission = CAP_INHERIT;
9376 $assign = true;
9378 if (!empty($assign)) {
9379 $systemcontext = context_system::instance();
9380 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
9385 * Builds XHTML to display the control.
9386 * The main purpose of this overloading is to display a warning when https
9387 * is not supported by the server
9388 * @param string $data Unused
9389 * @param string $query
9390 * @return string XHTML
9392 public function output_html($data, $query='') {
9393 global $OUTPUT;
9394 $html = parent::output_html($data, $query);
9396 if ((string)$data === $this->yes) {
9397 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9398 foreach ($notifications as $notification) {
9399 $message = get_string($notification[0], $notification[1]);
9400 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
9404 return $html;
9408 * Retrieves the current setting using the objects name
9410 * @return string
9412 public function get_setting() {
9413 global $CFG;
9415 // First check if is not set.
9416 $result = $this->config_read($this->name);
9417 if (is_null($result)) {
9418 return null;
9421 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9422 // Or if web services aren't enabled this can't be,
9423 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
9424 return 0;
9427 require_once($CFG->dirroot . '/webservice/lib.php');
9428 $webservicemanager = new webservice();
9429 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9430 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
9431 return $result;
9432 } else {
9433 return 0;
9438 * Save the selected setting
9440 * @param string $data The selected site
9441 * @return string empty string or error message
9443 public function write_setting($data) {
9444 global $DB, $CFG;
9446 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9447 if (empty($CFG->defaultuserroleid)) {
9448 return '';
9451 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
9453 require_once($CFG->dirroot . '/webservice/lib.php');
9454 $webservicemanager = new webservice();
9456 $updateprotocol = false;
9457 if ((string)$data === $this->yes) {
9458 //code run when enable mobile web service
9459 //enable web service systeme if necessary
9460 set_config('enablewebservices', true);
9462 //enable mobile service
9463 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9464 $mobileservice->enabled = 1;
9465 $webservicemanager->update_external_service($mobileservice);
9467 // Enable REST server.
9468 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9470 if (!in_array('rest', $activeprotocols)) {
9471 $activeprotocols[] = 'rest';
9472 $updateprotocol = true;
9475 if ($updateprotocol) {
9476 set_config('webserviceprotocols', implode(',', $activeprotocols));
9479 // Allow rest:use capability for authenticated user.
9480 $this->set_protocol_cap(true);
9482 } else {
9483 //disable web service system if no other services are enabled
9484 $otherenabledservices = $DB->get_records_select('external_services',
9485 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
9486 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
9487 if (empty($otherenabledservices)) {
9488 set_config('enablewebservices', false);
9490 // Also disable REST server.
9491 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9493 $protocolkey = array_search('rest', $activeprotocols);
9494 if ($protocolkey !== false) {
9495 unset($activeprotocols[$protocolkey]);
9496 $updateprotocol = true;
9499 if ($updateprotocol) {
9500 set_config('webserviceprotocols', implode(',', $activeprotocols));
9503 // Disallow rest:use capability for authenticated user.
9504 $this->set_protocol_cap(false);
9507 //disable the mobile service
9508 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
9509 $mobileservice->enabled = 0;
9510 $webservicemanager->update_external_service($mobileservice);
9513 return (parent::write_setting($data));
9518 * Special class for management of external services
9520 * @author Petr Skoda (skodak)
9522 class admin_setting_manageexternalservices extends admin_setting {
9524 * Calls parent::__construct with specific arguments
9526 public function __construct() {
9527 $this->nosave = true;
9528 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9532 * Always returns true, does nothing
9534 * @return true
9536 public function get_setting() {
9537 return true;
9541 * Always returns true, does nothing
9543 * @return true
9545 public function get_defaultsetting() {
9546 return true;
9550 * Always returns '', does not write anything
9552 * @return string Always returns ''
9554 public function write_setting($data) {
9555 // do not write any setting
9556 return '';
9560 * Checks if $query is one of the available external services
9562 * @param string $query The string to search for
9563 * @return bool Returns true if found, false if not
9565 public function is_related($query) {
9566 global $DB;
9568 if (parent::is_related($query)) {
9569 return true;
9572 $services = $DB->get_records('external_services', array(), 'id, name');
9573 foreach ($services as $service) {
9574 if (strpos(core_text::strtolower($service->name), $query) !== false) {
9575 return true;
9578 return false;
9582 * Builds the XHTML to display the control
9584 * @param string $data Unused
9585 * @param string $query
9586 * @return string
9588 public function output_html($data, $query='') {
9589 global $CFG, $OUTPUT, $DB;
9591 // display strings
9592 $stradministration = get_string('administration');
9593 $stredit = get_string('edit');
9594 $strservice = get_string('externalservice', 'webservice');
9595 $strdelete = get_string('delete');
9596 $strplugin = get_string('plugin', 'admin');
9597 $stradd = get_string('add');
9598 $strfunctions = get_string('functions', 'webservice');
9599 $strusers = get_string('users');
9600 $strserviceusers = get_string('serviceusers', 'webservice');
9602 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9603 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9604 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9606 // built in services
9607 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9608 $return = "";
9609 if (!empty($services)) {
9610 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9614 $table = new html_table();
9615 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9616 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9617 $table->id = 'builtinservices';
9618 $table->attributes['class'] = 'admintable externalservices generaltable';
9619 $table->data = array();
9621 // iterate through auth plugins and add to the display table
9622 foreach ($services as $service) {
9623 $name = $service->name;
9625 // hide/show link
9626 if ($service->enabled) {
9627 $displayname = "<span>$name</span>";
9628 } else {
9629 $displayname = "<span class=\"dimmed_text\">$name</span>";
9632 $plugin = $service->component;
9634 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9636 if ($service->restrictedusers) {
9637 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9638 } else {
9639 $users = get_string('allusers', 'webservice');
9642 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9644 // add a row to the table
9645 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9647 $return .= html_writer::table($table);
9650 // Custom services
9651 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9652 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9654 $table = new html_table();
9655 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9656 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9657 $table->id = 'customservices';
9658 $table->attributes['class'] = 'admintable externalservices generaltable';
9659 $table->data = array();
9661 // iterate through auth plugins and add to the display table
9662 foreach ($services as $service) {
9663 $name = $service->name;
9665 // hide/show link
9666 if ($service->enabled) {
9667 $displayname = "<span>$name</span>";
9668 } else {
9669 $displayname = "<span class=\"dimmed_text\">$name</span>";
9672 // delete link
9673 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9675 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9677 if ($service->restrictedusers) {
9678 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9679 } else {
9680 $users = get_string('allusers', 'webservice');
9683 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9685 // add a row to the table
9686 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9688 // add new custom service option
9689 $return .= html_writer::table($table);
9691 $return .= '<br />';
9692 // add a token to the table
9693 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9695 return highlight($query, $return);
9700 * Special class for overview of external services
9702 * @author Jerome Mouneyrac
9704 class admin_setting_webservicesoverview extends admin_setting {
9707 * Calls parent::__construct with specific arguments
9709 public function __construct() {
9710 $this->nosave = true;
9711 parent::__construct('webservicesoverviewui',
9712 get_string('webservicesoverview', 'webservice'), '', '');
9716 * Always returns true, does nothing
9718 * @return true
9720 public function get_setting() {
9721 return true;
9725 * Always returns true, does nothing
9727 * @return true
9729 public function get_defaultsetting() {
9730 return true;
9734 * Always returns '', does not write anything
9736 * @return string Always returns ''
9738 public function write_setting($data) {
9739 // do not write any setting
9740 return '';
9744 * Builds the XHTML to display the control
9746 * @param string $data Unused
9747 * @param string $query
9748 * @return string
9750 public function output_html($data, $query='') {
9751 global $CFG, $OUTPUT;
9753 $return = "";
9754 $brtag = html_writer::empty_tag('br');
9756 /// One system controlling Moodle with Token
9757 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9758 $table = new html_table();
9759 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9760 get_string('description'));
9761 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9762 $table->id = 'onesystemcontrol';
9763 $table->attributes['class'] = 'admintable wsoverview generaltable';
9764 $table->data = array();
9766 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9767 . $brtag . $brtag;
9769 /// 1. Enable Web Services
9770 $row = array();
9771 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9772 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9773 array('href' => $url));
9774 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
9775 if ($CFG->enablewebservices) {
9776 $status = get_string('yes');
9778 $row[1] = $status;
9779 $row[2] = get_string('enablewsdescription', 'webservice');
9780 $table->data[] = $row;
9782 /// 2. Enable protocols
9783 $row = array();
9784 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9785 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9786 array('href' => $url));
9787 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
9788 //retrieve activated protocol
9789 $active_protocols = empty($CFG->webserviceprotocols) ?
9790 array() : explode(',', $CFG->webserviceprotocols);
9791 if (!empty($active_protocols)) {
9792 $status = "";
9793 foreach ($active_protocols as $protocol) {
9794 $status .= $protocol . $brtag;
9797 $row[1] = $status;
9798 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9799 $table->data[] = $row;
9801 /// 3. Create user account
9802 $row = array();
9803 $url = new moodle_url("/user/editadvanced.php?id=-1");
9804 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9805 array('href' => $url));
9806 $row[1] = "";
9807 $row[2] = get_string('createuserdescription', 'webservice');
9808 $table->data[] = $row;
9810 /// 4. Add capability to users
9811 $row = array();
9812 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9813 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9814 array('href' => $url));
9815 $row[1] = "";
9816 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9817 $table->data[] = $row;
9819 /// 5. Select a web service
9820 $row = array();
9821 $url = new moodle_url("/admin/settings.php?section=externalservices");
9822 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9823 array('href' => $url));
9824 $row[1] = "";
9825 $row[2] = get_string('createservicedescription', 'webservice');
9826 $table->data[] = $row;
9828 /// 6. Add functions
9829 $row = array();
9830 $url = new moodle_url("/admin/settings.php?section=externalservices");
9831 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9832 array('href' => $url));
9833 $row[1] = "";
9834 $row[2] = get_string('addfunctionsdescription', 'webservice');
9835 $table->data[] = $row;
9837 /// 7. Add the specific user
9838 $row = array();
9839 $url = new moodle_url("/admin/settings.php?section=externalservices");
9840 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9841 array('href' => $url));
9842 $row[1] = "";
9843 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9844 $table->data[] = $row;
9846 /// 8. Create token for the specific user
9847 $row = array();
9848 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9849 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9850 array('href' => $url));
9851 $row[1] = "";
9852 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9853 $table->data[] = $row;
9855 /// 9. Enable the documentation
9856 $row = array();
9857 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9858 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9859 array('href' => $url));
9860 $status = '<span class="warning">' . get_string('no') . '</span>';
9861 if ($CFG->enablewsdocumentation) {
9862 $status = get_string('yes');
9864 $row[1] = $status;
9865 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9866 $table->data[] = $row;
9868 /// 10. Test the service
9869 $row = array();
9870 $url = new moodle_url("/admin/webservice/testclient.php");
9871 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9872 array('href' => $url));
9873 $row[1] = "";
9874 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9875 $table->data[] = $row;
9877 $return .= html_writer::table($table);
9879 /// Users as clients with token
9880 $return .= $brtag . $brtag . $brtag;
9881 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9882 $table = new html_table();
9883 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9884 get_string('description'));
9885 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9886 $table->id = 'userasclients';
9887 $table->attributes['class'] = 'admintable wsoverview generaltable';
9888 $table->data = array();
9890 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9891 $brtag . $brtag;
9893 /// 1. Enable Web Services
9894 $row = array();
9895 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9896 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9897 array('href' => $url));
9898 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
9899 if ($CFG->enablewebservices) {
9900 $status = get_string('yes');
9902 $row[1] = $status;
9903 $row[2] = get_string('enablewsdescription', 'webservice');
9904 $table->data[] = $row;
9906 /// 2. Enable protocols
9907 $row = array();
9908 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9909 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9910 array('href' => $url));
9911 $status = html_writer::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
9912 //retrieve activated protocol
9913 $active_protocols = empty($CFG->webserviceprotocols) ?
9914 array() : explode(',', $CFG->webserviceprotocols);
9915 if (!empty($active_protocols)) {
9916 $status = "";
9917 foreach ($active_protocols as $protocol) {
9918 $status .= $protocol . $brtag;
9921 $row[1] = $status;
9922 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9923 $table->data[] = $row;
9926 /// 3. Select a web service
9927 $row = array();
9928 $url = new moodle_url("/admin/settings.php?section=externalservices");
9929 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9930 array('href' => $url));
9931 $row[1] = "";
9932 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9933 $table->data[] = $row;
9935 /// 4. Add functions
9936 $row = array();
9937 $url = new moodle_url("/admin/settings.php?section=externalservices");
9938 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9939 array('href' => $url));
9940 $row[1] = "";
9941 $row[2] = get_string('addfunctionsdescription', 'webservice');
9942 $table->data[] = $row;
9944 /// 5. Add capability to users
9945 $row = array();
9946 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9947 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9948 array('href' => $url));
9949 $row[1] = "";
9950 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9951 $table->data[] = $row;
9953 /// 6. Test the service
9954 $row = array();
9955 $url = new moodle_url("/admin/webservice/testclient.php");
9956 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9957 array('href' => $url));
9958 $row[1] = "";
9959 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9960 $table->data[] = $row;
9962 $return .= html_writer::table($table);
9964 return highlight($query, $return);
9971 * Special class for web service protocol administration.
9973 * @author Petr Skoda (skodak)
9975 class admin_setting_managewebserviceprotocols extends admin_setting {
9978 * Calls parent::__construct with specific arguments
9980 public function __construct() {
9981 $this->nosave = true;
9982 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9986 * Always returns true, does nothing
9988 * @return true
9990 public function get_setting() {
9991 return true;
9995 * Always returns true, does nothing
9997 * @return true
9999 public function get_defaultsetting() {
10000 return true;
10004 * Always returns '', does not write anything
10006 * @return string Always returns ''
10008 public function write_setting($data) {
10009 // do not write any setting
10010 return '';
10014 * Checks if $query is one of the available webservices
10016 * @param string $query The string to search for
10017 * @return bool Returns true if found, false if not
10019 public function is_related($query) {
10020 if (parent::is_related($query)) {
10021 return true;
10024 $protocols = core_component::get_plugin_list('webservice');
10025 foreach ($protocols as $protocol=>$location) {
10026 if (strpos($protocol, $query) !== false) {
10027 return true;
10029 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10030 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
10031 return true;
10034 return false;
10038 * Builds the XHTML to display the control
10040 * @param string $data Unused
10041 * @param string $query
10042 * @return string
10044 public function output_html($data, $query='') {
10045 global $CFG, $OUTPUT;
10047 // display strings
10048 $stradministration = get_string('administration');
10049 $strsettings = get_string('settings');
10050 $stredit = get_string('edit');
10051 $strprotocol = get_string('protocol', 'webservice');
10052 $strenable = get_string('enable');
10053 $strdisable = get_string('disable');
10054 $strversion = get_string('version');
10056 $protocols_available = core_component::get_plugin_list('webservice');
10057 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
10058 ksort($protocols_available);
10060 foreach ($active_protocols as $key=>$protocol) {
10061 if (empty($protocols_available[$protocol])) {
10062 unset($active_protocols[$key]);
10066 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10067 $return .= $OUTPUT->box_start('generalbox webservicesui');
10069 $table = new html_table();
10070 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
10071 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10072 $table->id = 'webserviceprotocols';
10073 $table->attributes['class'] = 'admintable generaltable';
10074 $table->data = array();
10076 // iterate through auth plugins and add to the display table
10077 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10078 foreach ($protocols_available as $protocol => $location) {
10079 $name = get_string('pluginname', 'webservice_'.$protocol);
10081 $plugin = new stdClass();
10082 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
10083 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
10085 $version = isset($plugin->version) ? $plugin->version : '';
10087 // hide/show link
10088 if (in_array($protocol, $active_protocols)) {
10089 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
10090 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10091 $displayname = "<span>$name</span>";
10092 } else {
10093 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
10094 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10095 $displayname = "<span class=\"dimmed_text\">$name</span>";
10098 // settings link
10099 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
10100 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10101 } else {
10102 $settings = '';
10105 // add a row to the table
10106 $table->data[] = array($displayname, $version, $hideshow, $settings);
10108 $return .= html_writer::table($table);
10109 $return .= get_string('configwebserviceplugins', 'webservice');
10110 $return .= $OUTPUT->box_end();
10112 return highlight($query, $return);
10118 * Special class for web service token administration.
10120 * @author Jerome Mouneyrac
10122 class admin_setting_managewebservicetokens extends admin_setting {
10125 * Calls parent::__construct with specific arguments
10127 public function __construct() {
10128 $this->nosave = true;
10129 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
10133 * Always returns true, does nothing
10135 * @return true
10137 public function get_setting() {
10138 return true;
10142 * Always returns true, does nothing
10144 * @return true
10146 public function get_defaultsetting() {
10147 return true;
10151 * Always returns '', does not write anything
10153 * @return string Always returns ''
10155 public function write_setting($data) {
10156 // do not write any setting
10157 return '';
10161 * Builds the XHTML to display the control
10163 * @param string $data Unused
10164 * @param string $query
10165 * @return string
10167 public function output_html($data, $query='') {
10168 global $CFG, $OUTPUT;
10170 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
10171 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
10173 $return = $OUTPUT->box_start('generalbox webservicestokenui');
10175 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
10176 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
10179 $table = new \webservice\token_table('webservicetokens');
10180 $table->define_baseurl($baseurl);
10181 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
10182 $table->data = array();
10183 ob_start();
10184 $table->out(10, false);
10185 $tablehtml = ob_get_contents();
10186 ob_end_clean();
10187 $return .= $tablehtml;
10189 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
10191 $return .= $OUTPUT->box_end();
10192 // add a token to the table
10193 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
10194 $return .= get_string('add')."</a>";
10196 return highlight($query, $return);
10202 * Colour picker
10204 * @copyright 2010 Sam Hemelryk
10205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10207 class admin_setting_configcolourpicker extends admin_setting {
10210 * Information for previewing the colour
10212 * @var array|null
10214 protected $previewconfig = null;
10217 * Use default when empty.
10219 protected $usedefaultwhenempty = true;
10223 * @param string $name
10224 * @param string $visiblename
10225 * @param string $description
10226 * @param string $defaultsetting
10227 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10229 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10230 $usedefaultwhenempty = true) {
10231 $this->previewconfig = $previewconfig;
10232 $this->usedefaultwhenempty = $usedefaultwhenempty;
10233 parent::__construct($name, $visiblename, $description, $defaultsetting);
10234 $this->set_force_ltr(true);
10238 * Return the setting
10240 * @return mixed returns config if successful else null
10242 public function get_setting() {
10243 return $this->config_read($this->name);
10247 * Saves the setting
10249 * @param string $data
10250 * @return bool
10252 public function write_setting($data) {
10253 $data = $this->validate($data);
10254 if ($data === false) {
10255 return get_string('validateerror', 'admin');
10257 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
10261 * Validates the colour that was entered by the user
10263 * @param string $data
10264 * @return string|false
10266 protected function validate($data) {
10268 * List of valid HTML colour names
10270 * @var array
10272 $colornames = array(
10273 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10274 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10275 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10276 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10277 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10278 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10279 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10280 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10281 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10282 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10283 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10284 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10285 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10286 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10287 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10288 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10289 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10290 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10291 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10292 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10293 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10294 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10295 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10296 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10297 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10298 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10299 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10300 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10301 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10302 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10303 'whitesmoke', 'yellow', 'yellowgreen'
10306 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10307 if (strpos($data, '#')!==0) {
10308 $data = '#'.$data;
10310 return $data;
10311 } else if (in_array(strtolower($data), $colornames)) {
10312 return $data;
10313 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10314 return $data;
10315 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10316 return $data;
10317 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10318 return $data;
10319 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10320 return $data;
10321 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
10322 return $data;
10323 } else if (empty($data)) {
10324 if ($this->usedefaultwhenempty){
10325 return $this->defaultsetting;
10326 } else {
10327 return '';
10329 } else {
10330 return false;
10335 * Generates the HTML for the setting
10337 * @global moodle_page $PAGE
10338 * @global core_renderer $OUTPUT
10339 * @param string $data
10340 * @param string $query
10342 public function output_html($data, $query = '') {
10343 global $PAGE, $OUTPUT;
10345 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10346 $context = (object) [
10347 'id' => $this->get_id(),
10348 'name' => $this->get_full_name(),
10349 'value' => $data,
10350 'icon' => $icon->export_for_template($OUTPUT),
10351 'haspreviewconfig' => !empty($this->previewconfig),
10352 'forceltr' => $this->get_force_ltr()
10355 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10356 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
10358 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
10359 $this->get_defaultsetting(), $query);
10366 * Class used for uploading of one file into file storage,
10367 * the file name is stored in config table.
10369 * Please note you need to implement your own '_pluginfile' callback function,
10370 * this setting only stores the file, it does not deal with file serving.
10372 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10375 class admin_setting_configstoredfile extends admin_setting {
10376 /** @var array file area options - should be one file only */
10377 protected $options;
10378 /** @var string name of the file area */
10379 protected $filearea;
10380 /** @var int intemid */
10381 protected $itemid;
10382 /** @var string used for detection of changes */
10383 protected $oldhashes;
10386 * Create new stored file setting.
10388 * @param string $name low level setting name
10389 * @param string $visiblename human readable setting name
10390 * @param string $description description of setting
10391 * @param mixed $filearea file area for file storage
10392 * @param int $itemid itemid for file storage
10393 * @param array $options file area options
10395 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10396 parent::__construct($name, $visiblename, $description, '');
10397 $this->filearea = $filearea;
10398 $this->itemid = $itemid;
10399 $this->options = (array)$options;
10400 $this->customcontrol = true;
10404 * Applies defaults and returns all options.
10405 * @return array
10407 protected function get_options() {
10408 global $CFG;
10410 require_once("$CFG->libdir/filelib.php");
10411 require_once("$CFG->dirroot/repository/lib.php");
10412 $defaults = array(
10413 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10414 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
10415 'context' => context_system::instance());
10416 foreach($this->options as $k => $v) {
10417 $defaults[$k] = $v;
10420 return $defaults;
10423 public function get_setting() {
10424 return $this->config_read($this->name);
10427 public function write_setting($data) {
10428 global $USER;
10430 // Let's not deal with validation here, this is for admins only.
10431 $current = $this->get_setting();
10432 if (empty($data) && $current === null) {
10433 // This will be the case when applying default settings (installation).
10434 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
10435 } else if (!is_number($data)) {
10436 // Draft item id is expected here!
10437 return get_string('errorsetting', 'admin');
10440 $options = $this->get_options();
10441 $fs = get_file_storage();
10442 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10444 $this->oldhashes = null;
10445 if ($current) {
10446 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10447 if ($file = $fs->get_file_by_hash($hash)) {
10448 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
10450 unset($file);
10453 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
10454 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10455 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10456 // with an error because the draft area does not exist, as he did not use it.
10457 $usercontext = context_user::instance($USER->id);
10458 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
10459 return get_string('errorsetting', 'admin');
10463 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10464 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
10466 $filepath = '';
10467 if ($files) {
10468 /** @var stored_file $file */
10469 $file = reset($files);
10470 $filepath = $file->get_filepath().$file->get_filename();
10473 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
10476 public function post_write_settings($original) {
10477 $options = $this->get_options();
10478 $fs = get_file_storage();
10479 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10481 $current = $this->get_setting();
10482 $newhashes = null;
10483 if ($current) {
10484 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
10485 if ($file = $fs->get_file_by_hash($hash)) {
10486 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10488 unset($file);
10491 if ($this->oldhashes === $newhashes) {
10492 $this->oldhashes = null;
10493 return false;
10495 $this->oldhashes = null;
10497 $callbackfunction = $this->updatedcallback;
10498 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10499 $callbackfunction($this->get_full_name());
10501 return true;
10504 public function output_html($data, $query = '') {
10505 global $PAGE, $CFG;
10507 $options = $this->get_options();
10508 $id = $this->get_id();
10509 $elname = $this->get_full_name();
10510 $draftitemid = file_get_submitted_draft_itemid($elname);
10511 $component = is_null($this->plugin) ? 'core' : $this->plugin;
10512 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
10514 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10515 require_once("$CFG->dirroot/lib/form/filemanager.php");
10517 $fmoptions = new stdClass();
10518 $fmoptions->mainfile = $options['mainfile'];
10519 $fmoptions->maxbytes = $options['maxbytes'];
10520 $fmoptions->maxfiles = $options['maxfiles'];
10521 $fmoptions->client_id = uniqid();
10522 $fmoptions->itemid = $draftitemid;
10523 $fmoptions->subdirs = $options['subdirs'];
10524 $fmoptions->target = $id;
10525 $fmoptions->accepted_types = $options['accepted_types'];
10526 $fmoptions->return_types = $options['return_types'];
10527 $fmoptions->context = $options['context'];
10528 $fmoptions->areamaxbytes = $options['areamaxbytes'];
10530 $fm = new form_filemanager($fmoptions);
10531 $output = $PAGE->get_renderer('core', 'files');
10532 $html = $output->render($fm);
10534 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
10535 $html .= '<input value="" id="'.$id.'" type="hidden" />';
10537 return format_admin_setting($this, $this->visiblename,
10538 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
10539 $this->description, true, '', '', $query);
10545 * Administration interface for user specified regular expressions for device detection.
10547 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10549 class admin_setting_devicedetectregex extends admin_setting {
10552 * Calls parent::__construct with specific args
10554 * @param string $name
10555 * @param string $visiblename
10556 * @param string $description
10557 * @param mixed $defaultsetting
10559 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10560 global $CFG;
10561 parent::__construct($name, $visiblename, $description, $defaultsetting);
10565 * Return the current setting(s)
10567 * @return array Current settings array
10569 public function get_setting() {
10570 global $CFG;
10572 $config = $this->config_read($this->name);
10573 if (is_null($config)) {
10574 return null;
10577 return $this->prepare_form_data($config);
10581 * Save selected settings
10583 * @param array $data Array of settings to save
10584 * @return bool
10586 public function write_setting($data) {
10587 if (empty($data)) {
10588 $data = array();
10591 if ($this->config_write($this->name, $this->process_form_data($data))) {
10592 return ''; // success
10593 } else {
10594 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
10599 * Return XHTML field(s) for regexes
10601 * @param array $data Array of options to set in HTML
10602 * @return string XHTML string for the fields and wrapping div(s)
10604 public function output_html($data, $query='') {
10605 global $OUTPUT;
10607 $context = (object) [
10608 'expressions' => [],
10609 'name' => $this->get_full_name()
10612 if (empty($data)) {
10613 $looplimit = 1;
10614 } else {
10615 $looplimit = (count($data)/2)+1;
10618 for ($i=0; $i<$looplimit; $i++) {
10620 $expressionname = 'expression'.$i;
10622 if (!empty($data[$expressionname])){
10623 $expression = $data[$expressionname];
10624 } else {
10625 $expression = '';
10628 $valuename = 'value'.$i;
10630 if (!empty($data[$valuename])){
10631 $value = $data[$valuename];
10632 } else {
10633 $value= '';
10636 $context->expressions[] = [
10637 'index' => $i,
10638 'expression' => $expression,
10639 'value' => $value
10643 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10645 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10649 * Converts the string of regexes
10651 * @see self::process_form_data()
10652 * @param $regexes string of regexes
10653 * @return array of form fields and their values
10655 protected function prepare_form_data($regexes) {
10657 $regexes = json_decode($regexes);
10659 $form = array();
10661 $i = 0;
10663 foreach ($regexes as $value => $regex) {
10664 $expressionname = 'expression'.$i;
10665 $valuename = 'value'.$i;
10667 $form[$expressionname] = $regex;
10668 $form[$valuename] = $value;
10669 $i++;
10672 return $form;
10676 * Converts the data from admin settings form into a string of regexes
10678 * @see self::prepare_form_data()
10679 * @param array $data array of admin form fields and values
10680 * @return false|string of regexes
10682 protected function process_form_data(array $form) {
10684 $count = count($form); // number of form field values
10686 if ($count % 2) {
10687 // we must get five fields per expression
10688 return false;
10691 $regexes = array();
10692 for ($i = 0; $i < $count / 2; $i++) {
10693 $expressionname = "expression".$i;
10694 $valuename = "value".$i;
10696 $expression = trim($form['expression'.$i]);
10697 $value = trim($form['value'.$i]);
10699 if (empty($expression)){
10700 continue;
10703 $regexes[$value] = $expression;
10706 $regexes = json_encode($regexes);
10708 return $regexes;
10714 * Multiselect for current modules
10716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10718 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10719 private $excludesystem;
10722 * Calls parent::__construct - note array $choices is not required
10724 * @param string $name setting name
10725 * @param string $visiblename localised setting name
10726 * @param string $description setting description
10727 * @param array $defaultsetting a plain array of default module ids
10728 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10730 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10731 $excludesystem = true) {
10732 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10733 $this->excludesystem = $excludesystem;
10737 * Loads an array of current module choices
10739 * @return bool always return true
10741 public function load_choices() {
10742 if (is_array($this->choices)) {
10743 return true;
10745 $this->choices = array();
10747 global $CFG, $DB;
10748 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10749 foreach ($records as $record) {
10750 // Exclude modules if the code doesn't exist
10751 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10752 // Also exclude system modules (if specified)
10753 if (!($this->excludesystem &&
10754 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10755 MOD_ARCHETYPE_SYSTEM)) {
10756 $this->choices[$record->id] = $record->name;
10760 return true;
10765 * Admin setting to show if a php extension is enabled or not.
10767 * @copyright 2013 Damyon Wiese
10768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10770 class admin_setting_php_extension_enabled extends admin_setting {
10772 /** @var string The name of the extension to check for */
10773 private $extension;
10776 * Calls parent::__construct with specific arguments
10778 public function __construct($name, $visiblename, $description, $extension) {
10779 $this->extension = $extension;
10780 $this->nosave = true;
10781 parent::__construct($name, $visiblename, $description, '');
10785 * Always returns true, does nothing
10787 * @return true
10789 public function get_setting() {
10790 return true;
10794 * Always returns true, does nothing
10796 * @return true
10798 public function get_defaultsetting() {
10799 return true;
10803 * Always returns '', does not write anything
10805 * @return string Always returns ''
10807 public function write_setting($data) {
10808 // Do not write any setting.
10809 return '';
10813 * Outputs the html for this setting.
10814 * @return string Returns an XHTML string
10816 public function output_html($data, $query='') {
10817 global $OUTPUT;
10819 $o = '';
10820 if (!extension_loaded($this->extension)) {
10821 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10823 $o .= format_admin_setting($this, $this->visiblename, $warning);
10825 return $o;
10830 * Server timezone setting.
10832 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10834 * @author Petr Skoda <petr.skoda@totaralms.com>
10836 class admin_setting_servertimezone extends admin_setting_configselect {
10838 * Constructor.
10840 public function __construct() {
10841 $default = core_date::get_default_php_timezone();
10842 if ($default === 'UTC') {
10843 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10844 $default = 'Europe/London';
10847 parent::__construct('timezone',
10848 new lang_string('timezone', 'core_admin'),
10849 new lang_string('configtimezone', 'core_admin'), $default, null);
10853 * Lazy load timezone options.
10854 * @return bool true if loaded, false if error
10856 public function load_choices() {
10857 global $CFG;
10858 if (is_array($this->choices)) {
10859 return true;
10862 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10863 $this->choices = core_date::get_list_of_timezones($current, false);
10864 if ($current == 99) {
10865 // Do not show 99 unless it is current value, we want to get rid of it over time.
10866 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10867 core_date::get_default_php_timezone());
10870 return true;
10875 * Forced user timezone setting.
10877 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10878 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10879 * @author Petr Skoda <petr.skoda@totaralms.com>
10881 class admin_setting_forcetimezone extends admin_setting_configselect {
10883 * Constructor.
10885 public function __construct() {
10886 parent::__construct('forcetimezone',
10887 new lang_string('forcetimezone', 'core_admin'),
10888 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10892 * Lazy load timezone options.
10893 * @return bool true if loaded, false if error
10895 public function load_choices() {
10896 global $CFG;
10897 if (is_array($this->choices)) {
10898 return true;
10901 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10902 $this->choices = core_date::get_list_of_timezones($current, true);
10903 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10905 return true;
10911 * Search setup steps info.
10913 * @package core
10914 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10917 class admin_setting_searchsetupinfo extends admin_setting {
10920 * Calls parent::__construct with specific arguments
10922 public function __construct() {
10923 $this->nosave = true;
10924 parent::__construct('searchsetupinfo', '', '', '');
10928 * Always returns true, does nothing
10930 * @return true
10932 public function get_setting() {
10933 return true;
10937 * Always returns true, does nothing
10939 * @return true
10941 public function get_defaultsetting() {
10942 return true;
10946 * Always returns '', does not write anything
10948 * @param array $data
10949 * @return string Always returns ''
10951 public function write_setting($data) {
10952 // Do not write any setting.
10953 return '';
10957 * Builds the HTML to display the control
10959 * @param string $data Unused
10960 * @param string $query
10961 * @return string
10963 public function output_html($data, $query='') {
10964 global $CFG, $OUTPUT;
10966 $return = '';
10967 $brtag = html_writer::empty_tag('br');
10969 $searchareas = \core_search\manager::get_search_areas_list();
10970 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10971 $anyindexed = false;
10972 foreach ($searchareas as $areaid => $searcharea) {
10973 list($componentname, $varname) = $searcharea->get_config_var_name();
10974 if (get_config($componentname, $varname . '_indexingstart')) {
10975 $anyindexed = true;
10976 break;
10980 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10982 $table = new html_table();
10983 $table->head = array(get_string('step', 'search'), get_string('status'));
10984 $table->colclasses = array('leftalign step', 'leftalign status');
10985 $table->id = 'searchsetup';
10986 $table->attributes['class'] = 'admintable generaltable';
10987 $table->data = array();
10989 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10991 // Select a search engine.
10992 $row = array();
10993 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10994 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10995 array('href' => $url));
10997 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10998 if (!empty($CFG->searchengine)) {
10999 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
11000 array('class' => 'badge badge-success'));
11003 $row[1] = $status;
11004 $table->data[] = $row;
11006 // Available areas.
11007 $row = array();
11008 $url = new moodle_url('/admin/searchareas.php');
11009 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
11010 array('href' => $url));
11012 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11013 if ($anyenabled) {
11014 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11017 $row[1] = $status;
11018 $table->data[] = $row;
11020 // Setup search engine.
11021 $row = array();
11022 if (empty($CFG->searchengine)) {
11023 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11024 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11025 } else {
11026 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
11027 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
11028 array('href' => $url));
11029 // Check the engine status.
11030 $searchengine = \core_search\manager::search_engine_instance();
11031 try {
11032 $serverstatus = $searchengine->is_server_ready();
11033 } catch (\moodle_exception $e) {
11034 $serverstatus = $e->getMessage();
11036 if ($serverstatus === true) {
11037 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11038 } else {
11039 $status = html_writer::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11041 $row[1] = $status;
11043 $table->data[] = $row;
11045 // Indexed data.
11046 $row = array();
11047 $url = new moodle_url('/admin/searchareas.php');
11048 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11049 if ($anyindexed) {
11050 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11051 } else {
11052 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11054 $row[1] = $status;
11055 $table->data[] = $row;
11057 // Enable global search.
11058 $row = array();
11059 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11060 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
11061 array('href' => $url));
11062 $status = html_writer::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11063 if (\core_search\manager::is_global_search_enabled()) {
11064 $status = html_writer::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11066 $row[1] = $status;
11067 $table->data[] = $row;
11069 $return .= html_writer::table($table);
11071 return highlight($query, $return);
11077 * Used to validate the contents of SCSS code and ensuring they are parsable.
11079 * It does not attempt to detect undefined SCSS variables because it is designed
11080 * to be used without knowledge of other config/scss included.
11082 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11083 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11085 class admin_setting_scsscode extends admin_setting_configtextarea {
11088 * Validate the contents of the SCSS to ensure its parsable. Does not
11089 * attempt to detect undefined scss variables.
11091 * @param string $data The scss code from text field.
11092 * @return mixed bool true for success or string:error on failure.
11094 public function validate($data) {
11095 if (empty($data)) {
11096 return true;
11099 $scss = new core_scss();
11100 try {
11101 $scss->compile($data);
11102 } catch (ScssPhp\ScssPhp\Exception\ParserException $e) {
11103 return get_string('scssinvalid', 'admin', $e->getMessage());
11104 } catch (ScssPhp\ScssPhp\Exception\CompilerException $e) {
11105 // Silently ignore this - it could be a scss variable defined from somewhere
11106 // else which we are not examining here.
11107 return true;
11110 return true;
11116 * Administration setting to define a list of file types.
11118 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11119 * @copyright 2017 David Mudrák <david@moodle.com>
11120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11122 class admin_setting_filetypes extends admin_setting_configtext {
11124 /** @var array Allow selection from these file types only. */
11125 protected $onlytypes = [];
11127 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11128 protected $allowall = true;
11130 /** @var core_form\filetypes_util instance to use as a helper. */
11131 protected $util = null;
11134 * Constructor.
11136 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11137 * @param string $visiblename Localised label of the setting
11138 * @param string $description Localised description of the setting
11139 * @param string $defaultsetting Default setting value.
11140 * @param array $options Setting widget options, an array with optional keys:
11141 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11142 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11144 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11146 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
11148 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11149 $this->onlytypes = $options['onlytypes'];
11152 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
11153 $this->allowall = (bool)$options['allowall'];
11156 $this->util = new \core_form\filetypes_util();
11160 * Normalize the user's input and write it to the database as comma separated list.
11162 * Comma separated list as a text representation of the array was chosen to
11163 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11165 * @param string $data Value submitted by the admin.
11166 * @return string Epty string if all good, error message otherwise.
11168 public function write_setting($data) {
11169 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
11173 * Validate data before storage
11175 * @param string $data The setting values provided by the admin
11176 * @return bool|string True if ok, the string if error found
11178 public function validate($data) {
11180 // No need to call parent's validation here as we are PARAM_RAW.
11182 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
11183 return true;
11185 } else {
11186 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
11187 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
11192 * Return an HTML string for the setting element.
11194 * @param string $data The current setting value
11195 * @param string $query Admin search query to be highlighted
11196 * @return string HTML to be displayed
11198 public function output_html($data, $query='') {
11199 global $OUTPUT, $PAGE;
11201 $default = $this->get_defaultsetting();
11202 $context = (object) [
11203 'id' => $this->get_id(),
11204 'name' => $this->get_full_name(),
11205 'value' => $data,
11206 'descriptions' => $this->util->describe_file_types($data),
11208 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11210 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
11211 $this->get_id(),
11212 $this->visiblename->out(),
11213 $this->onlytypes,
11214 $this->allowall,
11217 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
11221 * Should the values be always displayed in LTR mode?
11223 * We always return true here because these values are not RTL compatible.
11225 * @return bool True because these values are not RTL compatible.
11227 public function get_force_ltr() {
11228 return true;
11233 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11236 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11238 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
11241 * Constructor.
11243 * @param string $name
11244 * @param string $visiblename
11245 * @param string $description
11246 * @param mixed $defaultsetting string or array
11247 * @param mixed $paramtype
11248 * @param string $cols
11249 * @param string $rows
11251 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
11252 $cols = '60', $rows = '8') {
11253 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11254 // Pre-set force LTR to false.
11255 $this->set_force_ltr(false);
11259 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11261 * @param string $data The age of digital consent map from text field.
11262 * @return mixed bool true for success or string:error on failure.
11264 public function validate($data) {
11265 if (empty($data)) {
11266 return true;
11269 try {
11270 \core_auth\digital_consent::parse_age_digital_consent_map($data);
11271 } catch (\moodle_exception $e) {
11272 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11275 return true;
11280 * Selection of plugins that can work as site policy handlers
11282 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11283 * @copyright 2018 Marina Glancy
11285 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
11288 * Constructor
11289 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11290 * for ones in config_plugins.
11291 * @param string $visiblename localised
11292 * @param string $description long localised info
11293 * @param string $defaultsetting
11295 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11296 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11300 * Lazy-load the available choices for the select box
11302 public function load_choices() {
11303 if (during_initial_install()) {
11304 return false;
11306 if (is_array($this->choices)) {
11307 return true;
11310 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11311 $manager = new \core_privacy\local\sitepolicy\manager();
11312 $plugins = $manager->get_all_handlers();
11313 foreach ($plugins as $pname => $unused) {
11314 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11315 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11318 return true;
11323 * Used to validate theme presets code and ensuring they compile well.
11325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11326 * @copyright 2019 Bas Brands <bas@moodle.com>
11328 class admin_setting_configthemepreset extends admin_setting_configselect {
11330 /** @var string The name of the theme to check for */
11331 private $themename;
11334 * Constructor
11335 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11336 * or 'myplugin/mysetting' for ones in config_plugins.
11337 * @param string $visiblename localised
11338 * @param string $description long localised info
11339 * @param string|int $defaultsetting
11340 * @param array $choices array of $value=>$label for each selection
11341 * @param string $themename name of theme to check presets for.
11343 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11344 $this->themename = $themename;
11345 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11349 * Write settings if validated
11351 * @param string $data
11352 * @return string
11354 public function write_setting($data) {
11355 $validated = $this->validate($data);
11356 if ($validated !== true) {
11357 return $validated;
11359 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
11363 * Validate the preset file to ensure its parsable.
11365 * @param string $data The preset file chosen.
11366 * @return mixed bool true for success or string:error on failure.
11368 public function validate($data) {
11370 if (in_array($data, ['default.scss', 'plain.scss'])) {
11371 return true;
11374 $fs = get_file_storage();
11375 $theme = theme_config::load($this->themename);
11376 $context = context_system::instance();
11378 // If the preset has not changed there is no need to validate it.
11379 if ($theme->settings->preset == $data) {
11380 return true;
11383 if ($presetfile = $fs->get_file($context->id, 'theme_' . $this->themename, 'preset', 0, '/', $data)) {
11384 // This operation uses a lot of resources.
11385 raise_memory_limit(MEMORY_EXTRA);
11386 core_php_time_limit::raise(300);
11388 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11389 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11391 $compiler = new core_scss();
11392 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11393 $compiler->append_raw_scss($presetfile->get_content());
11394 if ($scssproperties = $theme->get_scss_property()) {
11395 $compiler->setImportPaths($scssproperties[0]);
11397 $compiler->append_raw_scss($theme->get_extra_scss_code());
11399 try {
11400 $compiler->to_css();
11401 } catch (Exception $e) {
11402 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11405 // Try to save memory.
11406 $compiler = null;
11407 unset($compiler);
11410 return true;
11415 * Selection of plugins that can work as H5P libraries handlers
11417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11418 * @copyright 2020 Sara Arjona <sara@moodle.com>
11420 class admin_settings_h5plib_handler_select extends admin_setting_configselect {
11423 * Constructor
11424 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11425 * for ones in config_plugins.
11426 * @param string $visiblename localised
11427 * @param string $description long localised info
11428 * @param string $defaultsetting
11430 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11431 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
11435 * Lazy-load the available choices for the select box
11437 public function load_choices() {
11438 if (during_initial_install()) {
11439 return false;
11441 if (is_array($this->choices)) {
11442 return true;
11445 $this->choices = \core_h5p\local\library\autoloader::get_all_handlers();
11446 foreach ($this->choices as $name => $class) {
11447 $this->choices[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11448 ['name' => new lang_string('pluginname', $name), 'component' => $name]);
11451 return true;