2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
56 * Next, in foo.php, your file structure would resemble the following:
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();
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.
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
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
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();
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
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.',
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);
164 $strpluginname = $component;
168 $pluginname = $component;
169 if (get_string_manager()->string_exists('pluginname', $component)) {
170 $strpluginname = get_string('pluginname', $component);
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);
196 $plugininfo->uninstall_cleanup();
197 core_plugin_manager
::reset_caches();
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_adhoc', ['component' => $component]);
213 $DB->delete_records('task_scheduled', array('component' => $component));
215 // Delete Inbound Message datakeys.
216 $DB->delete_records_select('messageinbound_datakeys',
217 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
219 // Delete Inbound Message handlers.
220 $DB->delete_records('messageinbound_handlers', array('component' => $component));
222 // delete all the logs
223 $DB->delete_records('log', array('module' => $pluginname));
225 // delete log_display information
226 $DB->delete_records('log_display', array('component' => $component));
228 // delete the module configuration records
229 unset_all_config_for_plugin($component);
230 if ($type === 'mod') {
231 unset_all_config_for_plugin($pluginname);
234 // delete message provider
235 message_provider_uninstall($component);
237 // delete the plugin tables
238 $xmldbfilepath = $plugindirectory . '/db/install.xml';
239 drop_plugin_tables($component, $xmldbfilepath, false);
240 if ($type === 'mod' or $type === 'block') {
241 // non-frankenstyle table prefixes
242 drop_plugin_tables($name, $xmldbfilepath, false);
245 // delete the capabilities that were defined by this module
246 capabilities_cleanup($component);
248 // Delete all remaining files in the filepool owned by the component.
249 $fs = get_file_storage();
250 $fs->delete_component_files($component);
252 // Finally purge all caches.
255 // Invalidate the hash used for upgrade detections.
256 set_config('allversionshash', '');
258 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
262 * Returns the version of installed component
264 * @param string $component component name
265 * @param string $source either 'disk' or 'installed' - where to get the version information from
266 * @return string|bool version number or false if the component is not found
268 function get_component_version($component, $source='installed') {
271 list($type, $name) = core_component
::normalize_component($component);
273 // moodle core or a core subsystem
274 if ($type === 'core') {
275 if ($source === 'installed') {
276 if (empty($CFG->version
)) {
279 return $CFG->version
;
282 if (!is_readable($CFG->dirroot
.'/version.php')) {
285 $version = null; //initialize variable for IDEs
286 include($CFG->dirroot
.'/version.php');
293 if ($type === 'mod') {
294 if ($source === 'installed') {
295 if ($CFG->version
< 2013092001.02) {
296 return $DB->get_field('modules', 'version', array('name'=>$name));
298 return get_config('mod_'.$name, 'version');
302 $mods = core_component
::get_plugin_list('mod');
303 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
306 $plugin = new stdClass();
307 $plugin->version
= null;
309 include($mods[$name].'/version.php');
310 return $plugin->version
;
316 if ($type === 'block') {
317 if ($source === 'installed') {
318 if ($CFG->version
< 2013092001.02) {
319 return $DB->get_field('block', 'version', array('name'=>$name));
321 return get_config('block_'.$name, 'version');
324 $blocks = core_component
::get_plugin_list('block');
325 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
328 $plugin = new stdclass();
329 include($blocks[$name].'/version.php');
330 return $plugin->version
;
335 // all other plugin types
336 if ($source === 'installed') {
337 return get_config($type.'_'.$name, 'version');
339 $plugins = core_component
::get_plugin_list($type);
340 if (empty($plugins[$name])) {
343 $plugin = new stdclass();
344 include($plugins[$name].'/version.php');
345 return $plugin->version
;
351 * Delete all plugin tables
353 * @param string $name Name of plugin, used as table prefix
354 * @param string $file Path to install.xml file
355 * @param bool $feedback defaults to true
356 * @return bool Always returns true
358 function drop_plugin_tables($name, $file, $feedback=true) {
361 // first try normal delete
362 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
366 // then try to find all tables that start with name and are not in any xml file
367 $used_tables = get_used_table_names();
369 $tables = $DB->get_tables();
371 /// Iterate over, fixing id fields as necessary
372 foreach ($tables as $table) {
373 if (in_array($table, $used_tables)) {
377 if (strpos($table, $name) !== 0) {
381 // found orphan table --> delete it
382 if ($DB->get_manager()->table_exists($table)) {
383 $xmldb_table = new xmldb_table($table);
384 $DB->get_manager()->drop_table($xmldb_table);
392 * Returns names of all known tables == tables that moodle knows about.
394 * @return array Array of lowercase table names
396 function get_used_table_names() {
397 $table_names = array();
398 $dbdirs = get_db_directories();
400 foreach ($dbdirs as $dbdir) {
401 $file = $dbdir.'/install.xml';
403 $xmldb_file = new xmldb_file($file);
405 if (!$xmldb_file->fileExists()) {
409 $loaded = $xmldb_file->loadXMLStructure();
410 $structure = $xmldb_file->getStructure();
412 if ($loaded and $tables = $structure->getTables()) {
413 foreach($tables as $table) {
414 $table_names[] = strtolower($table->getName());
423 * Returns list of all directories where we expect install.xml files
424 * @return array Array of paths
426 function get_db_directories() {
431 /// First, the main one (lib/db)
432 $dbdirs[] = $CFG->libdir
.'/db';
434 /// Then, all the ones defined by core_component::get_plugin_types()
435 $plugintypes = core_component
::get_plugin_types();
436 foreach ($plugintypes as $plugintype => $pluginbasedir) {
437 if ($plugins = core_component
::get_plugin_list($plugintype)) {
438 foreach ($plugins as $plugin => $plugindir) {
439 $dbdirs[] = $plugindir.'/db';
448 * Try to obtain or release the cron lock.
449 * @param string $name name of lock
450 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
451 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
452 * @return bool true if lock obtained
454 function set_cron_lock($name, $until, $ignorecurrent=false) {
457 debugging("Tried to get a cron lock for a null fieldname");
461 // remove lock by force == remove from config table
462 if (is_null($until)) {
463 set_config($name, null);
467 if (!$ignorecurrent) {
468 // read value from db - other processes might have changed it
469 $value = $DB->get_field('config', 'value', array('name'=>$name));
471 if ($value and $value > time()) {
477 set_config($name, $until);
482 * Test if and critical warnings are present
485 function admin_critical_warnings_present() {
488 if (!has_capability('moodle/site:config', context_system
::instance())) {
492 if (!isset($SESSION->admin_critical_warning
)) {
493 $SESSION->admin_critical_warning
= 0;
494 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR
) {
495 $SESSION->admin_critical_warning
= 1;
499 return $SESSION->admin_critical_warning
;
503 * Detects if float supports at least 10 decimal digits
505 * Detects if float supports at least 10 decimal digits
506 * and also if float-->string conversion works as expected.
508 * @return bool true if problem found
510 function is_float_problem() {
511 $num1 = 2009010200.01;
512 $num2 = 2009010200.02;
514 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
518 * Try to verify that dataroot is not accessible from web.
520 * Try to verify that dataroot is not accessible from web.
521 * It is not 100% correct but might help to reduce number of vulnerable sites.
522 * Protection from httpd.conf and .htaccess is not detected properly.
524 * @uses INSECURE_DATAROOT_WARNING
525 * @uses INSECURE_DATAROOT_ERROR
526 * @param bool $fetchtest try to test public access by fetching file, default false
527 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
529 function is_dataroot_insecure($fetchtest=false) {
532 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot
.'/')); // win32 backslash workaround
534 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot
, 1);
535 $rp = strrev(trim($rp, '/'));
536 $rp = explode('/', $rp);
538 if (strpos($siteroot, '/'.$r.'/') === 0) {
539 $siteroot = substr($siteroot, strlen($r)+
1); // moodle web in subdirectory
541 break; // probably alias root
545 $siteroot = strrev($siteroot);
546 $dataroot = str_replace('\\', '/', $CFG->dataroot
.'/');
548 if (strpos($dataroot, $siteroot) !== 0) {
553 return INSECURE_DATAROOT_WARNING
;
556 // now try all methods to fetch a test file using http protocol
558 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot
.'/'));
559 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot
, $matches);
560 $httpdocroot = $matches[1];
561 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
562 make_upload_directory('diag');
563 $testfile = $CFG->dataroot
.'/diag/public.txt';
564 if (!file_exists($testfile)) {
565 file_put_contents($testfile, 'test file, do not delete');
566 @chmod
($testfile, $CFG->filepermissions
);
568 $teststr = trim(file_get_contents($testfile));
569 if (empty($teststr)) {
571 return INSECURE_DATAROOT_WARNING
;
574 $testurl = $datarooturl.'/diag/public.txt';
575 if (extension_loaded('curl') and
576 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
577 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
578 ($ch = @curl_init
($testurl)) !== false) {
579 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
580 curl_setopt($ch, CURLOPT_HEADER
, false);
581 $data = curl_exec($ch);
582 if (!curl_errno($ch)) {
584 if ($data === $teststr) {
586 return INSECURE_DATAROOT_ERROR
;
592 if ($data = @file_get_contents
($testurl)) {
594 if ($data === $teststr) {
595 return INSECURE_DATAROOT_ERROR
;
599 preg_match('|https?://([^/]+)|i', $testurl, $matches);
600 $sitename = $matches[1];
602 if ($fp = @fsockopen
($sitename, 80, $error)) {
603 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
604 $localurl = $matches[1];
605 $out = "GET $localurl HTTP/1.1\r\n";
606 $out .= "Host: $sitename\r\n";
607 $out .= "Connection: Close\r\n\r\n";
613 $data .= fgets($fp, 1024);
614 } else if (@fgets
($fp, 1024) === "\r\n") {
620 if ($data === $teststr) {
621 return INSECURE_DATAROOT_ERROR
;
625 return INSECURE_DATAROOT_WARNING
;
629 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
631 function enable_cli_maintenance_mode() {
634 if (file_exists("$CFG->dataroot/climaintenance.html")) {
635 unlink("$CFG->dataroot/climaintenance.html");
638 if (isset($CFG->maintenance_message
) and !html_is_blank($CFG->maintenance_message
)) {
639 $data = $CFG->maintenance_message
;
640 $data = bootstrap_renderer
::early_error_content($data, null, null, null);
641 $data = bootstrap_renderer
::plain_page(get_string('sitemaintenance', 'admin'), $data);
643 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
644 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
647 $data = get_string('sitemaintenance', 'admin');
648 $data = bootstrap_renderer
::early_error_content($data, null, null, null);
649 $data = bootstrap_renderer
::plain_page(get_string('sitemaintenancetitle', 'admin',
650 format_string($SITE->fullname
, true, ['context' => context_system
::instance()])), $data);
653 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
654 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions
);
657 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
661 * Interface for anything appearing in the admin tree
663 * The interface that is implemented by anything that appears in the admin tree
664 * block. It forces inheriting classes to define a method for checking user permissions
665 * and methods for finding something in the admin tree.
667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
669 interface part_of_admin_tree
{
672 * Finds a named part_of_admin_tree.
674 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
675 * and not parentable_part_of_admin_tree, then this function should only check if
676 * $this->name matches $name. If it does, it should return a reference to $this,
677 * otherwise, it should return a reference to NULL.
679 * If a class inherits parentable_part_of_admin_tree, this method should be called
680 * recursively on all child objects (assuming, of course, the parent object's name
681 * doesn't match the search criterion).
683 * @param string $name The internal name of the part_of_admin_tree we're searching for.
684 * @return mixed An object reference or a NULL reference.
686 public function locate($name);
689 * Removes named part_of_admin_tree.
691 * @param string $name The internal name of the part_of_admin_tree we want to remove.
692 * @return bool success.
694 public function prune($name);
698 * @param string $query
699 * @return mixed array-object structure of found settings and pages
701 public function search($query);
704 * Verifies current user's access to this part_of_admin_tree.
706 * Used to check if the current user has access to this part of the admin tree or
707 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
708 * then this method is usually just a call to has_capability() in the site context.
710 * If a class inherits parentable_part_of_admin_tree, this method should return the
711 * logical OR of the return of check_access() on all child objects.
713 * @return bool True if the user has access, false if she doesn't.
715 public function check_access();
718 * Mostly useful for removing of some parts of the tree in admin tree block.
720 * @return True is hidden from normal list view
722 public function is_hidden();
725 * Show we display Save button at the page bottom?
728 public function show_save();
733 * Interface implemented by any part_of_admin_tree that has children.
735 * The interface implemented by any part_of_admin_tree that can be a parent
736 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
737 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
738 * include an add method for adding other part_of_admin_tree objects as children.
740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
742 interface parentable_part_of_admin_tree
extends part_of_admin_tree
{
745 * Adds a part_of_admin_tree object to the admin tree.
747 * Used to add a part_of_admin_tree object to this object or a child of this
748 * object. $something should only be added if $destinationname matches
749 * $this->name. If it doesn't, add should be called on child objects that are
750 * also parentable_part_of_admin_tree's.
752 * $something should be appended as the last child in the $destinationname. If the
753 * $beforesibling is specified, $something should be prepended to it. If the given
754 * sibling is not found, $something should be appended to the end of $destinationname
755 * and a developer debugging message should be displayed.
757 * @param string $destinationname The internal name of the new parent for $something.
758 * @param part_of_admin_tree $something The object to be added.
759 * @return bool True on success, false on failure.
761 public function add($destinationname, $something, $beforesibling = null);
767 * The object used to represent folders (a.k.a. categories) in the admin tree block.
769 * Each admin_category object contains a number of part_of_admin_tree objects.
771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
773 class admin_category
implements parentable_part_of_admin_tree
{
775 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
777 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
779 /** @var string The displayed name for this category. Usually obtained through get_string() */
781 /** @var bool Should this category be hidden in admin tree block? */
783 /** @var mixed Either a string or an array or strings */
785 /** @var mixed Either a string or an array or strings */
788 /** @var array fast lookup category cache, all categories of one tree point to one cache */
789 protected $category_cache;
791 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
792 protected $sort = false;
793 /** @var bool If set to true children will be sorted in ascending order. */
794 protected $sortasc = true;
795 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
796 protected $sortsplit = true;
797 /** @var bool $sorted True if the children have been sorted and don't need resorting */
798 protected $sorted = false;
801 * Constructor for an empty admin category
803 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
804 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
805 * @param bool $hidden hide category in admin tree block, defaults to false
807 public function __construct($name, $visiblename, $hidden=false) {
808 $this->children
= array();
810 $this->visiblename
= $visiblename;
811 $this->hidden
= $hidden;
815 * Get the URL to view this page.
819 public function get_settings_page_url(): moodle_url
{
820 return new moodle_url(
821 '/admin/category.php',
823 'category' => $this->name
,
829 * Returns a reference to the part_of_admin_tree object with internal name $name.
831 * @param string $name The internal name of the object we want.
832 * @param bool $findpath initialize path and visiblepath arrays
833 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
836 public function locate($name, $findpath=false) {
837 if (!isset($this->category_cache
[$this->name
])) {
838 // somebody much have purged the cache
839 $this->category_cache
[$this->name
] = $this;
842 if ($this->name
== $name) {
844 $this->visiblepath
[] = $this->visiblename
;
845 $this->path
[] = $this->name
;
850 // quick category lookup
851 if (!$findpath and isset($this->category_cache
[$name])) {
852 return $this->category_cache
[$name];
856 foreach($this->children
as $childid=>$unused) {
857 if ($return = $this->children
[$childid]->locate($name, $findpath)) {
862 if (!is_null($return) and $findpath) {
863 $return->visiblepath
[] = $this->visiblename
;
864 $return->path
[] = $this->name
;
873 * @param string query
874 * @return mixed array-object structure of found settings and pages
876 public function search($query) {
878 foreach ($this->get_children() as $child) {
879 $subsearch = $child->search($query);
880 if (!is_array($subsearch)) {
881 debugging('Incorrect search result from '.$child->name
);
884 $result = array_merge($result, $subsearch);
890 * Removes part_of_admin_tree object with internal name $name.
892 * @param string $name The internal name of the object we want to remove.
893 * @return bool success
895 public function prune($name) {
897 if ($this->name
== $name) {
898 return false; //can not remove itself
901 foreach($this->children
as $precedence => $child) {
902 if ($child->name
== $name) {
903 // clear cache and delete self
904 while($this->category_cache
) {
905 // delete the cache, but keep the original array address
906 array_pop($this->category_cache
);
908 unset($this->children
[$precedence]);
910 } else if ($this->children
[$precedence]->prune($name)) {
918 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
920 * By default the new part of the tree is appended as the last child of the parent. You
921 * can specify a sibling node that the new part should be prepended to. If the given
922 * sibling is not found, the part is appended to the end (as it would be by default) and
923 * a developer debugging message is displayed.
925 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
926 * @param string $destinationame The internal name of the immediate parent that we want for $something.
927 * @param mixed $something A part_of_admin_tree or setting instance to be added.
928 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
929 * @return bool True if successfully added, false if $something can not be added.
931 public function add($parentname, $something, $beforesibling = null) {
934 $parent = $this->locate($parentname);
935 if (is_null($parent)) {
936 debugging('parent does not exist!');
940 if ($something instanceof part_of_admin_tree
) {
941 if (!($parent instanceof parentable_part_of_admin_tree
)) {
942 debugging('error - parts of tree can be inserted only into parentable parts');
945 if ($CFG->debugdeveloper
&& !is_null($this->locate($something->name
))) {
946 // The name of the node is already used, simply warn the developer that this should not happen.
947 // It is intentional to check for the debug level before performing the check.
948 debugging('Duplicate admin page name: ' . $something->name
, DEBUG_DEVELOPER
);
950 if (is_null($beforesibling)) {
951 // Append $something as the parent's last child.
952 $parent->children
[] = $something;
954 if (!is_string($beforesibling) or trim($beforesibling) === '') {
955 throw new coding_exception('Unexpected value of the beforesibling parameter');
957 // Try to find the position of the sibling.
958 $siblingposition = null;
959 foreach ($parent->children
as $childposition => $child) {
960 if ($child->name
=== $beforesibling) {
961 $siblingposition = $childposition;
965 if (is_null($siblingposition)) {
966 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER
);
967 $parent->children
[] = $something;
969 $parent->children
= array_merge(
970 array_slice($parent->children
, 0, $siblingposition),
972 array_slice($parent->children
, $siblingposition)
976 if ($something instanceof admin_category
) {
977 if (isset($this->category_cache
[$something->name
])) {
978 debugging('Duplicate admin category name: '.$something->name
);
980 $this->category_cache
[$something->name
] = $something;
981 $something->category_cache
=& $this->category_cache
;
982 foreach ($something->children
as $child) {
983 // just in case somebody already added subcategories
984 if ($child instanceof admin_category
) {
985 if (isset($this->category_cache
[$child->name
])) {
986 debugging('Duplicate admin category name: '.$child->name
);
988 $this->category_cache
[$child->name
] = $child;
989 $child->category_cache
=& $this->category_cache
;
998 debugging('error - can not add this element');
1005 * Checks if the user has access to anything in this category.
1007 * @return bool True if the user has access to at least one child in this category, false otherwise.
1009 public function check_access() {
1010 foreach ($this->children
as $child) {
1011 if ($child->check_access()) {
1019 * Is this category hidden in admin tree block?
1021 * @return bool True if hidden
1023 public function is_hidden() {
1024 return $this->hidden
;
1028 * Show we display Save button at the page bottom?
1031 public function show_save() {
1032 foreach ($this->children
as $child) {
1033 if ($child->show_save()) {
1041 * Sets sorting on this category.
1043 * Please note this function doesn't actually do the sorting.
1044 * It can be called anytime.
1045 * Sorting occurs when the user calls get_children.
1046 * Code using the children array directly won't see the sorted results.
1048 * @param bool $sort If set to true children will be sorted, if false they won't be.
1049 * @param bool $asc If true sorting will be ascending, otherwise descending.
1050 * @param bool $split If true we sort pages and sub categories separately.
1052 public function set_sorting($sort, $asc = true, $split = true) {
1053 $this->sort
= (bool)$sort;
1054 $this->sortasc
= (bool)$asc;
1055 $this->sortsplit
= (bool)$split;
1059 * Returns the children associated with this category.
1061 * @return part_of_admin_tree[]
1063 public function get_children() {
1064 // If we should sort and it hasn't already been sorted.
1065 if ($this->sort
&& !$this->sorted
) {
1066 if ($this->sortsplit
) {
1067 $categories = array();
1069 foreach ($this->children
as $child) {
1070 if ($child instanceof admin_category
) {
1071 $categories[] = $child;
1076 core_collator
::asort_objects_by_property($categories, 'visiblename');
1077 core_collator
::asort_objects_by_property($pages, 'visiblename');
1078 if (!$this->sortasc
) {
1079 $categories = array_reverse($categories);
1080 $pages = array_reverse($pages);
1082 $this->children
= array_merge($pages, $categories);
1084 core_collator
::asort_objects_by_property($this->children
, 'visiblename');
1085 if (!$this->sortasc
) {
1086 $this->children
= array_reverse($this->children
);
1089 $this->sorted
= true;
1091 return $this->children
;
1095 * Magically gets a property from this object.
1098 * @return part_of_admin_tree[]
1099 * @throws coding_exception
1101 public function __get($property) {
1102 if ($property === 'children') {
1103 return $this->get_children();
1105 throw new coding_exception('Invalid property requested.');
1109 * Magically sets a property against this object.
1111 * @param string $property
1112 * @param mixed $value
1113 * @throws coding_exception
1115 public function __set($property, $value) {
1116 if ($property === 'children') {
1117 $this->sorted
= false;
1118 $this->children
= $value;
1120 throw new coding_exception('Invalid property requested.');
1125 * Checks if an inaccessible property is set.
1127 * @param string $property
1129 * @throws coding_exception
1131 public function __isset($property) {
1132 if ($property === 'children') {
1133 return isset($this->children
);
1135 throw new coding_exception('Invalid property requested.');
1141 * Root of admin settings tree, does not have any parent.
1143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1145 class admin_root
extends admin_category
{
1146 /** @var array List of errors */
1148 /** @var string search query */
1150 /** @var bool full tree flag - true means all settings required, false only pages required */
1152 /** @var bool flag indicating loaded tree */
1154 /** @var mixed site custom defaults overriding defaults in settings files*/
1155 public $custom_defaults;
1158 * @param bool $fulltree true means all settings required,
1159 * false only pages required
1161 public function __construct($fulltree) {
1164 parent
::__construct('root', get_string('administration'), false);
1165 $this->errors
= array();
1167 $this->fulltree
= $fulltree;
1168 $this->loaded
= false;
1170 $this->category_cache
= array();
1172 // load custom defaults if found
1173 $this->custom_defaults
= null;
1174 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1175 if (is_readable($defaultsfile)) {
1176 $defaults = array();
1177 include($defaultsfile);
1178 if (is_array($defaults) and count($defaults)) {
1179 $this->custom_defaults
= $defaults;
1185 * Empties children array, and sets loaded to false
1187 * @param bool $requirefulltree
1189 public function purge_children($requirefulltree) {
1190 $this->children
= array();
1191 $this->fulltree
= ($requirefulltree ||
$this->fulltree
);
1192 $this->loaded
= false;
1193 //break circular dependencies - this helps PHP 5.2
1194 while($this->category_cache
) {
1195 array_pop($this->category_cache
);
1197 $this->category_cache
= array();
1203 * Links external PHP pages into the admin tree.
1205 * See detailed usage example at the top of this document (adminlib.php)
1207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1209 class admin_externalpage
implements part_of_admin_tree
{
1211 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1214 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1215 public $visiblename;
1217 /** @var string The external URL that we should link to when someone requests this external page. */
1220 /** @var array The role capability/permission a user must have to access this external page. */
1221 public $req_capability;
1223 /** @var object The context in which capability/permission should be checked, default is site context. */
1226 /** @var bool hidden in admin tree block. */
1229 /** @var mixed either string or array of string */
1232 /** @var array list of visible names of page parents */
1233 public $visiblepath;
1236 * Constructor for adding an external page into the admin tree.
1238 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1239 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1240 * @param string $url The external URL that we should link to when someone requests this external page.
1241 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1242 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1243 * @param stdClass $context The context the page relates to. Not sure what happens
1244 * if you specify something other than system or front page. Defaults to system.
1246 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1247 $this->name
= $name;
1248 $this->visiblename
= $visiblename;
1250 if (is_array($req_capability)) {
1251 $this->req_capability
= $req_capability;
1253 $this->req_capability
= array($req_capability);
1255 $this->hidden
= $hidden;
1256 $this->context
= $context;
1260 * Returns a reference to the part_of_admin_tree object with internal name $name.
1262 * @param string $name The internal name of the object we want.
1263 * @param bool $findpath defaults to false
1264 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1266 public function locate($name, $findpath=false) {
1267 if ($this->name
== $name) {
1269 $this->visiblepath
= array($this->visiblename
);
1270 $this->path
= array($this->name
);
1280 * This function always returns false, required function by interface
1282 * @param string $name
1285 public function prune($name) {
1290 * Search using query
1292 * @param string $query
1293 * @return mixed array-object structure of found settings and pages
1295 public function search($query) {
1297 if (strpos(strtolower($this->name
), $query) !== false) {
1299 } else if (strpos(core_text
::strtolower($this->visiblename
), $query) !== false) {
1303 $result = new stdClass();
1304 $result->page
= $this;
1305 $result->settings
= array();
1306 return array($this->name
=> $result);
1313 * Determines if the current user has access to this external page based on $this->req_capability.
1315 * @return bool True if user has access, false otherwise.
1317 public function check_access() {
1319 $context = empty($this->context
) ? context_system
::instance() : $this->context
;
1320 foreach($this->req_capability
as $cap) {
1321 if (has_capability($cap, $context)) {
1329 * Is this external page hidden in admin tree block?
1331 * @return bool True if hidden
1333 public function is_hidden() {
1334 return $this->hidden
;
1338 * Show we display Save button at the page bottom?
1341 public function show_save() {
1347 * Used to store details of the dependency between two settings elements.
1349 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1350 * @copyright 2017 Davo Smith, Synergy Learning
1352 class admin_settingdependency
{
1353 /** @var string the name of the setting to be shown/hidden */
1354 public $settingname;
1355 /** @var string the setting this is dependent on */
1356 public $dependenton;
1357 /** @var string the condition to show/hide the element */
1359 /** @var string the value to compare against */
1362 /** @var string[] list of valid conditions */
1363 private static $validconditions = ['checked', 'notchecked', 'noitemselected', 'eq', 'neq', 'in'];
1366 * admin_settingdependency constructor.
1367 * @param string $settingname
1368 * @param string $dependenton
1369 * @param string $condition
1370 * @param string $value
1371 * @throws \coding_exception
1373 public function __construct($settingname, $dependenton, $condition, $value) {
1374 $this->settingname
= $this->parse_name($settingname);
1375 $this->dependenton
= $this->parse_name($dependenton);
1376 $this->condition
= $condition;
1377 $this->value
= $value;
1379 if (!in_array($this->condition
, self
::$validconditions)) {
1380 throw new coding_exception("Invalid condition '$condition'");
1385 * Convert the setting name into the form field name.
1386 * @param string $name
1389 private function parse_name($name) {
1390 $bits = explode('/', $name);
1391 $name = array_pop($bits);
1394 $plugin = array_pop($bits);
1395 if ($plugin === 'moodle') {
1399 return 's_'.$plugin.'_'.$name;
1403 * Gather together all the dependencies in a format suitable for initialising javascript
1404 * @param admin_settingdependency[] $dependencies
1407 public static function prepare_for_javascript($dependencies) {
1409 foreach ($dependencies as $d) {
1410 if (!isset($result[$d->dependenton
])) {
1411 $result[$d->dependenton
] = [];
1413 if (!isset($result[$d->dependenton
][$d->condition
])) {
1414 $result[$d->dependenton
][$d->condition
] = [];
1416 if (!isset($result[$d->dependenton
][$d->condition
][$d->value
])) {
1417 $result[$d->dependenton
][$d->condition
][$d->value
] = [];
1419 $result[$d->dependenton
][$d->condition
][$d->value
][] = $d->settingname
;
1426 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1430 class admin_settingpage
implements part_of_admin_tree
{
1432 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1435 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1436 public $visiblename;
1438 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1441 /** @var admin_settingdependency[] list of settings to hide when certain conditions are met */
1442 protected $dependencies = [];
1444 /** @var array The role capability/permission a user must have to access this external page. */
1445 public $req_capability;
1447 /** @var object The context in which capability/permission should be checked, default is site context. */
1450 /** @var bool hidden in admin tree block. */
1453 /** @var mixed string of paths or array of strings of paths */
1456 /** @var array list of visible names of page parents */
1457 public $visiblepath;
1460 * see admin_settingpage for details of this function
1462 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1463 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1464 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1465 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1466 * @param stdClass $context The context the page relates to. Not sure what happens
1467 * if you specify something other than system or front page. Defaults to system.
1469 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1470 $this->settings
= new stdClass();
1471 $this->name
= $name;
1472 $this->visiblename
= $visiblename;
1473 if (is_array($req_capability)) {
1474 $this->req_capability
= $req_capability;
1476 $this->req_capability
= array($req_capability);
1478 $this->hidden
= $hidden;
1479 $this->context
= $context;
1483 * see admin_category
1485 * @param string $name
1486 * @param bool $findpath
1487 * @return mixed Object (this) if name == this->name, else returns null
1489 public function locate($name, $findpath=false) {
1490 if ($this->name
== $name) {
1492 $this->visiblepath
= array($this->visiblename
);
1493 $this->path
= array($this->name
);
1503 * Search string in settings page.
1505 * @param string $query
1508 public function search($query) {
1511 foreach ($this->settings
as $setting) {
1512 if ($setting->is_related($query)) {
1513 $found[] = $setting;
1518 $result = new stdClass();
1519 $result->page
= $this;
1520 $result->settings
= $found;
1521 return array($this->name
=> $result);
1525 if (strpos(strtolower($this->name
), $query) !== false) {
1527 } else if (strpos(core_text
::strtolower($this->visiblename
), $query) !== false) {
1531 $result = new stdClass();
1532 $result->page
= $this;
1533 $result->settings
= array();
1534 return array($this->name
=> $result);
1541 * This function always returns false, required by interface
1543 * @param string $name
1544 * @return bool Always false
1546 public function prune($name) {
1551 * adds an admin_setting to this admin_settingpage
1553 * 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
1554 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1556 * @param object $setting is the admin_setting object you want to add
1557 * @return bool true if successful, false if not
1559 public function add($setting) {
1560 if (!($setting instanceof admin_setting
)) {
1561 debugging('error - not a setting instance');
1565 $name = $setting->name
;
1566 if ($setting->plugin
) {
1567 $name = $setting->plugin
. $name;
1569 $this->settings
->{$name} = $setting;
1574 * Hide the named setting if the specified condition is matched.
1576 * @param string $settingname
1577 * @param string $dependenton
1578 * @param string $condition
1579 * @param string $value
1581 public function hide_if($settingname, $dependenton, $condition = 'notchecked', $value = '1') {
1582 $this->dependencies
[] = new admin_settingdependency($settingname, $dependenton, $condition, $value);
1584 // Reformat the dependency name to the plugin | name format used in the display.
1585 $dependenton = str_replace('/', ' | ', $dependenton);
1587 // Let the setting know, so it can be displayed underneath.
1588 $findname = str_replace('/', '', $settingname);
1589 foreach ($this->settings
as $name => $setting) {
1590 if ($name === $findname) {
1591 $setting->add_dependent_on($dependenton);
1597 * see admin_externalpage
1599 * @return bool Returns true for yes false for no
1601 public function check_access() {
1603 $context = empty($this->context
) ? context_system
::instance() : $this->context
;
1604 foreach($this->req_capability
as $cap) {
1605 if (has_capability($cap, $context)) {
1613 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1614 * @return string Returns an XHTML string
1616 public function output_html() {
1617 $adminroot = admin_get_root();
1618 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1619 foreach($this->settings
as $setting) {
1620 $fullname = $setting->get_full_name();
1621 if (array_key_exists($fullname, $adminroot->errors
)) {
1622 $data = $adminroot->errors
[$fullname]->data
;
1624 $data = $setting->get_setting();
1625 // do not use defaults if settings not available - upgrade settings handles the defaults!
1627 $return .= $setting->output_html($data);
1629 $return .= '</fieldset>';
1634 * Is this settings page hidden in admin tree block?
1636 * @return bool True if hidden
1638 public function is_hidden() {
1639 return $this->hidden
;
1643 * Show we display Save button at the page bottom?
1646 public function show_save() {
1647 foreach($this->settings
as $setting) {
1648 if (empty($setting->nosave
)) {
1656 * Should any of the settings on this page be shown / hidden based on conditions?
1659 public function has_dependencies() {
1660 return (bool)$this->dependencies
;
1664 * Format the setting show/hide conditions ready to initialise the page javascript
1667 public function get_dependencies_for_javascript() {
1668 if (!$this->has_dependencies()) {
1671 return admin_settingdependency
::prepare_for_javascript($this->dependencies
);
1677 * Admin settings class. Only exists on setting pages.
1678 * Read & write happens at this level; no authentication.
1680 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1682 abstract class admin_setting
{
1683 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1685 /** @var string localised name */
1686 public $visiblename;
1687 /** @var string localised long description in Markdown format */
1688 public $description;
1689 /** @var mixed Can be string or array of string */
1690 public $defaultsetting;
1692 public $updatedcallback;
1693 /** @var mixed can be String or Null. Null means main config table */
1694 public $plugin; // null means main config table
1695 /** @var bool true indicates this setting does not actually save anything, just information */
1696 public $nosave = false;
1697 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1698 public $affectsmodinfo = false;
1699 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1700 private $flags = array();
1701 /** @var bool Whether this field must be forced LTR. */
1702 private $forceltr = null;
1703 /** @var array list of other settings that may cause this setting to be hidden */
1704 private $dependenton = [];
1705 /** @var bool Whether this setting uses a custom form control */
1706 protected $customcontrol = false;
1710 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1711 * or 'myplugin/mysetting' for ones in config_plugins.
1712 * @param string $visiblename localised name
1713 * @param string $description localised long description
1714 * @param mixed $defaultsetting string or array depending on implementation
1716 public function __construct($name, $visiblename, $description, $defaultsetting) {
1717 $this->parse_setting_name($name);
1718 $this->visiblename
= $visiblename;
1719 $this->description
= $description;
1720 $this->defaultsetting
= $defaultsetting;
1724 * Generic function to add a flag to 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
1728 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1729 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1731 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1732 if (empty($this->flags
[$shortname])) {
1733 $this->flags
[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1735 $this->flags
[$shortname]->set_options($enabled, $default);
1740 * Set the enabled options flag on this admin setting.
1742 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1743 * @param bool $default - The default for the flag
1745 public function set_enabled_flag_options($enabled, $default) {
1746 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1750 * Set the advanced options flag on this admin setting.
1752 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1753 * @param bool $default - The default for the flag
1755 public function set_advanced_flag_options($enabled, $default) {
1756 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1761 * Set the locked options flag on this admin setting.
1763 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1764 * @param bool $default - The default for the flag
1766 public function set_locked_flag_options($enabled, $default) {
1767 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1771 * Set the required options flag on this admin setting.
1773 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED.
1774 * @param bool $default - The default for the flag.
1776 public function set_required_flag_options($enabled, $default) {
1777 $this->set_flag_options($enabled, $default, 'required', new lang_string('required', 'core_admin'));
1781 * Is this option forced in config.php?
1785 public function is_readonly(): bool {
1788 if (empty($this->plugin
)) {
1789 if (array_key_exists($this->name
, $CFG->config_php_settings
)) {
1793 if (array_key_exists($this->plugin
, $CFG->forced_plugin_settings
)
1794 and array_key_exists($this->name
, $CFG->forced_plugin_settings
[$this->plugin
])) {
1802 * Get the currently saved value for a setting flag
1804 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1807 public function get_setting_flag_value(admin_setting_flag
$flag) {
1808 $value = $this->config_read($this->name
. '_' . $flag->get_shortname());
1809 if (!isset($value)) {
1810 $value = $flag->get_default();
1813 return !empty($value);
1817 * Get the list of defaults for the flags on this setting.
1819 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1821 public function get_setting_flag_defaults(& $defaults) {
1822 foreach ($this->flags
as $flag) {
1823 if ($flag->is_enabled() && $flag->get_default()) {
1824 $defaults[] = $flag->get_displayname();
1830 * Output the input fields for the advanced and locked flags on this setting.
1832 * @param bool $adv - The current value of the advanced flag.
1833 * @param bool $locked - The current value of the locked flag.
1834 * @return string $output - The html for the flags.
1836 public function output_setting_flags() {
1839 foreach ($this->flags
as $flag) {
1840 if ($flag->is_enabled()) {
1841 $output .= $flag->output_setting_flag($this);
1845 if (!empty($output)) {
1846 return html_writer
::tag('span', $output, array('class' => 'adminsettingsflags'));
1852 * Write the values of the flags for this admin setting.
1854 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1855 * @return bool - true if successful.
1857 public function write_setting_flags($data) {
1859 foreach ($this->flags
as $flag) {
1860 $result = $result && $flag->write_setting_flag($this, $data);
1866 * Set up $this->name and potentially $this->plugin
1868 * Set up $this->name and possibly $this->plugin based on whether $name looks
1869 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1870 * on the names, that is, output a developer debug warning if the name
1871 * contains anything other than [a-zA-Z0-9_]+.
1873 * @param string $name the setting name passed in to the constructor.
1875 private function parse_setting_name($name) {
1876 $bits = explode('/', $name);
1877 if (count($bits) > 2) {
1878 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1880 $this->name
= array_pop($bits);
1881 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name
)) {
1882 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1884 if (!empty($bits)) {
1885 $this->plugin
= array_pop($bits);
1886 if ($this->plugin
=== 'moodle') {
1887 $this->plugin
= null;
1888 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin
)) {
1889 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1895 * Returns the fullname prefixed by the plugin
1898 public function get_full_name() {
1899 return 's_'.$this->plugin
.'_'.$this->name
;
1903 * Returns the ID string based on plugin and name
1906 public function get_id() {
1907 return 'id_s_'.$this->plugin
.'_'.$this->name
;
1911 * @param bool $affectsmodinfo If true, changes to this setting will
1912 * cause the course cache to be rebuilt
1914 public function set_affects_modinfo($affectsmodinfo) {
1915 $this->affectsmodinfo
= $affectsmodinfo;
1919 * Returns the config if possible
1921 * @return mixed returns config if successful else null
1923 public function config_read($name) {
1925 if (!empty($this->plugin
)) {
1926 $value = get_config($this->plugin
, $name);
1927 return $value === false ?
NULL : $value;
1930 if (isset($CFG->$name)) {
1939 * Used to set a config pair and log change
1941 * @param string $name
1942 * @param mixed $value Gets converted to string if not null
1943 * @return bool Write setting to config table
1945 public function config_write($name, $value) {
1946 global $DB, $USER, $CFG;
1948 if ($this->nosave
) {
1952 // make sure it is a real change
1953 $oldvalue = get_config($this->plugin
, $name);
1954 $oldvalue = ($oldvalue === false) ?
null : $oldvalue; // normalise
1955 $value = is_null($value) ?
null : (string)$value;
1957 if ($oldvalue === $value) {
1962 set_config($name, $value, $this->plugin
);
1964 // Some admin settings affect course modinfo
1965 if ($this->affectsmodinfo
) {
1966 // Clear course cache for all courses
1967 rebuild_course_cache(0, true);
1970 $this->add_to_config_log($name, $oldvalue, $value);
1972 return true; // BC only
1976 * Log config changes if necessary.
1977 * @param string $name
1978 * @param string $oldvalue
1979 * @param string $value
1981 protected function add_to_config_log($name, $oldvalue, $value) {
1982 add_to_config_log($name, $oldvalue, $value, $this->plugin
);
1986 * Returns current value of this setting
1987 * @return mixed array or string depending on instance, NULL means not set yet
1989 public abstract function get_setting();
1992 * Returns default setting if exists
1993 * @return mixed array or string depending on instance; NULL means no default, user must supply
1995 public function get_defaultsetting() {
1996 $adminroot = admin_get_root(false, false);
1997 if (!empty($adminroot->custom_defaults
)) {
1998 $plugin = is_null($this->plugin
) ?
'moodle' : $this->plugin
;
1999 if (isset($adminroot->custom_defaults
[$plugin])) {
2000 if (array_key_exists($this->name
, $adminroot->custom_defaults
[$plugin])) { // null is valid value here ;-)
2001 return $adminroot->custom_defaults
[$plugin][$this->name
];
2005 return $this->defaultsetting
;
2011 * @param mixed $data string or array, must not be NULL
2012 * @return string empty string if ok, string error message otherwise
2014 public abstract function write_setting($data);
2017 * Return part of form with setting
2018 * This function should always be overwritten
2020 * @param mixed $data array or string depending on setting
2021 * @param string $query
2024 public function output_html($data, $query='') {
2025 // should be overridden
2030 * Function called if setting updated - cleanup, cache reset, etc.
2031 * @param string $functionname Sets the function name
2034 public function set_updatedcallback($functionname) {
2035 $this->updatedcallback
= $functionname;
2039 * Execute postupdatecallback if necessary.
2040 * @param mixed $original original value before write_setting()
2041 * @return bool true if changed, false if not.
2043 public function post_write_settings($original) {
2044 // Comparison must work for arrays too.
2045 if (serialize($original) === serialize($this->get_setting())) {
2049 $callbackfunction = $this->updatedcallback
;
2050 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
2051 $callbackfunction($this->get_full_name());
2057 * Is setting related to query text - used when searching
2058 * @param string $query
2061 public function is_related($query) {
2062 if (strpos(strtolower($this->name
), $query) !== false) {
2065 if (strpos(core_text
::strtolower($this->visiblename
), $query) !== false) {
2068 if (strpos(core_text
::strtolower($this->description
), $query) !== false) {
2071 $current = $this->get_setting();
2072 if (!is_null($current)) {
2073 if (is_string($current)) {
2074 if (strpos(core_text
::strtolower($current), $query) !== false) {
2079 $default = $this->get_defaultsetting();
2080 if (!is_null($default)) {
2081 if (is_string($default)) {
2082 if (strpos(core_text
::strtolower($default), $query) !== false) {
2091 * Get whether this should be displayed in LTR mode.
2095 public function get_force_ltr() {
2096 return $this->forceltr
;
2100 * Set whether to force LTR or not.
2102 * @param bool $value True when forced, false when not force, null when unknown.
2104 public function set_force_ltr($value) {
2105 $this->forceltr
= $value;
2109 * Add a setting to the list of those that could cause this one to be hidden
2110 * @param string $dependenton
2112 public function add_dependent_on($dependenton) {
2113 $this->dependenton
[] = $dependenton;
2117 * Get a list of the settings that could cause this one to be hidden.
2120 public function get_dependent_on() {
2121 return $this->dependenton
;
2125 * Whether this setting uses a custom form control.
2126 * This function is especially useful to decide if we should render a label element for this setting or not.
2130 public function has_custom_form_control(): bool {
2131 return $this->customcontrol
;
2136 * An additional option that can be applied to an admin setting.
2137 * The currently supported options are 'ADVANCED', 'LOCKED' and 'REQUIRED'.
2139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2141 class admin_setting_flag
{
2142 /** @var bool Flag to indicate if this option can be toggled for this setting */
2143 private $enabled = false;
2144 /** @var bool Flag to indicate if this option defaults to true or false */
2145 private $default = false;
2146 /** @var string Short string used to create setting name - e.g. 'adv' */
2147 private $shortname = '';
2148 /** @var string String used as the label for this flag */
2149 private $displayname = '';
2150 /** @const Checkbox for this flag is displayed in admin page */
2151 const ENABLED
= true;
2152 /** @const Checkbox for this flag is not displayed in admin page */
2153 const DISABLED
= false;
2158 * @param bool $enabled Can this option can be toggled.
2159 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2160 * @param bool $default The default checked state for this setting option.
2161 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
2162 * @param string $displayname The displayname of this flag. Used as a label for the flag.
2164 public function __construct($enabled, $default, $shortname, $displayname) {
2165 $this->shortname
= $shortname;
2166 $this->displayname
= $displayname;
2167 $this->set_options($enabled, $default);
2171 * Update the values of this setting options class
2173 * @param bool $enabled Can this option can be toggled.
2174 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
2175 * @param bool $default The default checked state for this setting option.
2177 public function set_options($enabled, $default) {
2178 $this->enabled
= $enabled;
2179 $this->default = $default;
2183 * Should this option appear in the interface and be toggleable?
2185 * @return bool Is it enabled?
2187 public function is_enabled() {
2188 return $this->enabled
;
2192 * Should this option be checked by default?
2194 * @return bool Is it on by default?
2196 public function get_default() {
2197 return $this->default;
2201 * Return the short name for this flag. e.g. 'adv' or 'locked'
2205 public function get_shortname() {
2206 return $this->shortname
;
2210 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2214 public function get_displayname() {
2215 return $this->displayname
;
2219 * Save the submitted data for this flag - or set it to the default if $data is null.
2221 * @param admin_setting $setting - The admin setting for this flag
2222 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2225 public function write_setting_flag(admin_setting
$setting, $data) {
2227 if ($this->is_enabled()) {
2228 if (!isset($data)) {
2229 $value = $this->get_default();
2231 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2233 $result = $setting->config_write($setting->name
. '_' . $this->get_shortname(), $value);
2241 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2243 * @param admin_setting $setting - The admin setting for this flag
2244 * @return string - The html for the checkbox.
2246 public function output_setting_flag(admin_setting
$setting) {
2249 $value = $setting->get_setting_flag_value($this);
2251 $context = new stdClass();
2252 $context->id
= $setting->get_id() . '_' . $this->get_shortname();
2253 $context->name
= $setting->get_full_name() . '_' . $this->get_shortname();
2254 $context->value
= 1;
2255 $context->checked
= $value ?
true : false;
2256 $context->label
= $this->get_displayname();
2258 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2264 * No setting - just heading and text.
2266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2268 class admin_setting_heading
extends admin_setting
{
2271 * not a setting, just text
2272 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2273 * @param string $heading heading
2274 * @param string $information text in box
2276 public function __construct($name, $heading, $information) {
2277 $this->nosave
= true;
2278 parent
::__construct($name, $heading, $information, '');
2282 * Always returns true
2283 * @return bool Always returns true
2285 public function get_setting() {
2290 * Always returns true
2291 * @return bool Always returns true
2293 public function get_defaultsetting() {
2298 * Never write settings
2299 * @return string Always returns an empty string
2301 public function write_setting($data) {
2302 // do not write any setting
2307 * Returns an HTML string
2308 * @return string Returns an HTML string
2310 public function output_html($data, $query='') {
2312 $context = new stdClass();
2313 $context->title
= $this->visiblename
;
2314 $context->description
= $this->description
;
2315 $context->descriptionformatted
= highlight($query, markdown_to_html($this->description
));
2316 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2321 * No setting - just name and description in same row.
2323 * @copyright 2018 onwards Amaia Anabitarte
2324 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2326 class admin_setting_description
extends admin_setting
{
2329 * Not a setting, just text
2331 * @param string $name
2332 * @param string $visiblename
2333 * @param string $description
2335 public function __construct($name, $visiblename, $description) {
2336 $this->nosave
= true;
2337 parent
::__construct($name, $visiblename, $description, '');
2341 * Always returns true
2343 * @return bool Always returns true
2345 public function get_setting() {
2350 * Always returns true
2352 * @return bool Always returns true
2354 public function get_defaultsetting() {
2359 * Never write settings
2361 * @param mixed $data Gets converted to str for comparison against yes value
2362 * @return string Always returns an empty string
2364 public function write_setting($data) {
2365 // Do not write any setting.
2370 * Returns an HTML string
2372 * @param string $data
2373 * @param string $query
2374 * @return string Returns an HTML string
2376 public function output_html($data, $query='') {
2379 $context = new stdClass();
2380 $context->title
= $this->visiblename
;
2381 $context->description
= $this->description
;
2383 return $OUTPUT->render_from_template('core_admin/setting_description', $context);
2390 * The most flexible setting, the user enters text.
2392 * This type of field should be used for config settings which are using
2393 * English words and are not localised (passwords, database name, list of values, ...).
2395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2397 class admin_setting_configtext
extends admin_setting
{
2399 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2401 /** @var int default field size */
2405 * Config text constructor
2407 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2408 * @param string $visiblename localised
2409 * @param string $description long localised info
2410 * @param string $defaultsetting
2411 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2412 * @param int $size default field size
2414 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW
, $size=null) {
2415 $this->paramtype
= $paramtype;
2416 if (!is_null($size)) {
2417 $this->size
= $size;
2419 $this->size
= ($paramtype === PARAM_INT
) ?
5 : 30;
2421 parent
::__construct($name, $visiblename, $description, $defaultsetting);
2425 * Get whether this should be displayed in LTR mode.
2427 * Try to guess from the PARAM type unless specifically set.
2429 public function get_force_ltr() {
2430 $forceltr = parent
::get_force_ltr();
2431 if ($forceltr === null) {
2432 return !is_rtl_compatible($this->paramtype
);
2438 * Return the setting
2440 * @return mixed returns config if successful else null
2442 public function get_setting() {
2443 return $this->config_read($this->name
);
2446 public function write_setting($data) {
2447 if ($this->paramtype
=== PARAM_INT
and $data === '') {
2448 // do not complain if '' used instead of 0
2451 // $data is a string
2452 $validated = $this->validate($data);
2453 if ($validated !== true) {
2456 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
2460 * Validate data before storage
2461 * @param string data
2462 * @return mixed true if ok string if error found
2464 public function validate($data) {
2465 // allow paramtype to be a custom regex if it is the form of /pattern/
2466 if (preg_match('#^/.*/$#', $this->paramtype
)) {
2467 if (preg_match($this->paramtype
, $data)) {
2470 return get_string('validateerror', 'admin');
2473 } else if ($this->paramtype
=== PARAM_RAW
) {
2477 $cleaned = clean_param($data, $this->paramtype
);
2478 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2481 return get_string('validateerror', 'admin');
2487 * Return an XHTML string for the setting
2488 * @return string Returns an XHTML string
2490 public function output_html($data, $query='') {
2493 $default = $this->get_defaultsetting();
2494 $context = (object) [
2495 'size' => $this->size
,
2496 'id' => $this->get_id(),
2497 'name' => $this->get_full_name(),
2499 'forceltr' => $this->get_force_ltr(),
2500 'readonly' => $this->is_readonly(),
2502 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2504 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
2509 * Text input with a maximum length constraint.
2511 * @copyright 2015 onwards Ankit Agarwal
2512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2514 class admin_setting_configtext_with_maxlength
extends admin_setting_configtext
{
2516 /** @var int maximum number of chars allowed. */
2517 protected $maxlength;
2520 * Config text constructor
2522 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2523 * or 'myplugin/mysetting' for ones in config_plugins.
2524 * @param string $visiblename localised
2525 * @param string $description long localised info
2526 * @param string $defaultsetting
2527 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2528 * @param int $size default field size
2529 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2531 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW
,
2532 $size=null, $maxlength = 0) {
2533 $this->maxlength
= $maxlength;
2534 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2538 * Validate data before storage
2540 * @param string $data data
2541 * @return mixed true if ok string if error found
2543 public function validate($data) {
2544 $parentvalidation = parent
::validate($data);
2545 if ($parentvalidation === true) {
2546 if ($this->maxlength
> 0) {
2547 // Max length check.
2548 $length = core_text
::strlen($data);
2549 if ($length > $this->maxlength
) {
2550 return get_string('maximumchars', 'moodle', $this->maxlength
);
2554 return true; // No max length check needed.
2557 return $parentvalidation;
2563 * General text area without html editor.
2565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2567 class admin_setting_configtextarea
extends admin_setting_configtext
{
2572 * @param string $name
2573 * @param string $visiblename
2574 * @param string $description
2575 * @param mixed $defaultsetting string or array
2576 * @param mixed $paramtype
2577 * @param string $cols The number of columns to make the editor
2578 * @param string $rows The number of rows to make the editor
2580 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW
, $cols='60', $rows='8') {
2581 $this->rows
= $rows;
2582 $this->cols
= $cols;
2583 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2587 * Returns an XHTML string for the editor
2589 * @param string $data
2590 * @param string $query
2591 * @return string XHTML string for the editor
2593 public function output_html($data, $query='') {
2596 $default = $this->get_defaultsetting();
2597 $defaultinfo = $default;
2598 if (!is_null($default) and $default !== '') {
2599 $defaultinfo = "\n".$default;
2602 $context = (object) [
2603 'cols' => $this->cols
,
2604 'rows' => $this->rows
,
2605 'id' => $this->get_id(),
2606 'name' => $this->get_full_name(),
2608 'forceltr' => $this->get_force_ltr(),
2609 'readonly' => $this->is_readonly(),
2611 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2613 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $defaultinfo, $query);
2618 * General text area with html editor.
2620 class admin_setting_confightmleditor
extends admin_setting_configtextarea
{
2623 * @param string $name
2624 * @param string $visiblename
2625 * @param string $description
2626 * @param mixed $defaultsetting string or array
2627 * @param mixed $paramtype
2629 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW
, $cols='60', $rows='8') {
2630 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2631 $this->set_force_ltr(false);
2632 editors_head_setup();
2636 * Returns an XHTML string for the editor
2638 * @param string $data
2639 * @param string $query
2640 * @return string XHTML string for the editor
2642 public function output_html($data, $query='') {
2643 $editor = editors_get_preferred_editor(FORMAT_HTML
);
2644 $editor->set_text($data);
2645 $editor->use_editor($this->get_id(), array('noclean'=>true));
2646 return parent
::output_html($data, $query);
2650 * Checks if data has empty html.
2652 * @param string $data
2653 * @return string Empty when no errors.
2655 public function write_setting($data) {
2656 if (trim(html_to_text($data)) === '') {
2659 return parent
::write_setting($data);
2665 * Password field, allows unmasking of password
2667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2669 class admin_setting_configpasswordunmask
extends admin_setting_configtext
{
2673 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2674 * @param string $visiblename localised
2675 * @param string $description long localised info
2676 * @param string $defaultsetting default password
2678 public function __construct($name, $visiblename, $description, $defaultsetting) {
2679 parent
::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW
, 30);
2683 * Log config changes if necessary.
2684 * @param string $name
2685 * @param string $oldvalue
2686 * @param string $value
2688 protected function add_to_config_log($name, $oldvalue, $value) {
2689 if ($value !== '') {
2690 $value = '********';
2692 if ($oldvalue !== '' and $oldvalue !== null) {
2693 $oldvalue = '********';
2695 parent
::add_to_config_log($name, $oldvalue, $value);
2699 * Returns HTML for the field.
2701 * @param string $data Value for the field
2702 * @param string $query Passed as final argument for format_admin_setting
2703 * @return string Rendered HTML
2705 public function output_html($data, $query='') {
2708 $context = (object) [
2709 'id' => $this->get_id(),
2710 'name' => $this->get_full_name(),
2711 'size' => $this->size
,
2712 'value' => $this->is_readonly() ?
null : $data,
2713 'forceltr' => $this->get_force_ltr(),
2714 'readonly' => $this->is_readonly(),
2716 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2717 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', null, $query);
2722 * Password field, allows unmasking of password, with an advanced checkbox that controls an additional $name.'_adv' setting.
2724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2725 * @copyright 2018 Paul Holden (pholden@greenhead.ac.uk)
2727 class admin_setting_configpasswordunmask_with_advanced
extends admin_setting_configpasswordunmask
{
2732 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2733 * @param string $visiblename localised
2734 * @param string $description long localised info
2735 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
2737 public function __construct($name, $visiblename, $description, $defaultsetting) {
2738 parent
::__construct($name, $visiblename, $description, $defaultsetting['value']);
2739 $this->set_advanced_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['adv']));
2744 * Admin setting class for encrypted values using secure encryption.
2746 * @copyright 2019 The Open University
2747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2749 class admin_setting_encryptedpassword
extends admin_setting
{
2752 * Constructor. Same as parent except that the default value is always an empty string.
2754 * @param string $name Internal name used in config table
2755 * @param string $visiblename Name shown on form
2756 * @param string $description Description that appears below field
2758 public function __construct(string $name, string $visiblename, string $description) {
2759 parent
::__construct($name, $visiblename, $description, '');
2762 public function get_setting() {
2763 return $this->config_read($this->name
);
2766 public function write_setting($data) {
2767 $data = trim($data);
2769 // Value can really be set to nothing.
2772 // Encrypt value before saving it.
2773 $savedata = \core\encryption
::encrypt($data);
2775 return ($this->config_write($this->name
, $savedata) ?
'' : get_string('errorsetting', 'admin'));
2778 public function output_html($data, $query='') {
2781 $default = $this->get_defaultsetting();
2782 $context = (object) [
2783 'id' => $this->get_id(),
2784 'name' => $this->get_full_name(),
2785 'set' => $data !== '',
2786 'novalue' => $this->get_setting() === null
2788 $element = $OUTPUT->render_from_template('core_admin/setting_encryptedpassword', $context);
2790 return format_admin_setting($this, $this->visiblename
, $element, $this->description
,
2791 true, '', $default, $query);
2796 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2797 * Note: Only advanced makes sense right now - locked does not.
2799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2801 class admin_setting_configempty
extends admin_setting_configtext
{
2804 * @param string $name
2805 * @param string $visiblename
2806 * @param string $description
2808 public function __construct($name, $visiblename, $description) {
2809 parent
::__construct($name, $visiblename, $description, '', PARAM_RAW
);
2813 * Returns an XHTML string for the hidden field
2815 * @param string $data
2816 * @param string $query
2817 * @return string XHTML string for the editor
2819 public function output_html($data, $query='') {
2822 $context = (object) [
2823 'id' => $this->get_id(),
2824 'name' => $this->get_full_name()
2826 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2828 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', get_string('none'), $query);
2836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2838 class admin_setting_configfile
extends admin_setting_configtext
{
2841 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2842 * @param string $visiblename localised
2843 * @param string $description long localised info
2844 * @param string $defaultdirectory default directory location
2846 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2847 parent
::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW
, 50);
2851 * Returns XHTML for the field
2853 * Returns XHTML for the field and also checks whether the file
2854 * specified in $data exists using file_exists()
2856 * @param string $data File name and path to use in value attr
2857 * @param string $query
2858 * @return string XHTML field
2860 public function output_html($data, $query='') {
2861 global $CFG, $OUTPUT;
2863 $default = $this->get_defaultsetting();
2864 $context = (object) [
2865 'id' => $this->get_id(),
2866 'name' => $this->get_full_name(),
2867 'size' => $this->size
,
2869 'showvalidity' => !empty($data),
2870 'valid' => $data && file_exists($data),
2871 'readonly' => !empty($CFG->preventexecpath
) ||
$this->is_readonly(),
2872 'forceltr' => $this->get_force_ltr(),
2875 if ($context->readonly
) {
2876 $this->visiblename
.= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2879 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2881 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
2885 * Checks if execpatch has been disabled in config.php
2887 public function write_setting($data) {
2889 if (!empty($CFG->preventexecpath
)) {
2890 if ($this->get_setting() === null) {
2891 // Use default during installation.
2892 $data = $this->get_defaultsetting();
2893 if ($data === null) {
2900 return parent
::write_setting($data);
2907 * Path to executable file
2909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2911 class admin_setting_configexecutable
extends admin_setting_configfile
{
2914 * Returns an XHTML field
2916 * @param string $data This is the value for the field
2917 * @param string $query
2918 * @return string XHTML field
2920 public function output_html($data, $query='') {
2921 global $CFG, $OUTPUT;
2922 $default = $this->get_defaultsetting();
2923 require_once("$CFG->libdir/filelib.php");
2925 $context = (object) [
2926 'id' => $this->get_id(),
2927 'name' => $this->get_full_name(),
2928 'size' => $this->size
,
2930 'showvalidity' => !empty($data),
2931 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2932 'readonly' => !empty($CFG->preventexecpath
),
2933 'forceltr' => $this->get_force_ltr()
2936 if (!empty($CFG->preventexecpath
)) {
2937 $this->visiblename
.= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2940 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2942 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
2950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2952 class admin_setting_configdirectory
extends admin_setting_configfile
{
2955 * Returns an XHTML field
2957 * @param string $data This is the value for the field
2958 * @param string $query
2959 * @return string XHTML
2961 public function output_html($data, $query='') {
2962 global $CFG, $OUTPUT;
2963 $default = $this->get_defaultsetting();
2965 $context = (object) [
2966 'id' => $this->get_id(),
2967 'name' => $this->get_full_name(),
2968 'size' => $this->size
,
2970 'showvalidity' => !empty($data),
2971 'valid' => $data && file_exists($data) && is_dir($data),
2972 'readonly' => !empty($CFG->preventexecpath
),
2973 'forceltr' => $this->get_force_ltr()
2976 if (!empty($CFG->preventexecpath
)) {
2977 $this->visiblename
.= '<div class="alert alert-info">'.get_string('execpathnotallowed', 'admin').'</div>';
2980 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2982 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
2990 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2992 class admin_setting_configcheckbox
extends admin_setting
{
2993 /** @var string Value used when checked */
2995 /** @var string Value used when not checked */
3000 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3001 * @param string $visiblename localised
3002 * @param string $description long localised info
3003 * @param string $defaultsetting
3004 * @param string $yes value used when checked
3005 * @param string $no value used when not checked
3007 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
3008 parent
::__construct($name, $visiblename, $description, $defaultsetting);
3009 $this->yes
= (string)$yes;
3010 $this->no
= (string)$no;
3014 * Retrieves the current setting using the objects name
3018 public function get_setting() {
3019 return $this->config_read($this->name
);
3023 * Sets the value for the setting
3025 * Sets the value for the setting to either the yes or no values
3026 * of the object by comparing $data to yes
3028 * @param mixed $data Gets converted to str for comparison against yes value
3029 * @return string empty string or error
3031 public function write_setting($data) {
3032 if ((string)$data === $this->yes
) { // convert to strings before comparison
3037 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
3041 * Returns an XHTML checkbox field
3043 * @param string $data If $data matches yes then checkbox is checked
3044 * @param string $query
3045 * @return string XHTML field
3047 public function output_html($data, $query='') {
3050 $context = (object) [
3051 'id' => $this->get_id(),
3052 'name' => $this->get_full_name(),
3054 'value' => $this->yes
,
3055 'checked' => (string) $data === $this->yes
,
3056 'readonly' => $this->is_readonly(),
3059 $default = $this->get_defaultsetting();
3060 if (!is_null($default)) {
3061 if ((string)$default === $this->yes
) {
3062 $defaultinfo = get_string('checkboxyes', 'admin');
3064 $defaultinfo = get_string('checkboxno', 'admin');
3067 $defaultinfo = NULL;
3070 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
3072 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $defaultinfo, $query);
3078 * Multiple checkboxes, each represents different value, stored in csv format
3080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3082 class admin_setting_configmulticheckbox
extends admin_setting
{
3083 /** @var array Array of choices value=>label */
3085 /** @var callable|null Loader function for choices */
3086 protected $choiceloader = null;
3089 * Constructor: uses parent::__construct
3091 * The $choices parameter may be either an array of $value => $label format,
3092 * e.g. [1 => get_string('yes')], or a callback function which takes no parameters and
3093 * returns an array in that format.
3095 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3096 * @param string $visiblename localised
3097 * @param string $description long localised info
3098 * @param array $defaultsetting array of selected
3099 * @param array|callable $choices array of $value => $label for each checkbox, or a callback
3101 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3102 if (is_array($choices)) {
3103 $this->choices
= $choices;
3105 if (is_callable($choices)) {
3106 $this->choiceloader
= $choices;
3108 parent
::__construct($name, $visiblename, $description, $defaultsetting);
3112 * This function may be used in ancestors for lazy loading of choices
3114 * Override this method if loading of choices is expensive, such
3115 * as when it requires multiple db requests.
3117 * @return bool true if loaded, false if error
3119 public function load_choices() {
3120 if ($this->choiceloader
) {
3121 if (!is_array($this->choices
)) {
3122 $this->choices
= call_user_func($this->choiceloader
);
3129 * Is setting related to query text - used when searching
3131 * @param string $query
3132 * @return bool true on related, false on not or failure
3134 public function is_related($query) {
3135 if (!$this->load_choices() or empty($this->choices
)) {
3138 if (parent
::is_related($query)) {
3142 foreach ($this->choices
as $desc) {
3143 if (strpos(core_text
::strtolower($desc), $query) !== false) {
3151 * Returns the current setting if it is set
3153 * @return mixed null if null, else an array
3155 public function get_setting() {
3156 $result = $this->config_read($this->name
);
3158 if (is_null($result)) {
3161 if ($result === '') {
3164 $enabled = explode(',', $result);
3166 foreach ($enabled as $option) {
3167 $setting[$option] = 1;
3173 * Saves the setting(s) provided in $data
3175 * @param array $data An array of data, if not array returns empty str
3176 * @return mixed empty string on useless data or bool true=success, false=failed
3178 public function write_setting($data) {
3179 if (!is_array($data)) {
3180 return ''; // ignore it
3182 if (!$this->load_choices() or empty($this->choices
)) {
3185 unset($data['xxxxx']);
3187 foreach ($data as $key => $value) {
3188 if ($value and array_key_exists($key, $this->choices
)) {
3192 return $this->config_write($this->name
, implode(',', $result)) ?
'' : get_string('errorsetting', 'admin');
3196 * Returns XHTML field(s) as required by choices
3198 * Relies on data being an array should data ever be another valid vartype with
3199 * acceptable value this may cause a warning/error
3200 * if (!is_array($data)) would fix the problem
3202 * @todo Add vartype handling to ensure $data is an array
3204 * @param array $data An array of checked values
3205 * @param string $query
3206 * @return string XHTML field
3208 public function output_html($data, $query='') {
3211 if (!$this->load_choices() or empty($this->choices
)) {
3215 $default = $this->get_defaultsetting();
3216 if (is_null($default)) {
3219 if (is_null($data)) {
3223 $context = (object) [
3224 'id' => $this->get_id(),
3225 'name' => $this->get_full_name(),
3229 $defaults = array();
3230 foreach ($this->choices
as $key => $description) {
3231 if (!empty($default[$key])) {
3232 $defaults[] = $description;
3237 'checked' => !empty($data[$key]),
3238 'label' => highlightfast($query, $description)
3242 if (is_null($default)) {
3243 $defaultinfo = null;
3244 } else if (!empty($defaults)) {
3245 $defaultinfo = implode(', ', $defaults);
3247 $defaultinfo = get_string('none');
3250 $context->options
= $options;
3251 $context->hasoptions
= !empty($options);
3253 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
3255 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, false, '', $defaultinfo, $query);
3262 * Multiple checkboxes 2, value stored as string 00101011
3264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3266 class admin_setting_configmulticheckbox2
extends admin_setting_configmulticheckbox
{
3269 * Returns the setting if set
3271 * @return mixed null if not set, else an array of set settings
3273 public function get_setting() {
3274 $result = $this->config_read($this->name
);
3275 if (is_null($result)) {
3278 if (!$this->load_choices()) {
3281 $result = str_pad($result, count($this->choices
), '0');
3282 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY
);
3284 foreach ($this->choices
as $key=>$unused) {
3285 $value = array_shift($result);
3294 * Save setting(s) provided in $data param
3296 * @param array $data An array of settings to save
3297 * @return mixed empty string for bad data or bool true=>success, false=>error
3299 public function write_setting($data) {
3300 if (!is_array($data)) {
3301 return ''; // ignore it
3303 if (!$this->load_choices() or empty($this->choices
)) {
3307 foreach ($this->choices
as $key=>$unused) {
3308 if (!empty($data[$key])) {
3314 return $this->config_write($this->name
, $result) ?
'' : get_string('errorsetting', 'admin');
3320 * Select one value from list
3322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3324 class admin_setting_configselect
extends admin_setting
{
3325 /** @var array Array of choices value=>label */
3327 /** @var array Array of choices grouped using optgroups */
3329 /** @var callable|null Loader function for choices */
3330 protected $choiceloader = null;
3331 /** @var callable|null Validation function */
3332 protected $validatefunction = null;
3337 * If you want to lazy-load the choices, pass a callback function that returns a choice
3338 * array for the $choices parameter.
3340 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3341 * @param string $visiblename localised
3342 * @param string $description long localised info
3343 * @param string|int $defaultsetting
3344 * @param array|callable|null $choices array of $value=>$label for each selection, or callback
3346 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3347 // Look for optgroup and single options.
3348 if (is_array($choices)) {
3349 $this->choices
= [];
3350 foreach ($choices as $key => $val) {
3351 if (is_array($val)) {
3352 $this->optgroups
[$key] = $val;
3353 $this->choices
= array_merge($this->choices
, $val);
3355 $this->choices
[$key] = $val;
3359 if (is_callable($choices)) {
3360 $this->choiceloader
= $choices;
3363 parent
::__construct($name, $visiblename, $description, $defaultsetting);
3367 * Sets a validate function.
3369 * The callback will be passed one parameter, the new setting value, and should return either
3370 * an empty string '' if the value is OK, or an error message if not.
3372 * @param callable|null $validatefunction Validate function or null to clear
3373 * @since Moodle 3.10
3375 public function set_validate_function(?callable
$validatefunction = null) {
3376 $this->validatefunction
= $validatefunction;
3380 * This function may be used in ancestors for lazy loading of choices
3382 * Override this method if loading of choices is expensive, such
3383 * as when it requires multiple db requests.
3385 * @return bool true if loaded, false if error
3387 public function load_choices() {
3388 if ($this->choiceloader
) {
3389 if (!is_array($this->choices
)) {
3390 $this->choices
= call_user_func($this->choiceloader
);
3398 * Check if this is $query is related to a choice
3400 * @param string $query
3401 * @return bool true if related, false if not
3403 public function is_related($query) {
3404 if (parent
::is_related($query)) {
3407 if (!$this->load_choices()) {
3410 foreach ($this->choices
as $key=>$value) {
3411 if (strpos(core_text
::strtolower($key), $query) !== false) {
3414 if (strpos(core_text
::strtolower($value), $query) !== false) {
3422 * Return the setting
3424 * @return mixed returns config if successful else null
3426 public function get_setting() {
3427 return $this->config_read($this->name
);
3433 * @param string $data
3434 * @return string empty of error string
3436 public function write_setting($data) {
3437 if (!$this->load_choices() or empty($this->choices
)) {
3440 if (!array_key_exists($data, $this->choices
)) {
3441 return ''; // ignore it
3444 // Validate the new setting.
3445 $error = $this->validate_setting($data);
3450 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
3454 * Validate the setting. This uses the callback function if provided; subclasses could override
3455 * to carry out validation directly in the class.
3457 * @param string $data New value being set
3458 * @return string Empty string if valid, or error message text
3459 * @since Moodle 3.10
3461 protected function validate_setting(string $data): string {
3462 // If validation function is specified, call it now.
3463 if ($this->validatefunction
) {
3464 return call_user_func($this->validatefunction
, $data);
3471 * Returns XHTML select field
3473 * Ensure the options are loaded, and generate the XHTML for the select
3474 * element and any warning message. Separating this out from output_html
3475 * makes it easier to subclass this class.
3477 * @param string $data the option to show as selected.
3478 * @param string $current the currently selected option in the database, null if none.
3479 * @param string $default the default selected option.
3480 * @return array the HTML for the select element, and a warning message.
3481 * @deprecated since Moodle 3.2
3483 public function output_select_html($data, $current, $default, $extraname = '') {
3484 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER
);
3488 * Returns XHTML select field and wrapping div(s)
3490 * @see output_select_html()
3492 * @param string $data the option to show as selected
3493 * @param string $query
3494 * @return string XHTML field and wrapping div
3496 public function output_html($data, $query='') {
3499 $default = $this->get_defaultsetting();
3500 $current = $this->get_setting();
3502 if (!$this->load_choices() ||
empty($this->choices
)) {
3506 $context = (object) [
3507 'id' => $this->get_id(),
3508 'name' => $this->get_full_name(),
3511 if (!is_null($default) && array_key_exists($default, $this->choices
)) {
3512 $defaultinfo = $this->choices
[$default];
3514 $defaultinfo = NULL;
3519 if ($current === null) {
3521 } else if (empty($current) && (array_key_exists('', $this->choices
) ||
array_key_exists(0, $this->choices
))) {
3523 } else if (!array_key_exists($current, $this->choices
)) {
3524 $warning = get_string('warningcurrentsetting', 'admin', $current);
3525 if (!is_null($default) && $data == $current) {
3526 $data = $default; // Use default instead of first value when showing the form.
3531 $template = 'core_admin/setting_configselect';
3533 if (!empty($this->optgroups
)) {
3535 foreach ($this->optgroups
as $label => $choices) {
3536 $optgroup = array('label' => $label, 'options' => []);
3537 foreach ($choices as $value => $name) {
3538 $optgroup['options'][] = [
3541 'selected' => (string) $value == $data
3543 unset($this->choices
[$value]);
3545 $optgroups[] = $optgroup;
3547 $context->options
= $options;
3548 $context->optgroups
= $optgroups;
3549 $template = 'core_admin/setting_configselect_optgroup';
3552 foreach ($this->choices
as $value => $name) {
3556 'selected' => (string) $value == $data
3559 $context->options
= $options;
3560 $context->readonly
= $this->is_readonly();
3562 $element = $OUTPUT->render_from_template($template, $context);
3564 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, $warning, $defaultinfo, $query);
3569 * Select multiple items from list
3571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3573 class admin_setting_configmultiselect
extends admin_setting_configselect
{
3576 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3577 * @param string $visiblename localised
3578 * @param string $description long localised info
3579 * @param array $defaultsetting array of selected items
3580 * @param array $choices array of $value=>$label for each list item
3582 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3583 parent
::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3587 * Returns the select setting(s)
3589 * @return mixed null or array. Null if no settings else array of setting(s)
3591 public function get_setting() {
3592 $result = $this->config_read($this->name
);
3593 if (is_null($result)) {
3596 if ($result === '') {
3599 return explode(',', $result);
3603 * Saves setting(s) provided through $data
3605 * Potential bug in the works should anyone call with this function
3606 * using a vartype that is not an array
3608 * @param array $data
3610 public function write_setting($data) {
3611 if (!is_array($data)) {
3612 return ''; //ignore it
3614 if (!$this->load_choices() or empty($this->choices
)) {
3618 unset($data['xxxxx']);
3621 foreach ($data as $value) {
3622 if (!array_key_exists($value, $this->choices
)) {
3623 continue; // ignore it
3628 return ($this->config_write($this->name
, implode(',', $save)) ?
'' : get_string('errorsetting', 'admin'));
3632 * Is setting related to query text - used when searching
3634 * @param string $query
3635 * @return bool true if related, false if not
3637 public function is_related($query) {
3638 if (!$this->load_choices() or empty($this->choices
)) {
3641 if (parent
::is_related($query)) {
3645 foreach ($this->choices
as $desc) {
3646 if (strpos(core_text
::strtolower($desc), $query) !== false) {
3654 * Returns XHTML multi-select field
3656 * @todo Add vartype handling to ensure $data is an array
3657 * @param array $data Array of values to select by default
3658 * @param string $query
3659 * @return string XHTML multi-select field
3661 public function output_html($data, $query='') {
3664 if (!$this->load_choices() or empty($this->choices
)) {
3668 $default = $this->get_defaultsetting();
3669 if (is_null($default)) {
3672 if (is_null($data)) {
3676 $context = (object) [
3677 'id' => $this->get_id(),
3678 'name' => $this->get_full_name(),
3679 'size' => min(10, count($this->choices
))
3684 $template = 'core_admin/setting_configmultiselect';
3686 if (!empty($this->optgroups
)) {
3688 foreach ($this->optgroups
as $label => $choices) {
3689 $optgroup = array('label' => $label, 'options' => []);
3690 foreach ($choices as $value => $name) {
3691 if (in_array($value, $default)) {
3692 $defaults[] = $name;
3694 $optgroup['options'][] = [
3697 'selected' => in_array($value, $data)
3699 unset($this->choices
[$value]);
3701 $optgroups[] = $optgroup;
3703 $context->optgroups
= $optgroups;
3704 $template = 'core_admin/setting_configmultiselect_optgroup';
3707 foreach ($this->choices
as $value => $name) {
3708 if (in_array($value, $default)) {
3709 $defaults[] = $name;
3714 'selected' => in_array($value, $data)
3717 $context->options
= $options;
3718 $context->readonly
= $this->is_readonly();
3720 if (is_null($default)) {
3721 $defaultinfo = NULL;
3722 } if (!empty($defaults)) {
3723 $defaultinfo = implode(', ', $defaults);
3725 $defaultinfo = get_string('none');
3728 $element = $OUTPUT->render_from_template($template, $context);
3730 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $defaultinfo, $query);
3737 * This is a liiitle bit messy. we're using two selects, but we're returning
3738 * them as an array named after $name (so we only use $name2 internally for the setting)
3740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3742 class admin_setting_configtime
extends admin_setting
{
3743 /** @var string Used for setting second select (minutes) */
3748 * @param string $hoursname setting for hours
3749 * @param string $minutesname setting for hours
3750 * @param string $visiblename localised
3751 * @param string $description long localised info
3752 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3754 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3755 $this->name2
= $minutesname;
3756 parent
::__construct($hoursname, $visiblename, $description, $defaultsetting);
3760 * Get the selected time
3762 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3764 public function get_setting() {
3765 $result1 = $this->config_read($this->name
);
3766 $result2 = $this->config_read($this->name2
);
3767 if (is_null($result1) or is_null($result2)) {
3771 return array('h' => $result1, 'm' => $result2);
3775 * Store the time (hours and minutes)
3777 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3778 * @return bool true if success, false if not
3780 public function write_setting($data) {
3781 if (!is_array($data)) {
3785 $result = $this->config_write($this->name
, (int)$data['h']) && $this->config_write($this->name2
, (int)$data['m']);
3786 return ($result ?
'' : get_string('errorsetting', 'admin'));
3790 * Returns XHTML time select fields
3792 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3793 * @param string $query
3794 * @return string XHTML time select fields and wrapping div(s)
3796 public function output_html($data, $query='') {
3799 $default = $this->get_defaultsetting();
3800 if (is_array($default)) {
3801 $defaultinfo = $default['h'].':'.$default['m'];
3803 $defaultinfo = NULL;
3806 $context = (object) [
3807 'id' => $this->get_id(),
3808 'name' => $this->get_full_name(),
3809 'readonly' => $this->is_readonly(),
3810 'hours' => array_map(function($i) use ($data) {
3814 'selected' => $i == $data['h']
3817 'minutes' => array_map(function($i) use ($data) {
3821 'selected' => $i == $data['m']
3826 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3828 return format_admin_setting($this, $this->visiblename
, $element, $this->description
,
3829 $this->get_id() . 'h', '', $defaultinfo, $query);
3836 * Seconds duration setting.
3838 * @copyright 2012 Petr Skoda (http://skodak.org)
3839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3841 class admin_setting_configduration
extends admin_setting
{
3843 /** @var int default duration unit */
3844 protected $defaultunit;
3845 /** @var callable|null Validation function */
3846 protected $validatefunction = null;
3850 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3851 * or 'myplugin/mysetting' for ones in config_plugins.
3852 * @param string $visiblename localised name
3853 * @param string $description localised long description
3854 * @param mixed $defaultsetting string or array depending on implementation
3855 * @param int $defaultunit - day, week, etc. (in seconds)
3857 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3858 if (is_number($defaultsetting)) {
3859 $defaultsetting = self
::parse_seconds($defaultsetting);
3861 $units = self
::get_units();
3862 if (isset($units[$defaultunit])) {
3863 $this->defaultunit
= $defaultunit;
3865 $this->defaultunit
= 86400;
3867 parent
::__construct($name, $visiblename, $description, $defaultsetting);
3871 * Sets a validate function.
3873 * The callback will be passed one parameter, the new setting value, and should return either
3874 * an empty string '' if the value is OK, or an error message if not.
3876 * @param callable|null $validatefunction Validate function or null to clear
3877 * @since Moodle 3.10
3879 public function set_validate_function(?callable
$validatefunction = null) {
3880 $this->validatefunction
= $validatefunction;
3884 * Validate the setting. This uses the callback function if provided; subclasses could override
3885 * to carry out validation directly in the class.
3887 * @param int $data New value being set
3888 * @return string Empty string if valid, or error message text
3889 * @since Moodle 3.10
3891 protected function validate_setting(int $data): string {
3892 // If validation function is specified, call it now.
3893 if ($this->validatefunction
) {
3894 return call_user_func($this->validatefunction
, $data);
3897 return get_string('errorsetting', 'admin');
3904 * Returns selectable units.
3908 protected static function get_units() {
3910 604800 => get_string('weeks'),
3911 86400 => get_string('days'),
3912 3600 => get_string('hours'),
3913 60 => get_string('minutes'),
3914 1 => get_string('seconds'),
3919 * Converts seconds to some more user friendly string.
3921 * @param int $seconds
3924 protected static function get_duration_text($seconds) {
3925 if (empty($seconds)) {
3926 return get_string('none');
3928 $data = self
::parse_seconds($seconds);
3929 switch ($data['u']) {
3931 return get_string('numweeks', '', $data['v']);
3933 return get_string('numdays', '', $data['v']);
3935 return get_string('numhours', '', $data['v']);
3937 return get_string('numminutes', '', $data['v']);
3939 return get_string('numseconds', '', $data['v']*$data['u']);
3944 * Finds suitable units for given duration.
3946 * @param int $seconds
3949 protected static function parse_seconds($seconds) {
3950 foreach (self
::get_units() as $unit => $unused) {
3951 if ($seconds %
$unit === 0) {
3952 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3955 return array('v'=>(int)$seconds, 'u'=>1);
3959 * Get the selected duration as array.
3961 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3963 public function get_setting() {
3964 $seconds = $this->config_read($this->name
);
3965 if (is_null($seconds)) {
3969 return self
::parse_seconds($seconds);
3973 * Store the duration as seconds.
3975 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3976 * @return bool true if success, false if not
3978 public function write_setting($data) {
3979 if (!is_array($data)) {
3983 $seconds = (int)($data['v']*$data['u']);
3985 // Validate the new setting.
3986 $error = $this->validate_setting($seconds);
3991 $result = $this->config_write($this->name
, $seconds);
3992 return ($result ?
'' : get_string('errorsetting', 'admin'));
3996 * Returns duration text+select fields.
3998 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3999 * @param string $query
4000 * @return string duration text+select fields and wrapping div(s)
4002 public function output_html($data, $query='') {
4005 $default = $this->get_defaultsetting();
4006 if (is_number($default)) {
4007 $defaultinfo = self
::get_duration_text($default);
4008 } else if (is_array($default)) {
4009 $defaultinfo = self
::get_duration_text($default['v']*$default['u']);
4011 $defaultinfo = null;
4014 $inputid = $this->get_id() . 'v';
4015 $units = self
::get_units();
4016 $defaultunit = $this->defaultunit
;
4018 $context = (object) [
4019 'id' => $this->get_id(),
4020 'name' => $this->get_full_name(),
4021 'value' => $data['v'],
4022 'readonly' => $this->is_readonly(),
4023 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
4026 'name' => $units[$unit],
4027 'selected' => ($data['v'] == 0 && $unit == $defaultunit) ||
$unit == $data['u']
4029 }, array_keys($units))
4032 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
4034 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, $inputid, '', $defaultinfo, $query);
4040 * Seconds duration setting with an advanced checkbox, that controls a additional
4041 * $name.'_adv' setting.
4043 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4044 * @copyright 2014 The Open University
4046 class admin_setting_configduration_with_advanced
extends admin_setting_configduration
{
4049 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
4050 * or 'myplugin/mysetting' for ones in config_plugins.
4051 * @param string $visiblename localised name
4052 * @param string $description localised long description
4053 * @param array $defaultsetting array of int value, and bool whether it is
4054 * is advanced by default.
4055 * @param int $defaultunit - day, week, etc. (in seconds)
4057 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
4058 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
4059 $this->set_advanced_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['adv']));
4065 * Used to validate a textarea used for ip addresses
4067 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4068 * @copyright 2011 Petr Skoda (http://skodak.org)
4070 class admin_setting_configiplist
extends admin_setting_configtextarea
{
4073 * Validate the contents of the textarea as IP addresses
4075 * Used to validate a new line separated list of IP addresses collected from
4076 * a textarea control
4078 * @param string $data A list of IP Addresses separated by new lines
4079 * @return mixed bool true for success or string:error on failure
4081 public function validate($data) {
4083 $lines = explode("\n", $data);
4089 foreach ($lines as $line) {
4090 $tokens = explode('#', $line);
4091 $ip = trim($tokens[0]);
4095 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
4096 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
4097 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
4106 return get_string('validateiperror', 'admin', join(', ', $badips));
4112 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
4114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4115 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4117 class admin_setting_configmixedhostiplist
extends admin_setting_configtextarea
{
4120 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
4121 * Used to validate a new line separated list of entries collected from a textarea control.
4123 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
4124 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
4125 * via the get_setting() method, which has been overriden.
4127 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
4128 * @return mixed bool true for success or string:error on failure
4130 public function validate($data) {
4134 $entries = explode("\n", $data);
4137 foreach ($entries as $key => $entry) {
4138 $entry = trim($entry);
4139 if (empty($entry)) {
4140 return get_string('validateemptylineerror', 'admin');
4143 // Validate each string entry against the supported formats.
4144 if (\core\ip_utils
::is_ip_address($entry) || \core\ip_utils
::is_ipv6_range($entry)
4145 || \core\ip_utils
::is_ipv4_range($entry) || \core\ip_utils
::is_domain_name($entry)
4146 || \core\ip_utils
::is_domain_matching_pattern($entry)) {
4150 // Otherwise, the entry is invalid.
4151 $badentries[] = $entry;
4155 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
4161 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
4163 * @param string $data the setting data, as sent from the web form.
4164 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
4166 protected function ace_encode($data) {
4170 $entries = explode("\n", $data);
4171 foreach ($entries as $key => $entry) {
4172 $entry = trim($entry);
4173 // This regex matches any string that has non-ascii character.
4174 if (preg_match('/[^\x00-\x7f]/', $entry)) {
4175 // If we can convert the unicode string to an idn, do so.
4176 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
4177 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII
, INTL_IDNA_VARIANT_UTS46
);
4178 $entries[$key] = $val ?
$val : $entry;
4181 return implode("\n", $entries);
4185 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
4187 * @param string $data the setting data, as found in the database.
4188 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
4190 protected function ace_decode($data) {
4191 $entries = explode("\n", $data);
4192 foreach ($entries as $key => $entry) {
4193 $entry = trim($entry);
4194 if (strpos($entry, 'xn--') !== false) {
4195 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII
, INTL_IDNA_VARIANT_UTS46
);
4198 return implode("\n", $entries);
4202 * Override, providing utf8-decoding for ascii-encoded IDN strings.
4204 * @return mixed returns punycode-converted setting string if successful, else null.
4206 public function get_setting() {
4207 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
4208 $data = $this->config_read($this->name
);
4209 if (function_exists('idn_to_utf8') && !is_null($data)) {
4210 $data = $this->ace_decode($data);
4216 * Override, providing ascii-encoding for utf8 (native) IDN strings.
4218 * @param string $data
4221 public function write_setting($data) {
4222 if ($this->paramtype
=== PARAM_INT
and $data === '') {
4223 // Do not complain if '' used instead of 0.
4227 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
4228 if (function_exists('idn_to_ascii')) {
4229 $data = $this->ace_encode($data);
4232 $validated = $this->validate($data);
4233 if ($validated !== true) {
4236 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
4241 * Used to validate a textarea used for port numbers.
4243 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4244 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
4246 class admin_setting_configportlist
extends admin_setting_configtextarea
{
4249 * Validate the contents of the textarea as port numbers.
4250 * Used to validate a new line separated list of ports collected from a textarea control.
4252 * @param string $data A list of ports separated by new lines
4253 * @return mixed bool true for success or string:error on failure
4255 public function validate($data) {
4259 $ports = explode("\n", $data);
4261 foreach ($ports as $port) {
4262 $port = trim($port);
4264 return get_string('validateemptylineerror', 'admin');
4267 // Is the string a valid integer number?
4268 if (strval(intval($port)) !== $port ||
intval($port) <= 0) {
4269 $badentries[] = $port;
4273 return get_string('validateerrorlist', 'admin', $badentries);
4281 * An admin setting for selecting one or more users who have a capability
4282 * in the system context
4284 * An admin setting for selecting one or more users, who have a particular capability
4285 * in the system context. Warning, make sure the list will never be too long. There is
4286 * no paging or searching of this list.
4288 * To correctly get a list of users from this config setting, you need to call the
4289 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
4291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4293 class admin_setting_users_with_capability
extends admin_setting_configmultiselect
{
4294 /** @var string The capabilities name */
4295 protected $capability;
4296 /** @var int include admin users too */
4297 protected $includeadmins;
4302 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4303 * @param string $visiblename localised name
4304 * @param string $description localised long description
4305 * @param array $defaultsetting array of usernames
4306 * @param string $capability string capability name.
4307 * @param bool $includeadmins include administrators
4309 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
4310 $this->capability
= $capability;
4311 $this->includeadmins
= $includeadmins;
4312 parent
::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4316 * Load all of the uses who have the capability into choice array
4318 * @return bool Always returns true
4320 function load_choices() {
4321 if (is_array($this->choices
)) {
4324 list($sort, $sortparams) = users_order_by_sql('u');
4325 if (!empty($sortparams)) {
4326 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
4327 'This is unexpected, and a problem because there is no way to pass these ' .
4328 'parameters to get_users_by_capability. See MDL-34657.');
4330 $userfieldsapi = \core_user\fields
::for_name();
4331 $userfields = 'u.id, u.username, ' . $userfieldsapi->get_sql('u', false, '', '', false)->selects
;
4332 $users = get_users_by_capability(context_system
::instance(), $this->capability
, $userfields, $sort);
4333 $this->choices
= array(
4334 '$@NONE@$' => get_string('nobody'),
4335 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability
)),
4337 if ($this->includeadmins
) {
4338 $admins = get_admins();
4339 foreach ($admins as $user) {
4340 $this->choices
[$user->id
] = fullname($user);
4343 if (is_array($users)) {
4344 foreach ($users as $user) {
4345 $this->choices
[$user->id
] = fullname($user);
4352 * Returns the default setting for class
4354 * @return mixed Array, or string. Empty string if no default
4356 public function get_defaultsetting() {
4357 $this->load_choices();
4358 $defaultsetting = parent
::get_defaultsetting();
4359 if (empty($defaultsetting)) {
4360 return array('$@NONE@$');
4361 } else if (array_key_exists($defaultsetting, $this->choices
)) {
4362 return $defaultsetting;
4369 * Returns the current setting
4371 * @return mixed array or string
4373 public function get_setting() {
4374 $result = parent
::get_setting();
4375 if ($result === null) {
4376 // this is necessary for settings upgrade
4379 if (empty($result)) {
4380 $result = array('$@NONE@$');
4386 * Save the chosen setting provided as $data
4388 * @param array $data
4389 * @return mixed string or array
4391 public function write_setting($data) {
4392 // If all is selected, remove any explicit options.
4393 if (in_array('$@ALL@$', $data)) {
4394 $data = array('$@ALL@$');
4396 // None never needs to be written to the DB.
4397 if (in_array('$@NONE@$', $data)) {
4398 unset($data[array_search('$@NONE@$', $data)]);
4400 return parent
::write_setting($data);
4406 * Special checkbox for calendar - resets SESSION vars.
4408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4410 class admin_setting_special_adminseesall
extends admin_setting_configcheckbox
{
4412 * Calls the parent::__construct with default values
4414 * name => calendar_adminseesall
4415 * visiblename => get_string('adminseesall', 'admin')
4416 * description => get_string('helpadminseesall', 'admin')
4417 * defaultsetting => 0
4419 public function __construct() {
4420 parent
::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
4421 get_string('helpadminseesall', 'admin'), '0');
4425 * Stores the setting passed in $data
4427 * @param mixed gets converted to string for comparison
4428 * @return string empty string or error message
4430 public function write_setting($data) {
4432 return parent
::write_setting($data);
4437 * Special select for settings that are altered in setup.php and can not be altered on the fly
4439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4441 class admin_setting_special_selectsetup
extends admin_setting_configselect
{
4443 * Reads the setting directly from the database
4447 public function get_setting() {
4448 // read directly from db!
4449 return get_config(NULL, $this->name
);
4453 * Save the setting passed in $data
4455 * @param string $data The setting to save
4456 * @return string empty or error message
4458 public function write_setting($data) {
4460 // do not change active CFG setting!
4461 $current = $CFG->{$this->name
};
4462 $result = parent
::write_setting($data);
4463 $CFG->{$this->name
} = $current;
4470 * Special select for frontpage - stores data in course table
4472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4474 class admin_setting_sitesetselect
extends admin_setting_configselect
{
4476 * Returns the site name for the selected site
4479 * @return string The site name of the selected site
4481 public function get_setting() {
4482 $site = course_get_format(get_site())->get_course();
4483 return $site->{$this->name
};
4487 * Updates the database and save the setting
4489 * @param string data
4490 * @return string empty or error message
4492 public function write_setting($data) {
4493 global $DB, $SITE, $COURSE;
4494 if (!in_array($data, array_keys($this->choices
))) {
4495 return get_string('errorsetting', 'admin');
4497 $record = new stdClass();
4498 $record->id
= SITEID
;
4499 $temp = $this->name
;
4500 $record->$temp = $data;
4501 $record->timemodified
= time();
4503 course_get_format($SITE)->update_course_format_options($record);
4504 $DB->update_record('course', $record);
4507 $SITE = $DB->get_record('course', array('id'=>$SITE->id
), '*', MUST_EXIST
);
4508 if ($SITE->id
== $COURSE->id
) {
4511 format_base
::reset_course_cache($SITE->id
);
4520 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4525 class admin_setting_bloglevel
extends admin_setting_configselect
{
4527 * Updates the database and save the setting
4529 * @param string data
4530 * @return string empty or error message
4532 public function write_setting($data) {
4535 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4536 foreach ($blogblocks as $block) {
4537 $DB->set_field('block', 'visible', 0, array('id' => $block->id
));
4540 // reenable all blocks only when switching from disabled blogs
4541 if (isset($CFG->bloglevel
) and $CFG->bloglevel
== 0) {
4542 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4543 foreach ($blogblocks as $block) {
4544 $DB->set_field('block', 'visible', 1, array('id' => $block->id
));
4548 return parent
::write_setting($data);
4554 * Special select - lists on the frontpage - hacky
4556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4558 class admin_setting_courselist_frontpage
extends admin_setting
{
4559 /** @var array Array of choices value=>label */
4563 * Construct override, requires one param
4565 * @param bool $loggedin Is the user logged in
4567 public function __construct($loggedin) {
4569 require_once($CFG->dirroot
.'/course/lib.php');
4570 $name = 'frontpage'.($loggedin ?
'loggedin' : '');
4571 $visiblename = get_string('frontpage'.($loggedin ?
'loggedin' : ''),'admin');
4572 $description = get_string('configfrontpage'.($loggedin ?
'loggedin' : ''),'admin');
4573 $defaults = array(FRONTPAGEALLCOURSELIST
);
4574 parent
::__construct($name, $visiblename, $description, $defaults);
4578 * Loads the choices available
4580 * @return bool always returns true
4582 public function load_choices() {
4583 if (is_array($this->choices
)) {
4586 $this->choices
= array(FRONTPAGENEWS
=> get_string('frontpagenews'),
4587 FRONTPAGEALLCOURSELIST
=> get_string('frontpagecourselist'),
4588 FRONTPAGEENROLLEDCOURSELIST
=> get_string('frontpageenrolledcourselist'),
4589 FRONTPAGECATEGORYNAMES
=> get_string('frontpagecategorynames'),
4590 FRONTPAGECATEGORYCOMBO
=> get_string('frontpagecategorycombo'),
4591 FRONTPAGECOURSESEARCH
=> get_string('frontpagecoursesearch'),
4592 'none' => get_string('none'));
4593 if ($this->name
=== 'frontpage') {
4594 unset($this->choices
[FRONTPAGEENROLLEDCOURSELIST
]);
4600 * Returns the selected settings
4602 * @param mixed array or setting or null
4604 public function get_setting() {
4605 $result = $this->config_read($this->name
);
4606 if (is_null($result)) {
4609 if ($result === '') {
4612 return explode(',', $result);
4616 * Save the selected options
4618 * @param array $data
4619 * @return mixed empty string (data is not an array) or bool true=success false=failure
4621 public function write_setting($data) {
4622 if (!is_array($data)) {
4625 $this->load_choices();
4627 foreach($data as $datum) {
4628 if ($datum == 'none' or !array_key_exists($datum, $this->choices
)) {
4631 $save[$datum] = $datum; // no duplicates
4633 return ($this->config_write($this->name
, implode(',', $save)) ?
'' : get_string('errorsetting', 'admin'));
4637 * Return XHTML select field and wrapping div
4639 * @todo Add vartype handling to make sure $data is an array
4640 * @param array $data Array of elements to select by default
4641 * @return string XHTML select field and wrapping div
4643 public function output_html($data, $query='') {
4646 $this->load_choices();
4647 $currentsetting = array();
4648 foreach ($data as $key) {
4649 if ($key != 'none' and array_key_exists($key, $this->choices
)) {
4650 $currentsetting[] = $key; // already selected first
4654 $context = (object) [
4655 'id' => $this->get_id(),
4656 'name' => $this->get_full_name(),
4659 $options = $this->choices
;
4661 for ($i = 0; $i < count($this->choices
) - 1; $i++
) {
4662 if (!array_key_exists($i, $currentsetting)) {
4663 $currentsetting[$i] = 'none';
4667 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4669 'name' => $options[$option],
4671 'selected' => $currentsetting[$i] == $option
4673 }, array_keys($options))
4676 $context->selects
= $selects;
4678 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4680 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, false, '', null, $query);
4686 * Special checkbox for frontpage - stores data in course table
4688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4690 class admin_setting_sitesetcheckbox
extends admin_setting_configcheckbox
{
4692 * Returns the current sites name
4696 public function get_setting() {
4697 $site = course_get_format(get_site())->get_course();
4698 return $site->{$this->name
};
4702 * Save the selected setting
4704 * @param string $data The selected site
4705 * @return string empty string or error message
4707 public function write_setting($data) {
4708 global $DB, $SITE, $COURSE;
4709 $record = new stdClass();
4710 $record->id
= $SITE->id
;
4711 $record->{$this->name
} = ($data == '1' ?
1 : 0);
4712 $record->timemodified
= time();
4714 course_get_format($SITE)->update_course_format_options($record);
4715 $DB->update_record('course', $record);
4718 $SITE = $DB->get_record('course', array('id'=>$SITE->id
), '*', MUST_EXIST
);
4719 if ($SITE->id
== $COURSE->id
) {
4722 format_base
::reset_course_cache($SITE->id
);
4729 * Special text for frontpage - stores data in course table.
4730 * Empty string means not set here. Manual setting is required.
4732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4734 class admin_setting_sitesettext
extends admin_setting_configtext
{
4739 public function __construct() {
4740 call_user_func_array(['parent', '__construct'], func_get_args());
4741 $this->set_force_ltr(false);
4745 * Return the current setting
4747 * @return mixed string or null
4749 public function get_setting() {
4750 $site = course_get_format(get_site())->get_course();
4751 return $site->{$this->name
} != '' ?
$site->{$this->name
} : NULL;
4755 * Validate the selected data
4757 * @param string $data The selected value to validate
4758 * @return mixed true or message string
4760 public function validate($data) {
4762 $cleaned = clean_param($data, PARAM_TEXT
);
4763 if ($cleaned === '') {
4764 return get_string('required');
4766 if ($this->name
==='shortname' &&
4767 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id
))) {
4768 return get_string('shortnametaken', 'error', $data);
4770 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4773 return get_string('validateerror', 'admin');
4778 * Save the selected setting
4780 * @param string $data The selected value
4781 * @return string empty or error message
4783 public function write_setting($data) {
4784 global $DB, $SITE, $COURSE;
4785 $data = trim($data);
4786 $validated = $this->validate($data);
4787 if ($validated !== true) {
4791 $record = new stdClass();
4792 $record->id
= $SITE->id
;
4793 $record->{$this->name
} = $data;
4794 $record->timemodified
= time();
4796 course_get_format($SITE)->update_course_format_options($record);
4797 $DB->update_record('course', $record);
4800 $SITE = $DB->get_record('course', array('id'=>$SITE->id
), '*', MUST_EXIST
);
4801 if ($SITE->id
== $COURSE->id
) {
4804 format_base
::reset_course_cache($SITE->id
);
4812 * Special text editor for site description.
4814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4816 class admin_setting_special_frontpagedesc
extends admin_setting_confightmleditor
{
4819 * Calls parent::__construct with specific arguments
4821 public function __construct() {
4822 parent
::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4827 * Return the current setting
4828 * @return string The current setting
4830 public function get_setting() {
4831 $site = course_get_format(get_site())->get_course();
4832 return $site->{$this->name
};
4836 * Save the new setting
4838 * @param string $data The new value to save
4839 * @return string empty or error message
4841 public function write_setting($data) {
4842 global $DB, $SITE, $COURSE;
4843 $record = new stdClass();
4844 $record->id
= $SITE->id
;
4845 $record->{$this->name
} = $data;
4846 $record->timemodified
= time();
4848 course_get_format($SITE)->update_course_format_options($record);
4849 $DB->update_record('course', $record);
4852 $SITE = $DB->get_record('course', array('id'=>$SITE->id
), '*', MUST_EXIST
);
4853 if ($SITE->id
== $COURSE->id
) {
4856 format_base
::reset_course_cache($SITE->id
);
4864 * Administration interface for emoticon_manager settings.
4866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4868 class admin_setting_emoticons
extends admin_setting
{
4871 * Calls parent::__construct with specific args
4873 public function __construct() {
4876 $manager = get_emoticon_manager();
4877 $defaults = $this->prepare_form_data($manager->default_emoticons());
4878 parent
::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4882 * Return the current setting(s)
4884 * @return array Current settings array
4886 public function get_setting() {
4889 $manager = get_emoticon_manager();
4891 $config = $this->config_read($this->name
);
4892 if (is_null($config)) {
4896 $config = $manager->decode_stored_config($config);
4897 if (is_null($config)) {
4901 return $this->prepare_form_data($config);
4905 * Save selected settings
4907 * @param array $data Array of settings to save
4910 public function write_setting($data) {
4912 $manager = get_emoticon_manager();
4913 $emoticons = $this->process_form_data($data);
4915 if ($emoticons === false) {
4919 if ($this->config_write($this->name
, $manager->encode_stored_config($emoticons))) {
4920 return ''; // success
4922 return get_string('errorsetting', 'admin') . $this->visiblename
. html_writer
::empty_tag('br');
4927 * Return XHTML field(s) for options
4929 * @param array $data Array of options to set in HTML
4930 * @return string XHTML string for the fields and wrapping div(s)
4932 public function output_html($data, $query='') {
4935 $context = (object) [
4936 'name' => $this->get_full_name(),
4942 foreach ($data as $field => $value) {
4944 // When $i == 0: text.
4945 // When $i == 1: imagename.
4946 // When $i == 2: imagecomponent.
4947 // When $i == 3: altidentifier.
4948 // When $i == 4: altcomponent.
4949 $fields[$i] = (object) [
4958 if (!empty($fields[1]->value
)) {
4959 if (get_string_manager()->string_exists($fields[3]->value
, $fields[4]->value
)) {
4960 $alt = get_string($fields[3]->value
, $fields[4]->value
);
4962 $alt = $fields[0]->value
;
4964 $icon = new pix_emoticon($fields[1]->value
, $alt, $fields[2]->value
);
4966 $context->emoticons
[] = [
4967 'fields' => $fields,
4968 'icon' => $icon ?
$icon->export_for_template($OUTPUT) : null
4975 $context->reseturl
= new moodle_url('/admin/resetemoticons.php');
4976 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4977 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, false, '', NULL, $query);
4981 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4983 * @see self::process_form_data()
4984 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4985 * @return array of form fields and their values
4987 protected function prepare_form_data(array $emoticons) {
4991 foreach ($emoticons as $emoticon) {
4992 $form['text'.$i] = $emoticon->text
;
4993 $form['imagename'.$i] = $emoticon->imagename
;
4994 $form['imagecomponent'.$i] = $emoticon->imagecomponent
;
4995 $form['altidentifier'.$i] = $emoticon->altidentifier
;
4996 $form['altcomponent'.$i] = $emoticon->altcomponent
;
4999 // add one more blank field set for new object
5000 $form['text'.$i] = '';
5001 $form['imagename'.$i] = '';
5002 $form['imagecomponent'.$i] = '';
5003 $form['altidentifier'.$i] = '';
5004 $form['altcomponent'.$i] = '';
5010 * Converts the data from admin settings form into an array of emoticon objects
5012 * @see self::prepare_form_data()
5013 * @param array $data array of admin form fields and values
5014 * @return false|array of emoticon objects
5016 protected function process_form_data(array $form) {
5018 $count = count($form); // number of form field values
5021 // we must get five fields per emoticon object
5025 $emoticons = array();
5026 for ($i = 0; $i < $count / 5; $i++
) {
5027 $emoticon = new stdClass();
5028 $emoticon->text
= clean_param(trim($form['text'.$i]), PARAM_NOTAGS
);
5029 $emoticon->imagename
= clean_param(trim($form['imagename'.$i]), PARAM_PATH
);
5030 $emoticon->imagecomponent
= clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT
);
5031 $emoticon->altidentifier
= clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID
);
5032 $emoticon->altcomponent
= clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT
);
5034 if (strpos($emoticon->text
, ':/') !== false or strpos($emoticon->text
, '//') !== false) {
5035 // prevent from breaking http://url.addresses by accident
5036 $emoticon->text
= '';
5039 if (strlen($emoticon->text
) < 2) {
5040 // do not allow single character emoticons
5041 $emoticon->text
= '';
5044 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text
)) {
5045 // emoticon text must contain some non-alphanumeric character to prevent
5046 // breaking HTML tags
5047 $emoticon->text
= '';
5050 if ($emoticon->text
!== '' and $emoticon->imagename
!== '' and $emoticon->imagecomponent
!== '') {
5051 $emoticons[] = $emoticon;
5061 * Special setting for limiting of the list of available languages.
5063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 class admin_setting_langlist
extends admin_setting_configtext
{
5067 * Calls parent::__construct with specific arguments
5069 public function __construct() {
5070 parent
::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS
);
5074 * Validate that each language identifier exists on the site
5076 * @param string $data
5077 * @return bool|string True if validation successful, otherwise error string
5079 public function validate($data) {
5080 $parentcheck = parent
::validate($data);
5081 if ($parentcheck !== true) {
5082 return $parentcheck;
5089 // Normalize language identifiers.
5090 $langcodes = array_map('trim', explode(',', $data));
5091 foreach ($langcodes as $langcode) {
5092 // If the langcode contains optional alias, split it out.
5093 [$langcode, ] = preg_split('/\s*\|\s*/', $langcode, 2);
5095 if (!get_string_manager()->translation_exists($langcode)) {
5096 return get_string('invalidlanguagecode', 'error', $langcode);
5104 * Save the new setting
5106 * @param string $data The new setting
5109 public function write_setting($data) {
5110 $return = parent
::write_setting($data);
5111 get_string_manager()->reset_caches();
5118 * Allows to specify comma separated list of known country codes.
5120 * This is a simple subclass of the plain input text field with added validation so that all the codes are actually
5125 * @copyright 2020 David Mudrák <david@moodle.com>
5126 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5128 class admin_setting_countrycodes
extends admin_setting_configtext
{
5131 * Construct the instance of the setting.
5133 * @param string $name Name of the admin setting such as 'allcountrycodes' or 'myplugin/countries'.
5134 * @param lang_string|string $visiblename Language string with the field label text.
5135 * @param lang_string|string $description Language string with the field description text.
5136 * @param string $defaultsetting Default value of the setting.
5137 * @param int $size Input text field size.
5139 public function __construct($name, $visiblename, $description, $defaultsetting = '', $size = null) {
5140 parent
::__construct($name, $visiblename, $description, $defaultsetting, '/^(?:\w+(?:,\w+)*)?$/', $size);
5144 * Validate the setting value before storing it.
5146 * The value is first validated through custom regex so that it is a word consisting of letters, numbers or underscore; or
5147 * a comma separated list of such words.
5149 * @param string $data Value inserted into the setting field.
5150 * @return bool|string True if the value is OK, error string otherwise.
5152 public function validate($data) {
5154 $parentcheck = parent
::validate($data);
5156 if ($parentcheck !== true) {
5157 return $parentcheck;
5164 $allcountries = get_string_manager()->get_list_of_countries(true);
5166 foreach (explode(',', $data) as $code) {
5167 if (!isset($allcountries[$code])) {
5168 return get_string('invalidcountrycode', 'core_error', $code);
5178 * Selection of one of the recognised countries using the list
5179 * returned by {@link get_list_of_countries()}.
5181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5183 class admin_settings_country_select
extends admin_setting_configselect
{
5184 protected $includeall;
5185 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
5186 $this->includeall
= $includeall;
5187 parent
::__construct($name, $visiblename, $description, $defaultsetting, null);
5191 * Lazy-load the available choices for the select box
5193 public function load_choices() {
5195 if (is_array($this->choices
)) {
5198 $this->choices
= array_merge(
5199 array('0' => get_string('choosedots')),
5200 get_string_manager()->get_list_of_countries($this->includeall
));
5207 * admin_setting_configselect for the default number of sections in a course,
5208 * simply so we can lazy-load the choices.
5210 * @copyright 2011 The Open University
5211 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5213 class admin_settings_num_course_sections
extends admin_setting_configselect
{
5214 public function __construct($name, $visiblename, $description, $defaultsetting) {
5215 parent
::__construct($name, $visiblename, $description, $defaultsetting, array());
5218 /** Lazy-load the available choices for the select box */
5219 public function load_choices() {
5220 $max = get_config('moodlecourse', 'maxsections');
5221 if (!isset($max) ||
!is_numeric($max)) {
5224 for ($i = 0; $i <= $max; $i++
) {
5225 $this->choices
[$i] = "$i";
5233 * Course category selection
5235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5237 class admin_settings_coursecat_select
extends admin_setting_configselect_autocomplete
{
5239 * Calls parent::__construct with specific arguments
5241 public function __construct($name, $visiblename, $description, $defaultsetting = 1) {
5242 parent
::__construct($name, $visiblename, $description, $defaultsetting, $choices = null);
5246 * Load the available choices for the select box
5250 public function load_choices() {
5251 if (is_array($this->choices
)) {
5254 $this->choices
= core_course_category
::make_categories_list('', 0, ' / ');
5261 * Special control for selecting days to backup
5263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5265 class admin_setting_special_backupdays
extends admin_setting_configmulticheckbox2
{
5267 * Calls parent::__construct with specific arguments
5269 public function __construct() {
5270 parent
::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
5271 $this->plugin
= 'backup';
5275 * Load the available choices for the select box
5277 * @return bool Always returns true
5279 public function load_choices() {
5280 if (is_array($this->choices
)) {
5283 $this->choices
= array();
5284 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5285 foreach ($days as $day) {
5286 $this->choices
[$day] = get_string($day, 'calendar');
5293 * Special setting for backup auto destination.
5297 * @copyright 2014 Frédéric Massart - FMCorz.net
5298 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5300 class admin_setting_special_backup_auto_destination
extends admin_setting_configdirectory
{
5303 * Calls parent::__construct with specific arguments.
5305 public function __construct() {
5306 parent
::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
5310 * Check if the directory must be set, depending on backup/backup_auto_storage.
5312 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
5313 * there will be conflicts if this validation happens before the other one.
5315 * @param string $data Form data.
5316 * @return string Empty when no errors.
5318 public function write_setting($data) {
5319 $storage = (int) get_config('backup', 'backup_auto_storage');
5320 if ($storage !== 0) {
5321 if (empty($data) ||
!file_exists($data) ||
!is_dir($data) ||
!is_writable($data) ) {
5322 // The directory must exist and be writable.
5323 return get_string('backuperrorinvaliddestination');
5326 return parent
::write_setting($data);
5332 * Special debug setting
5334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5336 class admin_setting_special_debug
extends admin_setting_configselect
{
5338 * Calls parent::__construct with specific arguments
5340 public function __construct() {
5341 parent
::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE
, NULL);
5345 * Load the available choices for the select box
5349 public function load_choices() {
5350 if (is_array($this->choices
)) {
5353 $this->choices
= array(DEBUG_NONE
=> get_string('debugnone', 'admin'),
5354 DEBUG_MINIMAL
=> get_string('debugminimal', 'admin'),
5355 DEBUG_NORMAL
=> get_string('debugnormal', 'admin'),
5356 DEBUG_ALL
=> get_string('debugall', 'admin'),
5357 DEBUG_DEVELOPER
=> get_string('debugdeveloper', 'admin'));
5364 * Special admin control
5366 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5368 class admin_setting_special_calendar_weekend
extends admin_setting
{
5370 * Calls parent::__construct with specific arguments
5372 public function __construct() {
5373 $name = 'calendar_weekend';
5374 $visiblename = get_string('calendar_weekend', 'admin');
5375 $description = get_string('helpweekenddays', 'admin');
5376 $default = array ('0', '6'); // Saturdays and Sundays
5377 parent
::__construct($name, $visiblename, $description, $default);
5381 * Gets the current settings as an array
5383 * @return mixed Null if none, else array of settings
5385 public function get_setting() {
5386 $result = $this->config_read($this->name
);
5387 if (is_null($result)) {
5390 if ($result === '') {
5393 $settings = array();
5394 for ($i=0; $i<7; $i++
) {
5395 if ($result & (1 << $i)) {
5403 * Save the new settings
5405 * @param array $data Array of new settings
5408 public function write_setting($data) {
5409 if (!is_array($data)) {
5412 unset($data['xxxxx']);
5414 foreach($data as $index) {
5415 $result |
= 1 << $index;
5417 return ($this->config_write($this->name
, $result) ?
'' : get_string('errorsetting', 'admin'));
5421 * Return XHTML to display the control
5423 * @param array $data array of selected days
5424 * @param string $query
5425 * @return string XHTML for display (field + wrapping div(s)
5427 public function output_html($data, $query='') {
5430 // The order matters very much because of the implied numeric keys.
5431 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
5432 $context = (object) [
5433 'name' => $this->get_full_name(),
5434 'id' => $this->get_id(),
5435 'days' => array_map(function($index) use ($days, $data) {
5438 'label' => get_string($days[$index], 'calendar'),
5439 'checked' => in_array($index, $data)
5441 }, array_keys($days))
5444 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
5446 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, false, '', NULL, $query);
5453 * Admin setting that allows a user to pick a behaviour.
5455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5457 class admin_setting_question_behaviour
extends admin_setting_configselect
{
5459 * @param string $name name of config variable
5460 * @param string $visiblename display name
5461 * @param string $description description
5462 * @param string $default default.
5464 public function __construct($name, $visiblename, $description, $default) {
5465 parent
::__construct($name, $visiblename, $description, $default, null);
5469 * Load list of behaviours as choices
5470 * @return bool true => success, false => error.
5472 public function load_choices() {
5474 require_once($CFG->dirroot
. '/question/engine/lib.php');
5475 $this->choices
= question_engine
::get_behaviour_options('');
5482 * Admin setting that allows a user to pick appropriate roles for something.
5484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5486 class admin_setting_pickroles
extends admin_setting_configmulticheckbox
{
5487 /** @var array Array of capabilities which identify roles */
5491 * @param string $name Name of config variable
5492 * @param string $visiblename Display name
5493 * @param string $description Description
5494 * @param array $types Array of archetypes which identify
5495 * roles that will be enabled by default.
5497 public function __construct($name, $visiblename, $description, $types) {
5498 parent
::__construct($name, $visiblename, $description, NULL, NULL);
5499 $this->types
= $types;
5503 * Load roles as choices
5505 * @return bool true=>success, false=>error
5507 public function load_choices() {
5509 if (during_initial_install()) {
5512 if (is_array($this->choices
)) {
5515 if ($roles = get_all_roles()) {
5516 $this->choices
= role_fix_names($roles, null, ROLENAME_ORIGINAL
, true);
5524 * Return the default setting for this control
5526 * @return array Array of default settings
5528 public function get_defaultsetting() {
5531 if (during_initial_install()) {
5535 foreach($this->types
as $archetype) {
5536 if ($caproles = get_archetype_roles($archetype)) {
5537 foreach ($caproles as $caprole) {
5538 $result[$caprole->id
] = 1;
5548 * Admin setting that is a list of installed filter plugins.
5550 * @copyright 2015 The Open University
5551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5553 class admin_setting_pickfilters
extends admin_setting_configmulticheckbox
{
5558 * @param string $name unique ascii name, either 'mysetting' for settings
5559 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5560 * @param string $visiblename localised name
5561 * @param string $description localised long description
5562 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5564 public function __construct($name, $visiblename, $description, $default) {
5565 if (empty($default)) {
5568 $this->load_choices();
5569 foreach ($default as $plugin) {
5570 if (!isset($this->choices
[$plugin])) {
5571 unset($default[$plugin]);
5574 parent
::__construct($name, $visiblename, $description, $default, null);
5577 public function load_choices() {
5578 if (is_array($this->choices
)) {
5581 $this->choices
= array();
5583 foreach (core_component
::get_plugin_list('filter') as $plugin => $unused) {
5584 $this->choices
[$plugin] = filter_get_name($plugin);
5592 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5594 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5596 class admin_setting_configtext_with_advanced
extends admin_setting_configtext
{
5599 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5600 * @param string $visiblename localised
5601 * @param string $description long localised info
5602 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5603 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5604 * @param int $size default field size
5606 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW
, $size=null) {
5607 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5608 $this->set_advanced_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['adv']));
5614 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5616 * @copyright 2009 Petr Skoda (http://skodak.org)
5617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5619 class admin_setting_configcheckbox_with_advanced
extends admin_setting_configcheckbox
{
5623 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5624 * @param string $visiblename localised
5625 * @param string $description long localised info
5626 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5627 * @param string $yes value used when checked
5628 * @param string $no value used when not checked
5630 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5631 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5632 $this->set_advanced_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['adv']));
5639 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5641 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5643 * @copyright 2010 Sam Hemelryk
5644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5646 class admin_setting_configcheckbox_with_lock
extends admin_setting_configcheckbox
{
5649 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5650 * @param string $visiblename localised
5651 * @param string $description long localised info
5652 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5653 * @param string $yes value used when checked
5654 * @param string $no value used when not checked
5656 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5657 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5658 $this->set_locked_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['locked']));
5664 * Autocomplete as you type form element.
5666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5668 class admin_setting_configselect_autocomplete
extends admin_setting_configselect
{
5669 /** @var boolean $tags Should we allow typing new entries to the field? */
5670 protected $tags = false;
5671 /** @var string $ajax Name of an AMD module to send/process ajax requests. */
5672 protected $ajax = '';
5673 /** @var string $placeholder Placeholder text for an empty list. */
5674 protected $placeholder = '';
5675 /** @var bool $casesensitive Whether the search has to be case-sensitive. */
5676 protected $casesensitive = false;
5677 /** @var bool $showsuggestions Show suggestions by default - but this can be turned off. */
5678 protected $showsuggestions = true;
5679 /** @var string $noselectionstring String that is shown when there are no selections. */
5680 protected $noselectionstring = '';
5683 * Returns XHTML select field and wrapping div(s)
5685 * @see output_select_html()
5687 * @param string $data the option to show as selected
5688 * @param string $query
5689 * @return string XHTML field and wrapping div
5691 public function output_html($data, $query='') {
5694 $html = parent
::output_html($data, $query);
5700 $this->placeholder
= get_string('search');
5702 $params = array('#' . $this->get_id(), $this->tags
, $this->ajax
,
5703 $this->placeholder
, $this->casesensitive
, $this->showsuggestions
, $this->noselectionstring
);
5705 // Load autocomplete wrapper for select2 library.
5706 $PAGE->requires
->js_call_amd('core/form-autocomplete', 'enhance', $params);
5713 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5717 class admin_setting_configselect_with_advanced
extends admin_setting_configselect
{
5719 * Calls parent::__construct with specific arguments
5721 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5722 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5723 $this->set_advanced_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['adv']));
5729 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5731 * @copyright 2017 Marina Glancy
5732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5734 class admin_setting_configselect_with_lock
extends admin_setting_configselect
{
5737 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5738 * or 'myplugin/mysetting' for ones in config_plugins.
5739 * @param string $visiblename localised
5740 * @param string $description long localised info
5741 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5742 * @param array $choices array of $value=>$label for each selection
5744 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5745 parent
::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5746 $this->set_locked_flag_options(admin_setting_flag
::ENABLED
, !empty($defaultsetting['locked']));
5752 * Graded roles in gradebook
5754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5756 class admin_setting_special_gradebookroles
extends admin_setting_pickroles
{
5758 * Calls parent::__construct with specific arguments
5760 public function __construct() {
5761 parent
::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5762 get_string('configgradebookroles', 'admin'),
5770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5772 class admin_setting_regradingcheckbox
extends admin_setting_configcheckbox
{
5774 * Saves the new settings passed in $data
5776 * @param string $data
5777 * @return mixed string or Array
5779 public function write_setting($data) {
5782 $oldvalue = $this->config_read($this->name
);
5783 $return = parent
::write_setting($data);
5784 $newvalue = $this->config_read($this->name
);
5786 if ($oldvalue !== $newvalue) {
5787 // force full regrading
5788 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5797 * Which roles to show on course description page
5799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5801 class admin_setting_special_coursecontact
extends admin_setting_pickroles
{
5803 * Calls parent::__construct with specific arguments
5805 public function __construct() {
5806 parent
::__construct('coursecontact', get_string('coursecontact', 'admin'),
5807 get_string('coursecontact_desc', 'admin'),
5808 array('editingteacher'));
5809 $this->set_updatedcallback(function (){
5810 cache
::make('core', 'coursecontacts')->purge();
5818 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5820 class admin_setting_special_gradelimiting
extends admin_setting_configcheckbox
{
5822 * Calls parent::__construct with specific arguments
5824 public function __construct() {
5825 parent
::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5826 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5830 * Old syntax of class constructor. Deprecated in PHP7.
5832 * @deprecated since Moodle 3.1
5834 public function admin_setting_special_gradelimiting() {
5835 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER
);
5836 self
::__construct();
5840 * Force site regrading
5842 function regrade_all() {
5844 require_once("$CFG->libdir/gradelib.php");
5845 grade_force_site_regrading();
5849 * Saves the new settings
5851 * @param mixed $data
5852 * @return string empty string or error message
5854 function write_setting($data) {
5855 $previous = $this->get_setting();
5857 if ($previous === null) {
5859 $this->regrade_all();
5862 if ($data != $previous) {
5863 $this->regrade_all();
5866 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
5872 * Special setting for $CFG->grade_minmaxtouse.
5875 * @copyright 2015 Frédéric Massart - FMCorz.net
5876 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5878 class admin_setting_special_grademinmaxtouse
extends admin_setting_configselect
{
5883 public function __construct() {
5884 parent
::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5885 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM
,
5887 GRADE_MIN_MAX_FROM_GRADE_ITEM
=> get_string('gradeitemminmax', 'grades'),
5888 GRADE_MIN_MAX_FROM_GRADE_GRADE
=> get_string('gradegrademinmax', 'grades')
5894 * Saves the new setting.
5896 * @param mixed $data
5897 * @return string empty string or error message
5899 function write_setting($data) {
5902 $previous = $this->get_setting();
5903 $result = parent
::write_setting($data);
5905 // If saved and the value has changed.
5906 if (empty($result) && $previous != $data) {
5907 require_once($CFG->libdir
. '/gradelib.php');
5908 grade_force_site_regrading();
5918 * Primary grade export plugin - has state tracking.
5920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5922 class admin_setting_special_gradeexport
extends admin_setting_configmulticheckbox
{
5924 * Calls parent::__construct with specific arguments
5926 public function __construct() {
5927 parent
::__construct('gradeexport', get_string('gradeexport', 'admin'),
5928 get_string('configgradeexport', 'admin'), array(), NULL);
5932 * Load the available choices for the multicheckbox
5934 * @return bool always returns true
5936 public function load_choices() {
5937 if (is_array($this->choices
)) {
5940 $this->choices
= array();
5942 if ($plugins = core_component
::get_plugin_list('gradeexport')) {
5943 foreach($plugins as $plugin => $unused) {
5944 $this->choices
[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5953 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5955 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5957 class admin_setting_special_gradepointdefault
extends admin_setting_configtext
{
5959 * Config gradepointmax constructor
5961 * @param string $name Overidden by "gradepointmax"
5962 * @param string $visiblename Overridden by "gradepointmax" language string.
5963 * @param string $description Overridden by "gradepointmax_help" language string.
5964 * @param string $defaultsetting Not used, overridden by 100.
5965 * @param mixed $paramtype Overridden by PARAM_INT.
5966 * @param int $size Overridden by 5.
5968 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT
, $size = 5) {
5969 $name = 'gradepointdefault';
5970 $visiblename = get_string('gradepointdefault', 'grades');
5971 $description = get_string('gradepointdefault_help', 'grades');
5972 $defaultsetting = 100;
5973 $paramtype = PARAM_INT
;
5975 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5979 * Validate data before storage
5980 * @param string $data The submitted data
5981 * @return bool|string true if ok, string if error found
5983 public function validate($data) {
5985 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax
)) {
5988 return get_string('gradepointdefault_validateerror', 'grades');
5995 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5997 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5999 class admin_setting_special_gradepointmax
extends admin_setting_configtext
{
6002 * Config gradepointmax constructor
6004 * @param string $name Overidden by "gradepointmax"
6005 * @param string $visiblename Overridden by "gradepointmax" language string.
6006 * @param string $description Overridden by "gradepointmax_help" language string.
6007 * @param string $defaultsetting Not used, overridden by 100.
6008 * @param mixed $paramtype Overridden by PARAM_INT.
6009 * @param int $size Overridden by 5.
6011 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT
, $size = 5) {
6012 $name = 'gradepointmax';
6013 $visiblename = get_string('gradepointmax', 'grades');
6014 $description = get_string('gradepointmax_help', 'grades');
6015 $defaultsetting = 100;
6016 $paramtype = PARAM_INT
;
6018 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
6022 * Save the selected setting
6024 * @param string $data The selected site
6025 * @return string empty string or error message
6027 public function write_setting($data) {
6029 $data = (int)$this->defaultsetting
;
6033 return parent
::write_setting($data);
6037 * Validate data before storage
6038 * @param string $data The submitted data
6039 * @return bool|string true if ok, string if error found
6041 public function validate($data) {
6042 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
6045 return get_string('gradepointmax_validateerror', 'grades');
6050 * Return an XHTML string for the setting
6051 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6052 * @param string $query search query to be highlighted
6053 * @return string XHTML to display control
6055 public function output_html($data, $query = '') {
6058 $default = $this->get_defaultsetting();
6059 $context = (object) [
6060 'size' => $this->size
,
6061 'id' => $this->get_id(),
6062 'name' => $this->get_full_name(),
6067 'forceltr' => $this->get_force_ltr()
6069 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
6071 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
6077 * Grade category settings
6079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6081 class admin_setting_gradecat_combo
extends admin_setting
{
6082 /** @var array Array of choices */
6086 * Sets choices and calls parent::__construct with passed arguments
6087 * @param string $name
6088 * @param string $visiblename
6089 * @param string $description
6090 * @param mixed $defaultsetting string or array depending on implementation
6091 * @param array $choices An array of choices for the control
6093 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
6094 $this->choices
= $choices;
6095 parent
::__construct($name, $visiblename, $description, $defaultsetting);
6099 * Return the current setting(s) array
6101 * @return array Array of value=>xx, forced=>xx, adv=>xx
6103 public function get_setting() {
6106 $value = $this->config_read($this->name
);
6107 $flag = $this->config_read($this->name
.'_flag');
6109 if (is_null($value) or is_null($flag)) {
6114 $forced = (boolean
)(1 & $flag); // first bit
6115 $adv = (boolean
)(2 & $flag); // second bit
6117 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
6121 * Save the new settings passed in $data
6123 * @todo Add vartype handling to ensure $data is array
6124 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6125 * @return string empty or error message
6127 public function write_setting($data) {
6130 $value = $data['value'];
6131 $forced = empty($data['forced']) ?
0 : 1;
6132 $adv = empty($data['adv']) ?
0 : 2;
6133 $flag = ($forced |
$adv); //bitwise or
6135 if (!in_array($value, array_keys($this->choices
))) {
6136 return 'Error setting ';
6139 $oldvalue = $this->config_read($this->name
);
6140 $oldflag = (int)$this->config_read($this->name
.'_flag');
6141 $oldforced = (1 & $oldflag); // first bit
6143 $result1 = $this->config_write($this->name
, $value);
6144 $result2 = $this->config_write($this->name
.'_flag', $flag);
6146 // force regrade if needed
6147 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
6148 require_once($CFG->libdir
.'/gradelib.php');
6149 grade_category
::updated_forced_settings();
6152 if ($result1 and $result2) {
6155 return get_string('errorsetting', 'admin');
6160 * Return XHTML to display the field and wrapping div
6162 * @todo Add vartype handling to ensure $data is array
6163 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
6164 * @param string $query
6165 * @return string XHTML to display control
6167 public function output_html($data, $query='') {
6170 $value = $data['value'];
6172 $default = $this->get_defaultsetting();
6173 if (!is_null($default)) {
6174 $defaultinfo = array();
6175 if (isset($this->choices
[$default['value']])) {
6176 $defaultinfo[] = $this->choices
[$default['value']];
6178 if (!empty($default['forced'])) {
6179 $defaultinfo[] = get_string('force');
6181 if (!empty($default['adv'])) {
6182 $defaultinfo[] = get_string('advanced');
6184 $defaultinfo = implode(', ', $defaultinfo);
6187 $defaultinfo = NULL;
6190 $options = $this->choices
;
6191 $context = (object) [
6192 'id' => $this->get_id(),
6193 'name' => $this->get_full_name(),
6194 'forced' => !empty($data['forced']),
6195 'advanced' => !empty($data['adv']),
6196 'options' => array_map(function($option) use ($options, $value) {
6199 'name' => $options[$option],
6200 'selected' => $option == $value
6202 }, array_keys($options)),
6205 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
6207 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $defaultinfo, $query);
6213 * Selection of grade report in user profiles
6215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6217 class admin_setting_grade_profilereport
extends admin_setting_configselect
{
6219 * Calls parent::__construct with specific arguments
6221 public function __construct() {
6222 parent
::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
6226 * Loads an array of choices for the configselect control
6228 * @return bool always return true
6230 public function load_choices() {
6231 if (is_array($this->choices
)) {
6234 $this->choices
= array();
6237 require_once($CFG->libdir
.'/gradelib.php');
6239 foreach (core_component
::get_plugin_list('gradereport') as $plugin => $plugindir) {
6240 if (file_exists($plugindir.'/lib.php')) {
6241 require_once($plugindir.'/lib.php');
6242 $functionname = 'grade_report_'.$plugin.'_profilereport';
6243 if (function_exists($functionname)) {
6244 $this->choices
[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
6253 * Provides a selection of grade reports to be used for "grades".
6255 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
6256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6258 class admin_setting_my_grades_report
extends admin_setting_configselect
{
6261 * Calls parent::__construct with specific arguments.
6263 public function __construct() {
6264 parent
::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
6265 new lang_string('mygrades_desc', 'grades'), 'overview', null);
6269 * Loads an array of choices for the configselect control.
6271 * @return bool always returns true.
6273 public function load_choices() {
6274 global $CFG; // Remove this line and behold the horror of behat test failures!
6275 $this->choices
= array();
6276 foreach (core_component
::get_plugin_list('gradereport') as $plugin => $plugindir) {
6277 if (file_exists($plugindir . '/lib.php')) {
6278 require_once($plugindir . '/lib.php');
6279 // Check to see if the class exists. Check the correct plugin convention first.
6280 if (class_exists('gradereport_' . $plugin)) {
6281 $classname = 'gradereport_' . $plugin;
6282 } else if (class_exists('grade_report_' . $plugin)) {
6283 // We are using the old plugin naming convention.
6284 $classname = 'grade_report_' . $plugin;
6288 if ($classname::supports_mygrades()) {
6289 $this->choices
[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
6293 // Add an option to specify an external url.
6294 $this->choices
['external'] = get_string('externalurl', 'grades');
6300 * Special class for register auth selection
6302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6304 class admin_setting_special_registerauth
extends admin_setting_configselect
{
6306 * Calls parent::__construct with specific arguments
6308 public function __construct() {
6309 parent
::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
6313 * Returns the default option
6315 * @return string empty or default option
6317 public function get_defaultsetting() {
6318 $this->load_choices();
6319 $defaultsetting = parent
::get_defaultsetting();
6320 if (array_key_exists($defaultsetting, $this->choices
)) {
6321 return $defaultsetting;
6328 * Loads the possible choices for the array
6330 * @return bool always returns true
6332 public function load_choices() {
6335 if (is_array($this->choices
)) {
6338 $this->choices
= array();
6339 $this->choices
[''] = get_string('disable');
6341 $authsenabled = get_enabled_auth_plugins();
6343 foreach ($authsenabled as $auth) {
6344 $authplugin = get_auth_plugin($auth);
6345 if (!$authplugin->can_signup()) {
6348 // Get the auth title (from core or own auth lang files)
6349 $authtitle = $authplugin->get_title();
6350 $this->choices
[$auth] = $authtitle;
6358 * General plugins manager
6360 class admin_page_pluginsoverview
extends admin_externalpage
{
6363 * Sets basic information about the external page
6365 public function __construct() {
6367 parent
::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
6368 "$CFG->wwwroot/$CFG->admin/plugins.php");
6373 * Module manage page
6375 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6377 class admin_page_managemods
extends admin_externalpage
{
6379 * Calls parent::__construct with specific arguments
6381 public function __construct() {
6383 parent
::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
6387 * Try to find the specified module
6389 * @param string $query The module to search for
6392 public function search($query) {
6394 if ($result = parent
::search($query)) {
6399 if ($modules = $DB->get_records('modules')) {
6400 foreach ($modules as $module) {
6401 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
6404 if (strpos($module->name
, $query) !== false) {
6408 $strmodulename = get_string('modulename', $module->name
);
6409 if (strpos(core_text
::strtolower($strmodulename), $query) !== false) {
6416 $result = new stdClass();
6417 $result->page
= $this;
6418 $result->settings
= array();
6419 return array($this->name
=> $result);
6428 * Special class for enrol plugins management.
6430 * @copyright 2010 Petr Skoda {@link http://skodak.org}
6431 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6433 class admin_setting_manageenrols
extends admin_setting
{
6435 * Calls parent::__construct with specific arguments
6437 public function __construct() {
6438 $this->nosave
= true;
6439 parent
::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
6443 * Always returns true, does nothing
6447 public function get_setting() {
6452 * Always returns true, does nothing
6456 public function get_defaultsetting() {
6461 * Always returns '', does not write anything
6463 * @return string Always returns ''
6465 public function write_setting($data) {
6466 // do not write any setting
6471 * Checks if $query is one of the available enrol plugins
6473 * @param string $query The string to search for
6474 * @return bool Returns true if found, false if not
6476 public function is_related($query) {
6477 if (parent
::is_related($query)) {
6481 $query = core_text
::strtolower($query);
6482 $enrols = enrol_get_plugins(false);
6483 foreach ($enrols as $name=>$enrol) {
6484 $localised = get_string('pluginname', 'enrol_'.$name);
6485 if (strpos(core_text
::strtolower($name), $query) !== false) {
6488 if (strpos(core_text
::strtolower($localised), $query) !== false) {
6496 * Builds the XHTML to display the control
6498 * @param string $data Unused
6499 * @param string $query
6502 public function output_html($data, $query='') {
6503 global $CFG, $OUTPUT, $DB, $PAGE;
6506 $strup = get_string('up');
6507 $strdown = get_string('down');
6508 $strsettings = get_string('settings');
6509 $strenable = get_string('enable');
6510 $strdisable = get_string('disable');
6511 $struninstall = get_string('uninstallplugin', 'core_admin');
6512 $strusage = get_string('enrolusage', 'enrol');
6513 $strversion = get_string('version');
6514 $strtest = get_string('testsettings', 'core_enrol');
6516 $pluginmanager = core_plugin_manager
::instance();
6518 $enrols_available = enrol_get_plugins(false);
6519 $active_enrols = enrol_get_plugins(true);
6521 $allenrols = array();
6522 foreach ($active_enrols as $key=>$enrol) {
6523 $allenrols[$key] = true;
6525 foreach ($enrols_available as $key=>$enrol) {
6526 $allenrols[$key] = true;
6528 // Now find all borked plugins and at least allow then to uninstall.
6529 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
6530 foreach ($condidates as $candidate) {
6531 if (empty($allenrols[$candidate])) {
6532 $allenrols[$candidate] = true;
6536 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
6537 $return .= $OUTPUT->box_start('generalbox enrolsui');
6539 $table = new html_table();
6540 $table->head
= array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
6541 $table->colclasses
= array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6542 $table->id
= 'courseenrolmentplugins';
6543 $table->attributes
['class'] = 'admintable generaltable';
6544 $table->data
= array();
6546 // Iterate through enrol plugins and add to the display table.
6548 $enrolcount = count($active_enrols);
6549 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
6551 foreach($allenrols as $enrol => $unused) {
6552 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
6553 $version = get_config('enrol_'.$enrol, 'version');
6554 if ($version === false) {
6558 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
6559 $name = get_string('pluginname', 'enrol_'.$enrol);
6564 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
6565 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
6566 $usage = "$ci / $cp";
6570 if (isset($active_enrols[$enrol])) {
6571 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
6572 $hideshow = "<a href=\"$aurl\">";
6573 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
6575 $displayname = $name;
6576 } else if (isset($enrols_available[$enrol])) {
6577 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
6578 $hideshow = "<a href=\"$aurl\">";
6579 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
6581 $displayname = $name;
6582 $class = 'dimmed_text';
6586 $displayname = '<span class="notifyproblem">'.$name.'</span>';
6588 if ($PAGE->theme
->resolve_image_location('icon', 'enrol_' . $name, false)) {
6589 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
6591 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
6594 // Up/down link (only if enrol is enabled).
6597 if ($updowncount > 1) {
6598 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
6599 $updown .= "<a href=\"$aurl\">";
6600 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a> ';
6602 $updown .= $OUTPUT->spacer() . ' ';
6604 if ($updowncount < $enrolcount) {
6605 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6606 $updown .= "<a href=\"$aurl\">";
6607 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a> ';
6609 $updown .= $OUTPUT->spacer() . ' ';
6614 // Add settings link.
6617 } else if ($surl = $plugininfo->get_settings_url()) {
6618 $settings = html_writer
::link($surl, $strsettings);
6623 // Add uninstall info.
6625 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6626 $uninstall = html_writer
::link($uninstallurl, $struninstall);
6630 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6631 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6632 $test = html_writer
::link($testsettingsurl, $strtest);
6635 // Add a row to the table.
6636 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6638 $row->attributes
['class'] = $class;
6640 $table->data
[] = $row;
6642 $printed[$enrol] = true;
6645 $return .= html_writer
::table($table);
6646 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6647 $return .= $OUTPUT->box_end();
6648 return highlight($query, $return);
6654 * Blocks manage page
6656 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6658 class admin_page_manageblocks
extends admin_externalpage
{
6660 * Calls parent::__construct with specific arguments
6662 public function __construct() {
6664 parent
::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6668 * Search for a specific block
6670 * @param string $query The string to search for
6673 public function search($query) {
6675 if ($result = parent
::search($query)) {
6680 if ($blocks = $DB->get_records('block')) {
6681 foreach ($blocks as $block) {
6682 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6685 if (strpos($block->name
, $query) !== false) {
6689 $strblockname = get_string('pluginname', 'block_'.$block->name
);
6690 if (strpos(core_text
::strtolower($strblockname), $query) !== false) {
6697 $result = new stdClass();
6698 $result->page
= $this;
6699 $result->settings
= array();
6700 return array($this->name
=> $result);
6708 * Message outputs configuration
6710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6712 class admin_page_managemessageoutputs
extends admin_externalpage
{
6714 * Calls parent::__construct with specific arguments
6716 public function __construct() {
6718 parent
::__construct('managemessageoutputs',
6719 get_string('defaultmessageoutputs', 'message'),
6720 new moodle_url('/admin/message.php')
6725 * Search for a specific message processor
6727 * @param string $query The string to search for
6730 public function search($query) {
6732 if ($result = parent
::search($query)) {
6737 if ($processors = get_message_processors()) {
6738 foreach ($processors as $processor) {
6739 if (!$processor->available
) {
6742 if (strpos($processor->name
, $query) !== false) {
6746 $strprocessorname = get_string('pluginname', 'message_'.$processor->name
);
6747 if (strpos(core_text
::strtolower($strprocessorname), $query) !== false) {
6754 $result = new stdClass();
6755 $result->page
= $this;
6756 $result->settings
= array();
6757 return array($this->name
=> $result);
6765 * Manage question behaviours page
6767 * @copyright 2011 The Open University
6768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6770 class admin_page_manageqbehaviours
extends admin_externalpage
{
6774 public function __construct() {
6776 parent
::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6777 new moodle_url('/admin/qbehaviours.php'));
6781 * Search question behaviours for the specified string
6783 * @param string $query The string to search for in question behaviours
6786 public function search($query) {
6788 if ($result = parent
::search($query)) {
6793 require_once($CFG->dirroot
. '/question/engine/lib.php');
6794 foreach (core_component
::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6795 if (strpos(core_text
::strtolower(question_engine
::get_behaviour_name($behaviour)),
6796 $query) !== false) {
6802 $result = new stdClass();
6803 $result->page
= $this;
6804 $result->settings
= array();
6805 return array($this->name
=> $result);
6814 * Question type manage page
6816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6818 class admin_page_manageqtypes
extends admin_externalpage
{
6820 * Calls parent::__construct with specific arguments
6822 public function __construct() {
6824 parent
::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6825 new moodle_url('/admin/qtypes.php'));
6829 * Search question types for the specified string
6831 * @param string $query The string to search for in question types
6834 public function search($query) {
6836 if ($result = parent
::search($query)) {
6841 require_once($CFG->dirroot
. '/question/engine/bank.php');
6842 foreach (question_bank
::get_all_qtypes() as $qtype) {
6843 if (strpos(core_text
::strtolower($qtype->local_name()), $query) !== false) {
6849 $result = new stdClass();
6850 $result->page
= $this;
6851 $result->settings
= array();
6852 return array($this->name
=> $result);
6860 class admin_page_manageportfolios
extends admin_externalpage
{
6862 * Calls parent::__construct with specific arguments
6864 public function __construct() {
6866 parent
::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6867 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6871 * Searches page for the specified string.
6872 * @param string $query The string to search for
6873 * @return bool True if it is found on this page
6875 public function search($query) {
6877 if ($result = parent
::search($query)) {
6882 $portfolios = core_component
::get_plugin_list('portfolio');
6883 foreach ($portfolios as $p => $dir) {
6884 if (strpos($p, $query) !== false) {
6890 foreach (portfolio_instances(false, false) as $instance) {
6891 $title = $instance->get('name');
6892 if (strpos(core_text
::strtolower($title), $query) !== false) {
6900 $result = new stdClass();
6901 $result->page
= $this;
6902 $result->settings
= array();
6903 return array($this->name
=> $result);
6911 class admin_page_managerepositories
extends admin_externalpage
{
6913 * Calls parent::__construct with specific arguments
6915 public function __construct() {
6917 parent
::__construct('managerepositories', get_string('manage',
6918 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6922 * Searches page for the specified string.
6923 * @param string $query The string to search for
6924 * @return bool True if it is found on this page
6926 public function search($query) {
6928 if ($result = parent
::search($query)) {
6933 $repositories= core_component
::get_plugin_list('repository');
6934 foreach ($repositories as $p => $dir) {
6935 if (strpos($p, $query) !== false) {
6941 foreach (repository
::get_types() as $instance) {
6942 $title = $instance->get_typename();
6943 if (strpos(core_text
::strtolower($title), $query) !== false) {
6951 $result = new stdClass();
6952 $result->page
= $this;
6953 $result->settings
= array();
6954 return array($this->name
=> $result);
6963 * Special class for authentication administration.
6965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6967 class admin_setting_manageauths
extends admin_setting
{
6969 * Calls parent::__construct with specific arguments
6971 public function __construct() {
6972 $this->nosave
= true;
6973 parent
::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6977 * Always returns true
6981 public function get_setting() {
6986 * Always returns true
6990 public function get_defaultsetting() {
6995 * Always returns '' and doesn't write anything
6997 * @return string Always returns ''
6999 public function write_setting($data) {
7000 // do not write any setting
7005 * Search to find if Query is related to auth plugin
7007 * @param string $query The string to search for
7008 * @return bool true for related false for not
7010 public function is_related($query) {
7011 if (parent
::is_related($query)) {
7015 $authsavailable = core_component
::get_plugin_list('auth');
7016 foreach ($authsavailable as $auth => $dir) {
7017 if (strpos($auth, $query) !== false) {
7020 $authplugin = get_auth_plugin($auth);
7021 $authtitle = $authplugin->get_title();
7022 if (strpos(core_text
::strtolower($authtitle), $query) !== false) {
7030 * Return XHTML to display control
7032 * @param mixed $data Unused
7033 * @param string $query
7034 * @return string highlight
7036 public function output_html($data, $query='') {
7037 global $CFG, $OUTPUT, $DB;
7040 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
7041 'settings', 'edit', 'name', 'enable', 'disable',
7042 'up', 'down', 'none', 'users'));
7043 $txt->updown
= "$txt->up/$txt->down";
7044 $txt->uninstall
= get_string('uninstallplugin', 'core_admin');
7045 $txt->testsettings
= get_string('testsettings', 'core_auth');
7047 $authsavailable = core_component
::get_plugin_list('auth');
7048 get_enabled_auth_plugins(true); // fix the list of enabled auths
7049 if (empty($CFG->auth
)) {
7050 $authsenabled = array();
7052 $authsenabled = explode(',', $CFG->auth
);
7055 // construct the display array, with enabled auth plugins at the top, in order
7056 $displayauths = array();
7057 $registrationauths = array();
7058 $registrationauths[''] = $txt->disable
;
7059 $authplugins = array();
7060 foreach ($authsenabled as $auth) {
7061 $authplugin = get_auth_plugin($auth);
7062 $authplugins[$auth] = $authplugin;
7063 /// Get the auth title (from core or own auth lang files)
7064 $authtitle = $authplugin->get_title();
7066 $displayauths[$auth] = $authtitle;
7067 if ($authplugin->can_signup()) {
7068 $registrationauths[$auth] = $authtitle;
7072 foreach ($authsavailable as $auth => $dir) {
7073 if (array_key_exists($auth, $displayauths)) {
7074 continue; //already in the list
7076 $authplugin = get_auth_plugin($auth);
7077 $authplugins[$auth] = $authplugin;
7078 /// Get the auth title (from core or own auth lang files)
7079 $authtitle = $authplugin->get_title();
7081 $displayauths[$auth] = $authtitle;
7082 if ($authplugin->can_signup()) {
7083 $registrationauths[$auth] = $authtitle;
7087 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
7088 $return .= $OUTPUT->box_start('generalbox authsui');
7090 $table = new html_table();
7091 $table->head
= array($txt->name
, $txt->users
, $txt->enable
, $txt->updown
, $txt->settings
, $txt->testsettings
, $txt->uninstall
);
7092 $table->colclasses
= array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7093 $table->data
= array();
7094 $table->attributes
['class'] = 'admintable generaltable';
7095 $table->id
= 'manageauthtable';
7097 //add always enabled plugins first
7098 $displayname = $displayauths['manual'];
7099 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
7100 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
7101 $table->data
[] = array($displayname, $usercount, '', '', $settings, '', '');
7102 $displayname = $displayauths['nologin'];
7103 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
7104 $table->data
[] = array($displayname, $usercount, '', '', '', '', '');
7107 // iterate through auth plugins and add to the display table
7109 $authcount = count($authsenabled);
7110 $url = "auth.php?sesskey=" . sesskey();
7111 foreach ($displayauths as $auth => $name) {
7112 if ($auth == 'manual' or $auth == 'nologin') {
7117 if (in_array($auth, $authsenabled)) {
7118 $hideshow = "<a href=\"$url&action=disable&auth=$auth\">";
7119 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7121 $displayname = $name;
7124 $hideshow = "<a href=\"$url&action=enable&auth=$auth\">";
7125 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7127 $displayname = $name;
7128 $class = 'dimmed_text';
7131 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
7133 // up/down link (only if auth is enabled)
7136 if ($updowncount > 1) {
7137 $updown .= "<a href=\"$url&action=up&auth=$auth\">";
7138 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a> ';
7141 $updown .= $OUTPUT->spacer() . ' ';
7143 if ($updowncount < $authcount) {
7144 $updown .= "<a href=\"$url&action=down&auth=$auth\">";
7145 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a> ';
7148 $updown .= $OUTPUT->spacer() . ' ';
7154 if (file_exists($CFG->dirroot
.'/auth/'.$auth.'/settings.php')) {
7155 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
7156 } else if (file_exists($CFG->dirroot
.'/auth/'.$auth.'/config.html')) {
7157 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
7164 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
7165 $uninstall = html_writer
::link($uninstallurl, $txt->uninstall
);
7169 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
7170 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
7171 $test = html_writer
::link($testurl, $txt->testsettings
);
7174 // Add a row to the table.
7175 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
7177 $row->attributes
['class'] = $class;
7179 $table->data
[] = $row;
7181 $return .= html_writer
::table($table);
7182 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
7183 $return .= $OUTPUT->box_end();
7184 return highlight($query, $return);
7190 * Special class for authentication administration.
7192 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7194 class admin_setting_manageeditors
extends admin_setting
{
7196 * Calls parent::__construct with specific arguments
7198 public function __construct() {
7199 $this->nosave
= true;
7200 parent
::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
7204 * Always returns true, does nothing
7208 public function get_setting() {
7213 * Always returns true, does nothing
7217 public function get_defaultsetting() {
7222 * Always returns '', does not write anything
7224 * @return string Always returns ''
7226 public function write_setting($data) {
7227 // do not write any setting
7232 * Checks if $query is one of the available editors
7234 * @param string $query The string to search for
7235 * @return bool Returns true if found, false if not
7237 public function is_related($query) {
7238 if (parent
::is_related($query)) {
7242 $editors_available = editors_get_available();
7243 foreach ($editors_available as $editor=>$editorstr) {
7244 if (strpos($editor, $query) !== false) {
7247 if (strpos(core_text
::strtolower($editorstr), $query) !== false) {
7255 * Builds the XHTML to display the control
7257 * @param string $data Unused
7258 * @param string $query
7261 public function output_html($data, $query='') {
7262 global $CFG, $OUTPUT;
7265 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7266 'up', 'down', 'none'));
7267 $struninstall = get_string('uninstallplugin', 'core_admin');
7269 $txt->updown
= "$txt->up/$txt->down";
7271 $editors_available = editors_get_available();
7272 $active_editors = explode(',', $CFG->texteditors
);
7274 $active_editors = array_reverse($active_editors);
7275 foreach ($active_editors as $key=>$editor) {
7276 if (empty($editors_available[$editor])) {
7277 unset($active_editors[$key]);
7279 $name = $editors_available[$editor];
7280 unset($editors_available[$editor]);
7281 $editors_available[$editor] = $name;
7284 if (empty($active_editors)) {
7285 //$active_editors = array('textarea');
7287 $editors_available = array_reverse($editors_available, true);
7288 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
7289 $return .= $OUTPUT->box_start('generalbox editorsui');
7291 $table = new html_table();
7292 $table->head
= array($txt->name
, $txt->enable
, $txt->updown
, $txt->settings
, $struninstall);
7293 $table->colclasses
= array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7294 $table->id
= 'editormanagement';
7295 $table->attributes
['class'] = 'admintable generaltable';
7296 $table->data
= array();
7298 // iterate through auth plugins and add to the display table
7300 $editorcount = count($active_editors);
7301 $url = "editors.php?sesskey=" . sesskey();
7302 foreach ($editors_available as $editor => $name) {
7305 if (in_array($editor, $active_editors)) {
7306 $hideshow = "<a href=\"$url&action=disable&editor=$editor\">";
7307 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
7309 $displayname = $name;
7312 $hideshow = "<a href=\"$url&action=enable&editor=$editor\">";
7313 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
7315 $displayname = $name;
7316 $class = 'dimmed_text';
7319 // up/down link (only if auth is enabled)
7322 if ($updowncount > 1) {
7323 $updown .= "<a href=\"$url&action=up&editor=$editor\">";
7324 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a> ';
7327 $updown .= $OUTPUT->spacer() . ' ';
7329 if ($updowncount < $editorcount) {
7330 $updown .= "<a href=\"$url&action=down&editor=$editor\">";
7331 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a> ';
7334 $updown .= $OUTPUT->spacer() . ' ';
7340 if (file_exists($CFG->dirroot
.'/lib/editor/'.$editor.'/settings.php')) {
7341 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
7342 $settings = "<a href='$eurl'>{$txt->settings}</a>";
7348 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
7349 $uninstall = html_writer
::link($uninstallurl, $struninstall);
7352 // Add a row to the table.
7353 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7355 $row->attributes
['class'] = $class;
7357 $table->data
[] = $row;
7359 $return .= html_writer
::table($table);
7360 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
7361 $return .= $OUTPUT->box_end();
7362 return highlight($query, $return);
7367 * Special class for antiviruses administration.
7369 * @copyright 2015 Ruslan Kabalin, Lancaster University.
7370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7372 class admin_setting_manageantiviruses
extends admin_setting
{
7374 * Calls parent::__construct with specific arguments
7376 public function __construct() {
7377 $this->nosave
= true;
7378 parent
::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
7382 * Always returns true, does nothing
7386 public function get_setting() {
7391 * Always returns true, does nothing
7395 public function get_defaultsetting() {
7400 * Always returns '', does not write anything
7402 * @param string $data Unused
7403 * @return string Always returns ''
7405 public function write_setting($data) {
7406 // Do not write any setting.
7411 * Checks if $query is one of the available editors
7413 * @param string $query The string to search for
7414 * @return bool Returns true if found, false if not
7416 public function is_related($query) {
7417 if (parent
::is_related($query)) {
7421 $antivirusesavailable = \core\antivirus\manager
::get_available();
7422 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
7423 if (strpos($antivirus, $query) !== false) {
7426 if (strpos(core_text
::strtolower($antivirusstr), $query) !== false) {
7434 * Builds the XHTML to display the control
7436 * @param string $data Unused
7437 * @param string $query
7440 public function output_html($data, $query='') {
7441 global $CFG, $OUTPUT;
7444 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
7445 'up', 'down', 'none'));
7446 $struninstall = get_string('uninstallplugin', 'core_admin');
7448 $txt->updown
= "$txt->up/$txt->down";
7450 $antivirusesavailable = \core\antivirus\manager
::get_available();
7451 $activeantiviruses = explode(',', $CFG->antiviruses
);
7453 $activeantiviruses = array_reverse($activeantiviruses);
7454 foreach ($activeantiviruses as $key => $antivirus) {
7455 if (empty($antivirusesavailable[$antivirus])) {
7456 unset($activeantiviruses[$key]);
7458 $name = $antivirusesavailable[$antivirus];
7459 unset($antivirusesavailable[$antivirus]);
7460 $antivirusesavailable[$antivirus] = $name;
7463 $antivirusesavailable = array_reverse($antivirusesavailable, true);
7464 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
7465 $return .= $OUTPUT->box_start('generalbox antivirusesui');
7467 $table = new html_table();
7468 $table->head
= array($txt->name
, $txt->enable
, $txt->updown
, $txt->settings
, $struninstall);
7469 $table->colclasses
= array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7470 $table->id
= 'antivirusmanagement';
7471 $table->attributes
['class'] = 'admintable generaltable';
7472 $table->data
= array();
7474 // Iterate through auth plugins and add to the display table.
7476 $antiviruscount = count($activeantiviruses);
7477 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
7478 foreach ($antivirusesavailable as $antivirus => $name) {
7481 if (in_array($antivirus, $activeantiviruses)) {
7482 $hideshowurl = $baseurl;
7483 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
7484 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
7485 $hideshow = html_writer
::link($hideshowurl, $hideshowimg);
7487 $displayname = $name;
7489 $hideshowurl = $baseurl;
7490 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
7491 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
7492 $hideshow = html_writer
::link($hideshowurl, $hideshowimg);
7494 $displayname = $name;
7495 $class = 'dimmed_text';
7501 if ($updowncount > 1) {
7502 $updownurl = $baseurl;
7503 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
7504 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
7505 $updown = html_writer
::link($updownurl, $updownimg);
7507 $updownimg = $OUTPUT->spacer();
7509 if ($updowncount < $antiviruscount) {
7510 $updownurl = $baseurl;
7511 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
7512 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
7513 $updown = html_writer
::link($updownurl, $updownimg);
7515 $updownimg = $OUTPUT->spacer();
7521 if (file_exists($CFG->dirroot
.'/lib/antivirus/'.$antivirus.'/settings.php')) {
7522 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
7523 $settings = html_writer
::link($eurl, $txt->settings
);
7529 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
7530 $uninstall = html_writer
::link($uninstallurl, $struninstall);
7533 // Add a row to the table.
7534 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
7536 $row->attributes
['class'] = $class;
7538 $table->data
[] = $row;
7540 $return .= html_writer
::table($table);
7541 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer
::empty_tag('br') . get_string('tablenosave', 'admin');
7542 $return .= $OUTPUT->box_end();
7543 return highlight($query, $return);
7548 * Special class for license administration.
7550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7551 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7552 * @todo MDL-45184 This class will be deleted in Moodle 4.1.
7554 class admin_setting_managelicenses
extends admin_setting
{
7556 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7557 * @todo MDL-45184 This class will be deleted in Moodle 4.1
7559 public function __construct() {
7562 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7565 // Replace admin setting load with new external page load for tool_licensemanager, if not loaded already.
7566 if (!is_null($ADMIN->locate('licensemanager'))) {
7567 $temp = new admin_externalpage('licensemanager',
7568 get_string('licensemanager', 'tool_licensemanager'),
7569 \tool_licensemanager\helper
::get_licensemanager_url());
7571 $ADMIN->add('license', $temp);
7576 * Always returns true, does nothing
7578 * @deprecated since Moodle 3.9 MDL-45184.
7579 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7583 public function get_setting() {
7584 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7591 * Always returns true, does nothing
7593 * @deprecated since Moodle 3.9 MDL-45184.
7594 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7598 public function get_defaultsetting() {
7599 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7606 * Always returns '', does not write anything
7608 * @deprecated since Moodle 3.9 MDL-45184.
7609 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7611 * @return string Always returns ''
7613 public function write_setting($data) {
7614 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7617 // do not write any setting
7622 * Builds the XHTML to display the control
7624 * @deprecated since Moodle 3.9 MDL-45184. Please use \tool_licensemanager\manager instead.
7625 * @todo MDL-45184 This method will be deleted in Moodle 4.1
7627 * @param string $data Unused
7628 * @param string $query
7631 public function output_html($data, $query='') {
7632 debugging('admin_setting_managelicenses class is deprecated. Please use \tool_licensemanager\manager instead.',
7635 redirect(\tool_licensemanager\helper
::get_licensemanager_url());
7640 * Course formats manager. Allows to enable/disable formats and jump to settings
7642 class admin_setting_manageformats
extends admin_setting
{
7645 * Calls parent::__construct with specific arguments
7647 public function __construct() {
7648 $this->nosave
= true;
7649 parent
::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7653 * Always returns true
7657 public function get_setting() {
7662 * Always returns true
7666 public function get_defaultsetting() {
7671 * Always returns '' and doesn't write anything
7673 * @param mixed $data string or array, must not be NULL
7674 * @return string Always returns ''
7676 public function write_setting($data) {
7677 // do not write any setting
7682 * Search to find if Query is related to format plugin
7684 * @param string $query The string to search for
7685 * @return bool true for related false for not
7687 public function is_related($query) {
7688 if (parent
::is_related($query)) {
7691 $formats = core_plugin_manager
::instance()->get_plugins_of_type('format');
7692 foreach ($formats as $format) {
7693 if (strpos($format->component
, $query) !== false ||
7694 strpos(core_text
::strtolower($format->displayname
), $query) !== false) {
7702 * Return XHTML to display control
7704 * @param mixed $data Unused
7705 * @param string $query
7706 * @return string highlight
7708 public function output_html($data, $query='') {
7709 global $CFG, $OUTPUT;
7711 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7712 $return .= $OUTPUT->box_start('generalbox formatsui');
7714 $formats = core_plugin_manager
::instance()->get_plugins_of_type('format');
7717 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7718 $txt->uninstall
= get_string('uninstallplugin', 'core_admin');
7719 $txt->updown
= "$txt->up/$txt->down";
7721 $table = new html_table();
7722 $table->head
= array($txt->name
, $txt->enable
, $txt->updown
, $txt->uninstall
, $txt->settings
);
7723 $table->align
= array('left', 'center', 'center', 'center', 'center');
7724 $table->attributes
['class'] = 'manageformattable generaltable admintable';
7725 $table->data
= array();
7728 $defaultformat = get_config('moodlecourse', 'format');
7729 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7730 foreach ($formats as $format) {
7731 $url = new moodle_url('/admin/courseformats.php',
7732 array('sesskey' => sesskey(), 'format' => $format->name
));
7735 if ($format->is_enabled()) {
7736 $strformatname = $format->displayname
;
7737 if ($defaultformat === $format->name
) {
7738 $hideshow = $txt->default;
7740 $hideshow = html_writer
::link($url->out(false, array('action' => 'disable')),
7741 $OUTPUT->pix_icon('t/hide', $txt->disable
, 'moodle', array('class' => 'iconsmall')));
7744 $strformatname = $format->displayname
;
7745 $class = 'dimmed_text';
7746 $hideshow = html_writer
::link($url->out(false, array('action' => 'enable')),
7747 $OUTPUT->pix_icon('t/show', $txt->enable
, 'moodle', array('class' => 'iconsmall')));
7751 $updown .= html_writer
::link($url->out(false, array('action' => 'up')),
7752 $OUTPUT->pix_icon('t/up', $txt->up
, 'moodle', array('class' => 'iconsmall'))). '';
7756 if ($cnt < count($formats) - 1) {
7757 $updown .= ' '.html_writer
::link($url->out(false, array('action' => 'down')),
7758 $OUTPUT->pix_icon('t/down', $txt->down
, 'moodle', array('class' => 'iconsmall')));
7764 if ($format->get_settings_url()) {
7765 $settings = html_writer
::link($format->get_settings_url(), $txt->settings
);
7768 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('format_'.$format->name
, 'manage')) {
7769 $uninstall = html_writer
::link($uninstallurl, $txt->uninstall
);
7771 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7773 $row->attributes
['class'] = $class;
7775 $table->data
[] = $row;
7777 $return .= html_writer
::table($table);
7778 $link = html_writer
::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7779 $return .= html_writer
::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7780 $return .= $OUTPUT->box_end();
7781 return highlight($query, $return);
7786 * Custom fields manager. Allows to enable/disable custom fields and jump to settings.
7789 * @copyright 2018 Toni Barbera
7790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7792 class admin_setting_managecustomfields
extends admin_setting
{
7795 * Calls parent::__construct with specific arguments
7797 public function __construct() {
7798 $this->nosave
= true;
7799 parent
::__construct('customfieldsui', new lang_string('managecustomfields', 'core_admin'), '', '');
7803 * Always returns true
7807 public function get_setting() {
7812 * Always returns true
7816 public function get_defaultsetting() {
7821 * Always returns '' and doesn't write anything
7823 * @param mixed $data string or array, must not be NULL
7824 * @return string Always returns ''
7826 public function write_setting($data) {
7827 // Do not write any setting.
7832 * Search to find if Query is related to format plugin
7834 * @param string $query The string to search for
7835 * @return bool true for related false for not
7837 public function is_related($query) {
7838 if (parent
::is_related($query)) {
7841 $formats = core_plugin_manager
::instance()->get_plugins_of_type('customfield');
7842 foreach ($formats as $format) {
7843 if (strpos($format->component
, $query) !== false ||
7844 strpos(core_text
::strtolower($format->displayname
), $query) !== false) {
7852 * Return XHTML to display control
7854 * @param mixed $data Unused
7855 * @param string $query
7856 * @return string highlight
7858 public function output_html($data, $query='') {
7859 global $CFG, $OUTPUT;
7861 $return = $OUTPUT->heading(new lang_string('customfields', 'core_customfield'), 3, 'main');
7862 $return .= $OUTPUT->box_start('generalbox customfieldsui');
7864 $fields = core_plugin_manager
::instance()->get_plugins_of_type('customfield');
7866 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down'));
7867 $txt->uninstall
= get_string('uninstallplugin', 'core_admin');
7868 $txt->updown
= "$txt->up/$txt->down";
7870 $table = new html_table();
7871 $table->head
= array($txt->name
, $txt->enable
, $txt->uninstall
, $txt->settings
);
7872 $table->align
= array('left', 'center', 'center', 'center');
7873 $table->attributes
['class'] = 'managecustomfieldtable generaltable admintable';
7874 $table->data
= array();
7876 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7877 foreach ($fields as $field) {
7878 $url = new moodle_url('/admin/customfields.php',
7879 array('sesskey' => sesskey(), 'field' => $field->name
));
7881 if ($field->is_enabled()) {
7882 $strfieldname = $field->displayname
;
7883 $hideshow = html_writer
::link($url->out(false, array('action' => 'disable')),
7884 $OUTPUT->pix_icon('t/hide', $txt->disable
, 'moodle', array('class' => 'iconsmall')));
7886 $strfieldname = $field->displayname
;
7887 $class = 'dimmed_text';
7888 $hideshow = html_writer
::link($url->out(false, array('action' => 'enable')),
7889 $OUTPUT->pix_icon('t/show', $txt->enable
, 'moodle', array('class' => 'iconsmall')));
7892 if ($field->get_settings_url()) {
7893 $settings = html_writer
::link($field->get_settings_url(), $txt->settings
);
7896 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('customfield_'.$field->name
, 'manage')) {
7897 $uninstall = html_writer
::link($uninstallurl, $txt->uninstall
);
7899 $row = new html_table_row(array($strfieldname, $hideshow, $uninstall, $settings));
7900 $table->data
[] = $row;
7902 $return .= html_writer
::table($table);
7903 $return .= $OUTPUT->box_end();
7904 return highlight($query, $return);
7909 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7911 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7914 class admin_setting_managedataformats
extends admin_setting
{
7917 * Calls parent::__construct with specific arguments
7919 public function __construct() {
7920 $this->nosave
= true;
7921 parent
::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7925 * Always returns true
7929 public function get_setting() {
7934 * Always returns true
7938 public function get_defaultsetting() {
7943 * Always returns '' and doesn't write anything
7945 * @param mixed $data string or array, must not be NULL
7946 * @return string Always returns ''
7948 public function write_setting($data) {
7949 // Do not write any setting.
7954 * Search to find if Query is related to format plugin
7956 * @param string $query The string to search for
7957 * @return bool true for related false for not
7959 public function is_related($query) {
7960 if (parent
::is_related($query)) {
7963 $formats = core_plugin_manager
::instance()->get_plugins_of_type('dataformat');
7964 foreach ($formats as $format) {
7965 if (strpos($format->component
, $query) !== false ||
7966 strpos(core_text
::strtolower($format->displayname
), $query) !== false) {
7974 * Return XHTML to display control
7976 * @param mixed $data Unused
7977 * @param string $query
7978 * @return string highlight
7980 public function output_html($data, $query='') {
7981 global $CFG, $OUTPUT;
7984 $formats = core_plugin_manager
::instance()->get_plugins_of_type('dataformat');
7986 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7987 $txt->uninstall
= get_string('uninstallplugin', 'core_admin');
7988 $txt->updown
= "$txt->up/$txt->down";
7990 $table = new html_table();
7991 $table->head
= array($txt->name
, $txt->enable
, $txt->updown
, $txt->uninstall
, $txt->settings
);
7992 $table->align
= array('left', 'center', 'center', 'center', 'center');
7993 $table->attributes
['class'] = 'manageformattable generaltable admintable';
7994 $table->data
= array();
7997 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7999 foreach ($formats as $format) {
8000 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
8004 foreach ($formats as $format) {
8005 $status = $format->get_status();
8006 $url = new moodle_url('/admin/dataformats.php',
8007 array('sesskey' => sesskey(), 'name' => $format->name
));
8010 if ($format->is_enabled()) {
8011 $strformatname = $format->displayname
;
8012 if ($totalenabled == 1&& $format->is_enabled()) {
8015 $hideshow = html_writer
::link($url->out(false, array('action' => 'disable')),
8016 $OUTPUT->pix_icon('t/hide', $txt->disable
, 'moodle', array('class' => 'iconsmall')));
8019 $class = 'dimmed_text';
8020 $strformatname = $format->displayname
;
8021 $hideshow = html_writer
::link($url->out(false, array('action' => 'enable')),
8022 $OUTPUT->pix_icon('t/show', $txt->enable
, 'moodle', array('class' => 'iconsmall')));
8027 $updown .= html_writer
::link($url->out(false, array('action' => 'up')),
8028 $OUTPUT->pix_icon('t/up', $txt->up
, 'moodle', array('class' => 'iconsmall'))). '';
8032 if ($cnt < count($formats) - 1) {
8033 $updown .= ' '.html_writer
::link($url->out(false, array('action' => 'down')),
8034 $OUTPUT->pix_icon('t/down', $txt->down
, 'moodle', array('class' => 'iconsmall')));
8040 if ($status === core_plugin_manager
::PLUGIN_STATUS_MISSING
) {
8041 $uninstall = get_string('status_missing', 'core_plugin');
8042 } else if ($status === core_plugin_manager
::PLUGIN_STATUS_NEW
) {
8043 $uninstall = get_string('status_new', 'core_plugin');
8044 } else if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('dataformat_'.$format->name
, 'manage')) {
8045 if ($totalenabled != 1 ||
!$format->is_enabled()) {
8046 $uninstall = html_writer
::link($uninstallurl, $txt->uninstall
);
8051 if ($format->get_settings_url()) {
8052 $settings = html_writer
::link($format->get_settings_url(), $txt->settings
);
8055 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
8057 $row->attributes
['class'] = $class;
8059 $table->data
[] = $row;
8062 $return .= html_writer
::table($table);
8063 return highlight($query, $return);
8068 * Special class for filter administration.
8070 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8072 class admin_page_managefilters
extends admin_externalpage
{
8074 * Calls parent::__construct with specific arguments
8076 public function __construct() {
8078 parent
::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
8082 * Searches all installed filters for specified filter
8084 * @param string $query The filter(string) to search for
8085 * @param string $query
8087 public function search($query) {
8089 if ($result = parent
::search($query)) {
8094 $filternames = filter_get_all_installed();
8095 foreach ($filternames as $path => $strfiltername) {
8096 if (strpos(core_text
::strtolower($strfiltername), $query) !== false) {
8100 if (strpos($path, $query) !== false) {
8107 $result = new stdClass
;
8108 $result->page
= $this;
8109 $result->settings
= array();
8110 return array($this->name
=> $result);
8118 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8119 * Requires a get_rank method on the plugininfo class for sorting.
8121 * @copyright 2017 Damyon Wiese
8122 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8124 abstract class admin_setting_manage_plugins
extends admin_setting
{
8127 * Get the admin settings section name (just a unique string)
8131 public function get_section_name() {
8132 return 'manage' . $this->get_plugin_type() . 'plugins';
8136 * Get the admin settings section title (use get_string).
8140 abstract public function get_section_title();
8143 * Get the type of plugin to manage.
8147 abstract public function get_plugin_type();
8150 * Get the name of the second column.
8154 public function get_info_column_name() {
8159 * Get the type of plugin to manage.
8161 * @param plugininfo The plugin info class.
8164 abstract public function get_info_column($plugininfo);
8167 * Calls parent::__construct with specific arguments
8169 public function __construct() {
8170 $this->nosave
= true;
8171 parent
::__construct($this->get_section_name(), $this->get_section_title(), '', '');
8175 * Always returns true, does nothing
8179 public function get_setting() {
8184 * Always returns true, does nothing
8188 public function get_defaultsetting() {
8193 * Always returns '', does not write anything
8195 * @param mixed $data
8196 * @return string Always returns ''
8198 public function write_setting($data) {
8199 // Do not write any setting.
8204 * Checks if $query is one of the available plugins of this type
8206 * @param string $query The string to search for
8207 * @return bool Returns true if found, false if not
8209 public function is_related($query) {
8210 if (parent
::is_related($query)) {
8214 $query = core_text
::strtolower($query);
8215 $plugins = core_plugin_manager
::instance()->get_plugins_of_type($this->get_plugin_type());
8216 foreach ($plugins as $name => $plugin) {
8217 $localised = $plugin->displayname
;
8218 if (strpos(core_text
::strtolower($name), $query) !== false) {
8221 if (strpos(core_text
::strtolower($localised), $query) !== false) {
8229 * The URL for the management page for this plugintype.
8231 * @return moodle_url
8233 protected function get_manage_url() {
8234 return new moodle_url('/admin/updatesetting.php');
8238 * Builds the HTML to display the control.
8240 * @param string $data Unused
8241 * @param string $query
8244 public function output_html($data, $query = '') {
8245 global $CFG, $OUTPUT, $DB, $PAGE;
8247 $context = (object) [
8248 'manageurl' => new moodle_url($this->get_manage_url(), [
8249 'type' => $this->get_plugin_type(),
8250 'sesskey' => sesskey(),
8252 'infocolumnname' => $this->get_info_column_name(),
8256 $pluginmanager = core_plugin_manager
::instance();
8257 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
8258 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
8259 $plugins = array_merge($enabled, $allplugins);
8260 foreach ($plugins as $key => $plugin) {
8261 $pluginlink = new moodle_url($context->manageurl
, ['plugin' => $key]);
8263 $pluginkey = (object) [
8264 'plugin' => $plugin->displayname
,
8265 'enabled' => $plugin->is_enabled(),
8268 'movedownlink' => '',
8269 'settingslink' => $plugin->get_settings_url(),
8270 'uninstalllink' => '',
8274 // Enable/Disable link.
8275 $togglelink = new moodle_url($pluginlink);
8276 if ($plugin->is_enabled()) {
8277 $toggletarget = false;
8278 $togglelink->param('action', 'disable');
8280 if (count($context->plugins
)) {
8281 // This is not the first plugin.
8282 $pluginkey->moveuplink
= new moodle_url($pluginlink, ['action' => 'up']);
8285 if (count($enabled) > count($context->plugins
) +
1) {
8286 // This is not the last plugin.
8287 $pluginkey->movedownlink
= new moodle_url($pluginlink, ['action' => 'down']);
8290 $pluginkey->info
= $this->get_info_column($plugin);
8292 $toggletarget = true;
8293 $togglelink->param('action', 'enable');
8296 $pluginkey->toggletarget
= $toggletarget;
8297 $pluginkey->togglelink
= $togglelink;
8299 $frankenstyle = $plugin->type
. '_' . $plugin->name
;
8300 if ($uninstalllink = core_plugin_manager
::instance()->get_uninstall_url($frankenstyle, 'manage')) {
8301 // This plugin supports uninstallation.
8302 $pluginkey->uninstalllink
= $uninstalllink;
8305 if (!empty($this->get_info_column_name())) {
8306 // This plugintype has an info column.
8307 $pluginkey->info
= $this->get_info_column($plugin);
8310 $context->plugins
[] = $pluginkey;
8313 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
8314 return highlight($query, $str);
8319 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
8320 * Requires a get_rank method on the plugininfo class for sorting.
8322 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
8323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8325 class admin_setting_manage_fileconverter_plugins
extends admin_setting_manage_plugins
{
8326 public function get_section_title() {
8327 return get_string('type_fileconverter_plural', 'plugin');
8330 public function get_plugin_type() {
8331 return 'fileconverter';
8334 public function get_info_column_name() {
8335 return get_string('supportedconversions', 'plugin');
8338 public function get_info_column($plugininfo) {
8339 return $plugininfo->get_supported_conversions();
8344 * Special class for media player plugins management.
8346 * @copyright 2016 Marina Glancy
8347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8349 class admin_setting_managemediaplayers
extends admin_setting
{
8351 * Calls parent::__construct with specific arguments
8353 public function __construct() {
8354 $this->nosave
= true;
8355 parent
::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
8359 * Always returns true, does nothing
8363 public function get_setting() {
8368 * Always returns true, does nothing
8372 public function get_defaultsetting() {
8377 * Always returns '', does not write anything
8379 * @param mixed $data
8380 * @return string Always returns ''
8382 public function write_setting($data) {
8383 // Do not write any setting.
8388 * Checks if $query is one of the available enrol plugins
8390 * @param string $query The string to search for
8391 * @return bool Returns true if found, false if not
8393 public function is_related($query) {
8394 if (parent
::is_related($query)) {
8398 $query = core_text
::strtolower($query);
8399 $plugins = core_plugin_manager
::instance()->get_plugins_of_type('media');
8400 foreach ($plugins as $name => $plugin) {
8401 $localised = $plugin->displayname
;
8402 if (strpos(core_text
::strtolower($name), $query) !== false) {
8405 if (strpos(core_text
::strtolower($localised), $query) !== false) {
8413 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8414 * @return \core\plugininfo\media[]
8416 protected function get_sorted_plugins() {
8417 $pluginmanager = core_plugin_manager
::instance();
8419 $plugins = $pluginmanager->get_plugins_of_type('media');
8420 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8422 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
8423 \core_collator
::asort_objects_by_method($plugins, 'get_rank', \core_collator
::SORT_NUMERIC
);
8425 $order = array_values($enabledplugins);
8426 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
8428 $sortedplugins = array();
8429 foreach ($order as $name) {
8430 $sortedplugins[$name] = $plugins[$name];
8433 return $sortedplugins;
8437 * Builds the XHTML to display the control
8439 * @param string $data Unused
8440 * @param string $query
8443 public function output_html($data, $query='') {
8444 global $CFG, $OUTPUT, $DB, $PAGE;
8447 $strup = get_string('up');
8448 $strdown = get_string('down');
8449 $strsettings = get_string('settings');
8450 $strenable = get_string('enable');
8451 $strdisable = get_string('disable');
8452 $struninstall = get_string('uninstallplugin', 'core_admin');
8453 $strversion = get_string('version');
8454 $strname = get_string('name');
8455 $strsupports = get_string('supports', 'core_media');
8457 $pluginmanager = core_plugin_manager
::instance();
8459 $plugins = $this->get_sorted_plugins();
8460 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
8462 $return = $OUTPUT->box_start('generalbox mediaplayersui');
8464 $table = new html_table();
8465 $table->head
= array($strname, $strsupports, $strversion,
8466 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
8467 $table->colclasses
= array('leftalign', 'leftalign', 'centeralign',
8468 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8469 $table->id
= 'mediaplayerplugins';
8470 $table->attributes
['class'] = 'admintable generaltable';
8471 $table->data
= array();
8473 // Iterate through media plugins and add to the display table.
8475 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
8477 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8479 $usedextensions = [];
8480 foreach ($plugins as $name => $plugin) {
8481 $url->param('media', $name);
8482 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
8483 $version = $plugininfo->versiondb
;
8484 $supports = $plugininfo->supports($usedextensions);
8488 if (!$plugininfo->is_installed_and_upgraded()) {
8491 $displayname = '<span class="notifyproblem">'.$name.'</span>';
8493 $enabled = $plugininfo->is_enabled();
8495 $hideshow = html_writer
::link(new moodle_url($url, array('action' => 'disable')),
8496 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
8498 $hideshow = html_writer
::link(new moodle_url($url, array('action' => 'enable')),
8499 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
8500 $class = 'dimmed_text';
8502 $displayname = $plugin->displayname
;
8503 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
8504 $displayname .= ' ' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
8507 if ($PAGE->theme
->resolve_image_location('icon', 'media_' . $name, false)) {
8508 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
8510 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
8513 // Up/down link (only if enrol is enabled).
8516 if ($updowncount > 1) {
8517 $updown = html_writer
::link(new moodle_url($url, array('action' => 'up')),
8518 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
8522 if ($updowncount < count($enabledplugins)) {
8523 $updown .= html_writer
::link(new moodle_url($url, array('action' => 'down')),
8524 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
8532 $status = $plugininfo->get_status();
8533 if ($status === core_plugin_manager
::PLUGIN_STATUS_MISSING
) {
8534 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
8536 if ($status === core_plugin_manager
::PLUGIN_STATUS_NEW
) {
8537 $uninstall = get_string('status_new', 'core_plugin');
8538 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
8539 $uninstall .= html_writer
::link($uninstallurl, $struninstall);
8543 if ($plugininfo->get_settings_url()) {
8544 $settings = html_writer
::link($plugininfo->get_settings_url(), $strsettings);
8547 // Add a row to the table.
8548 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
8550 $row->attributes
['class'] = $class;
8552 $table->data
[] = $row;
8554 $printed[$name] = true;
8557 $return .= html_writer
::table($table);
8558 $return .= $OUTPUT->box_end();
8559 return highlight($query, $return);
8565 * Content bank content types manager. Allow reorder and to enable/disable content bank content types and jump to settings
8567 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
8568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8570 class admin_setting_managecontentbankcontenttypes
extends admin_setting
{
8573 * Calls parent::__construct with specific arguments
8575 public function __construct() {
8576 $this->nosave
= true;
8577 parent
::__construct('contentbank', new lang_string('managecontentbanktypes'), '', '');
8581 * Always returns true
8585 public function get_setting() {
8590 * Always returns true
8594 public function get_defaultsetting() {
8599 * Always returns '' and doesn't write anything
8601 * @param mixed $data string or array, must not be NULL
8602 * @return string Always returns ''
8604 public function write_setting($data) {
8605 // Do not write any setting.
8610 * Search to find if Query is related to content bank plugin
8612 * @param string $query The string to search for
8613 * @return bool true for related false for not
8615 public function is_related($query) {
8616 if (parent
::is_related($query)) {
8619 $types = core_plugin_manager
::instance()->get_plugins_of_type('contenttype');
8620 foreach ($types as $type) {
8621 if (strpos($type->component
, $query) !== false ||
8622 strpos(core_text
::strtolower($type->displayname
), $query) !== false) {
8630 * Return XHTML to display control
8632 * @param mixed $data Unused
8633 * @param string $query
8634 * @return string highlight
8636 public function output_html($data, $query='') {
8637 global $CFG, $OUTPUT;
8640 $types = core_plugin_manager
::instance()->get_plugins_of_type('contenttype');
8641 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'order', 'up', 'down', 'default'));
8642 $txt->uninstall
= get_string('uninstallplugin', 'core_admin');
8644 $table = new html_table();
8645 $table->head
= array($txt->name
, $txt->enable
, $txt->order
, $txt->settings
, $txt->uninstall
);
8646 $table->align
= array('left', 'center', 'center', 'center', 'center');
8647 $table->attributes
['class'] = 'managecontentbanktable generaltable admintable';
8648 $table->data
= array();
8649 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
8653 foreach ($types as $type) {
8654 if ($type->is_enabled() && $type->is_installed_and_upgraded()) {
8659 foreach ($types as $type) {
8660 $url = new moodle_url('/admin/contentbank.php',
8661 array('sesskey' => sesskey(), 'name' => $type->name
));
8664 $strtypename = $type->displayname
;
8665 if ($type->is_enabled()) {
8666 $hideshow = html_writer
::link($url->out(false, array('action' => 'disable')),
8667 $OUTPUT->pix_icon('t/hide', $txt->disable
, 'moodle', array('class' => 'iconsmall')));
8669 $class = 'dimmed_text';
8670 $hideshow = html_writer
::link($url->out(false, array('action' => 'enable')),
8671 $OUTPUT->pix_icon('t/show', $txt->enable
, 'moodle', array('class' => 'iconsmall')));
8676 $updown .= html_writer
::link($url->out(false, array('action' => 'up')),
8677 $OUTPUT->pix_icon('t/up', $txt->up
, 'moodle', array('class' => 'iconsmall'))). '';
8681 if ($count < count($types) - 1) {
8682 $updown .= ' '.html_writer
::link($url->out(false, array('action' => 'down')),
8683 $OUTPUT->pix_icon('t/down', $txt->down
, 'moodle', array('class' => 'iconsmall')));
8689 if ($type->get_settings_url()) {
8690 $settings = html_writer
::link($type->get_settings_url(), $txt->settings
);
8694 if ($uninstallurl = core_plugin_manager
::instance()->get_uninstall_url('contenttype_'.$type->name
, 'manage')) {
8695 $uninstall = html_writer
::link($uninstallurl, $txt->uninstall
);
8698 $row = new html_table_row(array($strtypename, $hideshow, $updown, $settings, $uninstall));
8700 $row->attributes
['class'] = $class;
8702 $table->data
[] = $row;
8705 $return .= html_writer
::table($table);
8706 return highlight($query, $return);
8711 * Initialise admin page - this function does require login and permission
8712 * checks specified in page definition.
8714 * This function must be called on each admin page before other code.
8716 * @global moodle_page $PAGE
8718 * @param string $section name of page
8719 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
8720 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
8721 * added to the turn blocks editing on/off form, so this page reloads correctly.
8722 * @param string $actualurl if the actual page being viewed is not the normal one for this
8723 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
8724 * @param array $options Additional options that can be specified for page setup.
8725 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
8727 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
8728 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
8730 $PAGE->set_context(null); // hack - set context to something, by default to system context
8733 require_login(null, false);
8735 if (!empty($options['pagelayout'])) {
8736 // A specific page layout has been requested.
8737 $PAGE->set_pagelayout($options['pagelayout']);
8738 } else if ($section === 'upgradesettings') {
8739 $PAGE->set_pagelayout('maintenance');
8741 $PAGE->set_pagelayout('admin');
8744 $adminroot = admin_get_root(false, false); // settings not required for external pages
8745 $extpage = $adminroot->locate($section, true);
8747 if (empty($extpage) or !($extpage instanceof admin_externalpage
)) {
8748 // The requested section isn't in the admin tree
8749 // It could be because the user has inadequate capapbilities or because the section doesn't exist
8750 if (!has_capability('moodle/site:config', context_system
::instance())) {
8751 // The requested section could depend on a different capability
8752 // but most likely the user has inadequate capabilities
8753 print_error('accessdenied', 'admin');
8755 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
8759 // this eliminates our need to authenticate on the actual pages
8760 if (!$extpage->check_access()) {
8761 print_error('accessdenied', 'admin');
8765 navigation_node
::require_admin_tree();
8767 // $PAGE->set_extra_button($extrabutton); TODO
8770 $actualurl = $extpage->url
;
8773 $PAGE->set_url($actualurl, $extraurlparams);
8774 if (strpos($PAGE->pagetype
, 'admin-') !== 0) {
8775 $PAGE->set_pagetype('admin-' . $PAGE->pagetype
);
8778 if (empty($SITE->fullname
) ||
empty($SITE->shortname
)) {
8779 // During initial install.
8780 $strinstallation = get_string('installation', 'install');
8781 $strsettings = get_string('settings');
8782 $PAGE->navbar
->add($strsettings);
8783 $PAGE->set_title($strinstallation);
8784 $PAGE->set_heading($strinstallation);
8785 $PAGE->set_cacheable(false);
8789 // Locate the current item on the navigation and make it active when found.
8790 $path = $extpage->path
;
8791 $node = $PAGE->settingsnav
;
8792 while ($node && count($path) > 0) {
8793 $node = $node->get(array_pop($path));
8796 $node->make_active();
8800 $adminediting = optional_param('adminedit', -1, PARAM_BOOL
);
8801 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
8802 $USER->editing
= $adminediting;
8805 $visiblepathtosection = array_reverse($extpage->visiblepath
);
8807 if ($PAGE->user_allowed_editing()) {
8808 if ($PAGE->user_is_editing()) {
8809 $caption = get_string('blockseditoff');
8810 $url = new moodle_url($PAGE->url
, array('adminedit'=>'0', 'sesskey'=>sesskey()));
8812 $caption = get_string('blocksediton');
8813 $url = new moodle_url($PAGE->url
, array('adminedit'=>'1', 'sesskey'=>sesskey()));
8815 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
8818 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
8819 $PAGE->set_heading($SITE->fullname
);
8821 // prevent caching in nav block
8822 $PAGE->navigation
->clear_cache();
8826 * Returns the reference to admin tree root
8828 * @return object admin_root object
8830 function admin_get_root($reload=false, $requirefulltree=true) {
8831 global $CFG, $DB, $OUTPUT, $ADMIN;
8833 if (is_null($ADMIN)) {
8834 // create the admin tree!
8835 $ADMIN = new admin_root($requirefulltree);
8838 if ($reload or ($requirefulltree and !$ADMIN->fulltree
)) {
8839 $ADMIN->purge_children($requirefulltree);
8842 if (!$ADMIN->loaded
) {
8843 // we process this file first to create categories first and in correct order
8844 require($CFG->dirroot
.'/'.$CFG->admin
.'/settings/top.php');
8846 // now we process all other files in admin/settings to build the admin tree
8847 foreach (glob($CFG->dirroot
.'/'.$CFG->admin
.'/settings/*.php') as $file) {
8848 if ($file == $CFG->dirroot
.'/'.$CFG->admin
.'/settings/top.php') {
8851 if ($file == $CFG->dirroot
.'/'.$CFG->admin
.'/settings/plugins.php') {
8852 // plugins are loaded last - they may insert pages anywhere
8857 require($CFG->dirroot
.'/'.$CFG->admin
.'/settings/plugins.php');
8859 $ADMIN->loaded
= true;
8865 /// settings utility functions
8868 * This function applies default settings.
8869 * Because setting the defaults of some settings can enable other settings,
8870 * this function is called recursively until no more new settings are found.
8872 * @param object $node, NULL means complete tree, null by default
8873 * @param bool $unconditional if true overrides all values with defaults, true by default
8874 * @param array $admindefaultsettings default admin settings to apply. Used recursively
8875 * @param array $settingsoutput The names and values of the changed settings. Used recursively
8876 * @return array $settingsoutput The names and values of the changed settings
8878 function admin_apply_default_settings($node=null, $unconditional=true, $admindefaultsettings=array(), $settingsoutput=array()) {
8881 if (is_null($node)) {
8882 core_plugin_manager
::reset_caches();
8883 $node = admin_get_root(true, true);
8884 $counter = count($settingsoutput);
8887 if ($node instanceof admin_category
) {
8888 $entries = array_keys($node->children
);
8889 foreach ($entries as $entry) {
8890 $settingsoutput = admin_apply_default_settings(
8891 $node->children
[$entry], $unconditional, $admindefaultsettings, $settingsoutput
8895 } else if ($node instanceof admin_settingpage
) {
8896 foreach ($node->settings
as $setting) {
8897 if (!$unconditional && !is_null($setting->get_setting())) {
8898 // Do not override existing defaults.
8901 $defaultsetting = $setting->get_defaultsetting();
8902 if (is_null($defaultsetting)) {
8903 // No value yet - default maybe applied after admin user creation or in upgradesettings.
8907 $settingname = $node->name
. '_' . $setting->name
; // Get a unique name for the setting.
8909 if (!array_key_exists($settingname, $admindefaultsettings)) { // Only update a setting if not already processed.
8910 $admindefaultsettings[$settingname] = $settingname;
8911 $settingsoutput[$settingname] = $defaultsetting;
8913 // Set the default for this setting.
8914 $setting->write_setting($defaultsetting);
8915 $setting->write_setting_flags(null);
8917 unset($admindefaultsettings[$settingname]); // Remove processed settings.
8922 // Call this function recursively until all settings are processed.
8923 if (($node instanceof admin_root
) && ($counter != count($settingsoutput))) {
8924 $settingsoutput = admin_apply_default_settings(null, $unconditional, $admindefaultsettings, $settingsoutput);
8926 // Just in case somebody modifies the list of active plugins directly.
8927 core_plugin_manager
::reset_caches();
8929 return $settingsoutput;
8933 * Store changed settings, this function updates the errors variable in $ADMIN
8935 * @param object $formdata from form
8936 * @return int number of changed settings
8938 function admin_write_settings($formdata) {
8939 global $CFG, $SITE, $DB;
8941 $olddbsessions = !empty($CFG->dbsessions
);
8942 $formdata = (array)$formdata;
8945 foreach ($formdata as $fullname=>$value) {
8946 if (strpos($fullname, 's_') !== 0) {
8947 continue; // not a config value
8949 $data[$fullname] = $value;
8952 $adminroot = admin_get_root();
8953 $settings = admin_find_write_settings($adminroot, $data);
8956 foreach ($settings as $fullname=>$setting) {
8957 /** @var $setting admin_setting */
8958 $original = $setting->get_setting();
8959 $error = $setting->write_setting($data[$fullname]);
8960 if ($error !== '') {
8961 $adminroot->errors
[$fullname] = new stdClass();
8962 $adminroot->errors
[$fullname]->data
= $data[$fullname];
8963 $adminroot->errors
[$fullname]->id
= $setting->get_id();
8964 $adminroot->errors
[$fullname]->error
= $error;
8966 $setting->write_setting_flags($data);
8968 if ($setting->post_write_settings($original)) {
8973 if ($olddbsessions != !empty($CFG->dbsessions
)) {
8977 // Now update $SITE - just update the fields, in case other people have a
8978 // a reference to it (e.g. $PAGE, $COURSE).
8979 $newsite = $DB->get_record('course', array('id'=>$SITE->id
));
8980 foreach (get_object_vars($newsite) as $field => $value) {
8981 $SITE->$field = $value;
8984 // now reload all settings - some of them might depend on the changed
8985 admin_get_root(true);
8990 * Internal recursive function - finds all settings from submitted form
8992 * @param object $node Instance of admin_category, or admin_settingpage
8993 * @param array $data
8996 function admin_find_write_settings($node, $data) {
9003 if ($node instanceof admin_category
) {
9004 if ($node->check_access()) {
9005 $entries = array_keys($node->children
);
9006 foreach ($entries as $entry) {
9007 $return = array_merge($return, admin_find_write_settings($node->children
[$entry], $data));
9011 } else if ($node instanceof admin_settingpage
) {
9012 if ($node->check_access()) {
9013 foreach ($node->settings
as $setting) {
9014 $fullname = $setting->get_full_name();
9015 if (array_key_exists($fullname, $data)) {
9016 $return[$fullname] = $setting;
9027 * Internal function - prints the search results
9029 * @param string $query String to search for
9030 * @return string empty or XHTML
9032 function admin_search_settings_html($query) {
9033 global $CFG, $OUTPUT, $PAGE;
9035 if (core_text
::strlen($query) < 2) {
9038 $query = core_text
::strtolower($query);
9040 $adminroot = admin_get_root();
9041 $findings = $adminroot->search($query);
9042 $savebutton = false;
9044 $tpldata = (object) [
9045 'actionurl' => $PAGE->url
->out(false),
9047 'sesskey' => sesskey(),
9050 foreach ($findings as $found) {
9051 $page = $found->page
;
9052 $settings = $found->settings
;
9053 if ($page->is_hidden()) {
9054 // hidden pages are not displayed in search results
9058 $heading = highlight($query, $page->visiblename
);
9060 if ($page instanceof admin_externalpage
) {
9061 $headingurl = new moodle_url($page->url
);
9062 } else if ($page instanceof admin_settingpage
) {
9063 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name
]);
9068 // Locate the page in the admin root and populate its visiblepath attribute.
9070 $located = $adminroot->locate($page->name
, true);
9072 foreach ($located->visiblepath
as $pathitem) {
9073 array_unshift($path, (string) $pathitem);
9077 $sectionsettings = [];
9078 if (!empty($settings)) {
9079 foreach ($settings as $setting) {
9080 if (empty($setting->nosave
)) {
9083 $fullname = $setting->get_full_name();
9084 if (array_key_exists($fullname, $adminroot->errors
)) {
9085 $data = $adminroot->errors
[$fullname]->data
;
9087 $data = $setting->get_setting();
9088 // do not use defaults if settings not available - upgradesettings handles the defaults!
9090 $sectionsettings[] = $setting->output_html($data, $query);
9094 $tpldata->results
[] = (object) [
9095 'title' => $heading,
9097 'url' => $headingurl->out(false),
9098 'settings' => $sectionsettings
9102 $tpldata->showsave
= $savebutton;
9103 $tpldata->hasresults
= !empty($tpldata->results
);
9105 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
9109 * Internal function - returns arrays of html pages with uninitialised settings
9111 * @param object $node Instance of admin_category or admin_settingpage
9114 function admin_output_new_settings_by_page($node) {
9118 if ($node instanceof admin_category
) {
9119 $entries = array_keys($node->children
);
9120 foreach ($entries as $entry) {
9121 $return +
= admin_output_new_settings_by_page($node->children
[$entry]);
9124 } else if ($node instanceof admin_settingpage
) {
9125 $newsettings = array();
9126 foreach ($node->settings
as $setting) {
9127 if (is_null($setting->get_setting())) {
9128 $newsettings[] = $setting;
9131 if (count($newsettings) > 0) {
9132 $adminroot = admin_get_root();
9133 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename
, 2, 'main');
9134 $page .= '<fieldset class="adminsettings">'."\n";
9135 foreach ($newsettings as $setting) {
9136 $fullname = $setting->get_full_name();
9137 if (array_key_exists($fullname, $adminroot->errors
)) {
9138 $data = $adminroot->errors
[$fullname]->data
;
9140 $data = $setting->get_setting();
9141 if (is_null($data)) {
9142 $data = $setting->get_defaultsetting();
9145 $page .= '<div class="clearer"><!-- --></div>'."\n";
9146 $page .= $setting->output_html($data);
9148 $page .= '</fieldset>';
9149 $return[$node->name
] = $page;
9157 * Format admin settings
9159 * @param object $setting
9160 * @param string $title label element
9161 * @param string $form form fragment, html code - not highlighted automatically
9162 * @param string $description
9163 * @param mixed $label link label to id, true by default or string being the label to connect it to
9164 * @param string $warning warning text
9165 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
9166 * @param string $query search query to be highlighted
9167 * @return string XHTML
9169 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
9170 global $CFG, $OUTPUT;
9172 $context = (object) [
9173 'name' => empty($setting->plugin
) ?
$setting->name
: "$setting->plugin | $setting->name",
9174 'fullname' => $setting->get_full_name(),
9177 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
9178 if ($label === true) {
9179 $context->labelfor
= $setting->get_id();
9180 } else if ($label === false) {
9181 $context->labelfor
= '';
9183 $context->labelfor
= $label;
9186 $form .= $setting->output_setting_flags();
9188 $context->warning
= $warning;
9189 $context->override
= '';
9190 if (empty($setting->plugin
)) {
9191 if (array_key_exists($setting->name
, $CFG->config_php_settings
)) {
9192 $context->override
= get_string('configoverride', 'admin');
9195 if (array_key_exists($setting->plugin
, $CFG->forced_plugin_settings
) and array_key_exists($setting->name
, $CFG->forced_plugin_settings
[$setting->plugin
])) {
9196 $context->override
= get_string('configoverride', 'admin');
9200 $defaults = array();
9201 if (!is_null($defaultinfo)) {
9202 if ($defaultinfo === '') {
9203 $defaultinfo = get_string('emptysettingvalue', 'admin');
9205 $defaults[] = $defaultinfo;
9208 $context->default = null;
9209 $setting->get_setting_flag_defaults($defaults);
9210 if (!empty($defaults)) {
9211 $defaultinfo = implode(', ', $defaults);
9212 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
9213 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
9217 $context->error
= '';
9218 $adminroot = admin_get_root();
9219 if (array_key_exists($context->fullname
, $adminroot->errors
)) {
9220 $context->error
= $adminroot->errors
[$context->fullname
]->error
;
9223 if ($dependenton = $setting->get_dependent_on()) {
9224 $context->dependenton
= get_string('settingdependenton', 'admin', implode(', ', $dependenton));
9227 $context->id
= 'admin-' . $setting->name
;
9228 $context->title
= highlightfast($query, $title);
9229 $context->name
= highlightfast($query, $context->name
);
9230 $context->description
= highlight($query, markdown_to_html($description));
9231 $context->element
= $form;
9232 $context->forceltr
= $setting->get_force_ltr();
9233 $context->customcontrol
= $setting->has_custom_form_control();
9235 return $OUTPUT->render_from_template('core_admin/setting', $context);
9239 * Based on find_new_settings{@link ()} in upgradesettings.php
9240 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
9242 * @param object $node Instance of admin_category, or admin_settingpage
9243 * @return boolean true if any settings haven't been initialised, false if they all have
9245 function any_new_admin_settings($node) {
9247 if ($node instanceof admin_category
) {
9248 $entries = array_keys($node->children
);
9249 foreach ($entries as $entry) {
9250 if (any_new_admin_settings($node->children
[$entry])) {
9255 } else if ($node instanceof admin_settingpage
) {
9256 foreach ($node->settings
as $setting) {
9257 if ($setting->get_setting() === NULL) {
9267 * Given a table and optionally a column name should replaces be done?
9269 * @param string $table name
9270 * @param string $column name
9271 * @return bool success or fail
9273 function db_should_replace($table, $column = '', $additionalskiptables = ''): bool {
9275 // TODO: this is horrible hack, we should have a hook and each plugin should be responsible for proper replacing...
9276 $skiptables = ['config', 'config_plugins', 'filter_config', 'sessions',
9277 'events_queue', 'repository_instance_config', 'block_instances', 'files'];
9279 // Additional skip tables.
9280 if (!empty($additionalskiptables)) {
9281 $skiptables = array_merge($skiptables, explode(',', str_replace(' ', '', $additionalskiptables)));
9284 // Don't process these.
9285 if (in_array($table, $skiptables)) {
9289 // To be safe never replace inside a table that looks related to logging.
9290 if (preg_match('/(^|_)logs?($|_)/', $table)) {
9294 // Do column based exclusions.
9295 if (!empty($column)) {
9296 // Don't touch anything that looks like a hash.
9297 if (preg_match('/hash$/', $column)) {
9306 * Moved from admin/replace.php so that we can use this in cron
9308 * @param string $search string to look for
9309 * @param string $replace string to replace
9310 * @return bool success or fail
9312 function db_replace($search, $replace, $additionalskiptables = '') {
9313 global $DB, $CFG, $OUTPUT;
9315 // Turn off time limits, sometimes upgrades can be slow.
9316 core_php_time_limit
::raise();
9318 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
9321 foreach ($tables as $table) {
9323 if (!db_should_replace($table, '', $additionalskiptables)) {
9327 if ($columns = $DB->get_columns($table)) {
9328 $DB->set_debug(true);
9329 foreach ($columns as $column) {
9330 if (!db_should_replace($table, $column->name
)) {
9333 $DB->replace_all_text($table, $column, $search, $replace);
9335 $DB->set_debug(false);
9339 // delete modinfo caches
9340 rebuild_course_cache(0, true);
9342 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
9343 $blocks = core_component
::get_plugin_list('block');
9344 foreach ($blocks as $blockname=>$fullblock) {
9345 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
9349 if (!is_readable($fullblock.'/lib.php')) {
9353 $function = 'block_'.$blockname.'_global_db_replace';
9354 include_once($fullblock.'/lib.php');
9355 if (!function_exists($function)) {
9359 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
9360 $function($search, $replace);
9361 echo $OUTPUT->notification("...finished", 'notifysuccess');
9364 // Trigger an event.
9366 'context' => context_system
::instance(),
9368 'search' => $search,
9369 'replace' => $replace
9372 $event = \core\event\database_text_field_content_replaced
::create($eventargs);
9381 * Manage repository settings
9383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9385 class admin_setting_managerepository
extends admin_setting
{
9390 * calls parent::__construct with specific arguments
9392 public function __construct() {
9394 parent
::__construct('managerepository', get_string('manage', 'repository'), '', '');
9395 $this->baseurl
= $CFG->wwwroot
. '/' . $CFG->admin
. '/repository.php?sesskey=' . sesskey();
9399 * Always returns true, does nothing
9403 public function get_setting() {
9408 * Always returns true does nothing
9412 public function get_defaultsetting() {
9417 * Always returns s_managerepository
9419 * @return string Always return 's_managerepository'
9421 public function get_full_name() {
9422 return 's_managerepository';
9426 * Always returns '' doesn't do anything
9428 public function write_setting($data) {
9429 $url = $this->baseurl
. '&new=' . $data;
9432 // Should not use redirect and exit here
9433 // Find a better way to do this.
9439 * Searches repository plugins for one that matches $query
9441 * @param string $query The string to search for
9442 * @return bool true if found, false if not
9444 public function is_related($query) {
9445 if (parent
::is_related($query)) {
9449 $repositories= core_component
::get_plugin_list('repository');
9450 foreach ($repositories as $p => $dir) {
9451 if (strpos($p, $query) !== false) {
9455 foreach (repository
::get_types() as $instance) {
9456 $title = $instance->get_typename();
9457 if (strpos(core_text
::strtolower($title), $query) !== false) {
9465 * Helper function that generates a moodle_url object
9466 * relevant to the repository
9469 function repository_action_url($repository) {
9470 return new moodle_url($this->baseurl
, array('sesskey'=>sesskey(), 'repos'=>$repository));
9474 * Builds XHTML to display the control
9476 * @param string $data Unused
9477 * @param string $query
9478 * @return string XHTML
9480 public function output_html($data, $query='') {
9481 global $CFG, $USER, $OUTPUT;
9483 // Get strings that are used
9484 $strshow = get_string('on', 'repository');
9485 $strhide = get_string('off', 'repository');
9486 $strdelete = get_string('disabled', 'repository');
9488 $actionchoicesforexisting = array(
9491 'delete' => $strdelete
9494 $actionchoicesfornew = array(
9495 'newon' => $strshow,
9496 'newoff' => $strhide,
9497 'delete' => $strdelete
9501 $return .= $OUTPUT->box_start('generalbox');
9503 // Set strings that are used multiple times
9504 $settingsstr = get_string('settings');
9505 $disablestr = get_string('disable');
9507 // Table to list plug-ins
9508 $table = new html_table();
9509 $table->head
= array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
9510 $table->align
= array('left', 'center', 'center', 'center', 'center');
9511 $table->data
= array();
9513 // Get list of used plug-ins
9514 $repositorytypes = repository
::get_types();
9515 if (!empty($repositorytypes)) {
9516 // Array to store plugins being used
9517 $alreadyplugins = array();
9518 $totalrepositorytypes = count($repositorytypes);
9520 foreach ($repositorytypes as $i) {
9522 $typename = $i->get_typename();
9523 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
9524 $typeoptionnames = repository
::static_function($typename, 'get_type_option_names');
9525 $instanceoptionnames = repository
::static_function($typename, 'get_instance_option_names');
9527 if (!empty($typeoptionnames) ||
!empty($instanceoptionnames)) {
9528 // Calculate number of instances in order to display them for the Moodle administrator
9529 if (!empty($instanceoptionnames)) {
9531 $params['context'] = array(context_system
::instance());
9532 $params['onlyvisible'] = false;
9533 $params['type'] = $typename;
9534 $admininstancenumber = count(repository
::static_function($typename, 'get_instances', $params));
9536 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
9537 $params['context'] = array();
9538 $instances = repository
::static_function($typename, 'get_instances', $params);
9539 $courseinstances = array();
9540 $userinstances = array();
9542 foreach ($instances as $instance) {
9543 $repocontext = context
::instance_by_id($instance->instance
->contextid
);
9544 if ($repocontext->contextlevel
== CONTEXT_COURSE
) {
9545 $courseinstances[] = $instance;
9546 } else if ($repocontext->contextlevel
== CONTEXT_USER
) {
9547 $userinstances[] = $instance;
9551 $instancenumber = count($courseinstances);
9552 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
9554 // user private instances
9555 $instancenumber = count($userinstances);
9556 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
9558 $admininstancenumbertext = "";
9559 $courseinstancenumbertext = "";
9560 $userinstancenumbertext = "";
9563 $settings .= '<a href="' . $this->baseurl
. '&action=edit&repos=' . $typename . '">' . $settingsstr .'</a>';
9565 $settings .= $OUTPUT->container_start('mdl-left');
9566 $settings .= '<br/>';
9567 $settings .= $admininstancenumbertext;
9568 $settings .= '<br/>';
9569 $settings .= $courseinstancenumbertext;
9570 $settings .= '<br/>';
9571 $settings .= $userinstancenumbertext;
9572 $settings .= $OUTPUT->container_end();
9574 // Get the current visibility
9575 if ($i->get_visible()) {
9576 $currentaction = 'show';
9578 $currentaction = 'hide';
9581 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
9583 // Display up/down link
9585 // Should be done with CSS instead.
9586 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
9588 if ($updowncount > 1) {
9589 $updown .= "<a href=\"$this->baseurl&action=moveup&repos=".$typename."\">";
9590 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a> ';
9595 if ($updowncount < $totalrepositorytypes) {
9596 $updown .= "<a href=\"$this->baseurl&action=movedown&repos=".$typename."\">";
9597 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a> ';
9605 $table->data
[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
9607 if (!in_array($typename, $alreadyplugins)) {
9608 $alreadyplugins[] = $typename;
9613 // Get all the plugins that exist on disk
9614 $plugins = core_component
::get_plugin_list('repository');
9615 if (!empty($plugins)) {
9616 foreach ($plugins as $plugin => $dir) {
9617 // Check that it has not already been listed
9618 if (!in_array($plugin, $alreadyplugins)) {
9619 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
9620 $table->data
[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
9625 $return .= html_writer
::table($table);
9626 $return .= $OUTPUT->box_end();
9627 return highlight($query, $return);
9632 * Special checkbox for enable mobile web service
9633 * If enable then we store the service id of the mobile service into config table
9634 * If disable then we unstore the service id from the config table
9636 class admin_setting_enablemobileservice
extends admin_setting_configcheckbox
{
9638 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
9642 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
9646 private function is_protocol_cap_allowed() {
9649 // If the $this->restuse variable is not set, it needs to be set.
9650 if (empty($this->restuse
) and $this->restuse
!==false) {
9652 $params['permission'] = CAP_ALLOW
;
9653 $params['roleid'] = $CFG->defaultuserroleid
;
9654 $params['capability'] = 'webservice/rest:use';
9655 $this->restuse
= $DB->record_exists('role_capabilities', $params);
9658 return $this->restuse
;
9662 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
9663 * @param type $status true to allow, false to not set
9665 private function set_protocol_cap($status) {
9667 if ($status and !$this->is_protocol_cap_allowed()) {
9668 //need to allow the cap
9669 $permission = CAP_ALLOW
;
9671 } else if (!$status and $this->is_protocol_cap_allowed()){
9672 //need to disallow the cap
9673 $permission = CAP_INHERIT
;
9676 if (!empty($assign)) {
9677 $systemcontext = context_system
::instance();
9678 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid
, $systemcontext->id
, true);
9683 * Builds XHTML to display the control.
9684 * The main purpose of this overloading is to display a warning when https
9685 * is not supported by the server
9686 * @param string $data Unused
9687 * @param string $query
9688 * @return string XHTML
9690 public function output_html($data, $query='') {
9692 $html = parent
::output_html($data, $query);
9694 if ((string)$data === $this->yes
) {
9695 $notifications = tool_mobile\api
::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
9696 foreach ($notifications as $notification) {
9697 $message = get_string($notification[0], $notification[1]);
9698 $html .= $OUTPUT->notification($message, \core\output\notification
::NOTIFY_WARNING
);
9706 * Retrieves the current setting using the objects name
9710 public function get_setting() {
9713 // First check if is not set.
9714 $result = $this->config_read($this->name
);
9715 if (is_null($result)) {
9719 // For install cli script, $CFG->defaultuserroleid is not set so return 0
9720 // Or if web services aren't enabled this can't be,
9721 if (empty($CFG->defaultuserroleid
) ||
empty($CFG->enablewebservices
)) {
9725 require_once($CFG->dirroot
. '/webservice/lib.php');
9726 $webservicemanager = new webservice();
9727 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE
);
9728 if ($mobileservice->enabled
and $this->is_protocol_cap_allowed()) {
9736 * Save the selected setting
9738 * @param string $data The selected site
9739 * @return string empty string or error message
9741 public function write_setting($data) {
9744 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
9745 if (empty($CFG->defaultuserroleid
)) {
9749 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE
;
9751 require_once($CFG->dirroot
. '/webservice/lib.php');
9752 $webservicemanager = new webservice();
9754 $updateprotocol = false;
9755 if ((string)$data === $this->yes
) {
9756 //code run when enable mobile web service
9757 //enable web service systeme if necessary
9758 set_config('enablewebservices', true);
9760 //enable mobile service
9761 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE
);
9762 $mobileservice->enabled
= 1;
9763 $webservicemanager->update_external_service($mobileservice);
9765 // Enable REST server.
9766 $activeprotocols = empty($CFG->webserviceprotocols
) ?
array() : explode(',', $CFG->webserviceprotocols
);
9768 if (!in_array('rest', $activeprotocols)) {
9769 $activeprotocols[] = 'rest';
9770 $updateprotocol = true;
9773 if ($updateprotocol) {
9774 set_config('webserviceprotocols', implode(',', $activeprotocols));
9777 // Allow rest:use capability for authenticated user.
9778 $this->set_protocol_cap(true);
9780 // Disable the mobile service.
9781 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE
);
9782 $mobileservice->enabled
= 0;
9783 $webservicemanager->update_external_service($mobileservice);
9786 return (parent
::write_setting($data));
9791 * Special class for management of external services
9793 * @author Petr Skoda (skodak)
9795 class admin_setting_manageexternalservices
extends admin_setting
{
9797 * Calls parent::__construct with specific arguments
9799 public function __construct() {
9800 $this->nosave
= true;
9801 parent
::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
9805 * Always returns true, does nothing
9809 public function get_setting() {
9814 * Always returns true, does nothing
9818 public function get_defaultsetting() {
9823 * Always returns '', does not write anything
9825 * @return string Always returns ''
9827 public function write_setting($data) {
9828 // do not write any setting
9833 * Checks if $query is one of the available external services
9835 * @param string $query The string to search for
9836 * @return bool Returns true if found, false if not
9838 public function is_related($query) {
9841 if (parent
::is_related($query)) {
9845 $services = $DB->get_records('external_services', array(), 'id, name');
9846 foreach ($services as $service) {
9847 if (strpos(core_text
::strtolower($service->name
), $query) !== false) {
9855 * Builds the XHTML to display the control
9857 * @param string $data Unused
9858 * @param string $query
9861 public function output_html($data, $query='') {
9862 global $CFG, $OUTPUT, $DB;
9865 $stradministration = get_string('administration');
9866 $stredit = get_string('edit');
9867 $strservice = get_string('externalservice', 'webservice');
9868 $strdelete = get_string('delete');
9869 $strplugin = get_string('plugin', 'admin');
9870 $stradd = get_string('add');
9871 $strfunctions = get_string('functions', 'webservice');
9872 $strusers = get_string('users');
9873 $strserviceusers = get_string('serviceusers', 'webservice');
9875 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
9876 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
9877 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
9879 // built in services
9880 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
9882 if (!empty($services)) {
9883 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
9887 $table = new html_table();
9888 $table->head
= array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
9889 $table->colclasses
= array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9890 $table->id
= 'builtinservices';
9891 $table->attributes
['class'] = 'admintable externalservices generaltable';
9892 $table->data
= array();
9894 // iterate through auth plugins and add to the display table
9895 foreach ($services as $service) {
9896 $name = $service->name
;
9899 if ($service->enabled
) {
9900 $displayname = "<span>$name</span>";
9902 $displayname = "<span class=\"dimmed_text\">$name</span>";
9905 $plugin = $service->component
;
9907 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9909 if ($service->restrictedusers
) {
9910 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9912 $users = get_string('allusers', 'webservice');
9915 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9917 // add a row to the table
9918 $table->data
[] = array($displayname, $plugin, $functions, $users, $edit);
9920 $return .= html_writer
::table($table);
9924 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9925 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9927 $table = new html_table();
9928 $table->head
= array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9929 $table->colclasses
= array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9930 $table->id
= 'customservices';
9931 $table->attributes
['class'] = 'admintable externalservices generaltable';
9932 $table->data
= array();
9934 // iterate through auth plugins and add to the display table
9935 foreach ($services as $service) {
9936 $name = $service->name
;
9939 if ($service->enabled
) {
9940 $displayname = "<span>$name</span>";
9942 $displayname = "<span class=\"dimmed_text\">$name</span>";
9946 $delete = "<a href=\"$esurl?action=delete&sesskey=".sesskey()."&id=$service->id\">$strdelete</a>";
9948 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9950 if ($service->restrictedusers
) {
9951 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9953 $users = get_string('allusers', 'webservice');
9956 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9958 // add a row to the table
9959 $table->data
[] = array($displayname, $delete, $functions, $users, $edit);
9961 // add new custom service option
9962 $return .= html_writer
::table($table);
9964 $return .= '<br />';
9965 // add a token to the table
9966 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9968 return highlight($query, $return);
9973 * Special class for overview of external services
9975 * @author Jerome Mouneyrac
9977 class admin_setting_webservicesoverview
extends admin_setting
{
9980 * Calls parent::__construct with specific arguments
9982 public function __construct() {
9983 $this->nosave
= true;
9984 parent
::__construct('webservicesoverviewui',
9985 get_string('webservicesoverview', 'webservice'), '', '');
9989 * Always returns true, does nothing
9993 public function get_setting() {
9998 * Always returns true, does nothing
10002 public function get_defaultsetting() {
10007 * Always returns '', does not write anything
10009 * @return string Always returns ''
10011 public function write_setting($data) {
10012 // do not write any setting
10017 * Builds the XHTML to display the control
10019 * @param string $data Unused
10020 * @param string $query
10023 public function output_html($data, $query='') {
10024 global $CFG, $OUTPUT;
10027 $brtag = html_writer
::empty_tag('br');
10029 /// One system controlling Moodle with Token
10030 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
10031 $table = new html_table();
10032 $table->head
= array(get_string('step', 'webservice'), get_string('status'),
10033 get_string('description'));
10034 $table->colclasses
= array('leftalign step', 'leftalign status', 'leftalign description');
10035 $table->id
= 'onesystemcontrol';
10036 $table->attributes
['class'] = 'admintable wsoverview generaltable';
10037 $table->data
= array();
10039 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
10042 /// 1. Enable Web Services
10044 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10045 $row[0] = "1. " . html_writer
::tag('a', get_string('enablews', 'webservice'),
10046 array('href' => $url));
10047 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10048 if ($CFG->enablewebservices
) {
10049 $status = get_string('yes');
10052 $row[2] = get_string('enablewsdescription', 'webservice');
10053 $table->data
[] = $row;
10055 /// 2. Enable protocols
10057 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10058 $row[0] = "2. " . html_writer
::tag('a', get_string('enableprotocols', 'webservice'),
10059 array('href' => $url));
10060 $status = html_writer
::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10061 //retrieve activated protocol
10062 $active_protocols = empty($CFG->webserviceprotocols
) ?
10063 array() : explode(',', $CFG->webserviceprotocols
);
10064 if (!empty($active_protocols)) {
10066 foreach ($active_protocols as $protocol) {
10067 $status .= $protocol . $brtag;
10071 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10072 $table->data
[] = $row;
10074 /// 3. Create user account
10076 $url = new moodle_url("/user/editadvanced.php?id=-1");
10077 $row[0] = "3. " . html_writer
::tag('a', get_string('createuser', 'webservice'),
10078 array('href' => $url));
10080 $row[2] = get_string('createuserdescription', 'webservice');
10081 $table->data
[] = $row;
10083 /// 4. Add capability to users
10085 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10086 $row[0] = "4. " . html_writer
::tag('a', get_string('checkusercapability', 'webservice'),
10087 array('href' => $url));
10089 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
10090 $table->data
[] = $row;
10092 /// 5. Select a web service
10094 $url = new moodle_url("/admin/settings.php?section=externalservices");
10095 $row[0] = "5. " . html_writer
::tag('a', get_string('selectservice', 'webservice'),
10096 array('href' => $url));
10098 $row[2] = get_string('createservicedescription', 'webservice');
10099 $table->data
[] = $row;
10101 /// 6. Add functions
10103 $url = new moodle_url("/admin/settings.php?section=externalservices");
10104 $row[0] = "6. " . html_writer
::tag('a', get_string('addfunctions', 'webservice'),
10105 array('href' => $url));
10107 $row[2] = get_string('addfunctionsdescription', 'webservice');
10108 $table->data
[] = $row;
10110 /// 7. Add the specific user
10112 $url = new moodle_url("/admin/settings.php?section=externalservices");
10113 $row[0] = "7. " . html_writer
::tag('a', get_string('selectspecificuser', 'webservice'),
10114 array('href' => $url));
10116 $row[2] = get_string('selectspecificuserdescription', 'webservice');
10117 $table->data
[] = $row;
10119 /// 8. Create token for the specific user
10121 $url = new moodle_url('/admin/webservice/tokens.php', ['action' => 'create']);
10122 $row[0] = "8. " . html_writer
::tag('a', get_string('createtokenforuser', 'webservice'),
10123 array('href' => $url));
10125 $row[2] = get_string('createtokenforuserdescription', 'webservice');
10126 $table->data
[] = $row;
10128 /// 9. Enable the documentation
10130 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
10131 $row[0] = "9. " . html_writer
::tag('a', get_string('enabledocumentation', 'webservice'),
10132 array('href' => $url));
10133 $status = '<span class="warning">' . get_string('no') . '</span>';
10134 if ($CFG->enablewsdocumentation
) {
10135 $status = get_string('yes');
10138 $row[2] = get_string('enabledocumentationdescription', 'webservice');
10139 $table->data
[] = $row;
10141 /// 10. Test the service
10143 $url = new moodle_url("/admin/webservice/testclient.php");
10144 $row[0] = "10. " . html_writer
::tag('a', get_string('testwithtestclient', 'webservice'),
10145 array('href' => $url));
10147 $row[2] = get_string('testwithtestclientdescription', 'webservice');
10148 $table->data
[] = $row;
10150 $return .= html_writer
::table($table);
10152 /// Users as clients with token
10153 $return .= $brtag . $brtag . $brtag;
10154 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
10155 $table = new html_table();
10156 $table->head
= array(get_string('step', 'webservice'), get_string('status'),
10157 get_string('description'));
10158 $table->colclasses
= array('leftalign step', 'leftalign status', 'leftalign description');
10159 $table->id
= 'userasclients';
10160 $table->attributes
['class'] = 'admintable wsoverview generaltable';
10161 $table->data
= array();
10163 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
10166 /// 1. Enable Web Services
10168 $url = new moodle_url("/admin/search.php?query=enablewebservices");
10169 $row[0] = "1. " . html_writer
::tag('a', get_string('enablews', 'webservice'),
10170 array('href' => $url));
10171 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
10172 if ($CFG->enablewebservices
) {
10173 $status = get_string('yes');
10176 $row[2] = get_string('enablewsdescription', 'webservice');
10177 $table->data
[] = $row;
10179 /// 2. Enable protocols
10181 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
10182 $row[0] = "2. " . html_writer
::tag('a', get_string('enableprotocols', 'webservice'),
10183 array('href' => $url));
10184 $status = html_writer
::tag('span', get_string('none'), array('class' => 'badge badge-danger'));
10185 //retrieve activated protocol
10186 $active_protocols = empty($CFG->webserviceprotocols
) ?
10187 array() : explode(',', $CFG->webserviceprotocols
);
10188 if (!empty($active_protocols)) {
10190 foreach ($active_protocols as $protocol) {
10191 $status .= $protocol . $brtag;
10195 $row[2] = get_string('enableprotocolsdescription', 'webservice');
10196 $table->data
[] = $row;
10199 /// 3. Select a web service
10201 $url = new moodle_url("/admin/settings.php?section=externalservices");
10202 $row[0] = "3. " . html_writer
::tag('a', get_string('selectservice', 'webservice'),
10203 array('href' => $url));
10205 $row[2] = get_string('createserviceforusersdescription', 'webservice');
10206 $table->data
[] = $row;
10208 /// 4. Add functions
10210 $url = new moodle_url("/admin/settings.php?section=externalservices");
10211 $row[0] = "4. " . html_writer
::tag('a', get_string('addfunctions', 'webservice'),
10212 array('href' => $url));
10214 $row[2] = get_string('addfunctionsdescription', 'webservice');
10215 $table->data
[] = $row;
10217 /// 5. Add capability to users
10219 $url = new moodle_url("/admin/roles/check.php?contextid=1");
10220 $row[0] = "5. " . html_writer
::tag('a', get_string('addcapabilitytousers', 'webservice'),
10221 array('href' => $url));
10223 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
10224 $table->data
[] = $row;
10226 /// 6. Test the service
10228 $url = new moodle_url("/admin/webservice/testclient.php");
10229 $row[0] = "6. " . html_writer
::tag('a', get_string('testwithtestclient', 'webservice'),
10230 array('href' => $url));
10232 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
10233 $table->data
[] = $row;
10235 $return .= html_writer
::table($table);
10237 return highlight($query, $return);
10244 * Special class for web service protocol administration.
10246 * @author Petr Skoda (skodak)
10248 class admin_setting_managewebserviceprotocols
extends admin_setting
{
10251 * Calls parent::__construct with specific arguments
10253 public function __construct() {
10254 $this->nosave
= true;
10255 parent
::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
10259 * Always returns true, does nothing
10263 public function get_setting() {
10268 * Always returns true, does nothing
10272 public function get_defaultsetting() {
10277 * Always returns '', does not write anything
10279 * @return string Always returns ''
10281 public function write_setting($data) {
10282 // do not write any setting
10287 * Checks if $query is one of the available webservices
10289 * @param string $query The string to search for
10290 * @return bool Returns true if found, false if not
10292 public function is_related($query) {
10293 if (parent
::is_related($query)) {
10297 $protocols = core_component
::get_plugin_list('webservice');
10298 foreach ($protocols as $protocol=>$location) {
10299 if (strpos($protocol, $query) !== false) {
10302 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
10303 if (strpos(core_text
::strtolower($protocolstr), $query) !== false) {
10311 * Builds the XHTML to display the control
10313 * @param string $data Unused
10314 * @param string $query
10317 public function output_html($data, $query='') {
10318 global $CFG, $OUTPUT;
10321 $stradministration = get_string('administration');
10322 $strsettings = get_string('settings');
10323 $stredit = get_string('edit');
10324 $strprotocol = get_string('protocol', 'webservice');
10325 $strenable = get_string('enable');
10326 $strdisable = get_string('disable');
10327 $strversion = get_string('version');
10329 $protocols_available = core_component
::get_plugin_list('webservice');
10330 $active_protocols = empty($CFG->webserviceprotocols
) ?
array() : explode(',', $CFG->webserviceprotocols
);
10331 ksort($protocols_available);
10333 foreach ($active_protocols as $key=>$protocol) {
10334 if (empty($protocols_available[$protocol])) {
10335 unset($active_protocols[$key]);
10339 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
10340 $return .= $OUTPUT->box_start('generalbox webservicesui');
10342 $table = new html_table();
10343 $table->head
= array($strprotocol, $strversion, $strenable, $strsettings);
10344 $table->colclasses
= array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
10345 $table->id
= 'webserviceprotocols';
10346 $table->attributes
['class'] = 'admintable generaltable';
10347 $table->data
= array();
10349 // iterate through auth plugins and add to the display table
10350 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
10351 foreach ($protocols_available as $protocol => $location) {
10352 $name = get_string('pluginname', 'webservice_'.$protocol);
10354 $plugin = new stdClass();
10355 if (file_exists($CFG->dirroot
.'/webservice/'.$protocol.'/version.php')) {
10356 include($CFG->dirroot
.'/webservice/'.$protocol.'/version.php');
10358 $version = isset($plugin->version
) ?
$plugin->version
: '';
10361 if (in_array($protocol, $active_protocols)) {
10362 $hideshow = "<a href=\"$url&action=disable&webservice=$protocol\">";
10363 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
10364 $displayname = "<span>$name</span>";
10366 $hideshow = "<a href=\"$url&action=enable&webservice=$protocol\">";
10367 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
10368 $displayname = "<span class=\"dimmed_text\">$name</span>";
10372 if (file_exists($CFG->dirroot
.'/webservice/'.$protocol.'/settings.php')) {
10373 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
10378 // add a row to the table
10379 $table->data
[] = array($displayname, $version, $hideshow, $settings);
10381 $return .= html_writer
::table($table);
10382 $return .= get_string('configwebserviceplugins', 'webservice');
10383 $return .= $OUTPUT->box_end();
10385 return highlight($query, $return);
10392 * @copyright 2010 Sam Hemelryk
10393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10395 class admin_setting_configcolourpicker
extends admin_setting
{
10398 * Information for previewing the colour
10402 protected $previewconfig = null;
10405 * Use default when empty.
10407 protected $usedefaultwhenempty = true;
10411 * @param string $name
10412 * @param string $visiblename
10413 * @param string $description
10414 * @param string $defaultsetting
10415 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
10417 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
10418 $usedefaultwhenempty = true) {
10419 $this->previewconfig
= $previewconfig;
10420 $this->usedefaultwhenempty
= $usedefaultwhenempty;
10421 parent
::__construct($name, $visiblename, $description, $defaultsetting);
10422 $this->set_force_ltr(true);
10426 * Return the setting
10428 * @return mixed returns config if successful else null
10430 public function get_setting() {
10431 return $this->config_read($this->name
);
10435 * Saves the setting
10437 * @param string $data
10440 public function write_setting($data) {
10441 $data = $this->validate($data);
10442 if ($data === false) {
10443 return get_string('validateerror', 'admin');
10445 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
10449 * Validates the colour that was entered by the user
10451 * @param string $data
10452 * @return string|false
10454 protected function validate($data) {
10456 * List of valid HTML colour names
10460 $colornames = array(
10461 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
10462 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
10463 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
10464 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
10465 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
10466 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
10467 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
10468 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
10469 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
10470 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
10471 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
10472 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
10473 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
10474 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
10475 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
10476 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
10477 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
10478 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
10479 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
10480 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
10481 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
10482 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
10483 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
10484 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
10485 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
10486 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
10487 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
10488 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
10489 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
10490 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
10491 'whitesmoke', 'yellow', 'yellowgreen'
10494 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
10495 if (strpos($data, '#')!==0) {
10499 } else if (in_array(strtolower($data), $colornames)) {
10501 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
10503 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
10505 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
10507 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
10509 } else if (($data == 'transparent') ||
($data == 'currentColor') ||
($data == 'inherit')) {
10511 } else if (empty($data)) {
10512 if ($this->usedefaultwhenempty
){
10513 return $this->defaultsetting
;
10523 * Generates the HTML for the setting
10525 * @global moodle_page $PAGE
10526 * @global core_renderer $OUTPUT
10527 * @param string $data
10528 * @param string $query
10530 public function output_html($data, $query = '') {
10531 global $PAGE, $OUTPUT;
10533 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
10534 $context = (object) [
10535 'id' => $this->get_id(),
10536 'name' => $this->get_full_name(),
10538 'icon' => $icon->export_for_template($OUTPUT),
10539 'haspreviewconfig' => !empty($this->previewconfig
),
10540 'forceltr' => $this->get_force_ltr(),
10541 'readonly' => $this->is_readonly(),
10544 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
10545 $PAGE->requires
->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig
));
10547 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '',
10548 $this->get_defaultsetting(), $query);
10555 * Class used for uploading of one file into file storage,
10556 * the file name is stored in config table.
10558 * Please note you need to implement your own '_pluginfile' callback function,
10559 * this setting only stores the file, it does not deal with file serving.
10561 * @copyright 2013 Petr Skoda {@link http://skodak.org}
10562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10564 class admin_setting_configstoredfile
extends admin_setting
{
10565 /** @var array file area options - should be one file only */
10566 protected $options;
10567 /** @var string name of the file area */
10568 protected $filearea;
10569 /** @var int intemid */
10571 /** @var string used for detection of changes */
10572 protected $oldhashes;
10575 * Create new stored file setting.
10577 * @param string $name low level setting name
10578 * @param string $visiblename human readable setting name
10579 * @param string $description description of setting
10580 * @param mixed $filearea file area for file storage
10581 * @param int $itemid itemid for file storage
10582 * @param array $options file area options
10584 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
10585 parent
::__construct($name, $visiblename, $description, '');
10586 $this->filearea
= $filearea;
10587 $this->itemid
= $itemid;
10588 $this->options
= (array)$options;
10589 $this->customcontrol
= true;
10593 * Applies defaults and returns all options.
10596 protected function get_options() {
10599 require_once("$CFG->libdir/filelib.php");
10600 require_once("$CFG->dirroot/repository/lib.php");
10602 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
10603 'accepted_types' => '*', 'return_types' => FILE_INTERNAL
, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED
,
10604 'context' => context_system
::instance());
10605 foreach($this->options
as $k => $v) {
10606 $defaults[$k] = $v;
10612 public function get_setting() {
10613 return $this->config_read($this->name
);
10616 public function write_setting($data) {
10619 // Let's not deal with validation here, this is for admins only.
10620 $current = $this->get_setting();
10621 if (empty($data) && $current === null) {
10622 // This will be the case when applying default settings (installation).
10623 return ($this->config_write($this->name
, '') ?
'' : get_string('errorsetting', 'admin'));
10624 } else if (!is_number($data)) {
10625 // Draft item id is expected here!
10626 return get_string('errorsetting', 'admin');
10629 $options = $this->get_options();
10630 $fs = get_file_storage();
10631 $component = is_null($this->plugin
) ?
'core' : $this->plugin
;
10633 $this->oldhashes
= null;
10635 $hash = sha1('/'.$options['context']->id
.'/'.$component.'/'.$this->filearea
.'/'.$this->itemid
.$current);
10636 if ($file = $fs->get_file_by_hash($hash)) {
10637 $this->oldhashes
= $file->get_contenthash().$file->get_pathnamehash();
10642 if ($fs->file_exists($options['context']->id
, $component, $this->filearea
, $this->itemid
, '/', '.')) {
10643 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
10644 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
10645 // with an error because the draft area does not exist, as he did not use it.
10646 $usercontext = context_user
::instance($USER->id
);
10647 if (!$fs->file_exists($usercontext->id
, 'user', 'draft', $data, '/', '.') && $current !== '') {
10648 return get_string('errorsetting', 'admin');
10652 file_save_draft_area_files($data, $options['context']->id
, $component, $this->filearea
, $this->itemid
, $options);
10653 $files = $fs->get_area_files($options['context']->id
, $component, $this->filearea
, $this->itemid
, 'sortorder,filepath,filename', false);
10657 /** @var stored_file $file */
10658 $file = reset($files);
10659 $filepath = $file->get_filepath().$file->get_filename();
10662 return ($this->config_write($this->name
, $filepath) ?
'' : get_string('errorsetting', 'admin'));
10665 public function post_write_settings($original) {
10666 $options = $this->get_options();
10667 $fs = get_file_storage();
10668 $component = is_null($this->plugin
) ?
'core' : $this->plugin
;
10670 $current = $this->get_setting();
10673 $hash = sha1('/'.$options['context']->id
.'/'.$component.'/'.$this->filearea
.'/'.$this->itemid
.$current);
10674 if ($file = $fs->get_file_by_hash($hash)) {
10675 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
10680 if ($this->oldhashes
=== $newhashes) {
10681 $this->oldhashes
= null;
10684 $this->oldhashes
= null;
10686 $callbackfunction = $this->updatedcallback
;
10687 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
10688 $callbackfunction($this->get_full_name());
10693 public function output_html($data, $query = '') {
10694 global $PAGE, $CFG;
10696 $options = $this->get_options();
10697 $id = $this->get_id();
10698 $elname = $this->get_full_name();
10699 $draftitemid = file_get_submitted_draft_itemid($elname);
10700 $component = is_null($this->plugin
) ?
'core' : $this->plugin
;
10701 file_prepare_draft_area($draftitemid, $options['context']->id
, $component, $this->filearea
, $this->itemid
, $options);
10703 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
10704 require_once("$CFG->dirroot/lib/form/filemanager.php");
10706 $fmoptions = new stdClass();
10707 $fmoptions->mainfile
= $options['mainfile'];
10708 $fmoptions->maxbytes
= $options['maxbytes'];
10709 $fmoptions->maxfiles
= $options['maxfiles'];
10710 $fmoptions->client_id
= uniqid();
10711 $fmoptions->itemid
= $draftitemid;
10712 $fmoptions->subdirs
= $options['subdirs'];
10713 $fmoptions->target
= $id;
10714 $fmoptions->accepted_types
= $options['accepted_types'];
10715 $fmoptions->return_types
= $options['return_types'];
10716 $fmoptions->context
= $options['context'];
10717 $fmoptions->areamaxbytes
= $options['areamaxbytes'];
10719 $fm = new form_filemanager($fmoptions);
10720 $output = $PAGE->get_renderer('core', 'files');
10721 $html = $output->render($fm);
10723 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
10724 $html .= '<input value="" id="'.$id.'" type="hidden" />';
10726 return format_admin_setting($this, $this->visiblename
,
10727 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
10728 $this->description
, true, '', '', $query);
10734 * Administration interface for user specified regular expressions for device detection.
10736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10738 class admin_setting_devicedetectregex
extends admin_setting
{
10741 * Calls parent::__construct with specific args
10743 * @param string $name
10744 * @param string $visiblename
10745 * @param string $description
10746 * @param mixed $defaultsetting
10748 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10750 parent
::__construct($name, $visiblename, $description, $defaultsetting);
10754 * Return the current setting(s)
10756 * @return array Current settings array
10758 public function get_setting() {
10761 $config = $this->config_read($this->name
);
10762 if (is_null($config)) {
10766 return $this->prepare_form_data($config);
10770 * Save selected settings
10772 * @param array $data Array of settings to save
10775 public function write_setting($data) {
10776 if (empty($data)) {
10780 if ($this->config_write($this->name
, $this->process_form_data($data))) {
10781 return ''; // success
10783 return get_string('errorsetting', 'admin') . $this->visiblename
. html_writer
::empty_tag('br');
10788 * Return XHTML field(s) for regexes
10790 * @param array $data Array of options to set in HTML
10791 * @return string XHTML string for the fields and wrapping div(s)
10793 public function output_html($data, $query='') {
10796 $context = (object) [
10797 'expressions' => [],
10798 'name' => $this->get_full_name()
10801 if (empty($data)) {
10804 $looplimit = (count($data)/2)+
1;
10807 for ($i=0; $i<$looplimit; $i++
) {
10809 $expressionname = 'expression'.$i;
10811 if (!empty($data[$expressionname])){
10812 $expression = $data[$expressionname];
10817 $valuename = 'value'.$i;
10819 if (!empty($data[$valuename])){
10820 $value = $data[$valuename];
10825 $context->expressions
[] = [
10827 'expression' => $expression,
10832 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10834 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, false, '', null, $query);
10838 * Converts the string of regexes
10840 * @see self::process_form_data()
10841 * @param $regexes string of regexes
10842 * @return array of form fields and their values
10844 protected function prepare_form_data($regexes) {
10846 $regexes = json_decode($regexes);
10852 foreach ($regexes as $value => $regex) {
10853 $expressionname = 'expression'.$i;
10854 $valuename = 'value'.$i;
10856 $form[$expressionname] = $regex;
10857 $form[$valuename] = $value;
10865 * Converts the data from admin settings form into a string of regexes
10867 * @see self::prepare_form_data()
10868 * @param array $data array of admin form fields and values
10869 * @return false|string of regexes
10871 protected function process_form_data(array $form) {
10873 $count = count($form); // number of form field values
10876 // we must get five fields per expression
10880 $regexes = array();
10881 for ($i = 0; $i < $count / 2; $i++
) {
10882 $expressionname = "expression".$i;
10883 $valuename = "value".$i;
10885 $expression = trim($form['expression'.$i]);
10886 $value = trim($form['value'.$i]);
10888 if (empty($expression)){
10892 $regexes[$value] = $expression;
10895 $regexes = json_encode($regexes);
10903 * Multiselect for current modules
10905 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10907 class admin_setting_configmultiselect_modules
extends admin_setting_configmultiselect
{
10908 private $excludesystem;
10911 * Calls parent::__construct - note array $choices is not required
10913 * @param string $name setting name
10914 * @param string $visiblename localised setting name
10915 * @param string $description setting description
10916 * @param array $defaultsetting a plain array of default module ids
10917 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10919 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10920 $excludesystem = true) {
10921 parent
::__construct($name, $visiblename, $description, $defaultsetting, null);
10922 $this->excludesystem
= $excludesystem;
10926 * Loads an array of current module choices
10928 * @return bool always return true
10930 public function load_choices() {
10931 if (is_array($this->choices
)) {
10934 $this->choices
= array();
10937 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10938 foreach ($records as $record) {
10939 // Exclude modules if the code doesn't exist
10940 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10941 // Also exclude system modules (if specified)
10942 if (!($this->excludesystem
&&
10943 plugin_supports('mod', $record->name
, FEATURE_MOD_ARCHETYPE
) ===
10944 MOD_ARCHETYPE_SYSTEM
)) {
10945 $this->choices
[$record->id
] = $record->name
;
10954 * Admin setting to show if a php extension is enabled or not.
10956 * @copyright 2013 Damyon Wiese
10957 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10959 class admin_setting_php_extension_enabled
extends admin_setting
{
10961 /** @var string The name of the extension to check for */
10962 private $extension;
10965 * Calls parent::__construct with specific arguments
10967 public function __construct($name, $visiblename, $description, $extension) {
10968 $this->extension
= $extension;
10969 $this->nosave
= true;
10970 parent
::__construct($name, $visiblename, $description, '');
10974 * Always returns true, does nothing
10978 public function get_setting() {
10983 * Always returns true, does nothing
10987 public function get_defaultsetting() {
10992 * Always returns '', does not write anything
10994 * @return string Always returns ''
10996 public function write_setting($data) {
10997 // Do not write any setting.
11002 * Outputs the html for this setting.
11003 * @return string Returns an XHTML string
11005 public function output_html($data, $query='') {
11009 if (!extension_loaded($this->extension
)) {
11010 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description
;
11012 $o .= format_admin_setting($this, $this->visiblename
, $warning);
11019 * Server timezone setting.
11021 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11023 * @author Petr Skoda <petr.skoda@totaralms.com>
11025 class admin_setting_servertimezone
extends admin_setting_configselect
{
11029 public function __construct() {
11030 $default = core_date
::get_default_php_timezone();
11031 if ($default === 'UTC') {
11032 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
11033 $default = 'Europe/London';
11036 parent
::__construct('timezone',
11037 new lang_string('timezone', 'core_admin'),
11038 new lang_string('configtimezone', 'core_admin'), $default, null);
11042 * Lazy load timezone options.
11043 * @return bool true if loaded, false if error
11045 public function load_choices() {
11047 if (is_array($this->choices
)) {
11051 $current = isset($CFG->timezone
) ?
$CFG->timezone
: null;
11052 $this->choices
= core_date
::get_list_of_timezones($current, false);
11053 if ($current == 99) {
11054 // Do not show 99 unless it is current value, we want to get rid of it over time.
11055 $this->choices
['99'] = new lang_string('timezonephpdefault', 'core_admin',
11056 core_date
::get_default_php_timezone());
11064 * Forced user timezone setting.
11066 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
11067 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11068 * @author Petr Skoda <petr.skoda@totaralms.com>
11070 class admin_setting_forcetimezone
extends admin_setting_configselect
{
11074 public function __construct() {
11075 parent
::__construct('forcetimezone',
11076 new lang_string('forcetimezone', 'core_admin'),
11077 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
11081 * Lazy load timezone options.
11082 * @return bool true if loaded, false if error
11084 public function load_choices() {
11086 if (is_array($this->choices
)) {
11090 $current = isset($CFG->forcetimezone
) ?
$CFG->forcetimezone
: null;
11091 $this->choices
= core_date
::get_list_of_timezones($current, true);
11092 $this->choices
['99'] = new lang_string('timezonenotforced', 'core_admin');
11100 * Search setup steps info.
11103 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
11104 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11106 class admin_setting_searchsetupinfo
extends admin_setting
{
11109 * Calls parent::__construct with specific arguments
11111 public function __construct() {
11112 $this->nosave
= true;
11113 parent
::__construct('searchsetupinfo', '', '', '');
11117 * Always returns true, does nothing
11121 public function get_setting() {
11126 * Always returns true, does nothing
11130 public function get_defaultsetting() {
11135 * Always returns '', does not write anything
11137 * @param array $data
11138 * @return string Always returns ''
11140 public function write_setting($data) {
11141 // Do not write any setting.
11146 * Builds the HTML to display the control
11148 * @param string $data Unused
11149 * @param string $query
11152 public function output_html($data, $query='') {
11153 global $CFG, $OUTPUT, $ADMIN;
11156 $brtag = html_writer
::empty_tag('br');
11158 $searchareas = \core_search\manager
::get_search_areas_list();
11159 $anyenabled = !empty(\core_search\manager
::get_search_areas_list(true));
11160 $anyindexed = false;
11161 foreach ($searchareas as $areaid => $searcharea) {
11162 list($componentname, $varname) = $searcharea->get_config_var_name();
11163 if (get_config($componentname, $varname . '_indexingstart')) {
11164 $anyindexed = true;
11169 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
11171 $table = new html_table();
11172 $table->head
= array(get_string('step', 'search'), get_string('status'));
11173 $table->colclasses
= array('leftalign step', 'leftalign status');
11174 $table->id
= 'searchsetup';
11175 $table->attributes
['class'] = 'admintable generaltable';
11176 $table->data
= array();
11178 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
11180 // Select a search engine.
11182 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
11183 $row[0] = '1. ' . html_writer
::tag('a', get_string('selectsearchengine', 'admin'),
11184 array('href' => $url));
11186 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11187 if (!empty($CFG->searchengine
)) {
11188 $status = html_writer
::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine
),
11189 array('class' => 'badge badge-success'));
11193 $table->data
[] = $row;
11195 // Available areas.
11197 $url = new moodle_url('/admin/searchareas.php');
11198 $row[0] = '2. ' . html_writer
::tag('a', get_string('enablesearchareas', 'admin'),
11199 array('href' => $url));
11201 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11203 $status = html_writer
::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11207 $table->data
[] = $row;
11209 // Setup search engine.
11211 if (empty($CFG->searchengine
)) {
11212 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
11213 $row[1] = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11215 if ($ADMIN->locate('search' . $CFG->searchengine
)) {
11216 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine
);
11217 $row[0] = '3. ' . html_writer
::link($url, get_string('setupsearchengine', 'core_admin'));
11219 $row[0] = '3. ' . get_string('setupsearchengine', 'core_admin');
11222 // Check the engine status.
11223 $searchengine = \core_search\manager
::search_engine_instance();
11225 $serverstatus = $searchengine->is_server_ready();
11226 } catch (\moodle_exception
$e) {
11227 $serverstatus = $e->getMessage();
11229 if ($serverstatus === true) {
11230 $status = html_writer
::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11232 $status = html_writer
::tag('span', $serverstatus, array('class' => 'badge badge-danger'));
11236 $table->data
[] = $row;
11240 $url = new moodle_url('/admin/searchareas.php');
11241 $row[0] = '4. ' . html_writer
::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
11243 $status = html_writer
::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11245 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11248 $table->data
[] = $row;
11250 // Enable global search.
11252 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
11253 $row[0] = '5. ' . html_writer
::tag('a', get_string('enableglobalsearch', 'admin'),
11254 array('href' => $url));
11255 $status = html_writer
::tag('span', get_string('no'), array('class' => 'badge badge-danger'));
11256 if (\core_search\manager
::is_global_search_enabled()) {
11257 $status = html_writer
::tag('span', get_string('yes'), array('class' => 'badge badge-success'));
11260 $table->data
[] = $row;
11262 $return .= html_writer
::table($table);
11264 return highlight($query, $return);
11270 * Used to validate the contents of SCSS code and ensuring they are parsable.
11272 * It does not attempt to detect undefined SCSS variables because it is designed
11273 * to be used without knowledge of other config/scss included.
11275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11276 * @copyright 2016 Dan Poltawski <dan@moodle.com>
11278 class admin_setting_scsscode
extends admin_setting_configtextarea
{
11281 * Validate the contents of the SCSS to ensure its parsable. Does not
11282 * attempt to detect undefined scss variables.
11284 * @param string $data The scss code from text field.
11285 * @return mixed bool true for success or string:error on failure.
11287 public function validate($data) {
11288 if (empty($data)) {
11292 $scss = new core_scss();
11294 $scss->compile($data);
11295 } catch (ScssPhp\ScssPhp\Exception\ParserException
$e) {
11296 return get_string('scssinvalid', 'admin', $e->getMessage());
11297 } catch (ScssPhp\ScssPhp\Exception\CompilerException
$e) {
11298 // Silently ignore this - it could be a scss variable defined from somewhere
11299 // else which we are not examining here.
11309 * Administration setting to define a list of file types.
11311 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
11312 * @copyright 2017 David Mudrák <david@moodle.com>
11313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11315 class admin_setting_filetypes
extends admin_setting_configtext
{
11317 /** @var array Allow selection from these file types only. */
11318 protected $onlytypes = [];
11320 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
11321 protected $allowall = true;
11323 /** @var core_form\filetypes_util instance to use as a helper. */
11324 protected $util = null;
11329 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
11330 * @param string $visiblename Localised label of the setting
11331 * @param string $description Localised description of the setting
11332 * @param string $defaultsetting Default setting value.
11333 * @param array $options Setting widget options, an array with optional keys:
11334 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
11335 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
11337 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
11339 parent
::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW
);
11341 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
11342 $this->onlytypes
= $options['onlytypes'];
11345 if (!$this->onlytypes
&& array_key_exists('allowall', $options)) {
11346 $this->allowall
= (bool)$options['allowall'];
11349 $this->util
= new \core_form\filetypes_util
();
11353 * Normalize the user's input and write it to the database as comma separated list.
11355 * Comma separated list as a text representation of the array was chosen to
11356 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
11358 * @param string $data Value submitted by the admin.
11359 * @return string Epty string if all good, error message otherwise.
11361 public function write_setting($data) {
11362 return parent
::write_setting(implode(',', $this->util
->normalize_file_types($data)));
11366 * Validate data before storage
11368 * @param string $data The setting values provided by the admin
11369 * @return bool|string True if ok, the string if error found
11371 public function validate($data) {
11373 // No need to call parent's validation here as we are PARAM_RAW.
11375 if ($this->util
->is_listed($data, $this->onlytypes
)) {
11379 $troublemakers = $this->util
->get_not_listed($data, $this->onlytypes
);
11380 return get_string('filetypesnotallowed', 'core_form', implode(' ', $troublemakers));
11385 * Return an HTML string for the setting element.
11387 * @param string $data The current setting value
11388 * @param string $query Admin search query to be highlighted
11389 * @return string HTML to be displayed
11391 public function output_html($data, $query='') {
11392 global $OUTPUT, $PAGE;
11394 $default = $this->get_defaultsetting();
11395 $context = (object) [
11396 'id' => $this->get_id(),
11397 'name' => $this->get_full_name(),
11399 'descriptions' => $this->util
->describe_file_types($data),
11401 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
11403 $PAGE->requires
->js_call_amd('core_form/filetypes', 'init', [
11405 $this->visiblename
->out(),
11410 return format_admin_setting($this, $this->visiblename
, $element, $this->description
, true, '', $default, $query);
11414 * Should the values be always displayed in LTR mode?
11416 * We always return true here because these values are not RTL compatible.
11418 * @return bool True because these values are not RTL compatible.
11420 public function get_force_ltr() {
11426 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
11428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11429 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
11431 class admin_setting_agedigitalconsentmap
extends admin_setting_configtextarea
{
11436 * @param string $name
11437 * @param string $visiblename
11438 * @param string $description
11439 * @param mixed $defaultsetting string or array
11440 * @param mixed $paramtype
11441 * @param string $cols
11442 * @param string $rows
11444 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW
,
11445 $cols = '60', $rows = '8') {
11446 parent
::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
11447 // Pre-set force LTR to false.
11448 $this->set_force_ltr(false);
11452 * Validate the content and format of the age of digital consent map to ensure it is parsable.
11454 * @param string $data The age of digital consent map from text field.
11455 * @return mixed bool true for success or string:error on failure.
11457 public function validate($data) {
11458 if (empty($data)) {
11463 \core_auth\digital_consent
::parse_age_digital_consent_map($data);
11464 } catch (\moodle_exception
$e) {
11465 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
11473 * Selection of plugins that can work as site policy handlers
11475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11476 * @copyright 2018 Marina Glancy
11478 class admin_settings_sitepolicy_handler_select
extends admin_setting_configselect
{
11482 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11483 * for ones in config_plugins.
11484 * @param string $visiblename localised
11485 * @param string $description long localised info
11486 * @param string $defaultsetting
11488 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11489 parent
::__construct($name, $visiblename, $description, $defaultsetting, null);
11493 * Lazy-load the available choices for the select box
11495 public function load_choices() {
11496 if (during_initial_install()) {
11499 if (is_array($this->choices
)) {
11503 $this->choices
= ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
11504 $manager = new \core_privacy\local\sitepolicy\
manager();
11505 $plugins = $manager->get_all_handlers();
11506 foreach ($plugins as $pname => $unused) {
11507 $this->choices
[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11508 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
11516 * Used to validate theme presets code and ensuring they compile well.
11518 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11519 * @copyright 2019 Bas Brands <bas@moodle.com>
11521 class admin_setting_configthemepreset
extends admin_setting_configselect
{
11523 /** @var string The name of the theme to check for */
11524 private $themename;
11528 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
11529 * or 'myplugin/mysetting' for ones in config_plugins.
11530 * @param string $visiblename localised
11531 * @param string $description long localised info
11532 * @param string|int $defaultsetting
11533 * @param array $choices array of $value=>$label for each selection
11534 * @param string $themename name of theme to check presets for.
11536 public function __construct($name, $visiblename, $description, $defaultsetting, $choices, $themename) {
11537 $this->themename
= $themename;
11538 parent
::__construct($name, $visiblename, $description, $defaultsetting, $choices);
11542 * Write settings if validated
11544 * @param string $data
11547 public function write_setting($data) {
11548 $validated = $this->validate($data);
11549 if ($validated !== true) {
11552 return ($this->config_write($this->name
, $data) ?
'' : get_string('errorsetting', 'admin'));
11556 * Validate the preset file to ensure its parsable.
11558 * @param string $data The preset file chosen.
11559 * @return mixed bool true for success or string:error on failure.
11561 public function validate($data) {
11563 if (in_array($data, ['default.scss', 'plain.scss'])) {
11567 $fs = get_file_storage();
11568 $theme = theme_config
::load($this->themename
);
11569 $context = context_system
::instance();
11571 // If the preset has not changed there is no need to validate it.
11572 if ($theme->settings
->preset
== $data) {
11576 if ($presetfile = $fs->get_file($context->id
, 'theme_' . $this->themename
, 'preset', 0, '/', $data)) {
11577 // This operation uses a lot of resources.
11578 raise_memory_limit(MEMORY_EXTRA
);
11579 core_php_time_limit
::raise(300);
11581 // TODO: MDL-62757 When changing anything in this method please do not forget to check
11582 // if the get_css_content_from_scss() method in class theme_config needs updating too.
11584 $compiler = new core_scss();
11585 $compiler->prepend_raw_scss($theme->get_pre_scss_code());
11586 $compiler->append_raw_scss($presetfile->get_content());
11587 if ($scssproperties = $theme->get_scss_property()) {
11588 $compiler->setImportPaths($scssproperties[0]);
11590 $compiler->append_raw_scss($theme->get_extra_scss_code());
11593 $compiler->to_css();
11594 } catch (Exception
$e) {
11595 return get_string('invalidthemepreset', 'admin', $e->getMessage());
11598 // Try to save memory.
11608 * Selection of plugins that can work as H5P libraries handlers
11610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
11611 * @copyright 2020 Sara Arjona <sara@moodle.com>
11613 class admin_settings_h5plib_handler_select
extends admin_setting_configselect
{
11617 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
11618 * for ones in config_plugins.
11619 * @param string $visiblename localised
11620 * @param string $description long localised info
11621 * @param string $defaultsetting
11623 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
11624 parent
::__construct($name, $visiblename, $description, $defaultsetting, null);
11628 * Lazy-load the available choices for the select box
11630 public function load_choices() {
11631 if (during_initial_install()) {
11634 if (is_array($this->choices
)) {
11638 $this->choices
= \core_h5p\local\library\autoloader
::get_all_handlers();
11639 foreach ($this->choices
as $name => $class) {
11640 $this->choices
[$name] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
11641 ['name' => new lang_string('pluginname', $name), 'component' => $name]);