MDL-62388 tool_dataprivacy: Fixing bs4stable table layout
[moodle.git] / lib / adminlib.php
blobb14741ef7a43a0c5641cdfa6dfbbe21267e628be
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(__DIR__.'/../../config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag areas, collections and instances associated with this plugin.
170 core_tag_area::uninstall($component);
172 // Custom plugin uninstall.
173 $plugindirectory = core_component::get_plugin_directory($type, $name);
174 $uninstalllib = $plugindirectory . '/db/uninstall.php';
175 if (file_exists($uninstalllib)) {
176 require_once($uninstalllib);
177 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
178 if (function_exists($uninstallfunction)) {
179 // Do not verify result, let plugin complain if necessary.
180 $uninstallfunction();
184 // Specific plugin type cleanup.
185 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
186 if ($plugininfo) {
187 $plugininfo->uninstall_cleanup();
188 core_plugin_manager::reset_caches();
190 $plugininfo = null;
192 // perform clean-up task common for all the plugin/subplugin types
194 //delete the web service functions and pre-built services
195 require_once($CFG->dirroot.'/lib/externallib.php');
196 external_delete_descriptions($component);
198 // delete calendar events
199 $DB->delete_records('event', array('modulename' => $pluginname));
201 // Delete scheduled tasks.
202 $DB->delete_records('task_scheduled', array('component' => $component));
204 // Delete Inbound Message datakeys.
205 $DB->delete_records_select('messageinbound_datakeys',
206 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
208 // Delete Inbound Message handlers.
209 $DB->delete_records('messageinbound_handlers', array('component' => $component));
211 // delete all the logs
212 $DB->delete_records('log', array('module' => $pluginname));
214 // delete log_display information
215 $DB->delete_records('log_display', array('component' => $component));
217 // delete the module configuration records
218 unset_all_config_for_plugin($component);
219 if ($type === 'mod') {
220 unset_all_config_for_plugin($pluginname);
223 // delete message provider
224 message_provider_uninstall($component);
226 // delete the plugin tables
227 $xmldbfilepath = $plugindirectory . '/db/install.xml';
228 drop_plugin_tables($component, $xmldbfilepath, false);
229 if ($type === 'mod' or $type === 'block') {
230 // non-frankenstyle table prefixes
231 drop_plugin_tables($name, $xmldbfilepath, false);
234 // delete the capabilities that were defined by this module
235 capabilities_cleanup($component);
237 // remove event handlers and dequeue pending events
238 events_uninstall($component);
240 // Delete all remaining files in the filepool owned by the component.
241 $fs = get_file_storage();
242 $fs->delete_component_files($component);
244 // Finally purge all caches.
245 purge_all_caches();
247 // Invalidate the hash used for upgrade detections.
248 set_config('allversionshash', '');
250 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
254 * Returns the version of installed component
256 * @param string $component component name
257 * @param string $source either 'disk' or 'installed' - where to get the version information from
258 * @return string|bool version number or false if the component is not found
260 function get_component_version($component, $source='installed') {
261 global $CFG, $DB;
263 list($type, $name) = core_component::normalize_component($component);
265 // moodle core or a core subsystem
266 if ($type === 'core') {
267 if ($source === 'installed') {
268 if (empty($CFG->version)) {
269 return false;
270 } else {
271 return $CFG->version;
273 } else {
274 if (!is_readable($CFG->dirroot.'/version.php')) {
275 return false;
276 } else {
277 $version = null; //initialize variable for IDEs
278 include($CFG->dirroot.'/version.php');
279 return $version;
284 // activity module
285 if ($type === 'mod') {
286 if ($source === 'installed') {
287 if ($CFG->version < 2013092001.02) {
288 return $DB->get_field('modules', 'version', array('name'=>$name));
289 } else {
290 return get_config('mod_'.$name, 'version');
293 } else {
294 $mods = core_component::get_plugin_list('mod');
295 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
296 return false;
297 } else {
298 $plugin = new stdClass();
299 $plugin->version = null;
300 $module = $plugin;
301 include($mods[$name].'/version.php');
302 return $plugin->version;
307 // block
308 if ($type === 'block') {
309 if ($source === 'installed') {
310 if ($CFG->version < 2013092001.02) {
311 return $DB->get_field('block', 'version', array('name'=>$name));
312 } else {
313 return get_config('block_'.$name, 'version');
315 } else {
316 $blocks = core_component::get_plugin_list('block');
317 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
318 return false;
319 } else {
320 $plugin = new stdclass();
321 include($blocks[$name].'/version.php');
322 return $plugin->version;
327 // all other plugin types
328 if ($source === 'installed') {
329 return get_config($type.'_'.$name, 'version');
330 } else {
331 $plugins = core_component::get_plugin_list($type);
332 if (empty($plugins[$name])) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($plugins[$name].'/version.php');
337 return $plugin->version;
343 * Delete all plugin tables
345 * @param string $name Name of plugin, used as table prefix
346 * @param string $file Path to install.xml file
347 * @param bool $feedback defaults to true
348 * @return bool Always returns true
350 function drop_plugin_tables($name, $file, $feedback=true) {
351 global $CFG, $DB;
353 // first try normal delete
354 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
355 return true;
358 // then try to find all tables that start with name and are not in any xml file
359 $used_tables = get_used_table_names();
361 $tables = $DB->get_tables();
363 /// Iterate over, fixing id fields as necessary
364 foreach ($tables as $table) {
365 if (in_array($table, $used_tables)) {
366 continue;
369 if (strpos($table, $name) !== 0) {
370 continue;
373 // found orphan table --> delete it
374 if ($DB->get_manager()->table_exists($table)) {
375 $xmldb_table = new xmldb_table($table);
376 $DB->get_manager()->drop_table($xmldb_table);
380 return true;
384 * Returns names of all known tables == tables that moodle knows about.
386 * @return array Array of lowercase table names
388 function get_used_table_names() {
389 $table_names = array();
390 $dbdirs = get_db_directories();
392 foreach ($dbdirs as $dbdir) {
393 $file = $dbdir.'/install.xml';
395 $xmldb_file = new xmldb_file($file);
397 if (!$xmldb_file->fileExists()) {
398 continue;
401 $loaded = $xmldb_file->loadXMLStructure();
402 $structure = $xmldb_file->getStructure();
404 if ($loaded and $tables = $structure->getTables()) {
405 foreach($tables as $table) {
406 $table_names[] = strtolower($table->getName());
411 return $table_names;
415 * Returns list of all directories where we expect install.xml files
416 * @return array Array of paths
418 function get_db_directories() {
419 global $CFG;
421 $dbdirs = array();
423 /// First, the main one (lib/db)
424 $dbdirs[] = $CFG->libdir.'/db';
426 /// Then, all the ones defined by core_component::get_plugin_types()
427 $plugintypes = core_component::get_plugin_types();
428 foreach ($plugintypes as $plugintype => $pluginbasedir) {
429 if ($plugins = core_component::get_plugin_list($plugintype)) {
430 foreach ($plugins as $plugin => $plugindir) {
431 $dbdirs[] = $plugindir.'/db';
436 return $dbdirs;
440 * Try to obtain or release the cron lock.
441 * @param string $name name of lock
442 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
443 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
444 * @return bool true if lock obtained
446 function set_cron_lock($name, $until, $ignorecurrent=false) {
447 global $DB;
448 if (empty($name)) {
449 debugging("Tried to get a cron lock for a null fieldname");
450 return false;
453 // remove lock by force == remove from config table
454 if (is_null($until)) {
455 set_config($name, null);
456 return true;
459 if (!$ignorecurrent) {
460 // read value from db - other processes might have changed it
461 $value = $DB->get_field('config', 'value', array('name'=>$name));
463 if ($value and $value > time()) {
464 //lock active
465 return false;
469 set_config($name, $until);
470 return true;
474 * Test if and critical warnings are present
475 * @return bool
477 function admin_critical_warnings_present() {
478 global $SESSION;
480 if (!has_capability('moodle/site:config', context_system::instance())) {
481 return 0;
484 if (!isset($SESSION->admin_critical_warning)) {
485 $SESSION->admin_critical_warning = 0;
486 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
487 $SESSION->admin_critical_warning = 1;
491 return $SESSION->admin_critical_warning;
495 * Detects if float supports at least 10 decimal digits
497 * Detects if float supports at least 10 decimal digits
498 * and also if float-->string conversion works as expected.
500 * @return bool true if problem found
502 function is_float_problem() {
503 $num1 = 2009010200.01;
504 $num2 = 2009010200.02;
506 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
510 * Try to verify that dataroot is not accessible from web.
512 * Try to verify that dataroot is not accessible from web.
513 * It is not 100% correct but might help to reduce number of vulnerable sites.
514 * Protection from httpd.conf and .htaccess is not detected properly.
516 * @uses INSECURE_DATAROOT_WARNING
517 * @uses INSECURE_DATAROOT_ERROR
518 * @param bool $fetchtest try to test public access by fetching file, default false
519 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
521 function is_dataroot_insecure($fetchtest=false) {
522 global $CFG;
524 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
526 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
527 $rp = strrev(trim($rp, '/'));
528 $rp = explode('/', $rp);
529 foreach($rp as $r) {
530 if (strpos($siteroot, '/'.$r.'/') === 0) {
531 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
532 } else {
533 break; // probably alias root
537 $siteroot = strrev($siteroot);
538 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
540 if (strpos($dataroot, $siteroot) !== 0) {
541 return false;
544 if (!$fetchtest) {
545 return INSECURE_DATAROOT_WARNING;
548 // now try all methods to fetch a test file using http protocol
550 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
551 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
552 $httpdocroot = $matches[1];
553 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
554 make_upload_directory('diag');
555 $testfile = $CFG->dataroot.'/diag/public.txt';
556 if (!file_exists($testfile)) {
557 file_put_contents($testfile, 'test file, do not delete');
558 @chmod($testfile, $CFG->filepermissions);
560 $teststr = trim(file_get_contents($testfile));
561 if (empty($teststr)) {
562 // hmm, strange
563 return INSECURE_DATAROOT_WARNING;
566 $testurl = $datarooturl.'/diag/public.txt';
567 if (extension_loaded('curl') and
568 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
569 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
570 ($ch = @curl_init($testurl)) !== false) {
571 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
572 curl_setopt($ch, CURLOPT_HEADER, false);
573 $data = curl_exec($ch);
574 if (!curl_errno($ch)) {
575 $data = trim($data);
576 if ($data === $teststr) {
577 curl_close($ch);
578 return INSECURE_DATAROOT_ERROR;
581 curl_close($ch);
584 if ($data = @file_get_contents($testurl)) {
585 $data = trim($data);
586 if ($data === $teststr) {
587 return INSECURE_DATAROOT_ERROR;
591 preg_match('|https?://([^/]+)|i', $testurl, $matches);
592 $sitename = $matches[1];
593 $error = 0;
594 if ($fp = @fsockopen($sitename, 80, $error)) {
595 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
596 $localurl = $matches[1];
597 $out = "GET $localurl HTTP/1.1\r\n";
598 $out .= "Host: $sitename\r\n";
599 $out .= "Connection: Close\r\n\r\n";
600 fwrite($fp, $out);
601 $data = '';
602 $incoming = false;
603 while (!feof($fp)) {
604 if ($incoming) {
605 $data .= fgets($fp, 1024);
606 } else if (@fgets($fp, 1024) === "\r\n") {
607 $incoming = true;
610 fclose($fp);
611 $data = trim($data);
612 if ($data === $teststr) {
613 return INSECURE_DATAROOT_ERROR;
617 return INSECURE_DATAROOT_WARNING;
621 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
623 function enable_cli_maintenance_mode() {
624 global $CFG;
626 if (file_exists("$CFG->dataroot/climaintenance.html")) {
627 unlink("$CFG->dataroot/climaintenance.html");
630 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
631 $data = $CFG->maintenance_message;
632 $data = bootstrap_renderer::early_error_content($data, null, null, null);
633 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
635 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
636 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
638 } else {
639 $data = get_string('sitemaintenance', 'admin');
640 $data = bootstrap_renderer::early_error_content($data, null, null, null);
641 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
644 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
645 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
648 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
652 * Interface for anything appearing in the admin tree
654 * The interface that is implemented by anything that appears in the admin tree
655 * block. It forces inheriting classes to define a method for checking user permissions
656 * and methods for finding something in the admin tree.
658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
660 interface part_of_admin_tree {
663 * Finds a named part_of_admin_tree.
665 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
666 * and not parentable_part_of_admin_tree, then this function should only check if
667 * $this->name matches $name. If it does, it should return a reference to $this,
668 * otherwise, it should return a reference to NULL.
670 * If a class inherits parentable_part_of_admin_tree, this method should be called
671 * recursively on all child objects (assuming, of course, the parent object's name
672 * doesn't match the search criterion).
674 * @param string $name The internal name of the part_of_admin_tree we're searching for.
675 * @return mixed An object reference or a NULL reference.
677 public function locate($name);
680 * Removes named part_of_admin_tree.
682 * @param string $name The internal name of the part_of_admin_tree we want to remove.
683 * @return bool success.
685 public function prune($name);
688 * Search using query
689 * @param string $query
690 * @return mixed array-object structure of found settings and pages
692 public function search($query);
695 * Verifies current user's access to this part_of_admin_tree.
697 * Used to check if the current user has access to this part of the admin tree or
698 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
699 * then this method is usually just a call to has_capability() in the site context.
701 * If a class inherits parentable_part_of_admin_tree, this method should return the
702 * logical OR of the return of check_access() on all child objects.
704 * @return bool True if the user has access, false if she doesn't.
706 public function check_access();
709 * Mostly useful for removing of some parts of the tree in admin tree block.
711 * @return True is hidden from normal list view
713 public function is_hidden();
716 * Show we display Save button at the page bottom?
717 * @return bool
719 public function show_save();
724 * Interface implemented by any part_of_admin_tree that has children.
726 * The interface implemented by any part_of_admin_tree that can be a parent
727 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
728 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
729 * include an add method for adding other part_of_admin_tree objects as children.
731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 interface parentable_part_of_admin_tree extends part_of_admin_tree {
736 * Adds a part_of_admin_tree object to the admin tree.
738 * Used to add a part_of_admin_tree object to this object or a child of this
739 * object. $something should only be added if $destinationname matches
740 * $this->name. If it doesn't, add should be called on child objects that are
741 * also parentable_part_of_admin_tree's.
743 * $something should be appended as the last child in the $destinationname. If the
744 * $beforesibling is specified, $something should be prepended to it. If the given
745 * sibling is not found, $something should be appended to the end of $destinationname
746 * and a developer debugging message should be displayed.
748 * @param string $destinationname The internal name of the new parent for $something.
749 * @param part_of_admin_tree $something The object to be added.
750 * @return bool True on success, false on failure.
752 public function add($destinationname, $something, $beforesibling = null);
758 * The object used to represent folders (a.k.a. categories) in the admin tree block.
760 * Each admin_category object contains a number of part_of_admin_tree objects.
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class admin_category implements parentable_part_of_admin_tree {
766 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
767 protected $children;
768 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
769 public $name;
770 /** @var string The displayed name for this category. Usually obtained through get_string() */
771 public $visiblename;
772 /** @var bool Should this category be hidden in admin tree block? */
773 public $hidden;
774 /** @var mixed Either a string or an array or strings */
775 public $path;
776 /** @var mixed Either a string or an array or strings */
777 public $visiblepath;
779 /** @var array fast lookup category cache, all categories of one tree point to one cache */
780 protected $category_cache;
782 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
783 protected $sort = false;
784 /** @var bool If set to true children will be sorted in ascending order. */
785 protected $sortasc = true;
786 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
787 protected $sortsplit = true;
788 /** @var bool $sorted True if the children have been sorted and don't need resorting */
789 protected $sorted = false;
792 * Constructor for an empty admin category
794 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
795 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
796 * @param bool $hidden hide category in admin tree block, defaults to false
798 public function __construct($name, $visiblename, $hidden=false) {
799 $this->children = array();
800 $this->name = $name;
801 $this->visiblename = $visiblename;
802 $this->hidden = $hidden;
806 * Returns a reference to the part_of_admin_tree object with internal name $name.
808 * @param string $name The internal name of the object we want.
809 * @param bool $findpath initialize path and visiblepath arrays
810 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
811 * defaults to false
813 public function locate($name, $findpath=false) {
814 if (!isset($this->category_cache[$this->name])) {
815 // somebody much have purged the cache
816 $this->category_cache[$this->name] = $this;
819 if ($this->name == $name) {
820 if ($findpath) {
821 $this->visiblepath[] = $this->visiblename;
822 $this->path[] = $this->name;
824 return $this;
827 // quick category lookup
828 if (!$findpath and isset($this->category_cache[$name])) {
829 return $this->category_cache[$name];
832 $return = NULL;
833 foreach($this->children as $childid=>$unused) {
834 if ($return = $this->children[$childid]->locate($name, $findpath)) {
835 break;
839 if (!is_null($return) and $findpath) {
840 $return->visiblepath[] = $this->visiblename;
841 $return->path[] = $this->name;
844 return $return;
848 * Search using query
850 * @param string query
851 * @return mixed array-object structure of found settings and pages
853 public function search($query) {
854 $result = array();
855 foreach ($this->get_children() as $child) {
856 $subsearch = $child->search($query);
857 if (!is_array($subsearch)) {
858 debugging('Incorrect search result from '.$child->name);
859 continue;
861 $result = array_merge($result, $subsearch);
863 return $result;
867 * Removes part_of_admin_tree object with internal name $name.
869 * @param string $name The internal name of the object we want to remove.
870 * @return bool success
872 public function prune($name) {
874 if ($this->name == $name) {
875 return false; //can not remove itself
878 foreach($this->children as $precedence => $child) {
879 if ($child->name == $name) {
880 // clear cache and delete self
881 while($this->category_cache) {
882 // delete the cache, but keep the original array address
883 array_pop($this->category_cache);
885 unset($this->children[$precedence]);
886 return true;
887 } else if ($this->children[$precedence]->prune($name)) {
888 return true;
891 return false;
895 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
897 * By default the new part of the tree is appended as the last child of the parent. You
898 * can specify a sibling node that the new part should be prepended to. If the given
899 * sibling is not found, the part is appended to the end (as it would be by default) and
900 * a developer debugging message is displayed.
902 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
903 * @param string $destinationame The internal name of the immediate parent that we want for $something.
904 * @param mixed $something A part_of_admin_tree or setting instance to be added.
905 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
906 * @return bool True if successfully added, false if $something can not be added.
908 public function add($parentname, $something, $beforesibling = null) {
909 global $CFG;
911 $parent = $this->locate($parentname);
912 if (is_null($parent)) {
913 debugging('parent does not exist!');
914 return false;
917 if ($something instanceof part_of_admin_tree) {
918 if (!($parent instanceof parentable_part_of_admin_tree)) {
919 debugging('error - parts of tree can be inserted only into parentable parts');
920 return false;
922 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
923 // The name of the node is already used, simply warn the developer that this should not happen.
924 // It is intentional to check for the debug level before performing the check.
925 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
927 if (is_null($beforesibling)) {
928 // Append $something as the parent's last child.
929 $parent->children[] = $something;
930 } else {
931 if (!is_string($beforesibling) or trim($beforesibling) === '') {
932 throw new coding_exception('Unexpected value of the beforesibling parameter');
934 // Try to find the position of the sibling.
935 $siblingposition = null;
936 foreach ($parent->children as $childposition => $child) {
937 if ($child->name === $beforesibling) {
938 $siblingposition = $childposition;
939 break;
942 if (is_null($siblingposition)) {
943 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
944 $parent->children[] = $something;
945 } else {
946 $parent->children = array_merge(
947 array_slice($parent->children, 0, $siblingposition),
948 array($something),
949 array_slice($parent->children, $siblingposition)
953 if ($something instanceof admin_category) {
954 if (isset($this->category_cache[$something->name])) {
955 debugging('Duplicate admin category name: '.$something->name);
956 } else {
957 $this->category_cache[$something->name] = $something;
958 $something->category_cache =& $this->category_cache;
959 foreach ($something->children as $child) {
960 // just in case somebody already added subcategories
961 if ($child instanceof admin_category) {
962 if (isset($this->category_cache[$child->name])) {
963 debugging('Duplicate admin category name: '.$child->name);
964 } else {
965 $this->category_cache[$child->name] = $child;
966 $child->category_cache =& $this->category_cache;
972 return true;
974 } else {
975 debugging('error - can not add this element');
976 return false;
982 * Checks if the user has access to anything in this category.
984 * @return bool True if the user has access to at least one child in this category, false otherwise.
986 public function check_access() {
987 foreach ($this->children as $child) {
988 if ($child->check_access()) {
989 return true;
992 return false;
996 * Is this category hidden in admin tree block?
998 * @return bool True if hidden
1000 public function is_hidden() {
1001 return $this->hidden;
1005 * Show we display Save button at the page bottom?
1006 * @return bool
1008 public function show_save() {
1009 foreach ($this->children as $child) {
1010 if ($child->show_save()) {
1011 return true;
1014 return false;
1018 * Sets sorting on this category.
1020 * Please note this function doesn't actually do the sorting.
1021 * It can be called anytime.
1022 * Sorting occurs when the user calls get_children.
1023 * Code using the children array directly won't see the sorted results.
1025 * @param bool $sort If set to true children will be sorted, if false they won't be.
1026 * @param bool $asc If true sorting will be ascending, otherwise descending.
1027 * @param bool $split If true we sort pages and sub categories separately.
1029 public function set_sorting($sort, $asc = true, $split = true) {
1030 $this->sort = (bool)$sort;
1031 $this->sortasc = (bool)$asc;
1032 $this->sortsplit = (bool)$split;
1036 * Returns the children associated with this category.
1038 * @return part_of_admin_tree[]
1040 public function get_children() {
1041 // If we should sort and it hasn't already been sorted.
1042 if ($this->sort && !$this->sorted) {
1043 if ($this->sortsplit) {
1044 $categories = array();
1045 $pages = array();
1046 foreach ($this->children as $child) {
1047 if ($child instanceof admin_category) {
1048 $categories[] = $child;
1049 } else {
1050 $pages[] = $child;
1053 core_collator::asort_objects_by_property($categories, 'visiblename');
1054 core_collator::asort_objects_by_property($pages, 'visiblename');
1055 if (!$this->sortasc) {
1056 $categories = array_reverse($categories);
1057 $pages = array_reverse($pages);
1059 $this->children = array_merge($pages, $categories);
1060 } else {
1061 core_collator::asort_objects_by_property($this->children, 'visiblename');
1062 if (!$this->sortasc) {
1063 $this->children = array_reverse($this->children);
1066 $this->sorted = true;
1068 return $this->children;
1072 * Magically gets a property from this object.
1074 * @param $property
1075 * @return part_of_admin_tree[]
1076 * @throws coding_exception
1078 public function __get($property) {
1079 if ($property === 'children') {
1080 return $this->get_children();
1082 throw new coding_exception('Invalid property requested.');
1086 * Magically sets a property against this object.
1088 * @param string $property
1089 * @param mixed $value
1090 * @throws coding_exception
1092 public function __set($property, $value) {
1093 if ($property === 'children') {
1094 $this->sorted = false;
1095 $this->children = $value;
1096 } else {
1097 throw new coding_exception('Invalid property requested.');
1102 * Checks if an inaccessible property is set.
1104 * @param string $property
1105 * @return bool
1106 * @throws coding_exception
1108 public function __isset($property) {
1109 if ($property === 'children') {
1110 return isset($this->children);
1112 throw new coding_exception('Invalid property requested.');
1118 * Root of admin settings tree, does not have any parent.
1120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1122 class admin_root extends admin_category {
1123 /** @var array List of errors */
1124 public $errors;
1125 /** @var string search query */
1126 public $search;
1127 /** @var bool full tree flag - true means all settings required, false only pages required */
1128 public $fulltree;
1129 /** @var bool flag indicating loaded tree */
1130 public $loaded;
1131 /** @var mixed site custom defaults overriding defaults in settings files*/
1132 public $custom_defaults;
1135 * @param bool $fulltree true means all settings required,
1136 * false only pages required
1138 public function __construct($fulltree) {
1139 global $CFG;
1141 parent::__construct('root', get_string('administration'), false);
1142 $this->errors = array();
1143 $this->search = '';
1144 $this->fulltree = $fulltree;
1145 $this->loaded = false;
1147 $this->category_cache = array();
1149 // load custom defaults if found
1150 $this->custom_defaults = null;
1151 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1152 if (is_readable($defaultsfile)) {
1153 $defaults = array();
1154 include($defaultsfile);
1155 if (is_array($defaults) and count($defaults)) {
1156 $this->custom_defaults = $defaults;
1162 * Empties children array, and sets loaded to false
1164 * @param bool $requirefulltree
1166 public function purge_children($requirefulltree) {
1167 $this->children = array();
1168 $this->fulltree = ($requirefulltree || $this->fulltree);
1169 $this->loaded = false;
1170 //break circular dependencies - this helps PHP 5.2
1171 while($this->category_cache) {
1172 array_pop($this->category_cache);
1174 $this->category_cache = array();
1180 * Links external PHP pages into the admin tree.
1182 * See detailed usage example at the top of this document (adminlib.php)
1184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1186 class admin_externalpage implements part_of_admin_tree {
1188 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1189 public $name;
1191 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1192 public $visiblename;
1194 /** @var string The external URL that we should link to when someone requests this external page. */
1195 public $url;
1197 /** @var string The role capability/permission a user must have to access this external page. */
1198 public $req_capability;
1200 /** @var object The context in which capability/permission should be checked, default is site context. */
1201 public $context;
1203 /** @var bool hidden in admin tree block. */
1204 public $hidden;
1206 /** @var mixed either string or array of string */
1207 public $path;
1209 /** @var array list of visible names of page parents */
1210 public $visiblepath;
1213 * Constructor for adding an external page into the admin tree.
1215 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1216 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1217 * @param string $url The external URL that we should link to when someone requests this external page.
1218 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1219 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1220 * @param stdClass $context The context the page relates to. Not sure what happens
1221 * if you specify something other than system or front page. Defaults to system.
1223 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1224 $this->name = $name;
1225 $this->visiblename = $visiblename;
1226 $this->url = $url;
1227 if (is_array($req_capability)) {
1228 $this->req_capability = $req_capability;
1229 } else {
1230 $this->req_capability = array($req_capability);
1232 $this->hidden = $hidden;
1233 $this->context = $context;
1237 * Returns a reference to the part_of_admin_tree object with internal name $name.
1239 * @param string $name The internal name of the object we want.
1240 * @param bool $findpath defaults to false
1241 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1243 public function locate($name, $findpath=false) {
1244 if ($this->name == $name) {
1245 if ($findpath) {
1246 $this->visiblepath = array($this->visiblename);
1247 $this->path = array($this->name);
1249 return $this;
1250 } else {
1251 $return = NULL;
1252 return $return;
1257 * This function always returns false, required function by interface
1259 * @param string $name
1260 * @return false
1262 public function prune($name) {
1263 return false;
1267 * Search using query
1269 * @param string $query
1270 * @return mixed array-object structure of found settings and pages
1272 public function search($query) {
1273 $found = false;
1274 if (strpos(strtolower($this->name), $query) !== false) {
1275 $found = true;
1276 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1277 $found = true;
1279 if ($found) {
1280 $result = new stdClass();
1281 $result->page = $this;
1282 $result->settings = array();
1283 return array($this->name => $result);
1284 } else {
1285 return array();
1290 * Determines if the current user has access to this external page based on $this->req_capability.
1292 * @return bool True if user has access, false otherwise.
1294 public function check_access() {
1295 global $CFG;
1296 $context = empty($this->context) ? context_system::instance() : $this->context;
1297 foreach($this->req_capability as $cap) {
1298 if (has_capability($cap, $context)) {
1299 return true;
1302 return false;
1306 * Is this external page hidden in admin tree block?
1308 * @return bool True if hidden
1310 public function is_hidden() {
1311 return $this->hidden;
1315 * Show we display Save button at the page bottom?
1316 * @return bool
1318 public function show_save() {
1319 return false;
1325 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1329 class admin_settingpage implements part_of_admin_tree {
1331 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1332 public $name;
1334 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1335 public $visiblename;
1337 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1338 public $settings;
1340 /** @var string The role capability/permission a user must have to access this external page. */
1341 public $req_capability;
1343 /** @var object The context in which capability/permission should be checked, default is site context. */
1344 public $context;
1346 /** @var bool hidden in admin tree block. */
1347 public $hidden;
1349 /** @var mixed string of paths or array of strings of paths */
1350 public $path;
1352 /** @var array list of visible names of page parents */
1353 public $visiblepath;
1356 * see admin_settingpage for details of this function
1358 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1359 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1360 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1361 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1362 * @param stdClass $context The context the page relates to. Not sure what happens
1363 * if you specify something other than system or front page. Defaults to system.
1365 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1366 $this->settings = new stdClass();
1367 $this->name = $name;
1368 $this->visiblename = $visiblename;
1369 if (is_array($req_capability)) {
1370 $this->req_capability = $req_capability;
1371 } else {
1372 $this->req_capability = array($req_capability);
1374 $this->hidden = $hidden;
1375 $this->context = $context;
1379 * see admin_category
1381 * @param string $name
1382 * @param bool $findpath
1383 * @return mixed Object (this) if name == this->name, else returns null
1385 public function locate($name, $findpath=false) {
1386 if ($this->name == $name) {
1387 if ($findpath) {
1388 $this->visiblepath = array($this->visiblename);
1389 $this->path = array($this->name);
1391 return $this;
1392 } else {
1393 $return = NULL;
1394 return $return;
1399 * Search string in settings page.
1401 * @param string $query
1402 * @return array
1404 public function search($query) {
1405 $found = array();
1407 foreach ($this->settings as $setting) {
1408 if ($setting->is_related($query)) {
1409 $found[] = $setting;
1413 if ($found) {
1414 $result = new stdClass();
1415 $result->page = $this;
1416 $result->settings = $found;
1417 return array($this->name => $result);
1420 $found = false;
1421 if (strpos(strtolower($this->name), $query) !== false) {
1422 $found = true;
1423 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1424 $found = true;
1426 if ($found) {
1427 $result = new stdClass();
1428 $result->page = $this;
1429 $result->settings = array();
1430 return array($this->name => $result);
1431 } else {
1432 return array();
1437 * This function always returns false, required by interface
1439 * @param string $name
1440 * @return bool Always false
1442 public function prune($name) {
1443 return false;
1447 * adds an admin_setting to this admin_settingpage
1449 * 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
1450 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1452 * @param object $setting is the admin_setting object you want to add
1453 * @return bool true if successful, false if not
1455 public function add($setting) {
1456 if (!($setting instanceof admin_setting)) {
1457 debugging('error - not a setting instance');
1458 return false;
1461 $name = $setting->name;
1462 if ($setting->plugin) {
1463 $name = $setting->plugin . $name;
1465 $this->settings->{$name} = $setting;
1466 return true;
1470 * see admin_externalpage
1472 * @return bool Returns true for yes false for no
1474 public function check_access() {
1475 global $CFG;
1476 $context = empty($this->context) ? context_system::instance() : $this->context;
1477 foreach($this->req_capability as $cap) {
1478 if (has_capability($cap, $context)) {
1479 return true;
1482 return false;
1486 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1487 * @return string Returns an XHTML string
1489 public function output_html() {
1490 $adminroot = admin_get_root();
1491 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1492 foreach($this->settings as $setting) {
1493 $fullname = $setting->get_full_name();
1494 if (array_key_exists($fullname, $adminroot->errors)) {
1495 $data = $adminroot->errors[$fullname]->data;
1496 } else {
1497 $data = $setting->get_setting();
1498 // do not use defaults if settings not available - upgrade settings handles the defaults!
1500 $return .= $setting->output_html($data);
1502 $return .= '</fieldset>';
1503 return $return;
1507 * Is this settings page hidden in admin tree block?
1509 * @return bool True if hidden
1511 public function is_hidden() {
1512 return $this->hidden;
1516 * Show we display Save button at the page bottom?
1517 * @return bool
1519 public function show_save() {
1520 foreach($this->settings as $setting) {
1521 if (empty($setting->nosave)) {
1522 return true;
1525 return false;
1531 * Admin settings class. Only exists on setting pages.
1532 * Read & write happens at this level; no authentication.
1534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1536 abstract class admin_setting {
1537 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1538 public $name;
1539 /** @var string localised name */
1540 public $visiblename;
1541 /** @var string localised long description in Markdown format */
1542 public $description;
1543 /** @var mixed Can be string or array of string */
1544 public $defaultsetting;
1545 /** @var string */
1546 public $updatedcallback;
1547 /** @var mixed can be String or Null. Null means main config table */
1548 public $plugin; // null means main config table
1549 /** @var bool true indicates this setting does not actually save anything, just information */
1550 public $nosave = false;
1551 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1552 public $affectsmodinfo = false;
1553 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1554 private $flags = array();
1555 /** @var bool Whether this field must be forced LTR. */
1556 private $forceltr = null;
1559 * Constructor
1560 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1561 * or 'myplugin/mysetting' for ones in config_plugins.
1562 * @param string $visiblename localised name
1563 * @param string $description localised long description
1564 * @param mixed $defaultsetting string or array depending on implementation
1566 public function __construct($name, $visiblename, $description, $defaultsetting) {
1567 $this->parse_setting_name($name);
1568 $this->visiblename = $visiblename;
1569 $this->description = $description;
1570 $this->defaultsetting = $defaultsetting;
1574 * Generic function to add a flag to this admin setting.
1576 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1577 * @param bool $default - The default for the flag
1578 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1579 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1581 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1582 if (empty($this->flags[$shortname])) {
1583 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1584 } else {
1585 $this->flags[$shortname]->set_options($enabled, $default);
1590 * Set the enabled options flag on this admin setting.
1592 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1593 * @param bool $default - The default for the flag
1595 public function set_enabled_flag_options($enabled, $default) {
1596 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1600 * Set the advanced options flag on this admin setting.
1602 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1603 * @param bool $default - The default for the flag
1605 public function set_advanced_flag_options($enabled, $default) {
1606 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1611 * Set the locked options flag on this admin setting.
1613 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1614 * @param bool $default - The default for the flag
1616 public function set_locked_flag_options($enabled, $default) {
1617 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1621 * Get the currently saved value for a setting flag
1623 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1624 * @return bool
1626 public function get_setting_flag_value(admin_setting_flag $flag) {
1627 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1628 if (!isset($value)) {
1629 $value = $flag->get_default();
1632 return !empty($value);
1636 * Get the list of defaults for the flags on this setting.
1638 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1640 public function get_setting_flag_defaults(& $defaults) {
1641 foreach ($this->flags as $flag) {
1642 if ($flag->is_enabled() && $flag->get_default()) {
1643 $defaults[] = $flag->get_displayname();
1649 * Output the input fields for the advanced and locked flags on this setting.
1651 * @param bool $adv - The current value of the advanced flag.
1652 * @param bool $locked - The current value of the locked flag.
1653 * @return string $output - The html for the flags.
1655 public function output_setting_flags() {
1656 $output = '';
1658 foreach ($this->flags as $flag) {
1659 if ($flag->is_enabled()) {
1660 $output .= $flag->output_setting_flag($this);
1664 if (!empty($output)) {
1665 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1667 return $output;
1671 * Write the values of the flags for this admin setting.
1673 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1674 * @return bool - true if successful.
1676 public function write_setting_flags($data) {
1677 $result = true;
1678 foreach ($this->flags as $flag) {
1679 $result = $result && $flag->write_setting_flag($this, $data);
1681 return $result;
1685 * Set up $this->name and potentially $this->plugin
1687 * Set up $this->name and possibly $this->plugin based on whether $name looks
1688 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1689 * on the names, that is, output a developer debug warning if the name
1690 * contains anything other than [a-zA-Z0-9_]+.
1692 * @param string $name the setting name passed in to the constructor.
1694 private function parse_setting_name($name) {
1695 $bits = explode('/', $name);
1696 if (count($bits) > 2) {
1697 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1699 $this->name = array_pop($bits);
1700 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1701 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1703 if (!empty($bits)) {
1704 $this->plugin = array_pop($bits);
1705 if ($this->plugin === 'moodle') {
1706 $this->plugin = null;
1707 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1708 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1714 * Returns the fullname prefixed by the plugin
1715 * @return string
1717 public function get_full_name() {
1718 return 's_'.$this->plugin.'_'.$this->name;
1722 * Returns the ID string based on plugin and name
1723 * @return string
1725 public function get_id() {
1726 return 'id_s_'.$this->plugin.'_'.$this->name;
1730 * @param bool $affectsmodinfo If true, changes to this setting will
1731 * cause the course cache to be rebuilt
1733 public function set_affects_modinfo($affectsmodinfo) {
1734 $this->affectsmodinfo = $affectsmodinfo;
1738 * Returns the config if possible
1740 * @return mixed returns config if successful else null
1742 public function config_read($name) {
1743 global $CFG;
1744 if (!empty($this->plugin)) {
1745 $value = get_config($this->plugin, $name);
1746 return $value === false ? NULL : $value;
1748 } else {
1749 if (isset($CFG->$name)) {
1750 return $CFG->$name;
1751 } else {
1752 return NULL;
1758 * Used to set a config pair and log change
1760 * @param string $name
1761 * @param mixed $value Gets converted to string if not null
1762 * @return bool Write setting to config table
1764 public function config_write($name, $value) {
1765 global $DB, $USER, $CFG;
1767 if ($this->nosave) {
1768 return true;
1771 // make sure it is a real change
1772 $oldvalue = get_config($this->plugin, $name);
1773 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1774 $value = is_null($value) ? null : (string)$value;
1776 if ($oldvalue === $value) {
1777 return true;
1780 // store change
1781 set_config($name, $value, $this->plugin);
1783 // Some admin settings affect course modinfo
1784 if ($this->affectsmodinfo) {
1785 // Clear course cache for all courses
1786 rebuild_course_cache(0, true);
1789 $this->add_to_config_log($name, $oldvalue, $value);
1791 return true; // BC only
1795 * Log config changes if necessary.
1796 * @param string $name
1797 * @param string $oldvalue
1798 * @param string $value
1800 protected function add_to_config_log($name, $oldvalue, $value) {
1801 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1805 * Returns current value of this setting
1806 * @return mixed array or string depending on instance, NULL means not set yet
1808 public abstract function get_setting();
1811 * Returns default setting if exists
1812 * @return mixed array or string depending on instance; NULL means no default, user must supply
1814 public function get_defaultsetting() {
1815 $adminroot = admin_get_root(false, false);
1816 if (!empty($adminroot->custom_defaults)) {
1817 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1818 if (isset($adminroot->custom_defaults[$plugin])) {
1819 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1820 return $adminroot->custom_defaults[$plugin][$this->name];
1824 return $this->defaultsetting;
1828 * Store new setting
1830 * @param mixed $data string or array, must not be NULL
1831 * @return string empty string if ok, string error message otherwise
1833 public abstract function write_setting($data);
1836 * Return part of form with setting
1837 * This function should always be overwritten
1839 * @param mixed $data array or string depending on setting
1840 * @param string $query
1841 * @return string
1843 public function output_html($data, $query='') {
1844 // should be overridden
1845 return;
1849 * Function called if setting updated - cleanup, cache reset, etc.
1850 * @param string $functionname Sets the function name
1851 * @return void
1853 public function set_updatedcallback($functionname) {
1854 $this->updatedcallback = $functionname;
1858 * Execute postupdatecallback if necessary.
1859 * @param mixed $original original value before write_setting()
1860 * @return bool true if changed, false if not.
1862 public function post_write_settings($original) {
1863 // Comparison must work for arrays too.
1864 if (serialize($original) === serialize($this->get_setting())) {
1865 return false;
1868 $callbackfunction = $this->updatedcallback;
1869 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
1870 $callbackfunction($this->get_full_name());
1872 return true;
1876 * Is setting related to query text - used when searching
1877 * @param string $query
1878 * @return bool
1880 public function is_related($query) {
1881 if (strpos(strtolower($this->name), $query) !== false) {
1882 return true;
1884 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1885 return true;
1887 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1888 return true;
1890 $current = $this->get_setting();
1891 if (!is_null($current)) {
1892 if (is_string($current)) {
1893 if (strpos(core_text::strtolower($current), $query) !== false) {
1894 return true;
1898 $default = $this->get_defaultsetting();
1899 if (!is_null($default)) {
1900 if (is_string($default)) {
1901 if (strpos(core_text::strtolower($default), $query) !== false) {
1902 return true;
1906 return false;
1910 * Get whether this should be displayed in LTR mode.
1912 * @return bool|null
1914 public function get_force_ltr() {
1915 return $this->forceltr;
1919 * Set whether to force LTR or not.
1921 * @param bool $value True when forced, false when not force, null when unknown.
1923 public function set_force_ltr($value) {
1924 $this->forceltr = $value;
1929 * An additional option that can be applied to an admin setting.
1930 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1934 class admin_setting_flag {
1935 /** @var bool Flag to indicate if this option can be toggled for this setting */
1936 private $enabled = false;
1937 /** @var bool Flag to indicate if this option defaults to true or false */
1938 private $default = false;
1939 /** @var string Short string used to create setting name - e.g. 'adv' */
1940 private $shortname = '';
1941 /** @var string String used as the label for this flag */
1942 private $displayname = '';
1943 /** @const Checkbox for this flag is displayed in admin page */
1944 const ENABLED = true;
1945 /** @const Checkbox for this flag is not displayed in admin page */
1946 const DISABLED = false;
1949 * Constructor
1951 * @param bool $enabled Can this option can be toggled.
1952 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1953 * @param bool $default The default checked state for this setting option.
1954 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1955 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1957 public function __construct($enabled, $default, $shortname, $displayname) {
1958 $this->shortname = $shortname;
1959 $this->displayname = $displayname;
1960 $this->set_options($enabled, $default);
1964 * Update the values of this setting options class
1966 * @param bool $enabled Can this option can be toggled.
1967 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1968 * @param bool $default The default checked state for this setting option.
1970 public function set_options($enabled, $default) {
1971 $this->enabled = $enabled;
1972 $this->default = $default;
1976 * Should this option appear in the interface and be toggleable?
1978 * @return bool Is it enabled?
1980 public function is_enabled() {
1981 return $this->enabled;
1985 * Should this option be checked by default?
1987 * @return bool Is it on by default?
1989 public function get_default() {
1990 return $this->default;
1994 * Return the short name for this flag. e.g. 'adv' or 'locked'
1996 * @return string
1998 public function get_shortname() {
1999 return $this->shortname;
2003 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2005 * @return string
2007 public function get_displayname() {
2008 return $this->displayname;
2012 * Save the submitted data for this flag - or set it to the default if $data is null.
2014 * @param admin_setting $setting - The admin setting for this flag
2015 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2016 * @return bool
2018 public function write_setting_flag(admin_setting $setting, $data) {
2019 $result = true;
2020 if ($this->is_enabled()) {
2021 if (!isset($data)) {
2022 $value = $this->get_default();
2023 } else {
2024 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2026 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2029 return $result;
2034 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2036 * @param admin_setting $setting - The admin setting for this flag
2037 * @return string - The html for the checkbox.
2039 public function output_setting_flag(admin_setting $setting) {
2040 global $OUTPUT;
2042 $value = $setting->get_setting_flag_value($this);
2044 $context = new stdClass();
2045 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2046 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2047 $context->value = 1;
2048 $context->checked = $value ? true : false;
2049 $context->label = $this->get_displayname();
2051 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2057 * No setting - just heading and text.
2059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2061 class admin_setting_heading extends admin_setting {
2064 * not a setting, just text
2065 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2066 * @param string $heading heading
2067 * @param string $information text in box
2069 public function __construct($name, $heading, $information) {
2070 $this->nosave = true;
2071 parent::__construct($name, $heading, $information, '');
2075 * Always returns true
2076 * @return bool Always returns true
2078 public function get_setting() {
2079 return true;
2083 * Always returns true
2084 * @return bool Always returns true
2086 public function get_defaultsetting() {
2087 return true;
2091 * Never write settings
2092 * @return string Always returns an empty string
2094 public function write_setting($data) {
2095 // do not write any setting
2096 return '';
2100 * Returns an HTML string
2101 * @return string Returns an HTML string
2103 public function output_html($data, $query='') {
2104 global $OUTPUT;
2105 $context = new stdClass();
2106 $context->title = $this->visiblename;
2107 $context->description = $this->description;
2108 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2109 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2115 * The most flexible setting, the user enters text.
2117 * This type of field should be used for config settings which are using
2118 * English words and are not localised (passwords, database name, list of values, ...).
2120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2122 class admin_setting_configtext extends admin_setting {
2124 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2125 public $paramtype;
2126 /** @var int default field size */
2127 public $size;
2130 * Config text constructor
2132 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2133 * @param string $visiblename localised
2134 * @param string $description long localised info
2135 * @param string $defaultsetting
2136 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2137 * @param int $size default field size
2139 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2140 $this->paramtype = $paramtype;
2141 if (!is_null($size)) {
2142 $this->size = $size;
2143 } else {
2144 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2146 parent::__construct($name, $visiblename, $description, $defaultsetting);
2150 * Get whether this should be displayed in LTR mode.
2152 * Try to guess from the PARAM type unless specifically set.
2154 public function get_force_ltr() {
2155 $forceltr = parent::get_force_ltr();
2156 if ($forceltr === null) {
2157 return !is_rtl_compatible($this->paramtype);
2159 return $forceltr;
2163 * Return the setting
2165 * @return mixed returns config if successful else null
2167 public function get_setting() {
2168 return $this->config_read($this->name);
2171 public function write_setting($data) {
2172 if ($this->paramtype === PARAM_INT and $data === '') {
2173 // do not complain if '' used instead of 0
2174 $data = 0;
2176 // $data is a string
2177 $validated = $this->validate($data);
2178 if ($validated !== true) {
2179 return $validated;
2181 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2185 * Validate data before storage
2186 * @param string data
2187 * @return mixed true if ok string if error found
2189 public function validate($data) {
2190 // allow paramtype to be a custom regex if it is the form of /pattern/
2191 if (preg_match('#^/.*/$#', $this->paramtype)) {
2192 if (preg_match($this->paramtype, $data)) {
2193 return true;
2194 } else {
2195 return get_string('validateerror', 'admin');
2198 } else if ($this->paramtype === PARAM_RAW) {
2199 return true;
2201 } else {
2202 $cleaned = clean_param($data, $this->paramtype);
2203 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2204 return true;
2205 } else {
2206 return get_string('validateerror', 'admin');
2212 * Return an XHTML string for the setting
2213 * @return string Returns an XHTML string
2215 public function output_html($data, $query='') {
2216 global $OUTPUT;
2218 $default = $this->get_defaultsetting();
2219 $context = (object) [
2220 'size' => $this->size,
2221 'id' => $this->get_id(),
2222 'name' => $this->get_full_name(),
2223 'value' => $data,
2224 'forceltr' => $this->get_force_ltr(),
2226 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2228 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2233 * Text input with a maximum length constraint.
2235 * @copyright 2015 onwards Ankit Agarwal
2236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2238 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2240 /** @var int maximum number of chars allowed. */
2241 protected $maxlength;
2244 * Config text constructor
2246 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2247 * or 'myplugin/mysetting' for ones in config_plugins.
2248 * @param string $visiblename localised
2249 * @param string $description long localised info
2250 * @param string $defaultsetting
2251 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2252 * @param int $size default field size
2253 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2255 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2256 $size=null, $maxlength = 0) {
2257 $this->maxlength = $maxlength;
2258 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2262 * Validate data before storage
2264 * @param string $data data
2265 * @return mixed true if ok string if error found
2267 public function validate($data) {
2268 $parentvalidation = parent::validate($data);
2269 if ($parentvalidation === true) {
2270 if ($this->maxlength > 0) {
2271 // Max length check.
2272 $length = core_text::strlen($data);
2273 if ($length > $this->maxlength) {
2274 return get_string('maximumchars', 'moodle', $this->maxlength);
2276 return true;
2277 } else {
2278 return true; // No max length check needed.
2280 } else {
2281 return $parentvalidation;
2287 * General text area without html editor.
2289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2291 class admin_setting_configtextarea extends admin_setting_configtext {
2292 private $rows;
2293 private $cols;
2296 * @param string $name
2297 * @param string $visiblename
2298 * @param string $description
2299 * @param mixed $defaultsetting string or array
2300 * @param mixed $paramtype
2301 * @param string $cols The number of columns to make the editor
2302 * @param string $rows The number of rows to make the editor
2304 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2305 $this->rows = $rows;
2306 $this->cols = $cols;
2307 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2311 * Returns an XHTML string for the editor
2313 * @param string $data
2314 * @param string $query
2315 * @return string XHTML string for the editor
2317 public function output_html($data, $query='') {
2318 global $OUTPUT;
2320 $default = $this->get_defaultsetting();
2321 $defaultinfo = $default;
2322 if (!is_null($default) and $default !== '') {
2323 $defaultinfo = "\n".$default;
2326 $context = (object) [
2327 'cols' => $this->cols,
2328 'rows' => $this->rows,
2329 'id' => $this->get_id(),
2330 'name' => $this->get_full_name(),
2331 'value' => $data,
2332 'forceltr' => $this->get_force_ltr(),
2334 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2336 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2341 * General text area with html editor.
2343 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2346 * @param string $name
2347 * @param string $visiblename
2348 * @param string $description
2349 * @param mixed $defaultsetting string or array
2350 * @param mixed $paramtype
2352 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2353 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2354 $this->set_force_ltr(false);
2355 editors_head_setup();
2359 * Returns an XHTML string for the editor
2361 * @param string $data
2362 * @param string $query
2363 * @return string XHTML string for the editor
2365 public function output_html($data, $query='') {
2366 $editor = editors_get_preferred_editor(FORMAT_HTML);
2367 $editor->set_text($data);
2368 $editor->use_editor($this->get_id(), array('noclean'=>true));
2369 return parent::output_html($data, $query);
2375 * Password field, allows unmasking of password
2377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2379 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2382 * Constructor
2383 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2384 * @param string $visiblename localised
2385 * @param string $description long localised info
2386 * @param string $defaultsetting default password
2388 public function __construct($name, $visiblename, $description, $defaultsetting) {
2389 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2393 * Log config changes if necessary.
2394 * @param string $name
2395 * @param string $oldvalue
2396 * @param string $value
2398 protected function add_to_config_log($name, $oldvalue, $value) {
2399 if ($value !== '') {
2400 $value = '********';
2402 if ($oldvalue !== '' and $oldvalue !== null) {
2403 $oldvalue = '********';
2405 parent::add_to_config_log($name, $oldvalue, $value);
2409 * Returns HTML for the field.
2411 * @param string $data Value for the field
2412 * @param string $query Passed as final argument for format_admin_setting
2413 * @return string Rendered HTML
2415 public function output_html($data, $query='') {
2416 global $OUTPUT;
2417 $context = (object) [
2418 'id' => $this->get_id(),
2419 'name' => $this->get_full_name(),
2420 'size' => $this->size,
2421 'value' => $data,
2422 'forceltr' => $this->get_force_ltr(),
2424 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2425 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2431 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2432 * Note: Only advanced makes sense right now - locked does not.
2434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2436 class admin_setting_configempty extends admin_setting_configtext {
2439 * @param string $name
2440 * @param string $visiblename
2441 * @param string $description
2443 public function __construct($name, $visiblename, $description) {
2444 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2448 * Returns an XHTML string for the hidden field
2450 * @param string $data
2451 * @param string $query
2452 * @return string XHTML string for the editor
2454 public function output_html($data, $query='') {
2455 global $OUTPUT;
2457 $context = (object) [
2458 'id' => $this->get_id(),
2459 'name' => $this->get_full_name()
2461 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2463 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2469 * Path to directory
2471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2473 class admin_setting_configfile extends admin_setting_configtext {
2475 * Constructor
2476 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2477 * @param string $visiblename localised
2478 * @param string $description long localised info
2479 * @param string $defaultdirectory default directory location
2481 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2482 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2486 * Returns XHTML for the field
2488 * Returns XHTML for the field and also checks whether the file
2489 * specified in $data exists using file_exists()
2491 * @param string $data File name and path to use in value attr
2492 * @param string $query
2493 * @return string XHTML field
2495 public function output_html($data, $query='') {
2496 global $CFG, $OUTPUT;
2498 $default = $this->get_defaultsetting();
2499 $context = (object) [
2500 'id' => $this->get_id(),
2501 'name' => $this->get_full_name(),
2502 'size' => $this->size,
2503 'value' => $data,
2504 'showvalidity' => !empty($data),
2505 'valid' => $data && file_exists($data),
2506 'readonly' => !empty($CFG->preventexecpath),
2507 'forceltr' => $this->get_force_ltr(),
2510 if ($context->readonly) {
2511 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2514 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2516 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2520 * Checks if execpatch has been disabled in config.php
2522 public function write_setting($data) {
2523 global $CFG;
2524 if (!empty($CFG->preventexecpath)) {
2525 if ($this->get_setting() === null) {
2526 // Use default during installation.
2527 $data = $this->get_defaultsetting();
2528 if ($data === null) {
2529 $data = '';
2531 } else {
2532 return '';
2535 return parent::write_setting($data);
2542 * Path to executable file
2544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2546 class admin_setting_configexecutable extends admin_setting_configfile {
2549 * Returns an XHTML field
2551 * @param string $data This is the value for the field
2552 * @param string $query
2553 * @return string XHTML field
2555 public function output_html($data, $query='') {
2556 global $CFG, $OUTPUT;
2557 $default = $this->get_defaultsetting();
2558 require_once("$CFG->libdir/filelib.php");
2560 $context = (object) [
2561 'id' => $this->get_id(),
2562 'name' => $this->get_full_name(),
2563 'size' => $this->size,
2564 'value' => $data,
2565 'showvalidity' => !empty($data),
2566 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2567 'readonly' => !empty($CFG->preventexecpath),
2568 'forceltr' => $this->get_force_ltr()
2571 if (!empty($CFG->preventexecpath)) {
2572 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2575 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2577 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2583 * Path to directory
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2587 class admin_setting_configdirectory extends admin_setting_configfile {
2590 * Returns an XHTML field
2592 * @param string $data This is the value for the field
2593 * @param string $query
2594 * @return string XHTML
2596 public function output_html($data, $query='') {
2597 global $CFG, $OUTPUT;
2598 $default = $this->get_defaultsetting();
2600 $context = (object) [
2601 'id' => $this->get_id(),
2602 'name' => $this->get_full_name(),
2603 'size' => $this->size,
2604 'value' => $data,
2605 'showvalidity' => !empty($data),
2606 'valid' => $data && file_exists($data) && is_dir($data),
2607 'readonly' => !empty($CFG->preventexecpath),
2608 'forceltr' => $this->get_force_ltr()
2611 if (!empty($CFG->preventexecpath)) {
2612 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2615 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2617 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2623 * Checkbox
2625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2627 class admin_setting_configcheckbox extends admin_setting {
2628 /** @var string Value used when checked */
2629 public $yes;
2630 /** @var string Value used when not checked */
2631 public $no;
2634 * Constructor
2635 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2636 * @param string $visiblename localised
2637 * @param string $description long localised info
2638 * @param string $defaultsetting
2639 * @param string $yes value used when checked
2640 * @param string $no value used when not checked
2642 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2643 parent::__construct($name, $visiblename, $description, $defaultsetting);
2644 $this->yes = (string)$yes;
2645 $this->no = (string)$no;
2649 * Retrieves the current setting using the objects name
2651 * @return string
2653 public function get_setting() {
2654 return $this->config_read($this->name);
2658 * Sets the value for the setting
2660 * Sets the value for the setting to either the yes or no values
2661 * of the object by comparing $data to yes
2663 * @param mixed $data Gets converted to str for comparison against yes value
2664 * @return string empty string or error
2666 public function write_setting($data) {
2667 if ((string)$data === $this->yes) { // convert to strings before comparison
2668 $data = $this->yes;
2669 } else {
2670 $data = $this->no;
2672 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2676 * Returns an XHTML checkbox field
2678 * @param string $data If $data matches yes then checkbox is checked
2679 * @param string $query
2680 * @return string XHTML field
2682 public function output_html($data, $query='') {
2683 global $OUTPUT;
2685 $context = (object) [
2686 'id' => $this->get_id(),
2687 'name' => $this->get_full_name(),
2688 'no' => $this->no,
2689 'value' => $this->yes,
2690 'checked' => (string) $data === $this->yes,
2693 $default = $this->get_defaultsetting();
2694 if (!is_null($default)) {
2695 if ((string)$default === $this->yes) {
2696 $defaultinfo = get_string('checkboxyes', 'admin');
2697 } else {
2698 $defaultinfo = get_string('checkboxno', 'admin');
2700 } else {
2701 $defaultinfo = NULL;
2704 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2706 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2712 * Multiple checkboxes, each represents different value, stored in csv format
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2716 class admin_setting_configmulticheckbox extends admin_setting {
2717 /** @var array Array of choices value=>label */
2718 public $choices;
2721 * Constructor: uses parent::__construct
2723 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2724 * @param string $visiblename localised
2725 * @param string $description long localised info
2726 * @param array $defaultsetting array of selected
2727 * @param array $choices array of $value=>$label for each checkbox
2729 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2730 $this->choices = $choices;
2731 parent::__construct($name, $visiblename, $description, $defaultsetting);
2735 * This public function may be used in ancestors for lazy loading of choices
2737 * @todo Check if this function is still required content commented out only returns true
2738 * @return bool true if loaded, false if error
2740 public function load_choices() {
2742 if (is_array($this->choices)) {
2743 return true;
2745 .... load choices here
2747 return true;
2751 * Is setting related to query text - used when searching
2753 * @param string $query
2754 * @return bool true on related, false on not or failure
2756 public function is_related($query) {
2757 if (!$this->load_choices() or empty($this->choices)) {
2758 return false;
2760 if (parent::is_related($query)) {
2761 return true;
2764 foreach ($this->choices as $desc) {
2765 if (strpos(core_text::strtolower($desc), $query) !== false) {
2766 return true;
2769 return false;
2773 * Returns the current setting if it is set
2775 * @return mixed null if null, else an array
2777 public function get_setting() {
2778 $result = $this->config_read($this->name);
2780 if (is_null($result)) {
2781 return NULL;
2783 if ($result === '') {
2784 return array();
2786 $enabled = explode(',', $result);
2787 $setting = array();
2788 foreach ($enabled as $option) {
2789 $setting[$option] = 1;
2791 return $setting;
2795 * Saves the setting(s) provided in $data
2797 * @param array $data An array of data, if not array returns empty str
2798 * @return mixed empty string on useless data or bool true=success, false=failed
2800 public function write_setting($data) {
2801 if (!is_array($data)) {
2802 return ''; // ignore it
2804 if (!$this->load_choices() or empty($this->choices)) {
2805 return '';
2807 unset($data['xxxxx']);
2808 $result = array();
2809 foreach ($data as $key => $value) {
2810 if ($value and array_key_exists($key, $this->choices)) {
2811 $result[] = $key;
2814 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2818 * Returns XHTML field(s) as required by choices
2820 * Relies on data being an array should data ever be another valid vartype with
2821 * acceptable value this may cause a warning/error
2822 * if (!is_array($data)) would fix the problem
2824 * @todo Add vartype handling to ensure $data is an array
2826 * @param array $data An array of checked values
2827 * @param string $query
2828 * @return string XHTML field
2830 public function output_html($data, $query='') {
2831 global $OUTPUT;
2833 if (!$this->load_choices() or empty($this->choices)) {
2834 return '';
2837 $default = $this->get_defaultsetting();
2838 if (is_null($default)) {
2839 $default = array();
2841 if (is_null($data)) {
2842 $data = array();
2845 $context = (object) [
2846 'id' => $this->get_id(),
2847 'name' => $this->get_full_name(),
2850 $options = array();
2851 $defaults = array();
2852 foreach ($this->choices as $key => $description) {
2853 if (!empty($default[$key])) {
2854 $defaults[] = $description;
2857 $options[] = [
2858 'key' => $key,
2859 'checked' => !empty($data[$key]),
2860 'label' => highlightfast($query, $description)
2864 if (is_null($default)) {
2865 $defaultinfo = null;
2866 } else if (!empty($defaults)) {
2867 $defaultinfo = implode(', ', $defaults);
2868 } else {
2869 $defaultinfo = get_string('none');
2872 $context->options = $options;
2873 $context->hasoptions = !empty($options);
2875 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
2877 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
2884 * Multiple checkboxes 2, value stored as string 00101011
2886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2888 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2891 * Returns the setting if set
2893 * @return mixed null if not set, else an array of set settings
2895 public function get_setting() {
2896 $result = $this->config_read($this->name);
2897 if (is_null($result)) {
2898 return NULL;
2900 if (!$this->load_choices()) {
2901 return NULL;
2903 $result = str_pad($result, count($this->choices), '0');
2904 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2905 $setting = array();
2906 foreach ($this->choices as $key=>$unused) {
2907 $value = array_shift($result);
2908 if ($value) {
2909 $setting[$key] = 1;
2912 return $setting;
2916 * Save setting(s) provided in $data param
2918 * @param array $data An array of settings to save
2919 * @return mixed empty string for bad data or bool true=>success, false=>error
2921 public function write_setting($data) {
2922 if (!is_array($data)) {
2923 return ''; // ignore it
2925 if (!$this->load_choices() or empty($this->choices)) {
2926 return '';
2928 $result = '';
2929 foreach ($this->choices as $key=>$unused) {
2930 if (!empty($data[$key])) {
2931 $result .= '1';
2932 } else {
2933 $result .= '0';
2936 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2942 * Select one value from list
2944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 class admin_setting_configselect extends admin_setting {
2947 /** @var array Array of choices value=>label */
2948 public $choices;
2949 /** @var array Array of choices grouped using optgroups */
2950 public $optgroups;
2953 * Constructor
2954 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2955 * @param string $visiblename localised
2956 * @param string $description long localised info
2957 * @param string|int $defaultsetting
2958 * @param array $choices array of $value=>$label for each selection
2960 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2961 // Look for optgroup and single options.
2962 if (is_array($choices)) {
2963 $this->choices = [];
2964 foreach ($choices as $key => $val) {
2965 if (is_array($val)) {
2966 $this->optgroups[$key] = $val;
2967 $this->choices = array_merge($this->choices, $val);
2968 } else {
2969 $this->choices[$key] = $val;
2974 parent::__construct($name, $visiblename, $description, $defaultsetting);
2978 * This function may be used in ancestors for lazy loading of choices
2980 * Override this method if loading of choices is expensive, such
2981 * as when it requires multiple db requests.
2983 * @return bool true if loaded, false if error
2985 public function load_choices() {
2987 if (is_array($this->choices)) {
2988 return true;
2990 .... load choices here
2992 return true;
2996 * Check if this is $query is related to a choice
2998 * @param string $query
2999 * @return bool true if related, false if not
3001 public function is_related($query) {
3002 if (parent::is_related($query)) {
3003 return true;
3005 if (!$this->load_choices()) {
3006 return false;
3008 foreach ($this->choices as $key=>$value) {
3009 if (strpos(core_text::strtolower($key), $query) !== false) {
3010 return true;
3012 if (strpos(core_text::strtolower($value), $query) !== false) {
3013 return true;
3016 return false;
3020 * Return the setting
3022 * @return mixed returns config if successful else null
3024 public function get_setting() {
3025 return $this->config_read($this->name);
3029 * Save a setting
3031 * @param string $data
3032 * @return string empty of error string
3034 public function write_setting($data) {
3035 if (!$this->load_choices() or empty($this->choices)) {
3036 return '';
3038 if (!array_key_exists($data, $this->choices)) {
3039 return ''; // ignore it
3042 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3046 * Returns XHTML select field
3048 * Ensure the options are loaded, and generate the XHTML for the select
3049 * element and any warning message. Separating this out from output_html
3050 * makes it easier to subclass this class.
3052 * @param string $data the option to show as selected.
3053 * @param string $current the currently selected option in the database, null if none.
3054 * @param string $default the default selected option.
3055 * @return array the HTML for the select element, and a warning message.
3056 * @deprecated since Moodle 3.2
3058 public function output_select_html($data, $current, $default, $extraname = '') {
3059 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3063 * Returns XHTML select field and wrapping div(s)
3065 * @see output_select_html()
3067 * @param string $data the option to show as selected
3068 * @param string $query
3069 * @return string XHTML field and wrapping div
3071 public function output_html($data, $query='') {
3072 global $OUTPUT;
3074 $default = $this->get_defaultsetting();
3075 $current = $this->get_setting();
3077 if (!$this->load_choices() || empty($this->choices)) {
3078 return '';
3081 $context = (object) [
3082 'id' => $this->get_id(),
3083 'name' => $this->get_full_name(),
3086 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3087 $defaultinfo = $this->choices[$default];
3088 } else {
3089 $defaultinfo = NULL;
3092 // Warnings.
3093 $warning = '';
3094 if ($current === null) {
3095 // First run.
3096 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3097 // No warning.
3098 } else if (!array_key_exists($current, $this->choices)) {
3099 $warning = get_string('warningcurrentsetting', 'admin', $current);
3100 if (!is_null($default) && $data == $current) {
3101 $data = $default; // Use default instead of first value when showing the form.
3105 $options = [];
3106 $template = 'core_admin/setting_configselect';
3108 if (!empty($this->optgroups)) {
3109 $optgroups = [];
3110 foreach ($this->optgroups as $label => $choices) {
3111 $optgroup = array('label' => $label, 'options' => []);
3112 foreach ($choices as $value => $name) {
3113 $optgroup['options'][] = [
3114 'value' => $value,
3115 'name' => $name,
3116 'selected' => (string) $value == $data
3118 unset($this->choices[$value]);
3120 $optgroups[] = $optgroup;
3122 $context->options = $options;
3123 $context->optgroups = $optgroups;
3124 $template = 'core_admin/setting_configselect_optgroup';
3127 foreach ($this->choices as $value => $name) {
3128 $options[] = [
3129 'value' => $value,
3130 'name' => $name,
3131 'selected' => (string) $value == $data
3134 $context->options = $options;
3136 $element = $OUTPUT->render_from_template($template, $context);
3138 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3144 * Select multiple items from list
3146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3148 class admin_setting_configmultiselect extends admin_setting_configselect {
3150 * Constructor
3151 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3152 * @param string $visiblename localised
3153 * @param string $description long localised info
3154 * @param array $defaultsetting array of selected items
3155 * @param array $choices array of $value=>$label for each list item
3157 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3158 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3162 * Returns the select setting(s)
3164 * @return mixed null or array. Null if no settings else array of setting(s)
3166 public function get_setting() {
3167 $result = $this->config_read($this->name);
3168 if (is_null($result)) {
3169 return NULL;
3171 if ($result === '') {
3172 return array();
3174 return explode(',', $result);
3178 * Saves setting(s) provided through $data
3180 * Potential bug in the works should anyone call with this function
3181 * using a vartype that is not an array
3183 * @param array $data
3185 public function write_setting($data) {
3186 if (!is_array($data)) {
3187 return ''; //ignore it
3189 if (!$this->load_choices() or empty($this->choices)) {
3190 return '';
3193 unset($data['xxxxx']);
3195 $save = array();
3196 foreach ($data as $value) {
3197 if (!array_key_exists($value, $this->choices)) {
3198 continue; // ignore it
3200 $save[] = $value;
3203 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3207 * Is setting related to query text - used when searching
3209 * @param string $query
3210 * @return bool true if related, false if not
3212 public function is_related($query) {
3213 if (!$this->load_choices() or empty($this->choices)) {
3214 return false;
3216 if (parent::is_related($query)) {
3217 return true;
3220 foreach ($this->choices as $desc) {
3221 if (strpos(core_text::strtolower($desc), $query) !== false) {
3222 return true;
3225 return false;
3229 * Returns XHTML multi-select field
3231 * @todo Add vartype handling to ensure $data is an array
3232 * @param array $data Array of values to select by default
3233 * @param string $query
3234 * @return string XHTML multi-select field
3236 public function output_html($data, $query='') {
3237 global $OUTPUT;
3239 if (!$this->load_choices() or empty($this->choices)) {
3240 return '';
3243 $default = $this->get_defaultsetting();
3244 if (is_null($default)) {
3245 $default = array();
3247 if (is_null($data)) {
3248 $data = array();
3251 $context = (object) [
3252 'id' => $this->get_id(),
3253 'name' => $this->get_full_name(),
3254 'size' => min(10, count($this->choices))
3257 $defaults = [];
3258 $options = [];
3259 $template = 'core_admin/setting_configmultiselect';
3261 if (!empty($this->optgroups)) {
3262 $optgroups = [];
3263 foreach ($this->optgroups as $label => $choices) {
3264 $optgroup = array('label' => $label, 'options' => []);
3265 foreach ($choices as $value => $name) {
3266 if (in_array($value, $default)) {
3267 $defaults[] = $name;
3269 $optgroup['options'][] = [
3270 'value' => $value,
3271 'name' => $name,
3272 'selected' => in_array($value, $data)
3274 unset($this->choices[$value]);
3276 $optgroups[] = $optgroup;
3278 $context->optgroups = $optgroups;
3279 $template = 'core_admin/setting_configmultiselect_optgroup';
3282 foreach ($this->choices as $value => $name) {
3283 if (in_array($value, $default)) {
3284 $defaults[] = $name;
3286 $options[] = [
3287 'value' => $value,
3288 'name' => $name,
3289 'selected' => in_array($value, $data)
3292 $context->options = $options;
3294 if (is_null($default)) {
3295 $defaultinfo = NULL;
3296 } if (!empty($defaults)) {
3297 $defaultinfo = implode(', ', $defaults);
3298 } else {
3299 $defaultinfo = get_string('none');
3302 $element = $OUTPUT->render_from_template($template, $context);
3304 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3309 * Time selector
3311 * This is a liiitle bit messy. we're using two selects, but we're returning
3312 * them as an array named after $name (so we only use $name2 internally for the setting)
3314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3316 class admin_setting_configtime extends admin_setting {
3317 /** @var string Used for setting second select (minutes) */
3318 public $name2;
3321 * Constructor
3322 * @param string $hoursname setting for hours
3323 * @param string $minutesname setting for hours
3324 * @param string $visiblename localised
3325 * @param string $description long localised info
3326 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3328 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3329 $this->name2 = $minutesname;
3330 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3334 * Get the selected time
3336 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3338 public function get_setting() {
3339 $result1 = $this->config_read($this->name);
3340 $result2 = $this->config_read($this->name2);
3341 if (is_null($result1) or is_null($result2)) {
3342 return NULL;
3345 return array('h' => $result1, 'm' => $result2);
3349 * Store the time (hours and minutes)
3351 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3352 * @return bool true if success, false if not
3354 public function write_setting($data) {
3355 if (!is_array($data)) {
3356 return '';
3359 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3360 return ($result ? '' : get_string('errorsetting', 'admin'));
3364 * Returns XHTML time select fields
3366 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3367 * @param string $query
3368 * @return string XHTML time select fields and wrapping div(s)
3370 public function output_html($data, $query='') {
3371 global $OUTPUT;
3373 $default = $this->get_defaultsetting();
3374 if (is_array($default)) {
3375 $defaultinfo = $default['h'].':'.$default['m'];
3376 } else {
3377 $defaultinfo = NULL;
3380 $context = (object) [
3381 'id' => $this->get_id(),
3382 'name' => $this->get_full_name(),
3383 'hours' => array_map(function($i) use ($data) {
3384 return [
3385 'value' => $i,
3386 'name' => $i,
3387 'selected' => $i == $data['h']
3389 }, range(0, 23)),
3390 'minutes' => array_map(function($i) use ($data) {
3391 return [
3392 'value' => $i,
3393 'name' => $i,
3394 'selected' => $i == $data['m']
3396 }, range(0, 59, 5))
3399 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3401 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3402 $this->get_id() . 'h', '', $defaultinfo, $query);
3409 * Seconds duration setting.
3411 * @copyright 2012 Petr Skoda (http://skodak.org)
3412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3414 class admin_setting_configduration extends admin_setting {
3416 /** @var int default duration unit */
3417 protected $defaultunit;
3420 * Constructor
3421 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3422 * or 'myplugin/mysetting' for ones in config_plugins.
3423 * @param string $visiblename localised name
3424 * @param string $description localised long description
3425 * @param mixed $defaultsetting string or array depending on implementation
3426 * @param int $defaultunit - day, week, etc. (in seconds)
3428 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3429 if (is_number($defaultsetting)) {
3430 $defaultsetting = self::parse_seconds($defaultsetting);
3432 $units = self::get_units();
3433 if (isset($units[$defaultunit])) {
3434 $this->defaultunit = $defaultunit;
3435 } else {
3436 $this->defaultunit = 86400;
3438 parent::__construct($name, $visiblename, $description, $defaultsetting);
3442 * Returns selectable units.
3443 * @static
3444 * @return array
3446 protected static function get_units() {
3447 return array(
3448 604800 => get_string('weeks'),
3449 86400 => get_string('days'),
3450 3600 => get_string('hours'),
3451 60 => get_string('minutes'),
3452 1 => get_string('seconds'),
3457 * Converts seconds to some more user friendly string.
3458 * @static
3459 * @param int $seconds
3460 * @return string
3462 protected static function get_duration_text($seconds) {
3463 if (empty($seconds)) {
3464 return get_string('none');
3466 $data = self::parse_seconds($seconds);
3467 switch ($data['u']) {
3468 case (60*60*24*7):
3469 return get_string('numweeks', '', $data['v']);
3470 case (60*60*24):
3471 return get_string('numdays', '', $data['v']);
3472 case (60*60):
3473 return get_string('numhours', '', $data['v']);
3474 case (60):
3475 return get_string('numminutes', '', $data['v']);
3476 default:
3477 return get_string('numseconds', '', $data['v']*$data['u']);
3482 * Finds suitable units for given duration.
3483 * @static
3484 * @param int $seconds
3485 * @return array
3487 protected static function parse_seconds($seconds) {
3488 foreach (self::get_units() as $unit => $unused) {
3489 if ($seconds % $unit === 0) {
3490 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3493 return array('v'=>(int)$seconds, 'u'=>1);
3497 * Get the selected duration as array.
3499 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3501 public function get_setting() {
3502 $seconds = $this->config_read($this->name);
3503 if (is_null($seconds)) {
3504 return null;
3507 return self::parse_seconds($seconds);
3511 * Store the duration as seconds.
3513 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3514 * @return bool true if success, false if not
3516 public function write_setting($data) {
3517 if (!is_array($data)) {
3518 return '';
3521 $seconds = (int)($data['v']*$data['u']);
3522 if ($seconds < 0) {
3523 return get_string('errorsetting', 'admin');
3526 $result = $this->config_write($this->name, $seconds);
3527 return ($result ? '' : get_string('errorsetting', 'admin'));
3531 * Returns duration text+select fields.
3533 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3534 * @param string $query
3535 * @return string duration text+select fields and wrapping div(s)
3537 public function output_html($data, $query='') {
3538 global $OUTPUT;
3540 $default = $this->get_defaultsetting();
3541 if (is_number($default)) {
3542 $defaultinfo = self::get_duration_text($default);
3543 } else if (is_array($default)) {
3544 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3545 } else {
3546 $defaultinfo = null;
3549 $inputid = $this->get_id() . 'v';
3550 $units = self::get_units();
3551 $defaultunit = $this->defaultunit;
3553 $context = (object) [
3554 'id' => $this->get_id(),
3555 'name' => $this->get_full_name(),
3556 'value' => $data['v'],
3557 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3558 return [
3559 'value' => $unit,
3560 'name' => $units[$unit],
3561 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3563 }, array_keys($units))
3566 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3568 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3574 * Seconds duration setting with an advanced checkbox, that controls a additional
3575 * $name.'_adv' setting.
3577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3578 * @copyright 2014 The Open University
3580 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3582 * Constructor
3583 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3584 * or 'myplugin/mysetting' for ones in config_plugins.
3585 * @param string $visiblename localised name
3586 * @param string $description localised long description
3587 * @param array $defaultsetting array of int value, and bool whether it is
3588 * is advanced by default.
3589 * @param int $defaultunit - day, week, etc. (in seconds)
3591 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3592 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3593 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3599 * Used to validate a textarea used for ip addresses
3601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3602 * @copyright 2011 Petr Skoda (http://skodak.org)
3604 class admin_setting_configiplist extends admin_setting_configtextarea {
3607 * Validate the contents of the textarea as IP addresses
3609 * Used to validate a new line separated list of IP addresses collected from
3610 * a textarea control
3612 * @param string $data A list of IP Addresses separated by new lines
3613 * @return mixed bool true for success or string:error on failure
3615 public function validate($data) {
3616 if(!empty($data)) {
3617 $ips = explode("\n", $data);
3618 } else {
3619 return true;
3621 $result = true;
3622 $badips = array();
3623 foreach($ips as $ip) {
3624 $ip = trim($ip);
3625 if (empty($ip)) {
3626 continue;
3628 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3629 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3630 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3631 } else {
3632 $result = false;
3633 $badips[] = $ip;
3636 if($result) {
3637 return true;
3638 } else {
3639 return get_string('validateiperror', 'admin', join(', ', $badips));
3645 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3648 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3650 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3653 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3654 * Used to validate a new line separated list of entries collected from a textarea control.
3656 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3657 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3658 * via the get_setting() method, which has been overriden.
3660 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3661 * @return mixed bool true for success or string:error on failure
3663 public function validate($data) {
3664 if (empty($data)) {
3665 return true;
3667 $entries = explode("\n", $data);
3668 $badentries = [];
3670 foreach ($entries as $key => $entry) {
3671 $entry = trim($entry);
3672 if (empty($entry)) {
3673 return get_string('validateemptylineerror', 'admin');
3676 // Validate each string entry against the supported formats.
3677 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3678 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3679 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3680 continue;
3683 // Otherwise, the entry is invalid.
3684 $badentries[] = $entry;
3687 if ($badentries) {
3688 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3690 return true;
3694 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3696 * @param string $data the setting data, as sent from the web form.
3697 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3699 protected function ace_encode($data) {
3700 if (empty($data)) {
3701 return $data;
3703 $entries = explode("\n", $data);
3704 foreach ($entries as $key => $entry) {
3705 $entry = trim($entry);
3706 // This regex matches any string that has non-ascii character.
3707 if (preg_match('/[^\x00-\x7f]/', $entry)) {
3708 // If we can convert the unicode string to an idn, do so.
3709 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3710 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3711 $entries[$key] = $val ? $val : $entry;
3714 return implode("\n", $entries);
3718 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
3720 * @param string $data the setting data, as found in the database.
3721 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
3723 protected function ace_decode($data) {
3724 $entries = explode("\n", $data);
3725 foreach ($entries as $key => $entry) {
3726 $entry = trim($entry);
3727 if (strpos($entry, 'xn--') !== false) {
3728 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3731 return implode("\n", $entries);
3735 * Override, providing utf8-decoding for ascii-encoded IDN strings.
3737 * @return mixed returns punycode-converted setting string if successful, else null.
3739 public function get_setting() {
3740 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
3741 $data = $this->config_read($this->name);
3742 if (function_exists('idn_to_utf8') && !is_null($data)) {
3743 $data = $this->ace_decode($data);
3745 return $data;
3749 * Override, providing ascii-encoding for utf8 (native) IDN strings.
3751 * @param string $data
3752 * @return string
3754 public function write_setting($data) {
3755 if ($this->paramtype === PARAM_INT and $data === '') {
3756 // Do not complain if '' used instead of 0.
3757 $data = 0;
3760 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
3761 if (function_exists('idn_to_ascii')) {
3762 $data = $this->ace_encode($data);
3765 $validated = $this->validate($data);
3766 if ($validated !== true) {
3767 return $validated;
3769 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3774 * Used to validate a textarea used for port numbers.
3776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3777 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3779 class admin_setting_configportlist extends admin_setting_configtextarea {
3782 * Validate the contents of the textarea as port numbers.
3783 * Used to validate a new line separated list of ports collected from a textarea control.
3785 * @param string $data A list of ports separated by new lines
3786 * @return mixed bool true for success or string:error on failure
3788 public function validate($data) {
3789 if (empty($data)) {
3790 return true;
3792 $ports = explode("\n", $data);
3793 $badentries = [];
3794 foreach ($ports as $port) {
3795 $port = trim($port);
3796 if (empty($port)) {
3797 return get_string('validateemptylineerror', 'admin');
3800 // Is the string a valid integer number?
3801 if (strval(intval($port)) !== $port || intval($port) <= 0) {
3802 $badentries[] = $port;
3805 if ($badentries) {
3806 return get_string('validateerrorlist', 'admin', $badentries);
3808 return true;
3814 * An admin setting for selecting one or more users who have a capability
3815 * in the system context
3817 * An admin setting for selecting one or more users, who have a particular capability
3818 * in the system context. Warning, make sure the list will never be too long. There is
3819 * no paging or searching of this list.
3821 * To correctly get a list of users from this config setting, you need to call the
3822 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3826 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3827 /** @var string The capabilities name */
3828 protected $capability;
3829 /** @var int include admin users too */
3830 protected $includeadmins;
3833 * Constructor.
3835 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3836 * @param string $visiblename localised name
3837 * @param string $description localised long description
3838 * @param array $defaultsetting array of usernames
3839 * @param string $capability string capability name.
3840 * @param bool $includeadmins include administrators
3842 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3843 $this->capability = $capability;
3844 $this->includeadmins = $includeadmins;
3845 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3849 * Load all of the uses who have the capability into choice array
3851 * @return bool Always returns true
3853 function load_choices() {
3854 if (is_array($this->choices)) {
3855 return true;
3857 list($sort, $sortparams) = users_order_by_sql('u');
3858 if (!empty($sortparams)) {
3859 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3860 'This is unexpected, and a problem because there is no way to pass these ' .
3861 'parameters to get_users_by_capability. See MDL-34657.');
3863 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3864 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3865 $this->choices = array(
3866 '$@NONE@$' => get_string('nobody'),
3867 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3869 if ($this->includeadmins) {
3870 $admins = get_admins();
3871 foreach ($admins as $user) {
3872 $this->choices[$user->id] = fullname($user);
3875 if (is_array($users)) {
3876 foreach ($users as $user) {
3877 $this->choices[$user->id] = fullname($user);
3880 return true;
3884 * Returns the default setting for class
3886 * @return mixed Array, or string. Empty string if no default
3888 public function get_defaultsetting() {
3889 $this->load_choices();
3890 $defaultsetting = parent::get_defaultsetting();
3891 if (empty($defaultsetting)) {
3892 return array('$@NONE@$');
3893 } else if (array_key_exists($defaultsetting, $this->choices)) {
3894 return $defaultsetting;
3895 } else {
3896 return '';
3901 * Returns the current setting
3903 * @return mixed array or string
3905 public function get_setting() {
3906 $result = parent::get_setting();
3907 if ($result === null) {
3908 // this is necessary for settings upgrade
3909 return null;
3911 if (empty($result)) {
3912 $result = array('$@NONE@$');
3914 return $result;
3918 * Save the chosen setting provided as $data
3920 * @param array $data
3921 * @return mixed string or array
3923 public function write_setting($data) {
3924 // If all is selected, remove any explicit options.
3925 if (in_array('$@ALL@$', $data)) {
3926 $data = array('$@ALL@$');
3928 // None never needs to be written to the DB.
3929 if (in_array('$@NONE@$', $data)) {
3930 unset($data[array_search('$@NONE@$', $data)]);
3932 return parent::write_setting($data);
3938 * Special checkbox for calendar - resets SESSION vars.
3940 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3942 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3944 * Calls the parent::__construct with default values
3946 * name => calendar_adminseesall
3947 * visiblename => get_string('adminseesall', 'admin')
3948 * description => get_string('helpadminseesall', 'admin')
3949 * defaultsetting => 0
3951 public function __construct() {
3952 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3953 get_string('helpadminseesall', 'admin'), '0');
3957 * Stores the setting passed in $data
3959 * @param mixed gets converted to string for comparison
3960 * @return string empty string or error message
3962 public function write_setting($data) {
3963 global $SESSION;
3964 return parent::write_setting($data);
3969 * Special select for settings that are altered in setup.php and can not be altered on the fly
3971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3973 class admin_setting_special_selectsetup extends admin_setting_configselect {
3975 * Reads the setting directly from the database
3977 * @return mixed
3979 public function get_setting() {
3980 // read directly from db!
3981 return get_config(NULL, $this->name);
3985 * Save the setting passed in $data
3987 * @param string $data The setting to save
3988 * @return string empty or error message
3990 public function write_setting($data) {
3991 global $CFG;
3992 // do not change active CFG setting!
3993 $current = $CFG->{$this->name};
3994 $result = parent::write_setting($data);
3995 $CFG->{$this->name} = $current;
3996 return $result;
4002 * Special select for frontpage - stores data in course table
4004 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4006 class admin_setting_sitesetselect extends admin_setting_configselect {
4008 * Returns the site name for the selected site
4010 * @see get_site()
4011 * @return string The site name of the selected site
4013 public function get_setting() {
4014 $site = course_get_format(get_site())->get_course();
4015 return $site->{$this->name};
4019 * Updates the database and save the setting
4021 * @param string data
4022 * @return string empty or error message
4024 public function write_setting($data) {
4025 global $DB, $SITE, $COURSE;
4026 if (!in_array($data, array_keys($this->choices))) {
4027 return get_string('errorsetting', 'admin');
4029 $record = new stdClass();
4030 $record->id = SITEID;
4031 $temp = $this->name;
4032 $record->$temp = $data;
4033 $record->timemodified = time();
4035 course_get_format($SITE)->update_course_format_options($record);
4036 $DB->update_record('course', $record);
4038 // Reset caches.
4039 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4040 if ($SITE->id == $COURSE->id) {
4041 $COURSE = $SITE;
4043 format_base::reset_course_cache($SITE->id);
4045 return '';
4052 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4053 * block to hidden.
4055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4057 class admin_setting_bloglevel extends admin_setting_configselect {
4059 * Updates the database and save the setting
4061 * @param string data
4062 * @return string empty or error message
4064 public function write_setting($data) {
4065 global $DB, $CFG;
4066 if ($data == 0) {
4067 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4068 foreach ($blogblocks as $block) {
4069 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4071 } else {
4072 // reenable all blocks only when switching from disabled blogs
4073 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4074 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4075 foreach ($blogblocks as $block) {
4076 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4080 return parent::write_setting($data);
4086 * Special select - lists on the frontpage - hacky
4088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4090 class admin_setting_courselist_frontpage extends admin_setting {
4091 /** @var array Array of choices value=>label */
4092 public $choices;
4095 * Construct override, requires one param
4097 * @param bool $loggedin Is the user logged in
4099 public function __construct($loggedin) {
4100 global $CFG;
4101 require_once($CFG->dirroot.'/course/lib.php');
4102 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4103 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4104 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4105 $defaults = array(FRONTPAGEALLCOURSELIST);
4106 parent::__construct($name, $visiblename, $description, $defaults);
4110 * Loads the choices available
4112 * @return bool always returns true
4114 public function load_choices() {
4115 if (is_array($this->choices)) {
4116 return true;
4118 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4119 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4120 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4121 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4122 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4123 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4124 'none' => get_string('none'));
4125 if ($this->name === 'frontpage') {
4126 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4128 return true;
4132 * Returns the selected settings
4134 * @param mixed array or setting or null
4136 public function get_setting() {
4137 $result = $this->config_read($this->name);
4138 if (is_null($result)) {
4139 return NULL;
4141 if ($result === '') {
4142 return array();
4144 return explode(',', $result);
4148 * Save the selected options
4150 * @param array $data
4151 * @return mixed empty string (data is not an array) or bool true=success false=failure
4153 public function write_setting($data) {
4154 if (!is_array($data)) {
4155 return '';
4157 $this->load_choices();
4158 $save = array();
4159 foreach($data as $datum) {
4160 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4161 continue;
4163 $save[$datum] = $datum; // no duplicates
4165 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4169 * Return XHTML select field and wrapping div
4171 * @todo Add vartype handling to make sure $data is an array
4172 * @param array $data Array of elements to select by default
4173 * @return string XHTML select field and wrapping div
4175 public function output_html($data, $query='') {
4176 global $OUTPUT;
4178 $this->load_choices();
4179 $currentsetting = array();
4180 foreach ($data as $key) {
4181 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4182 $currentsetting[] = $key; // already selected first
4186 $context = (object) [
4187 'id' => $this->get_id(),
4188 'name' => $this->get_full_name(),
4191 $options = $this->choices;
4192 $selects = [];
4193 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4194 if (!array_key_exists($i, $currentsetting)) {
4195 $currentsetting[$i] = 'none';
4197 $selects[] = [
4198 'key' => $i,
4199 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4200 return [
4201 'name' => $options[$option],
4202 'value' => $option,
4203 'selected' => $currentsetting[$i] == $option
4205 }, array_keys($options))
4208 $context->selects = $selects;
4210 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4212 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4218 * Special checkbox for frontpage - stores data in course table
4220 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4222 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4224 * Returns the current sites name
4226 * @return string
4228 public function get_setting() {
4229 $site = course_get_format(get_site())->get_course();
4230 return $site->{$this->name};
4234 * Save the selected setting
4236 * @param string $data The selected site
4237 * @return string empty string or error message
4239 public function write_setting($data) {
4240 global $DB, $SITE, $COURSE;
4241 $record = new stdClass();
4242 $record->id = $SITE->id;
4243 $record->{$this->name} = ($data == '1' ? 1 : 0);
4244 $record->timemodified = time();
4246 course_get_format($SITE)->update_course_format_options($record);
4247 $DB->update_record('course', $record);
4249 // Reset caches.
4250 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4251 if ($SITE->id == $COURSE->id) {
4252 $COURSE = $SITE;
4254 format_base::reset_course_cache($SITE->id);
4256 return '';
4261 * Special text for frontpage - stores data in course table.
4262 * Empty string means not set here. Manual setting is required.
4264 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4266 class admin_setting_sitesettext extends admin_setting_configtext {
4269 * Constructor.
4271 public function __construct() {
4272 call_user_func_array(['parent', '__construct'], func_get_args());
4273 $this->set_force_ltr(false);
4277 * Return the current setting
4279 * @return mixed string or null
4281 public function get_setting() {
4282 $site = course_get_format(get_site())->get_course();
4283 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4287 * Validate the selected data
4289 * @param string $data The selected value to validate
4290 * @return mixed true or message string
4292 public function validate($data) {
4293 global $DB, $SITE;
4294 $cleaned = clean_param($data, PARAM_TEXT);
4295 if ($cleaned === '') {
4296 return get_string('required');
4298 if ($this->name ==='shortname' &&
4299 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4300 return get_string('shortnametaken', 'error', $data);
4302 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4303 return true;
4304 } else {
4305 return get_string('validateerror', 'admin');
4310 * Save the selected setting
4312 * @param string $data The selected value
4313 * @return string empty or error message
4315 public function write_setting($data) {
4316 global $DB, $SITE, $COURSE;
4317 $data = trim($data);
4318 $validated = $this->validate($data);
4319 if ($validated !== true) {
4320 return $validated;
4323 $record = new stdClass();
4324 $record->id = $SITE->id;
4325 $record->{$this->name} = $data;
4326 $record->timemodified = time();
4328 course_get_format($SITE)->update_course_format_options($record);
4329 $DB->update_record('course', $record);
4331 // Reset caches.
4332 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4333 if ($SITE->id == $COURSE->id) {
4334 $COURSE = $SITE;
4336 format_base::reset_course_cache($SITE->id);
4338 return '';
4344 * Special text editor for site description.
4346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4348 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4351 * Calls parent::__construct with specific arguments
4353 public function __construct() {
4354 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4355 PARAM_RAW, 60, 15);
4359 * Return the current setting
4360 * @return string The current setting
4362 public function get_setting() {
4363 $site = course_get_format(get_site())->get_course();
4364 return $site->{$this->name};
4368 * Save the new setting
4370 * @param string $data The new value to save
4371 * @return string empty or error message
4373 public function write_setting($data) {
4374 global $DB, $SITE, $COURSE;
4375 $record = new stdClass();
4376 $record->id = $SITE->id;
4377 $record->{$this->name} = $data;
4378 $record->timemodified = time();
4380 course_get_format($SITE)->update_course_format_options($record);
4381 $DB->update_record('course', $record);
4383 // Reset caches.
4384 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4385 if ($SITE->id == $COURSE->id) {
4386 $COURSE = $SITE;
4388 format_base::reset_course_cache($SITE->id);
4390 return '';
4396 * Administration interface for emoticon_manager settings.
4398 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4400 class admin_setting_emoticons extends admin_setting {
4403 * Calls parent::__construct with specific args
4405 public function __construct() {
4406 global $CFG;
4408 $manager = get_emoticon_manager();
4409 $defaults = $this->prepare_form_data($manager->default_emoticons());
4410 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4414 * Return the current setting(s)
4416 * @return array Current settings array
4418 public function get_setting() {
4419 global $CFG;
4421 $manager = get_emoticon_manager();
4423 $config = $this->config_read($this->name);
4424 if (is_null($config)) {
4425 return null;
4428 $config = $manager->decode_stored_config($config);
4429 if (is_null($config)) {
4430 return null;
4433 return $this->prepare_form_data($config);
4437 * Save selected settings
4439 * @param array $data Array of settings to save
4440 * @return bool
4442 public function write_setting($data) {
4444 $manager = get_emoticon_manager();
4445 $emoticons = $this->process_form_data($data);
4447 if ($emoticons === false) {
4448 return false;
4451 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4452 return ''; // success
4453 } else {
4454 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4459 * Return XHTML field(s) for options
4461 * @param array $data Array of options to set in HTML
4462 * @return string XHTML string for the fields and wrapping div(s)
4464 public function output_html($data, $query='') {
4465 global $OUTPUT;
4467 $context = (object) [
4468 'name' => $this->get_full_name(),
4469 'emoticons' => [],
4470 'forceltr' => true,
4473 $i = 0;
4474 foreach ($data as $field => $value) {
4476 // When $i == 0: text.
4477 // When $i == 1: imagename.
4478 // When $i == 2: imagecomponent.
4479 // When $i == 3: altidentifier.
4480 // When $i == 4: altcomponent.
4481 $fields[$i] = (object) [
4482 'field' => $field,
4483 'value' => $value,
4484 'index' => $i
4486 $i++;
4488 if ($i > 4) {
4489 $icon = null;
4490 if (!empty($fields[1]->value)) {
4491 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4492 $alt = get_string($fields[3]->value, $fields[4]->value);
4493 } else {
4494 $alt = $fields[0]->value;
4496 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4498 $context->emoticons[] = [
4499 'fields' => $fields,
4500 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4502 $fields = [];
4503 $i = 0;
4507 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4508 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4509 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4513 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4515 * @see self::process_form_data()
4516 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4517 * @return array of form fields and their values
4519 protected function prepare_form_data(array $emoticons) {
4521 $form = array();
4522 $i = 0;
4523 foreach ($emoticons as $emoticon) {
4524 $form['text'.$i] = $emoticon->text;
4525 $form['imagename'.$i] = $emoticon->imagename;
4526 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4527 $form['altidentifier'.$i] = $emoticon->altidentifier;
4528 $form['altcomponent'.$i] = $emoticon->altcomponent;
4529 $i++;
4531 // add one more blank field set for new object
4532 $form['text'.$i] = '';
4533 $form['imagename'.$i] = '';
4534 $form['imagecomponent'.$i] = '';
4535 $form['altidentifier'.$i] = '';
4536 $form['altcomponent'.$i] = '';
4538 return $form;
4542 * Converts the data from admin settings form into an array of emoticon objects
4544 * @see self::prepare_form_data()
4545 * @param array $data array of admin form fields and values
4546 * @return false|array of emoticon objects
4548 protected function process_form_data(array $form) {
4550 $count = count($form); // number of form field values
4552 if ($count % 5) {
4553 // we must get five fields per emoticon object
4554 return false;
4557 $emoticons = array();
4558 for ($i = 0; $i < $count / 5; $i++) {
4559 $emoticon = new stdClass();
4560 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4561 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4562 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4563 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4564 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4566 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4567 // prevent from breaking http://url.addresses by accident
4568 $emoticon->text = '';
4571 if (strlen($emoticon->text) < 2) {
4572 // do not allow single character emoticons
4573 $emoticon->text = '';
4576 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4577 // emoticon text must contain some non-alphanumeric character to prevent
4578 // breaking HTML tags
4579 $emoticon->text = '';
4582 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4583 $emoticons[] = $emoticon;
4586 return $emoticons;
4593 * Special setting for limiting of the list of available languages.
4595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4597 class admin_setting_langlist extends admin_setting_configtext {
4599 * Calls parent::__construct with specific arguments
4601 public function __construct() {
4602 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4606 * Save the new setting
4608 * @param string $data The new setting
4609 * @return bool
4611 public function write_setting($data) {
4612 $return = parent::write_setting($data);
4613 get_string_manager()->reset_caches();
4614 return $return;
4620 * Selection of one of the recognised countries using the list
4621 * returned by {@link get_list_of_countries()}.
4623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4625 class admin_settings_country_select extends admin_setting_configselect {
4626 protected $includeall;
4627 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4628 $this->includeall = $includeall;
4629 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4633 * Lazy-load the available choices for the select box
4635 public function load_choices() {
4636 global $CFG;
4637 if (is_array($this->choices)) {
4638 return true;
4640 $this->choices = array_merge(
4641 array('0' => get_string('choosedots')),
4642 get_string_manager()->get_list_of_countries($this->includeall));
4643 return true;
4649 * admin_setting_configselect for the default number of sections in a course,
4650 * simply so we can lazy-load the choices.
4652 * @copyright 2011 The Open University
4653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4655 class admin_settings_num_course_sections extends admin_setting_configselect {
4656 public function __construct($name, $visiblename, $description, $defaultsetting) {
4657 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4660 /** Lazy-load the available choices for the select box */
4661 public function load_choices() {
4662 $max = get_config('moodlecourse', 'maxsections');
4663 if (!isset($max) || !is_numeric($max)) {
4664 $max = 52;
4666 for ($i = 0; $i <= $max; $i++) {
4667 $this->choices[$i] = "$i";
4669 return true;
4675 * Course category selection
4677 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4679 class admin_settings_coursecat_select extends admin_setting_configselect {
4681 * Calls parent::__construct with specific arguments
4683 public function __construct($name, $visiblename, $description, $defaultsetting) {
4684 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4688 * Load the available choices for the select box
4690 * @return bool
4692 public function load_choices() {
4693 global $CFG;
4694 require_once($CFG->dirroot.'/course/lib.php');
4695 if (is_array($this->choices)) {
4696 return true;
4698 $this->choices = make_categories_options();
4699 return true;
4705 * Special control for selecting days to backup
4707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4709 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4711 * Calls parent::__construct with specific arguments
4713 public function __construct() {
4714 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4715 $this->plugin = 'backup';
4719 * Load the available choices for the select box
4721 * @return bool Always returns true
4723 public function load_choices() {
4724 if (is_array($this->choices)) {
4725 return true;
4727 $this->choices = array();
4728 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4729 foreach ($days as $day) {
4730 $this->choices[$day] = get_string($day, 'calendar');
4732 return true;
4737 * Special setting for backup auto destination.
4739 * @package core
4740 * @subpackage admin
4741 * @copyright 2014 Frédéric Massart - FMCorz.net
4742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4744 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4747 * Calls parent::__construct with specific arguments.
4749 public function __construct() {
4750 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4754 * Check if the directory must be set, depending on backup/backup_auto_storage.
4756 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4757 * there will be conflicts if this validation happens before the other one.
4759 * @param string $data Form data.
4760 * @return string Empty when no errors.
4762 public function write_setting($data) {
4763 $storage = (int) get_config('backup', 'backup_auto_storage');
4764 if ($storage !== 0) {
4765 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4766 // The directory must exist and be writable.
4767 return get_string('backuperrorinvaliddestination');
4770 return parent::write_setting($data);
4776 * Special debug setting
4778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4780 class admin_setting_special_debug extends admin_setting_configselect {
4782 * Calls parent::__construct with specific arguments
4784 public function __construct() {
4785 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4789 * Load the available choices for the select box
4791 * @return bool
4793 public function load_choices() {
4794 if (is_array($this->choices)) {
4795 return true;
4797 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4798 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4799 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4800 DEBUG_ALL => get_string('debugall', 'admin'),
4801 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4802 return true;
4808 * Special admin control
4810 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4812 class admin_setting_special_calendar_weekend extends admin_setting {
4814 * Calls parent::__construct with specific arguments
4816 public function __construct() {
4817 $name = 'calendar_weekend';
4818 $visiblename = get_string('calendar_weekend', 'admin');
4819 $description = get_string('helpweekenddays', 'admin');
4820 $default = array ('0', '6'); // Saturdays and Sundays
4821 parent::__construct($name, $visiblename, $description, $default);
4825 * Gets the current settings as an array
4827 * @return mixed Null if none, else array of settings
4829 public function get_setting() {
4830 $result = $this->config_read($this->name);
4831 if (is_null($result)) {
4832 return NULL;
4834 if ($result === '') {
4835 return array();
4837 $settings = array();
4838 for ($i=0; $i<7; $i++) {
4839 if ($result & (1 << $i)) {
4840 $settings[] = $i;
4843 return $settings;
4847 * Save the new settings
4849 * @param array $data Array of new settings
4850 * @return bool
4852 public function write_setting($data) {
4853 if (!is_array($data)) {
4854 return '';
4856 unset($data['xxxxx']);
4857 $result = 0;
4858 foreach($data as $index) {
4859 $result |= 1 << $index;
4861 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4865 * Return XHTML to display the control
4867 * @param array $data array of selected days
4868 * @param string $query
4869 * @return string XHTML for display (field + wrapping div(s)
4871 public function output_html($data, $query='') {
4872 global $OUTPUT;
4874 // The order matters very much because of the implied numeric keys.
4875 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4876 $context = (object) [
4877 'name' => $this->get_full_name(),
4878 'id' => $this->get_id(),
4879 'days' => array_map(function($index) use ($days, $data) {
4880 return [
4881 'index' => $index,
4882 'label' => get_string($days[$index], 'calendar'),
4883 'checked' => in_array($index, $data)
4885 }, array_keys($days))
4888 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
4890 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4897 * Admin setting that allows a user to pick a behaviour.
4899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4901 class admin_setting_question_behaviour extends admin_setting_configselect {
4903 * @param string $name name of config variable
4904 * @param string $visiblename display name
4905 * @param string $description description
4906 * @param string $default default.
4908 public function __construct($name, $visiblename, $description, $default) {
4909 parent::__construct($name, $visiblename, $description, $default, null);
4913 * Load list of behaviours as choices
4914 * @return bool true => success, false => error.
4916 public function load_choices() {
4917 global $CFG;
4918 require_once($CFG->dirroot . '/question/engine/lib.php');
4919 $this->choices = question_engine::get_behaviour_options('');
4920 return true;
4926 * Admin setting that allows a user to pick appropriate roles for something.
4928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4930 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4931 /** @var array Array of capabilities which identify roles */
4932 private $types;
4935 * @param string $name Name of config variable
4936 * @param string $visiblename Display name
4937 * @param string $description Description
4938 * @param array $types Array of archetypes which identify
4939 * roles that will be enabled by default.
4941 public function __construct($name, $visiblename, $description, $types) {
4942 parent::__construct($name, $visiblename, $description, NULL, NULL);
4943 $this->types = $types;
4947 * Load roles as choices
4949 * @return bool true=>success, false=>error
4951 public function load_choices() {
4952 global $CFG, $DB;
4953 if (during_initial_install()) {
4954 return false;
4956 if (is_array($this->choices)) {
4957 return true;
4959 if ($roles = get_all_roles()) {
4960 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4961 return true;
4962 } else {
4963 return false;
4968 * Return the default setting for this control
4970 * @return array Array of default settings
4972 public function get_defaultsetting() {
4973 global $CFG;
4975 if (during_initial_install()) {
4976 return null;
4978 $result = array();
4979 foreach($this->types as $archetype) {
4980 if ($caproles = get_archetype_roles($archetype)) {
4981 foreach ($caproles as $caprole) {
4982 $result[$caprole->id] = 1;
4986 return $result;
4992 * Admin setting that is a list of installed filter plugins.
4994 * @copyright 2015 The Open University
4995 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4997 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5000 * Constructor
5002 * @param string $name unique ascii name, either 'mysetting' for settings
5003 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5004 * @param string $visiblename localised name
5005 * @param string $description localised long description
5006 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5008 public function __construct($name, $visiblename, $description, $default) {
5009 if (empty($default)) {
5010 $default = array();
5012 $this->load_choices();
5013 foreach ($default as $plugin) {
5014 if (!isset($this->choices[$plugin])) {
5015 unset($default[$plugin]);
5018 parent::__construct($name, $visiblename, $description, $default, null);
5021 public function load_choices() {
5022 if (is_array($this->choices)) {
5023 return true;
5025 $this->choices = array();
5027 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5028 $this->choices[$plugin] = filter_get_name($plugin);
5030 return true;
5036 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5040 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5042 * Constructor
5043 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5044 * @param string $visiblename localised
5045 * @param string $description long localised info
5046 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5047 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5048 * @param int $size default field size
5050 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5051 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5052 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5058 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5060 * @copyright 2009 Petr Skoda (http://skodak.org)
5061 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5063 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5066 * Constructor
5067 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5068 * @param string $visiblename localised
5069 * @param string $description long localised info
5070 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5071 * @param string $yes value used when checked
5072 * @param string $no value used when not checked
5074 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5075 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5076 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5083 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5085 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5087 * @copyright 2010 Sam Hemelryk
5088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5090 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5092 * Constructor
5093 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5094 * @param string $visiblename localised
5095 * @param string $description long localised info
5096 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5097 * @param string $yes value used when checked
5098 * @param string $no value used when not checked
5100 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5101 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5102 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5109 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5113 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5115 * Calls parent::__construct with specific arguments
5117 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5118 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5119 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5125 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5127 * @copyright 2017 Marina Glancy
5128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5130 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5132 * Constructor
5133 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5134 * or 'myplugin/mysetting' for ones in config_plugins.
5135 * @param string $visiblename localised
5136 * @param string $description long localised info
5137 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5138 * @param array $choices array of $value=>$label for each selection
5140 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5141 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5142 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5148 * Graded roles in gradebook
5150 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5152 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5154 * Calls parent::__construct with specific arguments
5156 public function __construct() {
5157 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5158 get_string('configgradebookroles', 'admin'),
5159 array('student'));
5166 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5168 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5170 * Saves the new settings passed in $data
5172 * @param string $data
5173 * @return mixed string or Array
5175 public function write_setting($data) {
5176 global $CFG, $DB;
5178 $oldvalue = $this->config_read($this->name);
5179 $return = parent::write_setting($data);
5180 $newvalue = $this->config_read($this->name);
5182 if ($oldvalue !== $newvalue) {
5183 // force full regrading
5184 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5187 return $return;
5193 * Which roles to show on course description page
5195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5197 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5199 * Calls parent::__construct with specific arguments
5201 public function __construct() {
5202 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5203 get_string('coursecontact_desc', 'admin'),
5204 array('editingteacher'));
5205 $this->set_updatedcallback(function (){
5206 cache::make('core', 'coursecontacts')->purge();
5214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5216 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5218 * Calls parent::__construct with specific arguments
5220 public function __construct() {
5221 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5222 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5226 * Old syntax of class constructor. Deprecated in PHP7.
5228 * @deprecated since Moodle 3.1
5230 public function admin_setting_special_gradelimiting() {
5231 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5232 self::__construct();
5236 * Force site regrading
5238 function regrade_all() {
5239 global $CFG;
5240 require_once("$CFG->libdir/gradelib.php");
5241 grade_force_site_regrading();
5245 * Saves the new settings
5247 * @param mixed $data
5248 * @return string empty string or error message
5250 function write_setting($data) {
5251 $previous = $this->get_setting();
5253 if ($previous === null) {
5254 if ($data) {
5255 $this->regrade_all();
5257 } else {
5258 if ($data != $previous) {
5259 $this->regrade_all();
5262 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5268 * Special setting for $CFG->grade_minmaxtouse.
5270 * @package core
5271 * @copyright 2015 Frédéric Massart - FMCorz.net
5272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5274 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5277 * Constructor.
5279 public function __construct() {
5280 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5281 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5282 array(
5283 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5284 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5290 * Saves the new setting.
5292 * @param mixed $data
5293 * @return string empty string or error message
5295 function write_setting($data) {
5296 global $CFG;
5298 $previous = $this->get_setting();
5299 $result = parent::write_setting($data);
5301 // If saved and the value has changed.
5302 if (empty($result) && $previous != $data) {
5303 require_once($CFG->libdir . '/gradelib.php');
5304 grade_force_site_regrading();
5307 return $result;
5314 * Primary grade export plugin - has state tracking.
5316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5318 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5320 * Calls parent::__construct with specific arguments
5322 public function __construct() {
5323 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5324 get_string('configgradeexport', 'admin'), array(), NULL);
5328 * Load the available choices for the multicheckbox
5330 * @return bool always returns true
5332 public function load_choices() {
5333 if (is_array($this->choices)) {
5334 return true;
5336 $this->choices = array();
5338 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5339 foreach($plugins as $plugin => $unused) {
5340 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5343 return true;
5349 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5353 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5355 * Config gradepointmax constructor
5357 * @param string $name Overidden by "gradepointmax"
5358 * @param string $visiblename Overridden by "gradepointmax" language string.
5359 * @param string $description Overridden by "gradepointmax_help" language string.
5360 * @param string $defaultsetting Not used, overridden by 100.
5361 * @param mixed $paramtype Overridden by PARAM_INT.
5362 * @param int $size Overridden by 5.
5364 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5365 $name = 'gradepointdefault';
5366 $visiblename = get_string('gradepointdefault', 'grades');
5367 $description = get_string('gradepointdefault_help', 'grades');
5368 $defaultsetting = 100;
5369 $paramtype = PARAM_INT;
5370 $size = 5;
5371 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5375 * Validate data before storage
5376 * @param string $data The submitted data
5377 * @return bool|string true if ok, string if error found
5379 public function validate($data) {
5380 global $CFG;
5381 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5382 return true;
5383 } else {
5384 return get_string('gradepointdefault_validateerror', 'grades');
5391 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5395 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5398 * Config gradepointmax constructor
5400 * @param string $name Overidden by "gradepointmax"
5401 * @param string $visiblename Overridden by "gradepointmax" language string.
5402 * @param string $description Overridden by "gradepointmax_help" language string.
5403 * @param string $defaultsetting Not used, overridden by 100.
5404 * @param mixed $paramtype Overridden by PARAM_INT.
5405 * @param int $size Overridden by 5.
5407 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5408 $name = 'gradepointmax';
5409 $visiblename = get_string('gradepointmax', 'grades');
5410 $description = get_string('gradepointmax_help', 'grades');
5411 $defaultsetting = 100;
5412 $paramtype = PARAM_INT;
5413 $size = 5;
5414 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5418 * Save the selected setting
5420 * @param string $data The selected site
5421 * @return string empty string or error message
5423 public function write_setting($data) {
5424 if ($data === '') {
5425 $data = (int)$this->defaultsetting;
5426 } else {
5427 $data = $data;
5429 return parent::write_setting($data);
5433 * Validate data before storage
5434 * @param string $data The submitted data
5435 * @return bool|string true if ok, string if error found
5437 public function validate($data) {
5438 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5439 return true;
5440 } else {
5441 return get_string('gradepointmax_validateerror', 'grades');
5446 * Return an XHTML string for the setting
5447 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5448 * @param string $query search query to be highlighted
5449 * @return string XHTML to display control
5451 public function output_html($data, $query = '') {
5452 global $OUTPUT;
5454 $default = $this->get_defaultsetting();
5455 $context = (object) [
5456 'size' => $this->size,
5457 'id' => $this->get_id(),
5458 'name' => $this->get_full_name(),
5459 'value' => $data,
5460 'attributes' => [
5461 'maxlength' => 5
5463 'forceltr' => $this->get_force_ltr()
5465 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5467 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5473 * Grade category settings
5475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5477 class admin_setting_gradecat_combo extends admin_setting {
5478 /** @var array Array of choices */
5479 public $choices;
5482 * Sets choices and calls parent::__construct with passed arguments
5483 * @param string $name
5484 * @param string $visiblename
5485 * @param string $description
5486 * @param mixed $defaultsetting string or array depending on implementation
5487 * @param array $choices An array of choices for the control
5489 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5490 $this->choices = $choices;
5491 parent::__construct($name, $visiblename, $description, $defaultsetting);
5495 * Return the current setting(s) array
5497 * @return array Array of value=>xx, forced=>xx, adv=>xx
5499 public function get_setting() {
5500 global $CFG;
5502 $value = $this->config_read($this->name);
5503 $flag = $this->config_read($this->name.'_flag');
5505 if (is_null($value) or is_null($flag)) {
5506 return NULL;
5509 $flag = (int)$flag;
5510 $forced = (boolean)(1 & $flag); // first bit
5511 $adv = (boolean)(2 & $flag); // second bit
5513 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5517 * Save the new settings passed in $data
5519 * @todo Add vartype handling to ensure $data is array
5520 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5521 * @return string empty or error message
5523 public function write_setting($data) {
5524 global $CFG;
5526 $value = $data['value'];
5527 $forced = empty($data['forced']) ? 0 : 1;
5528 $adv = empty($data['adv']) ? 0 : 2;
5529 $flag = ($forced | $adv); //bitwise or
5531 if (!in_array($value, array_keys($this->choices))) {
5532 return 'Error setting ';
5535 $oldvalue = $this->config_read($this->name);
5536 $oldflag = (int)$this->config_read($this->name.'_flag');
5537 $oldforced = (1 & $oldflag); // first bit
5539 $result1 = $this->config_write($this->name, $value);
5540 $result2 = $this->config_write($this->name.'_flag', $flag);
5542 // force regrade if needed
5543 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5544 require_once($CFG->libdir.'/gradelib.php');
5545 grade_category::updated_forced_settings();
5548 if ($result1 and $result2) {
5549 return '';
5550 } else {
5551 return get_string('errorsetting', 'admin');
5556 * Return XHTML to display the field and wrapping div
5558 * @todo Add vartype handling to ensure $data is array
5559 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5560 * @param string $query
5561 * @return string XHTML to display control
5563 public function output_html($data, $query='') {
5564 global $OUTPUT;
5566 $value = $data['value'];
5568 $default = $this->get_defaultsetting();
5569 if (!is_null($default)) {
5570 $defaultinfo = array();
5571 if (isset($this->choices[$default['value']])) {
5572 $defaultinfo[] = $this->choices[$default['value']];
5574 if (!empty($default['forced'])) {
5575 $defaultinfo[] = get_string('force');
5577 if (!empty($default['adv'])) {
5578 $defaultinfo[] = get_string('advanced');
5580 $defaultinfo = implode(', ', $defaultinfo);
5582 } else {
5583 $defaultinfo = NULL;
5586 $options = $this->choices;
5587 $context = (object) [
5588 'id' => $this->get_id(),
5589 'name' => $this->get_full_name(),
5590 'forced' => !empty($data['forced']),
5591 'advanced' => !empty($data['adv']),
5592 'options' => array_map(function($option) use ($options, $value) {
5593 return [
5594 'value' => $option,
5595 'name' => $options[$option],
5596 'selected' => $option == $value
5598 }, array_keys($options)),
5601 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5603 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5609 * Selection of grade report in user profiles
5611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5613 class admin_setting_grade_profilereport extends admin_setting_configselect {
5615 * Calls parent::__construct with specific arguments
5617 public function __construct() {
5618 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5622 * Loads an array of choices for the configselect control
5624 * @return bool always return true
5626 public function load_choices() {
5627 if (is_array($this->choices)) {
5628 return true;
5630 $this->choices = array();
5632 global $CFG;
5633 require_once($CFG->libdir.'/gradelib.php');
5635 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5636 if (file_exists($plugindir.'/lib.php')) {
5637 require_once($plugindir.'/lib.php');
5638 $functionname = 'grade_report_'.$plugin.'_profilereport';
5639 if (function_exists($functionname)) {
5640 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5644 return true;
5649 * Provides a selection of grade reports to be used for "grades".
5651 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5652 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5654 class admin_setting_my_grades_report extends admin_setting_configselect {
5657 * Calls parent::__construct with specific arguments.
5659 public function __construct() {
5660 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5661 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5665 * Loads an array of choices for the configselect control.
5667 * @return bool always returns true.
5669 public function load_choices() {
5670 global $CFG; // Remove this line and behold the horror of behat test failures!
5671 $this->choices = array();
5672 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5673 if (file_exists($plugindir . '/lib.php')) {
5674 require_once($plugindir . '/lib.php');
5675 // Check to see if the class exists. Check the correct plugin convention first.
5676 if (class_exists('gradereport_' . $plugin)) {
5677 $classname = 'gradereport_' . $plugin;
5678 } else if (class_exists('grade_report_' . $plugin)) {
5679 // We are using the old plugin naming convention.
5680 $classname = 'grade_report_' . $plugin;
5681 } else {
5682 continue;
5684 if ($classname::supports_mygrades()) {
5685 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5689 // Add an option to specify an external url.
5690 $this->choices['external'] = get_string('externalurl', 'grades');
5691 return true;
5696 * Special class for register auth selection
5698 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5700 class admin_setting_special_registerauth extends admin_setting_configselect {
5702 * Calls parent::__construct with specific arguments
5704 public function __construct() {
5705 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5709 * Returns the default option
5711 * @return string empty or default option
5713 public function get_defaultsetting() {
5714 $this->load_choices();
5715 $defaultsetting = parent::get_defaultsetting();
5716 if (array_key_exists($defaultsetting, $this->choices)) {
5717 return $defaultsetting;
5718 } else {
5719 return '';
5724 * Loads the possible choices for the array
5726 * @return bool always returns true
5728 public function load_choices() {
5729 global $CFG;
5731 if (is_array($this->choices)) {
5732 return true;
5734 $this->choices = array();
5735 $this->choices[''] = get_string('disable');
5737 $authsenabled = get_enabled_auth_plugins(true);
5739 foreach ($authsenabled as $auth) {
5740 $authplugin = get_auth_plugin($auth);
5741 if (!$authplugin->can_signup()) {
5742 continue;
5744 // Get the auth title (from core or own auth lang files)
5745 $authtitle = $authplugin->get_title();
5746 $this->choices[$auth] = $authtitle;
5748 return true;
5754 * General plugins manager
5756 class admin_page_pluginsoverview extends admin_externalpage {
5759 * Sets basic information about the external page
5761 public function __construct() {
5762 global $CFG;
5763 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5764 "$CFG->wwwroot/$CFG->admin/plugins.php");
5769 * Module manage page
5771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5773 class admin_page_managemods extends admin_externalpage {
5775 * Calls parent::__construct with specific arguments
5777 public function __construct() {
5778 global $CFG;
5779 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5783 * Try to find the specified module
5785 * @param string $query The module to search for
5786 * @return array
5788 public function search($query) {
5789 global $CFG, $DB;
5790 if ($result = parent::search($query)) {
5791 return $result;
5794 $found = false;
5795 if ($modules = $DB->get_records('modules')) {
5796 foreach ($modules as $module) {
5797 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5798 continue;
5800 if (strpos($module->name, $query) !== false) {
5801 $found = true;
5802 break;
5804 $strmodulename = get_string('modulename', $module->name);
5805 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5806 $found = true;
5807 break;
5811 if ($found) {
5812 $result = new stdClass();
5813 $result->page = $this;
5814 $result->settings = array();
5815 return array($this->name => $result);
5816 } else {
5817 return array();
5824 * Special class for enrol plugins management.
5826 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5829 class admin_setting_manageenrols extends admin_setting {
5831 * Calls parent::__construct with specific arguments
5833 public function __construct() {
5834 $this->nosave = true;
5835 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5839 * Always returns true, does nothing
5841 * @return true
5843 public function get_setting() {
5844 return true;
5848 * Always returns true, does nothing
5850 * @return true
5852 public function get_defaultsetting() {
5853 return true;
5857 * Always returns '', does not write anything
5859 * @return string Always returns ''
5861 public function write_setting($data) {
5862 // do not write any setting
5863 return '';
5867 * Checks if $query is one of the available enrol plugins
5869 * @param string $query The string to search for
5870 * @return bool Returns true if found, false if not
5872 public function is_related($query) {
5873 if (parent::is_related($query)) {
5874 return true;
5877 $query = core_text::strtolower($query);
5878 $enrols = enrol_get_plugins(false);
5879 foreach ($enrols as $name=>$enrol) {
5880 $localised = get_string('pluginname', 'enrol_'.$name);
5881 if (strpos(core_text::strtolower($name), $query) !== false) {
5882 return true;
5884 if (strpos(core_text::strtolower($localised), $query) !== false) {
5885 return true;
5888 return false;
5892 * Builds the XHTML to display the control
5894 * @param string $data Unused
5895 * @param string $query
5896 * @return string
5898 public function output_html($data, $query='') {
5899 global $CFG, $OUTPUT, $DB, $PAGE;
5901 // Display strings.
5902 $strup = get_string('up');
5903 $strdown = get_string('down');
5904 $strsettings = get_string('settings');
5905 $strenable = get_string('enable');
5906 $strdisable = get_string('disable');
5907 $struninstall = get_string('uninstallplugin', 'core_admin');
5908 $strusage = get_string('enrolusage', 'enrol');
5909 $strversion = get_string('version');
5910 $strtest = get_string('testsettings', 'core_enrol');
5912 $pluginmanager = core_plugin_manager::instance();
5914 $enrols_available = enrol_get_plugins(false);
5915 $active_enrols = enrol_get_plugins(true);
5917 $allenrols = array();
5918 foreach ($active_enrols as $key=>$enrol) {
5919 $allenrols[$key] = true;
5921 foreach ($enrols_available as $key=>$enrol) {
5922 $allenrols[$key] = true;
5924 // Now find all borked plugins and at least allow then to uninstall.
5925 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5926 foreach ($condidates as $candidate) {
5927 if (empty($allenrols[$candidate])) {
5928 $allenrols[$candidate] = true;
5932 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5933 $return .= $OUTPUT->box_start('generalbox enrolsui');
5935 $table = new html_table();
5936 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5937 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5938 $table->id = 'courseenrolmentplugins';
5939 $table->attributes['class'] = 'admintable generaltable';
5940 $table->data = array();
5942 // Iterate through enrol plugins and add to the display table.
5943 $updowncount = 1;
5944 $enrolcount = count($active_enrols);
5945 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5946 $printed = array();
5947 foreach($allenrols as $enrol => $unused) {
5948 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5949 $version = get_config('enrol_'.$enrol, 'version');
5950 if ($version === false) {
5951 $version = '';
5954 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5955 $name = get_string('pluginname', 'enrol_'.$enrol);
5956 } else {
5957 $name = $enrol;
5959 // Usage.
5960 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5961 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5962 $usage = "$ci / $cp";
5964 // Hide/show links.
5965 $class = '';
5966 if (isset($active_enrols[$enrol])) {
5967 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5968 $hideshow = "<a href=\"$aurl\">";
5969 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
5970 $enabled = true;
5971 $displayname = $name;
5972 } else if (isset($enrols_available[$enrol])) {
5973 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5974 $hideshow = "<a href=\"$aurl\">";
5975 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
5976 $enabled = false;
5977 $displayname = $name;
5978 $class = 'dimmed_text';
5979 } else {
5980 $hideshow = '';
5981 $enabled = false;
5982 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5984 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5985 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5986 } else {
5987 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5990 // Up/down link (only if enrol is enabled).
5991 $updown = '';
5992 if ($enabled) {
5993 if ($updowncount > 1) {
5994 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5995 $updown .= "<a href=\"$aurl\">";
5996 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
5997 } else {
5998 $updown .= $OUTPUT->spacer() . '&nbsp;';
6000 if ($updowncount < $enrolcount) {
6001 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6002 $updown .= "<a href=\"$aurl\">";
6003 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6004 } else {
6005 $updown .= $OUTPUT->spacer() . '&nbsp;';
6007 ++$updowncount;
6010 // Add settings link.
6011 if (!$version) {
6012 $settings = '';
6013 } else if ($surl = $plugininfo->get_settings_url()) {
6014 $settings = html_writer::link($surl, $strsettings);
6015 } else {
6016 $settings = '';
6019 // Add uninstall info.
6020 $uninstall = '';
6021 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6022 $uninstall = html_writer::link($uninstallurl, $struninstall);
6025 $test = '';
6026 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6027 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6028 $test = html_writer::link($testsettingsurl, $strtest);
6031 // Add a row to the table.
6032 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6033 if ($class) {
6034 $row->attributes['class'] = $class;
6036 $table->data[] = $row;
6038 $printed[$enrol] = true;
6041 $return .= html_writer::table($table);
6042 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6043 $return .= $OUTPUT->box_end();
6044 return highlight($query, $return);
6050 * Blocks manage page
6052 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6054 class admin_page_manageblocks extends admin_externalpage {
6056 * Calls parent::__construct with specific arguments
6058 public function __construct() {
6059 global $CFG;
6060 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6064 * Search for a specific block
6066 * @param string $query The string to search for
6067 * @return array
6069 public function search($query) {
6070 global $CFG, $DB;
6071 if ($result = parent::search($query)) {
6072 return $result;
6075 $found = false;
6076 if ($blocks = $DB->get_records('block')) {
6077 foreach ($blocks as $block) {
6078 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6079 continue;
6081 if (strpos($block->name, $query) !== false) {
6082 $found = true;
6083 break;
6085 $strblockname = get_string('pluginname', 'block_'.$block->name);
6086 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6087 $found = true;
6088 break;
6092 if ($found) {
6093 $result = new stdClass();
6094 $result->page = $this;
6095 $result->settings = array();
6096 return array($this->name => $result);
6097 } else {
6098 return array();
6104 * Message outputs configuration
6106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6108 class admin_page_managemessageoutputs extends admin_externalpage {
6110 * Calls parent::__construct with specific arguments
6112 public function __construct() {
6113 global $CFG;
6114 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
6118 * Search for a specific message processor
6120 * @param string $query The string to search for
6121 * @return array
6123 public function search($query) {
6124 global $CFG, $DB;
6125 if ($result = parent::search($query)) {
6126 return $result;
6129 $found = false;
6130 if ($processors = get_message_processors()) {
6131 foreach ($processors as $processor) {
6132 if (!$processor->available) {
6133 continue;
6135 if (strpos($processor->name, $query) !== false) {
6136 $found = true;
6137 break;
6139 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6140 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6141 $found = true;
6142 break;
6146 if ($found) {
6147 $result = new stdClass();
6148 $result->page = $this;
6149 $result->settings = array();
6150 return array($this->name => $result);
6151 } else {
6152 return array();
6158 * Default message outputs configuration
6160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6162 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6164 * Calls parent::__construct with specific arguments
6166 public function __construct() {
6167 global $CFG;
6168 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6174 * Manage question behaviours page
6176 * @copyright 2011 The Open University
6177 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6179 class admin_page_manageqbehaviours extends admin_externalpage {
6181 * Constructor
6183 public function __construct() {
6184 global $CFG;
6185 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6186 new moodle_url('/admin/qbehaviours.php'));
6190 * Search question behaviours for the specified string
6192 * @param string $query The string to search for in question behaviours
6193 * @return array
6195 public function search($query) {
6196 global $CFG;
6197 if ($result = parent::search($query)) {
6198 return $result;
6201 $found = false;
6202 require_once($CFG->dirroot . '/question/engine/lib.php');
6203 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6204 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6205 $query) !== false) {
6206 $found = true;
6207 break;
6210 if ($found) {
6211 $result = new stdClass();
6212 $result->page = $this;
6213 $result->settings = array();
6214 return array($this->name => $result);
6215 } else {
6216 return array();
6223 * Question type manage page
6225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6227 class admin_page_manageqtypes extends admin_externalpage {
6229 * Calls parent::__construct with specific arguments
6231 public function __construct() {
6232 global $CFG;
6233 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6234 new moodle_url('/admin/qtypes.php'));
6238 * Search question types for the specified string
6240 * @param string $query The string to search for in question types
6241 * @return array
6243 public function search($query) {
6244 global $CFG;
6245 if ($result = parent::search($query)) {
6246 return $result;
6249 $found = false;
6250 require_once($CFG->dirroot . '/question/engine/bank.php');
6251 foreach (question_bank::get_all_qtypes() as $qtype) {
6252 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6253 $found = true;
6254 break;
6257 if ($found) {
6258 $result = new stdClass();
6259 $result->page = $this;
6260 $result->settings = array();
6261 return array($this->name => $result);
6262 } else {
6263 return array();
6269 class admin_page_manageportfolios extends admin_externalpage {
6271 * Calls parent::__construct with specific arguments
6273 public function __construct() {
6274 global $CFG;
6275 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6276 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6280 * Searches page for the specified string.
6281 * @param string $query The string to search for
6282 * @return bool True if it is found on this page
6284 public function search($query) {
6285 global $CFG;
6286 if ($result = parent::search($query)) {
6287 return $result;
6290 $found = false;
6291 $portfolios = core_component::get_plugin_list('portfolio');
6292 foreach ($portfolios as $p => $dir) {
6293 if (strpos($p, $query) !== false) {
6294 $found = true;
6295 break;
6298 if (!$found) {
6299 foreach (portfolio_instances(false, false) as $instance) {
6300 $title = $instance->get('name');
6301 if (strpos(core_text::strtolower($title), $query) !== false) {
6302 $found = true;
6303 break;
6308 if ($found) {
6309 $result = new stdClass();
6310 $result->page = $this;
6311 $result->settings = array();
6312 return array($this->name => $result);
6313 } else {
6314 return array();
6320 class admin_page_managerepositories extends admin_externalpage {
6322 * Calls parent::__construct with specific arguments
6324 public function __construct() {
6325 global $CFG;
6326 parent::__construct('managerepositories', get_string('manage',
6327 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6331 * Searches page for the specified string.
6332 * @param string $query The string to search for
6333 * @return bool True if it is found on this page
6335 public function search($query) {
6336 global $CFG;
6337 if ($result = parent::search($query)) {
6338 return $result;
6341 $found = false;
6342 $repositories= core_component::get_plugin_list('repository');
6343 foreach ($repositories as $p => $dir) {
6344 if (strpos($p, $query) !== false) {
6345 $found = true;
6346 break;
6349 if (!$found) {
6350 foreach (repository::get_types() as $instance) {
6351 $title = $instance->get_typename();
6352 if (strpos(core_text::strtolower($title), $query) !== false) {
6353 $found = true;
6354 break;
6359 if ($found) {
6360 $result = new stdClass();
6361 $result->page = $this;
6362 $result->settings = array();
6363 return array($this->name => $result);
6364 } else {
6365 return array();
6372 * Special class for authentication administration.
6374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6376 class admin_setting_manageauths extends admin_setting {
6378 * Calls parent::__construct with specific arguments
6380 public function __construct() {
6381 $this->nosave = true;
6382 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6386 * Always returns true
6388 * @return true
6390 public function get_setting() {
6391 return true;
6395 * Always returns true
6397 * @return true
6399 public function get_defaultsetting() {
6400 return true;
6404 * Always returns '' and doesn't write anything
6406 * @return string Always returns ''
6408 public function write_setting($data) {
6409 // do not write any setting
6410 return '';
6414 * Search to find if Query is related to auth plugin
6416 * @param string $query The string to search for
6417 * @return bool true for related false for not
6419 public function is_related($query) {
6420 if (parent::is_related($query)) {
6421 return true;
6424 $authsavailable = core_component::get_plugin_list('auth');
6425 foreach ($authsavailable as $auth => $dir) {
6426 if (strpos($auth, $query) !== false) {
6427 return true;
6429 $authplugin = get_auth_plugin($auth);
6430 $authtitle = $authplugin->get_title();
6431 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6432 return true;
6435 return false;
6439 * Return XHTML to display control
6441 * @param mixed $data Unused
6442 * @param string $query
6443 * @return string highlight
6445 public function output_html($data, $query='') {
6446 global $CFG, $OUTPUT, $DB;
6448 // display strings
6449 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6450 'settings', 'edit', 'name', 'enable', 'disable',
6451 'up', 'down', 'none', 'users'));
6452 $txt->updown = "$txt->up/$txt->down";
6453 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6454 $txt->testsettings = get_string('testsettings', 'core_auth');
6456 $authsavailable = core_component::get_plugin_list('auth');
6457 get_enabled_auth_plugins(true); // fix the list of enabled auths
6458 if (empty($CFG->auth)) {
6459 $authsenabled = array();
6460 } else {
6461 $authsenabled = explode(',', $CFG->auth);
6464 // construct the display array, with enabled auth plugins at the top, in order
6465 $displayauths = array();
6466 $registrationauths = array();
6467 $registrationauths[''] = $txt->disable;
6468 $authplugins = array();
6469 foreach ($authsenabled as $auth) {
6470 $authplugin = get_auth_plugin($auth);
6471 $authplugins[$auth] = $authplugin;
6472 /// Get the auth title (from core or own auth lang files)
6473 $authtitle = $authplugin->get_title();
6474 /// Apply titles
6475 $displayauths[$auth] = $authtitle;
6476 if ($authplugin->can_signup()) {
6477 $registrationauths[$auth] = $authtitle;
6481 foreach ($authsavailable as $auth => $dir) {
6482 if (array_key_exists($auth, $displayauths)) {
6483 continue; //already in the list
6485 $authplugin = get_auth_plugin($auth);
6486 $authplugins[$auth] = $authplugin;
6487 /// Get the auth title (from core or own auth lang files)
6488 $authtitle = $authplugin->get_title();
6489 /// Apply titles
6490 $displayauths[$auth] = $authtitle;
6491 if ($authplugin->can_signup()) {
6492 $registrationauths[$auth] = $authtitle;
6496 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6497 $return .= $OUTPUT->box_start('generalbox authsui');
6499 $table = new html_table();
6500 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6501 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6502 $table->data = array();
6503 $table->attributes['class'] = 'admintable generaltable';
6504 $table->id = 'manageauthtable';
6506 //add always enabled plugins first
6507 $displayname = $displayauths['manual'];
6508 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6509 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6510 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6511 $displayname = $displayauths['nologin'];
6512 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6513 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6516 // iterate through auth plugins and add to the display table
6517 $updowncount = 1;
6518 $authcount = count($authsenabled);
6519 $url = "auth.php?sesskey=" . sesskey();
6520 foreach ($displayauths as $auth => $name) {
6521 if ($auth == 'manual' or $auth == 'nologin') {
6522 continue;
6524 $class = '';
6525 // hide/show link
6526 if (in_array($auth, $authsenabled)) {
6527 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6528 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6529 $enabled = true;
6530 $displayname = $name;
6532 else {
6533 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6534 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6535 $enabled = false;
6536 $displayname = $name;
6537 $class = 'dimmed_text';
6540 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6542 // up/down link (only if auth is enabled)
6543 $updown = '';
6544 if ($enabled) {
6545 if ($updowncount > 1) {
6546 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6547 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6549 else {
6550 $updown .= $OUTPUT->spacer() . '&nbsp;';
6552 if ($updowncount < $authcount) {
6553 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6554 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6556 else {
6557 $updown .= $OUTPUT->spacer() . '&nbsp;';
6559 ++ $updowncount;
6562 // settings link
6563 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6564 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6565 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6566 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6567 } else {
6568 $settings = '';
6571 // Uninstall link.
6572 $uninstall = '';
6573 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6574 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6577 $test = '';
6578 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6579 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6580 $test = html_writer::link($testurl, $txt->testsettings);
6583 // Add a row to the table.
6584 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6585 if ($class) {
6586 $row->attributes['class'] = $class;
6588 $table->data[] = $row;
6590 $return .= html_writer::table($table);
6591 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6592 $return .= $OUTPUT->box_end();
6593 return highlight($query, $return);
6599 * Special class for authentication administration.
6601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6603 class admin_setting_manageeditors extends admin_setting {
6605 * Calls parent::__construct with specific arguments
6607 public function __construct() {
6608 $this->nosave = true;
6609 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6613 * Always returns true, does nothing
6615 * @return true
6617 public function get_setting() {
6618 return true;
6622 * Always returns true, does nothing
6624 * @return true
6626 public function get_defaultsetting() {
6627 return true;
6631 * Always returns '', does not write anything
6633 * @return string Always returns ''
6635 public function write_setting($data) {
6636 // do not write any setting
6637 return '';
6641 * Checks if $query is one of the available editors
6643 * @param string $query The string to search for
6644 * @return bool Returns true if found, false if not
6646 public function is_related($query) {
6647 if (parent::is_related($query)) {
6648 return true;
6651 $editors_available = editors_get_available();
6652 foreach ($editors_available as $editor=>$editorstr) {
6653 if (strpos($editor, $query) !== false) {
6654 return true;
6656 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6657 return true;
6660 return false;
6664 * Builds the XHTML to display the control
6666 * @param string $data Unused
6667 * @param string $query
6668 * @return string
6670 public function output_html($data, $query='') {
6671 global $CFG, $OUTPUT;
6673 // display strings
6674 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6675 'up', 'down', 'none'));
6676 $struninstall = get_string('uninstallplugin', 'core_admin');
6678 $txt->updown = "$txt->up/$txt->down";
6680 $editors_available = editors_get_available();
6681 $active_editors = explode(',', $CFG->texteditors);
6683 $active_editors = array_reverse($active_editors);
6684 foreach ($active_editors as $key=>$editor) {
6685 if (empty($editors_available[$editor])) {
6686 unset($active_editors[$key]);
6687 } else {
6688 $name = $editors_available[$editor];
6689 unset($editors_available[$editor]);
6690 $editors_available[$editor] = $name;
6693 if (empty($active_editors)) {
6694 //$active_editors = array('textarea');
6696 $editors_available = array_reverse($editors_available, true);
6697 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6698 $return .= $OUTPUT->box_start('generalbox editorsui');
6700 $table = new html_table();
6701 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6702 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6703 $table->id = 'editormanagement';
6704 $table->attributes['class'] = 'admintable generaltable';
6705 $table->data = array();
6707 // iterate through auth plugins and add to the display table
6708 $updowncount = 1;
6709 $editorcount = count($active_editors);
6710 $url = "editors.php?sesskey=" . sesskey();
6711 foreach ($editors_available as $editor => $name) {
6712 // hide/show link
6713 $class = '';
6714 if (in_array($editor, $active_editors)) {
6715 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6716 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6717 $enabled = true;
6718 $displayname = $name;
6720 else {
6721 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6722 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6723 $enabled = false;
6724 $displayname = $name;
6725 $class = 'dimmed_text';
6728 // up/down link (only if auth is enabled)
6729 $updown = '';
6730 if ($enabled) {
6731 if ($updowncount > 1) {
6732 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6733 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6735 else {
6736 $updown .= $OUTPUT->spacer() . '&nbsp;';
6738 if ($updowncount < $editorcount) {
6739 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6740 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6742 else {
6743 $updown .= $OUTPUT->spacer() . '&nbsp;';
6745 ++ $updowncount;
6748 // settings link
6749 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6750 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6751 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6752 } else {
6753 $settings = '';
6756 $uninstall = '';
6757 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6758 $uninstall = html_writer::link($uninstallurl, $struninstall);
6761 // Add a row to the table.
6762 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6763 if ($class) {
6764 $row->attributes['class'] = $class;
6766 $table->data[] = $row;
6768 $return .= html_writer::table($table);
6769 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6770 $return .= $OUTPUT->box_end();
6771 return highlight($query, $return);
6776 * Special class for antiviruses administration.
6778 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6781 class admin_setting_manageantiviruses extends admin_setting {
6783 * Calls parent::__construct with specific arguments
6785 public function __construct() {
6786 $this->nosave = true;
6787 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6791 * Always returns true, does nothing
6793 * @return true
6795 public function get_setting() {
6796 return true;
6800 * Always returns true, does nothing
6802 * @return true
6804 public function get_defaultsetting() {
6805 return true;
6809 * Always returns '', does not write anything
6811 * @param string $data Unused
6812 * @return string Always returns ''
6814 public function write_setting($data) {
6815 // Do not write any setting.
6816 return '';
6820 * Checks if $query is one of the available editors
6822 * @param string $query The string to search for
6823 * @return bool Returns true if found, false if not
6825 public function is_related($query) {
6826 if (parent::is_related($query)) {
6827 return true;
6830 $antivirusesavailable = \core\antivirus\manager::get_available();
6831 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6832 if (strpos($antivirus, $query) !== false) {
6833 return true;
6835 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6836 return true;
6839 return false;
6843 * Builds the XHTML to display the control
6845 * @param string $data Unused
6846 * @param string $query
6847 * @return string
6849 public function output_html($data, $query='') {
6850 global $CFG, $OUTPUT;
6852 // Display strings.
6853 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6854 'up', 'down', 'none'));
6855 $struninstall = get_string('uninstallplugin', 'core_admin');
6857 $txt->updown = "$txt->up/$txt->down";
6859 $antivirusesavailable = \core\antivirus\manager::get_available();
6860 $activeantiviruses = explode(',', $CFG->antiviruses);
6862 $activeantiviruses = array_reverse($activeantiviruses);
6863 foreach ($activeantiviruses as $key => $antivirus) {
6864 if (empty($antivirusesavailable[$antivirus])) {
6865 unset($activeantiviruses[$key]);
6866 } else {
6867 $name = $antivirusesavailable[$antivirus];
6868 unset($antivirusesavailable[$antivirus]);
6869 $antivirusesavailable[$antivirus] = $name;
6872 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6873 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6874 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6876 $table = new html_table();
6877 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6878 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6879 $table->id = 'antivirusmanagement';
6880 $table->attributes['class'] = 'admintable generaltable';
6881 $table->data = array();
6883 // Iterate through auth plugins and add to the display table.
6884 $updowncount = 1;
6885 $antiviruscount = count($activeantiviruses);
6886 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6887 foreach ($antivirusesavailable as $antivirus => $name) {
6888 // Hide/show link.
6889 $class = '';
6890 if (in_array($antivirus, $activeantiviruses)) {
6891 $hideshowurl = $baseurl;
6892 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6893 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
6894 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6895 $enabled = true;
6896 $displayname = $name;
6897 } else {
6898 $hideshowurl = $baseurl;
6899 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6900 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
6901 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6902 $enabled = false;
6903 $displayname = $name;
6904 $class = 'dimmed_text';
6907 // Up/down link.
6908 $updown = '';
6909 if ($enabled) {
6910 if ($updowncount > 1) {
6911 $updownurl = $baseurl;
6912 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6913 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
6914 $updown = html_writer::link($updownurl, $updownimg);
6915 } else {
6916 $updownimg = $OUTPUT->spacer();
6918 if ($updowncount < $antiviruscount) {
6919 $updownurl = $baseurl;
6920 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6921 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
6922 $updown = html_writer::link($updownurl, $updownimg);
6923 } else {
6924 $updownimg = $OUTPUT->spacer();
6926 ++ $updowncount;
6929 // Settings link.
6930 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6931 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6932 $settings = html_writer::link($eurl, $txt->settings);
6933 } else {
6934 $settings = '';
6937 $uninstall = '';
6938 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6939 $uninstall = html_writer::link($uninstallurl, $struninstall);
6942 // Add a row to the table.
6943 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6944 if ($class) {
6945 $row->attributes['class'] = $class;
6947 $table->data[] = $row;
6949 $return .= html_writer::table($table);
6950 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6951 $return .= $OUTPUT->box_end();
6952 return highlight($query, $return);
6957 * Special class for license administration.
6959 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6961 class admin_setting_managelicenses extends admin_setting {
6963 * Calls parent::__construct with specific arguments
6965 public function __construct() {
6966 $this->nosave = true;
6967 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6971 * Always returns true, does nothing
6973 * @return true
6975 public function get_setting() {
6976 return true;
6980 * Always returns true, does nothing
6982 * @return true
6984 public function get_defaultsetting() {
6985 return true;
6989 * Always returns '', does not write anything
6991 * @return string Always returns ''
6993 public function write_setting($data) {
6994 // do not write any setting
6995 return '';
6999 * Builds the XHTML to display the control
7001 * @param string $data Unused
7002 * @param string $query
7003 * @return string
7005 public function output_html($data, $query='') {
7006 global $CFG, $OUTPUT;
7007 require_once($CFG->libdir . '/licenselib.php');
7008 $url = "licenses.php?sesskey=" . sesskey();
7010 // display strings
7011 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
7012 $licenses = license_manager::get_licenses();
7014 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
7016 $return .= $OUTPUT->box_start('generalbox editorsui');
7018 $table = new html_table();
7019 $table->head = array($txt->name, $txt->enable);
7020 $table->colclasses = array('leftalign', 'centeralign');
7021 $table->id = 'availablelicenses';
7022 $table->attributes['class'] = 'admintable generaltable';
7023 $table->data = array();
7025 foreach ($licenses as $value) {
7026 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
7028 if ($value->enabled == 1) {
7029 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
7030 $OUTPUT->pix_icon('t/hide', get_string('disable')));
7031 } else {
7032 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
7033 $OUTPUT->pix_icon('t/show', get_string('enable')));
7036 if ($value->shortname == $CFG->sitedefaultlicense) {
7037 $displayname .= ' '.$OUTPUT->pix_icon('t/locked', get_string('default'));
7038 $hideshow = '';
7041 $enabled = true;
7043 $table->data[] =array($displayname, $hideshow);
7045 $return .= html_writer::table($table);
7046 $return .= $OUTPUT->box_end();
7047 return highlight($query, $return);
7052 * Course formats manager. Allows to enable/disable formats and jump to settings
7054 class admin_setting_manageformats extends admin_setting {
7057 * Calls parent::__construct with specific arguments
7059 public function __construct() {
7060 $this->nosave = true;
7061 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7065 * Always returns true
7067 * @return true
7069 public function get_setting() {
7070 return true;
7074 * Always returns true
7076 * @return true
7078 public function get_defaultsetting() {
7079 return true;
7083 * Always returns '' and doesn't write anything
7085 * @param mixed $data string or array, must not be NULL
7086 * @return string Always returns ''
7088 public function write_setting($data) {
7089 // do not write any setting
7090 return '';
7094 * Search to find if Query is related to format plugin
7096 * @param string $query The string to search for
7097 * @return bool true for related false for not
7099 public function is_related($query) {
7100 if (parent::is_related($query)) {
7101 return true;
7103 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7104 foreach ($formats as $format) {
7105 if (strpos($format->component, $query) !== false ||
7106 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7107 return true;
7110 return false;
7114 * Return XHTML to display control
7116 * @param mixed $data Unused
7117 * @param string $query
7118 * @return string highlight
7120 public function output_html($data, $query='') {
7121 global $CFG, $OUTPUT;
7122 $return = '';
7123 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7124 $return .= $OUTPUT->box_start('generalbox formatsui');
7126 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7128 // display strings
7129 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7130 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7131 $txt->updown = "$txt->up/$txt->down";
7133 $table = new html_table();
7134 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7135 $table->align = array('left', 'center', 'center', 'center', 'center');
7136 $table->attributes['class'] = 'manageformattable generaltable admintable';
7137 $table->data = array();
7139 $cnt = 0;
7140 $defaultformat = get_config('moodlecourse', 'format');
7141 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7142 foreach ($formats as $format) {
7143 $url = new moodle_url('/admin/courseformats.php',
7144 array('sesskey' => sesskey(), 'format' => $format->name));
7145 $isdefault = '';
7146 $class = '';
7147 if ($format->is_enabled()) {
7148 $strformatname = $format->displayname;
7149 if ($defaultformat === $format->name) {
7150 $hideshow = $txt->default;
7151 } else {
7152 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7153 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7155 } else {
7156 $strformatname = $format->displayname;
7157 $class = 'dimmed_text';
7158 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7159 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7161 $updown = '';
7162 if ($cnt) {
7163 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7164 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7165 } else {
7166 $updown .= $spacer;
7168 if ($cnt < count($formats) - 1) {
7169 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7170 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7171 } else {
7172 $updown .= $spacer;
7174 $cnt++;
7175 $settings = '';
7176 if ($format->get_settings_url()) {
7177 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7179 $uninstall = '';
7180 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7181 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7183 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7184 if ($class) {
7185 $row->attributes['class'] = $class;
7187 $table->data[] = $row;
7189 $return .= html_writer::table($table);
7190 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7191 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7192 $return .= $OUTPUT->box_end();
7193 return highlight($query, $return);
7198 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7200 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7203 class admin_setting_managedataformats extends admin_setting {
7206 * Calls parent::__construct with specific arguments
7208 public function __construct() {
7209 $this->nosave = true;
7210 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7214 * Always returns true
7216 * @return true
7218 public function get_setting() {
7219 return true;
7223 * Always returns true
7225 * @return true
7227 public function get_defaultsetting() {
7228 return true;
7232 * Always returns '' and doesn't write anything
7234 * @param mixed $data string or array, must not be NULL
7235 * @return string Always returns ''
7237 public function write_setting($data) {
7238 // Do not write any setting.
7239 return '';
7243 * Search to find if Query is related to format plugin
7245 * @param string $query The string to search for
7246 * @return bool true for related false for not
7248 public function is_related($query) {
7249 if (parent::is_related($query)) {
7250 return true;
7252 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7253 foreach ($formats as $format) {
7254 if (strpos($format->component, $query) !== false ||
7255 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7256 return true;
7259 return false;
7263 * Return XHTML to display control
7265 * @param mixed $data Unused
7266 * @param string $query
7267 * @return string highlight
7269 public function output_html($data, $query='') {
7270 global $CFG, $OUTPUT;
7271 $return = '';
7273 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7275 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7276 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7277 $txt->updown = "$txt->up/$txt->down";
7279 $table = new html_table();
7280 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7281 $table->align = array('left', 'center', 'center', 'center', 'center');
7282 $table->attributes['class'] = 'manageformattable generaltable admintable';
7283 $table->data = array();
7285 $cnt = 0;
7286 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7287 $totalenabled = 0;
7288 foreach ($formats as $format) {
7289 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7290 $totalenabled++;
7293 foreach ($formats as $format) {
7294 $status = $format->get_status();
7295 $url = new moodle_url('/admin/dataformats.php',
7296 array('sesskey' => sesskey(), 'name' => $format->name));
7298 $class = '';
7299 if ($format->is_enabled()) {
7300 $strformatname = $format->displayname;
7301 if ($totalenabled == 1&& $format->is_enabled()) {
7302 $hideshow = '';
7303 } else {
7304 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7305 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7307 } else {
7308 $class = 'dimmed_text';
7309 $strformatname = $format->displayname;
7310 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7311 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7314 $updown = '';
7315 if ($cnt) {
7316 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7317 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7318 } else {
7319 $updown .= $spacer;
7321 if ($cnt < count($formats) - 1) {
7322 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7323 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7324 } else {
7325 $updown .= $spacer;
7328 $uninstall = '';
7329 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7330 $uninstall = get_string('status_missing', 'core_plugin');
7331 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7332 $uninstall = get_string('status_new', 'core_plugin');
7333 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7334 if ($totalenabled != 1 || !$format->is_enabled()) {
7335 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7339 $settings = '';
7340 if ($format->get_settings_url()) {
7341 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7344 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7345 if ($class) {
7346 $row->attributes['class'] = $class;
7348 $table->data[] = $row;
7349 $cnt++;
7351 $return .= html_writer::table($table);
7352 return highlight($query, $return);
7357 * Special class for filter administration.
7359 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7361 class admin_page_managefilters extends admin_externalpage {
7363 * Calls parent::__construct with specific arguments
7365 public function __construct() {
7366 global $CFG;
7367 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7371 * Searches all installed filters for specified filter
7373 * @param string $query The filter(string) to search for
7374 * @param string $query
7376 public function search($query) {
7377 global $CFG;
7378 if ($result = parent::search($query)) {
7379 return $result;
7382 $found = false;
7383 $filternames = filter_get_all_installed();
7384 foreach ($filternames as $path => $strfiltername) {
7385 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7386 $found = true;
7387 break;
7389 if (strpos($path, $query) !== false) {
7390 $found = true;
7391 break;
7395 if ($found) {
7396 $result = new stdClass;
7397 $result->page = $this;
7398 $result->settings = array();
7399 return array($this->name => $result);
7400 } else {
7401 return array();
7407 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7408 * Requires a get_rank method on the plugininfo class for sorting.
7410 * @copyright 2017 Damyon Wiese
7411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7413 abstract class admin_setting_manage_plugins extends admin_setting {
7416 * Get the admin settings section name (just a unique string)
7418 * @return string
7420 public function get_section_name() {
7421 return 'manage' . $this->get_plugin_type() . 'plugins';
7425 * Get the admin settings section title (use get_string).
7427 * @return string
7429 abstract public function get_section_title();
7432 * Get the type of plugin to manage.
7434 * @return string
7436 abstract public function get_plugin_type();
7439 * Get the name of the second column.
7441 * @return string
7443 public function get_info_column_name() {
7444 return '';
7448 * Get the type of plugin to manage.
7450 * @param plugininfo The plugin info class.
7451 * @return string
7453 abstract public function get_info_column($plugininfo);
7456 * Calls parent::__construct with specific arguments
7458 public function __construct() {
7459 $this->nosave = true;
7460 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7464 * Always returns true, does nothing
7466 * @return true
7468 public function get_setting() {
7469 return true;
7473 * Always returns true, does nothing
7475 * @return true
7477 public function get_defaultsetting() {
7478 return true;
7482 * Always returns '', does not write anything
7484 * @param mixed $data
7485 * @return string Always returns ''
7487 public function write_setting($data) {
7488 // Do not write any setting.
7489 return '';
7493 * Checks if $query is one of the available plugins of this type
7495 * @param string $query The string to search for
7496 * @return bool Returns true if found, false if not
7498 public function is_related($query) {
7499 if (parent::is_related($query)) {
7500 return true;
7503 $query = core_text::strtolower($query);
7504 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7505 foreach ($plugins as $name => $plugin) {
7506 $localised = $plugin->displayname;
7507 if (strpos(core_text::strtolower($name), $query) !== false) {
7508 return true;
7510 if (strpos(core_text::strtolower($localised), $query) !== false) {
7511 return true;
7514 return false;
7518 * The URL for the management page for this plugintype.
7520 * @return moodle_url
7522 protected function get_manage_url() {
7523 return new moodle_url('/admin/updatesetting.php');
7527 * Builds the HTML to display the control.
7529 * @param string $data Unused
7530 * @param string $query
7531 * @return string
7533 public function output_html($data, $query = '') {
7534 global $CFG, $OUTPUT, $DB, $PAGE;
7536 $context = (object) [
7537 'manageurl' => new moodle_url($this->get_manage_url(), [
7538 'type' => $this->get_plugin_type(),
7539 'sesskey' => sesskey(),
7541 'infocolumnname' => $this->get_info_column_name(),
7542 'plugins' => [],
7545 $pluginmanager = core_plugin_manager::instance();
7546 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7547 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7548 $plugins = array_merge($enabled, $allplugins);
7549 foreach ($plugins as $key => $plugin) {
7550 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7552 $pluginkey = (object) [
7553 'plugin' => $plugin->displayname,
7554 'enabled' => $plugin->is_enabled(),
7555 'togglelink' => '',
7556 'moveuplink' => '',
7557 'movedownlink' => '',
7558 'settingslink' => $plugin->get_settings_url(),
7559 'uninstalllink' => '',
7560 'info' => '',
7563 // Enable/Disable link.
7564 $togglelink = new moodle_url($pluginlink);
7565 if ($plugin->is_enabled()) {
7566 $toggletarget = false;
7567 $togglelink->param('action', 'disable');
7569 if (count($context->plugins)) {
7570 // This is not the first plugin.
7571 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7574 if (count($enabled) > count($context->plugins) + 1) {
7575 // This is not the last plugin.
7576 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7579 $pluginkey->info = $this->get_info_column($plugin);
7580 } else {
7581 $toggletarget = true;
7582 $togglelink->param('action', 'enable');
7585 $pluginkey->toggletarget = $toggletarget;
7586 $pluginkey->togglelink = $togglelink;
7588 $frankenstyle = $plugin->type . '_' . $plugin->name;
7589 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
7590 // This plugin supports uninstallation.
7591 $pluginkey->uninstalllink = $uninstalllink;
7594 if (!empty($this->get_info_column_name())) {
7595 // This plugintype has an info column.
7596 $pluginkey->info = $this->get_info_column($plugin);
7599 $context->plugins[] = $pluginkey;
7602 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
7603 return highlight($query, $str);
7608 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7609 * Requires a get_rank method on the plugininfo class for sorting.
7611 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
7612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7614 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
7615 public function get_section_title() {
7616 return get_string('type_fileconverter_plural', 'plugin');
7619 public function get_plugin_type() {
7620 return 'fileconverter';
7623 public function get_info_column_name() {
7624 return get_string('supportedconversions', 'plugin');
7627 public function get_info_column($plugininfo) {
7628 return $plugininfo->get_supported_conversions();
7633 * Special class for media player plugins management.
7635 * @copyright 2016 Marina Glancy
7636 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7638 class admin_setting_managemediaplayers extends admin_setting {
7640 * Calls parent::__construct with specific arguments
7642 public function __construct() {
7643 $this->nosave = true;
7644 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
7648 * Always returns true, does nothing
7650 * @return true
7652 public function get_setting() {
7653 return true;
7657 * Always returns true, does nothing
7659 * @return true
7661 public function get_defaultsetting() {
7662 return true;
7666 * Always returns '', does not write anything
7668 * @param mixed $data
7669 * @return string Always returns ''
7671 public function write_setting($data) {
7672 // Do not write any setting.
7673 return '';
7677 * Checks if $query is one of the available enrol plugins
7679 * @param string $query The string to search for
7680 * @return bool Returns true if found, false if not
7682 public function is_related($query) {
7683 if (parent::is_related($query)) {
7684 return true;
7687 $query = core_text::strtolower($query);
7688 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
7689 foreach ($plugins as $name => $plugin) {
7690 $localised = $plugin->displayname;
7691 if (strpos(core_text::strtolower($name), $query) !== false) {
7692 return true;
7694 if (strpos(core_text::strtolower($localised), $query) !== false) {
7695 return true;
7698 return false;
7702 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7703 * @return \core\plugininfo\media[]
7705 protected function get_sorted_plugins() {
7706 $pluginmanager = core_plugin_manager::instance();
7708 $plugins = $pluginmanager->get_plugins_of_type('media');
7709 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7711 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7712 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
7714 $order = array_values($enabledplugins);
7715 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
7717 $sortedplugins = array();
7718 foreach ($order as $name) {
7719 $sortedplugins[$name] = $plugins[$name];
7722 return $sortedplugins;
7726 * Builds the XHTML to display the control
7728 * @param string $data Unused
7729 * @param string $query
7730 * @return string
7732 public function output_html($data, $query='') {
7733 global $CFG, $OUTPUT, $DB, $PAGE;
7735 // Display strings.
7736 $strup = get_string('up');
7737 $strdown = get_string('down');
7738 $strsettings = get_string('settings');
7739 $strenable = get_string('enable');
7740 $strdisable = get_string('disable');
7741 $struninstall = get_string('uninstallplugin', 'core_admin');
7742 $strversion = get_string('version');
7743 $strname = get_string('name');
7744 $strsupports = get_string('supports', 'core_media');
7746 $pluginmanager = core_plugin_manager::instance();
7748 $plugins = $this->get_sorted_plugins();
7749 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7751 $return = $OUTPUT->box_start('generalbox mediaplayersui');
7753 $table = new html_table();
7754 $table->head = array($strname, $strsupports, $strversion,
7755 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
7756 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
7757 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7758 $table->id = 'mediaplayerplugins';
7759 $table->attributes['class'] = 'admintable generaltable';
7760 $table->data = array();
7762 // Iterate through media plugins and add to the display table.
7763 $updowncount = 1;
7764 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
7765 $printed = array();
7766 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7768 $usedextensions = [];
7769 foreach ($plugins as $name => $plugin) {
7770 $url->param('media', $name);
7771 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
7772 $version = $plugininfo->versiondb;
7773 $supports = $plugininfo->supports($usedextensions);
7775 // Hide/show links.
7776 $class = '';
7777 if (!$plugininfo->is_installed_and_upgraded()) {
7778 $hideshow = '';
7779 $enabled = false;
7780 $displayname = '<span class="notifyproblem">'.$name.'</span>';
7781 } else {
7782 $enabled = $plugininfo->is_enabled();
7783 if ($enabled) {
7784 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
7785 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
7786 } else {
7787 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
7788 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
7789 $class = 'dimmed_text';
7791 $displayname = $plugin->displayname;
7792 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
7793 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
7796 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
7797 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
7798 } else {
7799 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
7802 // Up/down link (only if enrol is enabled).
7803 $updown = '';
7804 if ($enabled) {
7805 if ($updowncount > 1) {
7806 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
7807 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
7808 } else {
7809 $updown = $spacer;
7811 if ($updowncount < count($enabledplugins)) {
7812 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
7813 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
7814 } else {
7815 $updown .= $spacer;
7817 ++$updowncount;
7820 $uninstall = '';
7821 $status = $plugininfo->get_status();
7822 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7823 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
7825 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7826 $uninstall = get_string('status_new', 'core_plugin');
7827 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
7828 $uninstall .= html_writer::link($uninstallurl, $struninstall);
7831 $settings = '';
7832 if ($plugininfo->get_settings_url()) {
7833 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
7836 // Add a row to the table.
7837 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
7838 if ($class) {
7839 $row->attributes['class'] = $class;
7841 $table->data[] = $row;
7843 $printed[$name] = true;
7846 $return .= html_writer::table($table);
7847 $return .= $OUTPUT->box_end();
7848 return highlight($query, $return);
7853 * Initialise admin page - this function does require login and permission
7854 * checks specified in page definition.
7856 * This function must be called on each admin page before other code.
7858 * @global moodle_page $PAGE
7860 * @param string $section name of page
7861 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7862 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7863 * added to the turn blocks editing on/off form, so this page reloads correctly.
7864 * @param string $actualurl if the actual page being viewed is not the normal one for this
7865 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7866 * @param array $options Additional options that can be specified for page setup.
7867 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7869 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7870 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7872 $PAGE->set_context(null); // hack - set context to something, by default to system context
7874 $site = get_site();
7875 require_login();
7877 if (!empty($options['pagelayout'])) {
7878 // A specific page layout has been requested.
7879 $PAGE->set_pagelayout($options['pagelayout']);
7880 } else if ($section === 'upgradesettings') {
7881 $PAGE->set_pagelayout('maintenance');
7882 } else {
7883 $PAGE->set_pagelayout('admin');
7886 $adminroot = admin_get_root(false, false); // settings not required for external pages
7887 $extpage = $adminroot->locate($section, true);
7889 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7890 // The requested section isn't in the admin tree
7891 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7892 if (!has_capability('moodle/site:config', context_system::instance())) {
7893 // The requested section could depend on a different capability
7894 // but most likely the user has inadequate capabilities
7895 print_error('accessdenied', 'admin');
7896 } else {
7897 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7901 // this eliminates our need to authenticate on the actual pages
7902 if (!$extpage->check_access()) {
7903 print_error('accessdenied', 'admin');
7904 die;
7907 navigation_node::require_admin_tree();
7909 // $PAGE->set_extra_button($extrabutton); TODO
7911 if (!$actualurl) {
7912 $actualurl = $extpage->url;
7915 $PAGE->set_url($actualurl, $extraurlparams);
7916 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7917 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7920 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7921 // During initial install.
7922 $strinstallation = get_string('installation', 'install');
7923 $strsettings = get_string('settings');
7924 $PAGE->navbar->add($strsettings);
7925 $PAGE->set_title($strinstallation);
7926 $PAGE->set_heading($strinstallation);
7927 $PAGE->set_cacheable(false);
7928 return;
7931 // Locate the current item on the navigation and make it active when found.
7932 $path = $extpage->path;
7933 $node = $PAGE->settingsnav;
7934 while ($node && count($path) > 0) {
7935 $node = $node->get(array_pop($path));
7937 if ($node) {
7938 $node->make_active();
7941 // Normal case.
7942 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7943 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7944 $USER->editing = $adminediting;
7947 $visiblepathtosection = array_reverse($extpage->visiblepath);
7949 if ($PAGE->user_allowed_editing()) {
7950 if ($PAGE->user_is_editing()) {
7951 $caption = get_string('blockseditoff');
7952 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7953 } else {
7954 $caption = get_string('blocksediton');
7955 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7957 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7960 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7961 $PAGE->set_heading($SITE->fullname);
7963 // prevent caching in nav block
7964 $PAGE->navigation->clear_cache();
7968 * Returns the reference to admin tree root
7970 * @return object admin_root object
7972 function admin_get_root($reload=false, $requirefulltree=true) {
7973 global $CFG, $DB, $OUTPUT;
7975 static $ADMIN = NULL;
7977 if (is_null($ADMIN)) {
7978 // create the admin tree!
7979 $ADMIN = new admin_root($requirefulltree);
7982 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7983 $ADMIN->purge_children($requirefulltree);
7986 if (!$ADMIN->loaded) {
7987 // we process this file first to create categories first and in correct order
7988 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7990 // now we process all other files in admin/settings to build the admin tree
7991 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7992 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7993 continue;
7995 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7996 // plugins are loaded last - they may insert pages anywhere
7997 continue;
7999 require($file);
8001 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8003 $ADMIN->loaded = true;
8006 return $ADMIN;
8009 /// settings utility functions
8012 * This function applies default settings.
8014 * @param object $node, NULL means complete tree, null by default
8015 * @param bool $unconditional if true overrides all values with defaults, null buy default
8017 function admin_apply_default_settings($node=NULL, $unconditional=true) {
8018 global $CFG;
8020 if (is_null($node)) {
8021 core_plugin_manager::reset_caches();
8022 $node = admin_get_root(true, true);
8025 if ($node instanceof admin_category) {
8026 $entries = array_keys($node->children);
8027 foreach ($entries as $entry) {
8028 admin_apply_default_settings($node->children[$entry], $unconditional);
8031 } else if ($node instanceof admin_settingpage) {
8032 foreach ($node->settings as $setting) {
8033 if (!$unconditional and !is_null($setting->get_setting())) {
8034 //do not override existing defaults
8035 continue;
8037 $defaultsetting = $setting->get_defaultsetting();
8038 if (is_null($defaultsetting)) {
8039 // no value yet - default maybe applied after admin user creation or in upgradesettings
8040 continue;
8042 $setting->write_setting($defaultsetting);
8043 $setting->write_setting_flags(null);
8046 // Just in case somebody modifies the list of active plugins directly.
8047 core_plugin_manager::reset_caches();
8051 * Store changed settings, this function updates the errors variable in $ADMIN
8053 * @param object $formdata from form
8054 * @return int number of changed settings
8056 function admin_write_settings($formdata) {
8057 global $CFG, $SITE, $DB;
8059 $olddbsessions = !empty($CFG->dbsessions);
8060 $formdata = (array)$formdata;
8062 $data = array();
8063 foreach ($formdata as $fullname=>$value) {
8064 if (strpos($fullname, 's_') !== 0) {
8065 continue; // not a config value
8067 $data[$fullname] = $value;
8070 $adminroot = admin_get_root();
8071 $settings = admin_find_write_settings($adminroot, $data);
8073 $count = 0;
8074 foreach ($settings as $fullname=>$setting) {
8075 /** @var $setting admin_setting */
8076 $original = $setting->get_setting();
8077 $error = $setting->write_setting($data[$fullname]);
8078 if ($error !== '') {
8079 $adminroot->errors[$fullname] = new stdClass();
8080 $adminroot->errors[$fullname]->data = $data[$fullname];
8081 $adminroot->errors[$fullname]->id = $setting->get_id();
8082 $adminroot->errors[$fullname]->error = $error;
8083 } else {
8084 $setting->write_setting_flags($data);
8086 if ($setting->post_write_settings($original)) {
8087 $count++;
8091 if ($olddbsessions != !empty($CFG->dbsessions)) {
8092 require_logout();
8095 // Now update $SITE - just update the fields, in case other people have a
8096 // a reference to it (e.g. $PAGE, $COURSE).
8097 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8098 foreach (get_object_vars($newsite) as $field => $value) {
8099 $SITE->$field = $value;
8102 // now reload all settings - some of them might depend on the changed
8103 admin_get_root(true);
8104 return $count;
8108 * Internal recursive function - finds all settings from submitted form
8110 * @param object $node Instance of admin_category, or admin_settingpage
8111 * @param array $data
8112 * @return array
8114 function admin_find_write_settings($node, $data) {
8115 $return = array();
8117 if (empty($data)) {
8118 return $return;
8121 if ($node instanceof admin_category) {
8122 if ($node->check_access()) {
8123 $entries = array_keys($node->children);
8124 foreach ($entries as $entry) {
8125 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8129 } else if ($node instanceof admin_settingpage) {
8130 if ($node->check_access()) {
8131 foreach ($node->settings as $setting) {
8132 $fullname = $setting->get_full_name();
8133 if (array_key_exists($fullname, $data)) {
8134 $return[$fullname] = $setting;
8141 return $return;
8145 * Internal function - prints the search results
8147 * @param string $query String to search for
8148 * @return string empty or XHTML
8150 function admin_search_settings_html($query) {
8151 global $CFG, $OUTPUT, $PAGE;
8153 if (core_text::strlen($query) < 2) {
8154 return '';
8156 $query = core_text::strtolower($query);
8158 $adminroot = admin_get_root();
8159 $findings = $adminroot->search($query);
8160 $savebutton = false;
8162 $tpldata = (object) [
8163 'actionurl' => $PAGE->url->out(false),
8164 'results' => [],
8165 'sesskey' => sesskey(),
8168 foreach ($findings as $found) {
8169 $page = $found->page;
8170 $settings = $found->settings;
8171 if ($page->is_hidden()) {
8172 // hidden pages are not displayed in search results
8173 continue;
8176 $heading = highlight($query, $page->visiblename);
8177 $headingurl = null;
8178 if ($page instanceof admin_externalpage) {
8179 $headingurl = new moodle_url($page->url);
8180 } else if ($page instanceof admin_settingpage) {
8181 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8182 } else {
8183 continue;
8186 $sectionsettings = [];
8187 if (!empty($settings)) {
8188 foreach ($settings as $setting) {
8189 if (empty($setting->nosave)) {
8190 $savebutton = true;
8192 $fullname = $setting->get_full_name();
8193 if (array_key_exists($fullname, $adminroot->errors)) {
8194 $data = $adminroot->errors[$fullname]->data;
8195 } else {
8196 $data = $setting->get_setting();
8197 // do not use defaults if settings not available - upgradesettings handles the defaults!
8199 $sectionsettings[] = $setting->output_html($data, $query);
8203 $tpldata->results[] = (object) [
8204 'title' => $heading,
8205 'url' => $headingurl->out(false),
8206 'settings' => $sectionsettings
8210 $tpldata->showsave = $savebutton;
8211 $tpldata->hasresults = !empty($tpldata->results);
8213 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8217 * Internal function - returns arrays of html pages with uninitialised settings
8219 * @param object $node Instance of admin_category or admin_settingpage
8220 * @return array
8222 function admin_output_new_settings_by_page($node) {
8223 global $OUTPUT;
8224 $return = array();
8226 if ($node instanceof admin_category) {
8227 $entries = array_keys($node->children);
8228 foreach ($entries as $entry) {
8229 $return += admin_output_new_settings_by_page($node->children[$entry]);
8232 } else if ($node instanceof admin_settingpage) {
8233 $newsettings = array();
8234 foreach ($node->settings as $setting) {
8235 if (is_null($setting->get_setting())) {
8236 $newsettings[] = $setting;
8239 if (count($newsettings) > 0) {
8240 $adminroot = admin_get_root();
8241 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8242 $page .= '<fieldset class="adminsettings">'."\n";
8243 foreach ($newsettings as $setting) {
8244 $fullname = $setting->get_full_name();
8245 if (array_key_exists($fullname, $adminroot->errors)) {
8246 $data = $adminroot->errors[$fullname]->data;
8247 } else {
8248 $data = $setting->get_setting();
8249 if (is_null($data)) {
8250 $data = $setting->get_defaultsetting();
8253 $page .= '<div class="clearer"><!-- --></div>'."\n";
8254 $page .= $setting->output_html($data);
8256 $page .= '</fieldset>';
8257 $return[$node->name] = $page;
8261 return $return;
8265 * Format admin settings
8267 * @param object $setting
8268 * @param string $title label element
8269 * @param string $form form fragment, html code - not highlighted automatically
8270 * @param string $description
8271 * @param mixed $label link label to id, true by default or string being the label to connect it to
8272 * @param string $warning warning text
8273 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8274 * @param string $query search query to be highlighted
8275 * @return string XHTML
8277 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8278 global $CFG, $OUTPUT;
8280 $context = (object) [
8281 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8282 'fullname' => $setting->get_full_name(),
8285 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8286 if ($label === true) {
8287 $context->labelfor = $setting->get_id();
8288 } else if ($label === false) {
8289 $context->labelfor = '';
8290 } else {
8291 $context->labelfor = $label;
8294 $form .= $setting->output_setting_flags();
8296 $context->warning = $warning;
8297 $context->override = '';
8298 if (empty($setting->plugin)) {
8299 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8300 $context->override = get_string('configoverride', 'admin');
8302 } else {
8303 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8304 $context->override = get_string('configoverride', 'admin');
8308 $defaults = array();
8309 if (!is_null($defaultinfo)) {
8310 if ($defaultinfo === '') {
8311 $defaultinfo = get_string('emptysettingvalue', 'admin');
8313 $defaults[] = $defaultinfo;
8316 $context->default = null;
8317 $setting->get_setting_flag_defaults($defaults);
8318 if (!empty($defaults)) {
8319 $defaultinfo = implode(', ', $defaults);
8320 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8321 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8325 $context->error = '';
8326 $adminroot = admin_get_root();
8327 if (array_key_exists($context->fullname, $adminroot->errors)) {
8328 $context->error = $adminroot->errors[$context->fullname]->error;
8331 $context->id = 'admin-' . $setting->name;
8332 $context->title = highlightfast($query, $title);
8333 $context->name = highlightfast($query, $context->name);
8334 $context->description = highlight($query, markdown_to_html($description));
8335 $context->element = $form;
8336 $context->forceltr = $setting->get_force_ltr();
8338 return $OUTPUT->render_from_template('core_admin/setting', $context);
8342 * Based on find_new_settings{@link ()} in upgradesettings.php
8343 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8345 * @param object $node Instance of admin_category, or admin_settingpage
8346 * @return boolean true if any settings haven't been initialised, false if they all have
8348 function any_new_admin_settings($node) {
8350 if ($node instanceof admin_category) {
8351 $entries = array_keys($node->children);
8352 foreach ($entries as $entry) {
8353 if (any_new_admin_settings($node->children[$entry])) {
8354 return true;
8358 } else if ($node instanceof admin_settingpage) {
8359 foreach ($node->settings as $setting) {
8360 if ($setting->get_setting() === NULL) {
8361 return true;
8366 return false;
8370 * Moved from admin/replace.php so that we can use this in cron
8372 * @param string $search string to look for
8373 * @param string $replace string to replace
8374 * @return bool success or fail
8376 function db_replace($search, $replace) {
8377 global $DB, $CFG, $OUTPUT;
8379 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8380 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
8381 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
8382 'block_instances', '');
8384 // Turn off time limits, sometimes upgrades can be slow.
8385 core_php_time_limit::raise();
8387 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
8388 return false;
8390 foreach ($tables as $table) {
8392 if (in_array($table, $skiptables)) { // Don't process these
8393 continue;
8396 if ($columns = $DB->get_columns($table)) {
8397 $DB->set_debug(true);
8398 foreach ($columns as $column) {
8399 $DB->replace_all_text($table, $column, $search, $replace);
8401 $DB->set_debug(false);
8405 // delete modinfo caches
8406 rebuild_course_cache(0, true);
8408 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
8409 $blocks = core_component::get_plugin_list('block');
8410 foreach ($blocks as $blockname=>$fullblock) {
8411 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8412 continue;
8415 if (!is_readable($fullblock.'/lib.php')) {
8416 continue;
8419 $function = 'block_'.$blockname.'_global_db_replace';
8420 include_once($fullblock.'/lib.php');
8421 if (!function_exists($function)) {
8422 continue;
8425 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
8426 $function($search, $replace);
8427 echo $OUTPUT->notification("...finished", 'notifysuccess');
8430 purge_all_caches();
8432 return true;
8436 * Manage repository settings
8438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8440 class admin_setting_managerepository extends admin_setting {
8441 /** @var string */
8442 private $baseurl;
8445 * calls parent::__construct with specific arguments
8447 public function __construct() {
8448 global $CFG;
8449 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
8450 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
8454 * Always returns true, does nothing
8456 * @return true
8458 public function get_setting() {
8459 return true;
8463 * Always returns true does nothing
8465 * @return true
8467 public function get_defaultsetting() {
8468 return true;
8472 * Always returns s_managerepository
8474 * @return string Always return 's_managerepository'
8476 public function get_full_name() {
8477 return 's_managerepository';
8481 * Always returns '' doesn't do anything
8483 public function write_setting($data) {
8484 $url = $this->baseurl . '&amp;new=' . $data;
8485 return '';
8486 // TODO
8487 // Should not use redirect and exit here
8488 // Find a better way to do this.
8489 // redirect($url);
8490 // exit;
8494 * Searches repository plugins for one that matches $query
8496 * @param string $query The string to search for
8497 * @return bool true if found, false if not
8499 public function is_related($query) {
8500 if (parent::is_related($query)) {
8501 return true;
8504 $repositories= core_component::get_plugin_list('repository');
8505 foreach ($repositories as $p => $dir) {
8506 if (strpos($p, $query) !== false) {
8507 return true;
8510 foreach (repository::get_types() as $instance) {
8511 $title = $instance->get_typename();
8512 if (strpos(core_text::strtolower($title), $query) !== false) {
8513 return true;
8516 return false;
8520 * Helper function that generates a moodle_url object
8521 * relevant to the repository
8524 function repository_action_url($repository) {
8525 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
8529 * Builds XHTML to display the control
8531 * @param string $data Unused
8532 * @param string $query
8533 * @return string XHTML
8535 public function output_html($data, $query='') {
8536 global $CFG, $USER, $OUTPUT;
8538 // Get strings that are used
8539 $strshow = get_string('on', 'repository');
8540 $strhide = get_string('off', 'repository');
8541 $strdelete = get_string('disabled', 'repository');
8543 $actionchoicesforexisting = array(
8544 'show' => $strshow,
8545 'hide' => $strhide,
8546 'delete' => $strdelete
8549 $actionchoicesfornew = array(
8550 'newon' => $strshow,
8551 'newoff' => $strhide,
8552 'delete' => $strdelete
8555 $return = '';
8556 $return .= $OUTPUT->box_start('generalbox');
8558 // Set strings that are used multiple times
8559 $settingsstr = get_string('settings');
8560 $disablestr = get_string('disable');
8562 // Table to list plug-ins
8563 $table = new html_table();
8564 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
8565 $table->align = array('left', 'center', 'center', 'center', 'center');
8566 $table->data = array();
8568 // Get list of used plug-ins
8569 $repositorytypes = repository::get_types();
8570 if (!empty($repositorytypes)) {
8571 // Array to store plugins being used
8572 $alreadyplugins = array();
8573 $totalrepositorytypes = count($repositorytypes);
8574 $updowncount = 1;
8575 foreach ($repositorytypes as $i) {
8576 $settings = '';
8577 $typename = $i->get_typename();
8578 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
8579 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
8580 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
8582 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
8583 // Calculate number of instances in order to display them for the Moodle administrator
8584 if (!empty($instanceoptionnames)) {
8585 $params = array();
8586 $params['context'] = array(context_system::instance());
8587 $params['onlyvisible'] = false;
8588 $params['type'] = $typename;
8589 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
8590 // site instances
8591 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
8592 $params['context'] = array();
8593 $instances = repository::static_function($typename, 'get_instances', $params);
8594 $courseinstances = array();
8595 $userinstances = array();
8597 foreach ($instances as $instance) {
8598 $repocontext = context::instance_by_id($instance->instance->contextid);
8599 if ($repocontext->contextlevel == CONTEXT_COURSE) {
8600 $courseinstances[] = $instance;
8601 } else if ($repocontext->contextlevel == CONTEXT_USER) {
8602 $userinstances[] = $instance;
8605 // course instances
8606 $instancenumber = count($courseinstances);
8607 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
8609 // user private instances
8610 $instancenumber = count($userinstances);
8611 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
8612 } else {
8613 $admininstancenumbertext = "";
8614 $courseinstancenumbertext = "";
8615 $userinstancenumbertext = "";
8618 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
8620 $settings .= $OUTPUT->container_start('mdl-left');
8621 $settings .= '<br/>';
8622 $settings .= $admininstancenumbertext;
8623 $settings .= '<br/>';
8624 $settings .= $courseinstancenumbertext;
8625 $settings .= '<br/>';
8626 $settings .= $userinstancenumbertext;
8627 $settings .= $OUTPUT->container_end();
8629 // Get the current visibility
8630 if ($i->get_visible()) {
8631 $currentaction = 'show';
8632 } else {
8633 $currentaction = 'hide';
8636 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
8638 // Display up/down link
8639 $updown = '';
8640 // Should be done with CSS instead.
8641 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
8643 if ($updowncount > 1) {
8644 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
8645 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
8647 else {
8648 $updown .= $spacer;
8650 if ($updowncount < $totalrepositorytypes) {
8651 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
8652 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
8654 else {
8655 $updown .= $spacer;
8658 $updowncount++;
8660 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
8662 if (!in_array($typename, $alreadyplugins)) {
8663 $alreadyplugins[] = $typename;
8668 // Get all the plugins that exist on disk
8669 $plugins = core_component::get_plugin_list('repository');
8670 if (!empty($plugins)) {
8671 foreach ($plugins as $plugin => $dir) {
8672 // Check that it has not already been listed
8673 if (!in_array($plugin, $alreadyplugins)) {
8674 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
8675 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
8680 $return .= html_writer::table($table);
8681 $return .= $OUTPUT->box_end();
8682 return highlight($query, $return);
8687 * Special checkbox for enable mobile web service
8688 * If enable then we store the service id of the mobile service into config table
8689 * If disable then we unstore the service id from the config table
8691 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
8693 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
8694 private $restuse;
8697 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
8699 * @return boolean
8701 private function is_protocol_cap_allowed() {
8702 global $DB, $CFG;
8704 // If the $this->restuse variable is not set, it needs to be set.
8705 if (empty($this->restuse) and $this->restuse!==false) {
8706 $params = array();
8707 $params['permission'] = CAP_ALLOW;
8708 $params['roleid'] = $CFG->defaultuserroleid;
8709 $params['capability'] = 'webservice/rest:use';
8710 $this->restuse = $DB->record_exists('role_capabilities', $params);
8713 return $this->restuse;
8717 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
8718 * @param type $status true to allow, false to not set
8720 private function set_protocol_cap($status) {
8721 global $CFG;
8722 if ($status and !$this->is_protocol_cap_allowed()) {
8723 //need to allow the cap
8724 $permission = CAP_ALLOW;
8725 $assign = true;
8726 } else if (!$status and $this->is_protocol_cap_allowed()){
8727 //need to disallow the cap
8728 $permission = CAP_INHERIT;
8729 $assign = true;
8731 if (!empty($assign)) {
8732 $systemcontext = context_system::instance();
8733 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8738 * Builds XHTML to display the control.
8739 * The main purpose of this overloading is to display a warning when https
8740 * is not supported by the server
8741 * @param string $data Unused
8742 * @param string $query
8743 * @return string XHTML
8745 public function output_html($data, $query='') {
8746 global $OUTPUT;
8747 $html = parent::output_html($data, $query);
8749 if ((string)$data === $this->yes) {
8750 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
8751 foreach ($notifications as $notification) {
8752 $message = get_string($notification[0], $notification[1]);
8753 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
8757 return $html;
8761 * Retrieves the current setting using the objects name
8763 * @return string
8765 public function get_setting() {
8766 global $CFG;
8768 // First check if is not set.
8769 $result = $this->config_read($this->name);
8770 if (is_null($result)) {
8771 return null;
8774 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8775 // Or if web services aren't enabled this can't be,
8776 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8777 return 0;
8780 require_once($CFG->dirroot . '/webservice/lib.php');
8781 $webservicemanager = new webservice();
8782 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8783 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8784 return $result;
8785 } else {
8786 return 0;
8791 * Save the selected setting
8793 * @param string $data The selected site
8794 * @return string empty string or error message
8796 public function write_setting($data) {
8797 global $DB, $CFG;
8799 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8800 if (empty($CFG->defaultuserroleid)) {
8801 return '';
8804 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8806 require_once($CFG->dirroot . '/webservice/lib.php');
8807 $webservicemanager = new webservice();
8809 $updateprotocol = false;
8810 if ((string)$data === $this->yes) {
8811 //code run when enable mobile web service
8812 //enable web service systeme if necessary
8813 set_config('enablewebservices', true);
8815 //enable mobile service
8816 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8817 $mobileservice->enabled = 1;
8818 $webservicemanager->update_external_service($mobileservice);
8820 // Enable REST server.
8821 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8823 if (!in_array('rest', $activeprotocols)) {
8824 $activeprotocols[] = 'rest';
8825 $updateprotocol = true;
8828 if ($updateprotocol) {
8829 set_config('webserviceprotocols', implode(',', $activeprotocols));
8832 // Allow rest:use capability for authenticated user.
8833 $this->set_protocol_cap(true);
8835 } else {
8836 //disable web service system if no other services are enabled
8837 $otherenabledservices = $DB->get_records_select('external_services',
8838 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8839 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8840 if (empty($otherenabledservices)) {
8841 set_config('enablewebservices', false);
8843 // Also disable REST server.
8844 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8846 $protocolkey = array_search('rest', $activeprotocols);
8847 if ($protocolkey !== false) {
8848 unset($activeprotocols[$protocolkey]);
8849 $updateprotocol = true;
8852 if ($updateprotocol) {
8853 set_config('webserviceprotocols', implode(',', $activeprotocols));
8856 // Disallow rest:use capability for authenticated user.
8857 $this->set_protocol_cap(false);
8860 //disable the mobile service
8861 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8862 $mobileservice->enabled = 0;
8863 $webservicemanager->update_external_service($mobileservice);
8866 return (parent::write_setting($data));
8871 * Special class for management of external services
8873 * @author Petr Skoda (skodak)
8875 class admin_setting_manageexternalservices extends admin_setting {
8877 * Calls parent::__construct with specific arguments
8879 public function __construct() {
8880 $this->nosave = true;
8881 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8885 * Always returns true, does nothing
8887 * @return true
8889 public function get_setting() {
8890 return true;
8894 * Always returns true, does nothing
8896 * @return true
8898 public function get_defaultsetting() {
8899 return true;
8903 * Always returns '', does not write anything
8905 * @return string Always returns ''
8907 public function write_setting($data) {
8908 // do not write any setting
8909 return '';
8913 * Checks if $query is one of the available external services
8915 * @param string $query The string to search for
8916 * @return bool Returns true if found, false if not
8918 public function is_related($query) {
8919 global $DB;
8921 if (parent::is_related($query)) {
8922 return true;
8925 $services = $DB->get_records('external_services', array(), 'id, name');
8926 foreach ($services as $service) {
8927 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8928 return true;
8931 return false;
8935 * Builds the XHTML to display the control
8937 * @param string $data Unused
8938 * @param string $query
8939 * @return string
8941 public function output_html($data, $query='') {
8942 global $CFG, $OUTPUT, $DB;
8944 // display strings
8945 $stradministration = get_string('administration');
8946 $stredit = get_string('edit');
8947 $strservice = get_string('externalservice', 'webservice');
8948 $strdelete = get_string('delete');
8949 $strplugin = get_string('plugin', 'admin');
8950 $stradd = get_string('add');
8951 $strfunctions = get_string('functions', 'webservice');
8952 $strusers = get_string('users');
8953 $strserviceusers = get_string('serviceusers', 'webservice');
8955 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8956 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8957 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8959 // built in services
8960 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8961 $return = "";
8962 if (!empty($services)) {
8963 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8967 $table = new html_table();
8968 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8969 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8970 $table->id = 'builtinservices';
8971 $table->attributes['class'] = 'admintable externalservices generaltable';
8972 $table->data = array();
8974 // iterate through auth plugins and add to the display table
8975 foreach ($services as $service) {
8976 $name = $service->name;
8978 // hide/show link
8979 if ($service->enabled) {
8980 $displayname = "<span>$name</span>";
8981 } else {
8982 $displayname = "<span class=\"dimmed_text\">$name</span>";
8985 $plugin = $service->component;
8987 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8989 if ($service->restrictedusers) {
8990 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8991 } else {
8992 $users = get_string('allusers', 'webservice');
8995 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8997 // add a row to the table
8998 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9000 $return .= html_writer::table($table);
9003 // Custom services
9004 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9005 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9007 $table = new html_table();
9008 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9009 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9010 $table->id = 'customservices';
9011 $table->attributes['class'] = 'admintable externalservices generaltable';
9012 $table->data = array();
9014 // iterate through auth plugins and add to the display table
9015 foreach ($services as $service) {
9016 $name = $service->name;
9018 // hide/show link
9019 if ($service->enabled) {
9020 $displayname = "<span>$name</span>";
9021 } else {
9022 $displayname = "<span class=\"dimmed_text\">$name</span>";
9025 // delete link
9026 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9028 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9030 if ($service->restrictedusers) {
9031 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9032 } else {
9033 $users = get_string('allusers', 'webservice');
9036 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9038 // add a row to the table
9039 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9041 // add new custom service option
9042 $return .= html_writer::table($table);
9044 $return .= '<br />';
9045 // add a token to the table
9046 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9048 return highlight($query, $return);
9053 * Special class for overview of external services
9055 * @author Jerome Mouneyrac
9057 class admin_setting_webservicesoverview extends admin_setting {
9060 * Calls parent::__construct with specific arguments
9062 public function __construct() {
9063 $this->nosave = true;
9064 parent::__construct('webservicesoverviewui',
9065 get_string('webservicesoverview', 'webservice'), '', '');
9069 * Always returns true, does nothing
9071 * @return true
9073 public function get_setting() {
9074 return true;
9078 * Always returns true, does nothing
9080 * @return true
9082 public function get_defaultsetting() {
9083 return true;
9087 * Always returns '', does not write anything
9089 * @return string Always returns ''
9091 public function write_setting($data) {
9092 // do not write any setting
9093 return '';
9097 * Builds the XHTML to display the control
9099 * @param string $data Unused
9100 * @param string $query
9101 * @return string
9103 public function output_html($data, $query='') {
9104 global $CFG, $OUTPUT;
9106 $return = "";
9107 $brtag = html_writer::empty_tag('br');
9109 /// One system controlling Moodle with Token
9110 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9111 $table = new html_table();
9112 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9113 get_string('description'));
9114 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9115 $table->id = 'onesystemcontrol';
9116 $table->attributes['class'] = 'admintable wsoverview generaltable';
9117 $table->data = array();
9119 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9120 . $brtag . $brtag;
9122 /// 1. Enable Web Services
9123 $row = array();
9124 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9125 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9126 array('href' => $url));
9127 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9128 if ($CFG->enablewebservices) {
9129 $status = get_string('yes');
9131 $row[1] = $status;
9132 $row[2] = get_string('enablewsdescription', 'webservice');
9133 $table->data[] = $row;
9135 /// 2. Enable protocols
9136 $row = array();
9137 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9138 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9139 array('href' => $url));
9140 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9141 //retrieve activated protocol
9142 $active_protocols = empty($CFG->webserviceprotocols) ?
9143 array() : explode(',', $CFG->webserviceprotocols);
9144 if (!empty($active_protocols)) {
9145 $status = "";
9146 foreach ($active_protocols as $protocol) {
9147 $status .= $protocol . $brtag;
9150 $row[1] = $status;
9151 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9152 $table->data[] = $row;
9154 /// 3. Create user account
9155 $row = array();
9156 $url = new moodle_url("/user/editadvanced.php?id=-1");
9157 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9158 array('href' => $url));
9159 $row[1] = "";
9160 $row[2] = get_string('createuserdescription', 'webservice');
9161 $table->data[] = $row;
9163 /// 4. Add capability to users
9164 $row = array();
9165 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9166 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9167 array('href' => $url));
9168 $row[1] = "";
9169 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9170 $table->data[] = $row;
9172 /// 5. Select a web service
9173 $row = array();
9174 $url = new moodle_url("/admin/settings.php?section=externalservices");
9175 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9176 array('href' => $url));
9177 $row[1] = "";
9178 $row[2] = get_string('createservicedescription', 'webservice');
9179 $table->data[] = $row;
9181 /// 6. Add functions
9182 $row = array();
9183 $url = new moodle_url("/admin/settings.php?section=externalservices");
9184 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9185 array('href' => $url));
9186 $row[1] = "";
9187 $row[2] = get_string('addfunctionsdescription', 'webservice');
9188 $table->data[] = $row;
9190 /// 7. Add the specific user
9191 $row = array();
9192 $url = new moodle_url("/admin/settings.php?section=externalservices");
9193 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9194 array('href' => $url));
9195 $row[1] = "";
9196 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9197 $table->data[] = $row;
9199 /// 8. Create token for the specific user
9200 $row = array();
9201 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9202 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9203 array('href' => $url));
9204 $row[1] = "";
9205 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9206 $table->data[] = $row;
9208 /// 9. Enable the documentation
9209 $row = array();
9210 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9211 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9212 array('href' => $url));
9213 $status = '<span class="warning">' . get_string('no') . '</span>';
9214 if ($CFG->enablewsdocumentation) {
9215 $status = get_string('yes');
9217 $row[1] = $status;
9218 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9219 $table->data[] = $row;
9221 /// 10. Test the service
9222 $row = array();
9223 $url = new moodle_url("/admin/webservice/testclient.php");
9224 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9225 array('href' => $url));
9226 $row[1] = "";
9227 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9228 $table->data[] = $row;
9230 $return .= html_writer::table($table);
9232 /// Users as clients with token
9233 $return .= $brtag . $brtag . $brtag;
9234 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9235 $table = new html_table();
9236 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9237 get_string('description'));
9238 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9239 $table->id = 'userasclients';
9240 $table->attributes['class'] = 'admintable wsoverview generaltable';
9241 $table->data = array();
9243 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9244 $brtag . $brtag;
9246 /// 1. Enable Web Services
9247 $row = array();
9248 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9249 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9250 array('href' => $url));
9251 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9252 if ($CFG->enablewebservices) {
9253 $status = get_string('yes');
9255 $row[1] = $status;
9256 $row[2] = get_string('enablewsdescription', 'webservice');
9257 $table->data[] = $row;
9259 /// 2. Enable protocols
9260 $row = array();
9261 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9262 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9263 array('href' => $url));
9264 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9265 //retrieve activated protocol
9266 $active_protocols = empty($CFG->webserviceprotocols) ?
9267 array() : explode(',', $CFG->webserviceprotocols);
9268 if (!empty($active_protocols)) {
9269 $status = "";
9270 foreach ($active_protocols as $protocol) {
9271 $status .= $protocol . $brtag;
9274 $row[1] = $status;
9275 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9276 $table->data[] = $row;
9279 /// 3. Select a web service
9280 $row = array();
9281 $url = new moodle_url("/admin/settings.php?section=externalservices");
9282 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9283 array('href' => $url));
9284 $row[1] = "";
9285 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9286 $table->data[] = $row;
9288 /// 4. Add functions
9289 $row = array();
9290 $url = new moodle_url("/admin/settings.php?section=externalservices");
9291 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9292 array('href' => $url));
9293 $row[1] = "";
9294 $row[2] = get_string('addfunctionsdescription', 'webservice');
9295 $table->data[] = $row;
9297 /// 5. Add capability to users
9298 $row = array();
9299 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9300 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9301 array('href' => $url));
9302 $row[1] = "";
9303 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9304 $table->data[] = $row;
9306 /// 6. Test the service
9307 $row = array();
9308 $url = new moodle_url("/admin/webservice/testclient.php");
9309 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9310 array('href' => $url));
9311 $row[1] = "";
9312 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9313 $table->data[] = $row;
9315 $return .= html_writer::table($table);
9317 return highlight($query, $return);
9324 * Special class for web service protocol administration.
9326 * @author Petr Skoda (skodak)
9328 class admin_setting_managewebserviceprotocols extends admin_setting {
9331 * Calls parent::__construct with specific arguments
9333 public function __construct() {
9334 $this->nosave = true;
9335 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9339 * Always returns true, does nothing
9341 * @return true
9343 public function get_setting() {
9344 return true;
9348 * Always returns true, does nothing
9350 * @return true
9352 public function get_defaultsetting() {
9353 return true;
9357 * Always returns '', does not write anything
9359 * @return string Always returns ''
9361 public function write_setting($data) {
9362 // do not write any setting
9363 return '';
9367 * Checks if $query is one of the available webservices
9369 * @param string $query The string to search for
9370 * @return bool Returns true if found, false if not
9372 public function is_related($query) {
9373 if (parent::is_related($query)) {
9374 return true;
9377 $protocols = core_component::get_plugin_list('webservice');
9378 foreach ($protocols as $protocol=>$location) {
9379 if (strpos($protocol, $query) !== false) {
9380 return true;
9382 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
9383 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
9384 return true;
9387 return false;
9391 * Builds the XHTML to display the control
9393 * @param string $data Unused
9394 * @param string $query
9395 * @return string
9397 public function output_html($data, $query='') {
9398 global $CFG, $OUTPUT;
9400 // display strings
9401 $stradministration = get_string('administration');
9402 $strsettings = get_string('settings');
9403 $stredit = get_string('edit');
9404 $strprotocol = get_string('protocol', 'webservice');
9405 $strenable = get_string('enable');
9406 $strdisable = get_string('disable');
9407 $strversion = get_string('version');
9409 $protocols_available = core_component::get_plugin_list('webservice');
9410 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9411 ksort($protocols_available);
9413 foreach ($active_protocols as $key=>$protocol) {
9414 if (empty($protocols_available[$protocol])) {
9415 unset($active_protocols[$key]);
9419 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
9420 $return .= $OUTPUT->box_start('generalbox webservicesui');
9422 $table = new html_table();
9423 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
9424 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
9425 $table->id = 'webserviceprotocols';
9426 $table->attributes['class'] = 'admintable generaltable';
9427 $table->data = array();
9429 // iterate through auth plugins and add to the display table
9430 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
9431 foreach ($protocols_available as $protocol => $location) {
9432 $name = get_string('pluginname', 'webservice_'.$protocol);
9434 $plugin = new stdClass();
9435 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
9436 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
9438 $version = isset($plugin->version) ? $plugin->version : '';
9440 // hide/show link
9441 if (in_array($protocol, $active_protocols)) {
9442 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
9443 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
9444 $displayname = "<span>$name</span>";
9445 } else {
9446 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
9447 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
9448 $displayname = "<span class=\"dimmed_text\">$name</span>";
9451 // settings link
9452 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
9453 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
9454 } else {
9455 $settings = '';
9458 // add a row to the table
9459 $table->data[] = array($displayname, $version, $hideshow, $settings);
9461 $return .= html_writer::table($table);
9462 $return .= get_string('configwebserviceplugins', 'webservice');
9463 $return .= $OUTPUT->box_end();
9465 return highlight($query, $return);
9471 * Special class for web service token administration.
9473 * @author Jerome Mouneyrac
9475 class admin_setting_managewebservicetokens extends admin_setting {
9478 * Calls parent::__construct with specific arguments
9480 public function __construct() {
9481 $this->nosave = true;
9482 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
9486 * Always returns true, does nothing
9488 * @return true
9490 public function get_setting() {
9491 return true;
9495 * Always returns true, does nothing
9497 * @return true
9499 public function get_defaultsetting() {
9500 return true;
9504 * Always returns '', does not write anything
9506 * @return string Always returns ''
9508 public function write_setting($data) {
9509 // do not write any setting
9510 return '';
9514 * Builds the XHTML to display the control
9516 * @param string $data Unused
9517 * @param string $query
9518 * @return string
9520 public function output_html($data, $query='') {
9521 global $CFG, $OUTPUT;
9523 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
9524 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
9526 $return = $OUTPUT->box_start('generalbox webservicestokenui');
9528 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
9529 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
9532 $table = new \webservice\token_table('webservicetokens');
9533 $table->define_baseurl($baseurl);
9534 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
9535 $table->data = array();
9536 ob_start();
9537 $table->out(10, false);
9538 $tablehtml = ob_get_contents();
9539 ob_end_clean();
9540 $return .= $tablehtml;
9542 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
9544 $return .= $OUTPUT->box_end();
9545 // add a token to the table
9546 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
9547 $return .= get_string('add')."</a>";
9549 return highlight($query, $return);
9555 * Colour picker
9557 * @copyright 2010 Sam Hemelryk
9558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9560 class admin_setting_configcolourpicker extends admin_setting {
9563 * Information for previewing the colour
9565 * @var array|null
9567 protected $previewconfig = null;
9570 * Use default when empty.
9572 protected $usedefaultwhenempty = true;
9576 * @param string $name
9577 * @param string $visiblename
9578 * @param string $description
9579 * @param string $defaultsetting
9580 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
9582 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
9583 $usedefaultwhenempty = true) {
9584 $this->previewconfig = $previewconfig;
9585 $this->usedefaultwhenempty = $usedefaultwhenempty;
9586 parent::__construct($name, $visiblename, $description, $defaultsetting);
9587 $this->set_force_ltr(true);
9591 * Return the setting
9593 * @return mixed returns config if successful else null
9595 public function get_setting() {
9596 return $this->config_read($this->name);
9600 * Saves the setting
9602 * @param string $data
9603 * @return bool
9605 public function write_setting($data) {
9606 $data = $this->validate($data);
9607 if ($data === false) {
9608 return get_string('validateerror', 'admin');
9610 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
9614 * Validates the colour that was entered by the user
9616 * @param string $data
9617 * @return string|false
9619 protected function validate($data) {
9621 * List of valid HTML colour names
9623 * @var array
9625 $colornames = array(
9626 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
9627 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
9628 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
9629 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
9630 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
9631 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
9632 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
9633 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
9634 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
9635 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
9636 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
9637 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
9638 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
9639 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
9640 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
9641 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
9642 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
9643 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
9644 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
9645 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
9646 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
9647 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
9648 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
9649 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
9650 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
9651 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
9652 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
9653 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
9654 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
9655 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
9656 'whitesmoke', 'yellow', 'yellowgreen'
9659 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
9660 if (strpos($data, '#')!==0) {
9661 $data = '#'.$data;
9663 return $data;
9664 } else if (in_array(strtolower($data), $colornames)) {
9665 return $data;
9666 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9667 return $data;
9668 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9669 return $data;
9670 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9671 return $data;
9672 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9673 return $data;
9674 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9675 return $data;
9676 } else if (empty($data)) {
9677 if ($this->usedefaultwhenempty){
9678 return $this->defaultsetting;
9679 } else {
9680 return '';
9682 } else {
9683 return false;
9688 * Generates the HTML for the setting
9690 * @global moodle_page $PAGE
9691 * @global core_renderer $OUTPUT
9692 * @param string $data
9693 * @param string $query
9695 public function output_html($data, $query = '') {
9696 global $PAGE, $OUTPUT;
9698 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
9699 $context = (object) [
9700 'id' => $this->get_id(),
9701 'name' => $this->get_full_name(),
9702 'value' => $data,
9703 'icon' => $icon->export_for_template($OUTPUT),
9704 'haspreviewconfig' => !empty($this->previewconfig),
9705 'forceltr' => $this->get_force_ltr()
9708 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
9709 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9711 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
9712 $this->get_defaultsetting(), $query);
9719 * Class used for uploading of one file into file storage,
9720 * the file name is stored in config table.
9722 * Please note you need to implement your own '_pluginfile' callback function,
9723 * this setting only stores the file, it does not deal with file serving.
9725 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9726 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9728 class admin_setting_configstoredfile extends admin_setting {
9729 /** @var array file area options - should be one file only */
9730 protected $options;
9731 /** @var string name of the file area */
9732 protected $filearea;
9733 /** @var int intemid */
9734 protected $itemid;
9735 /** @var string used for detection of changes */
9736 protected $oldhashes;
9739 * Create new stored file setting.
9741 * @param string $name low level setting name
9742 * @param string $visiblename human readable setting name
9743 * @param string $description description of setting
9744 * @param mixed $filearea file area for file storage
9745 * @param int $itemid itemid for file storage
9746 * @param array $options file area options
9748 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9749 parent::__construct($name, $visiblename, $description, '');
9750 $this->filearea = $filearea;
9751 $this->itemid = $itemid;
9752 $this->options = (array)$options;
9756 * Applies defaults and returns all options.
9757 * @return array
9759 protected function get_options() {
9760 global $CFG;
9762 require_once("$CFG->libdir/filelib.php");
9763 require_once("$CFG->dirroot/repository/lib.php");
9764 $defaults = array(
9765 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9766 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9767 'context' => context_system::instance());
9768 foreach($this->options as $k => $v) {
9769 $defaults[$k] = $v;
9772 return $defaults;
9775 public function get_setting() {
9776 return $this->config_read($this->name);
9779 public function write_setting($data) {
9780 global $USER;
9782 // Let's not deal with validation here, this is for admins only.
9783 $current = $this->get_setting();
9784 if (empty($data) && $current === null) {
9785 // This will be the case when applying default settings (installation).
9786 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9787 } else if (!is_number($data)) {
9788 // Draft item id is expected here!
9789 return get_string('errorsetting', 'admin');
9792 $options = $this->get_options();
9793 $fs = get_file_storage();
9794 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9796 $this->oldhashes = null;
9797 if ($current) {
9798 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9799 if ($file = $fs->get_file_by_hash($hash)) {
9800 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9802 unset($file);
9805 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9806 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9807 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9808 // with an error because the draft area does not exist, as he did not use it.
9809 $usercontext = context_user::instance($USER->id);
9810 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9811 return get_string('errorsetting', 'admin');
9815 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9816 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9818 $filepath = '';
9819 if ($files) {
9820 /** @var stored_file $file */
9821 $file = reset($files);
9822 $filepath = $file->get_filepath().$file->get_filename();
9825 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9828 public function post_write_settings($original) {
9829 $options = $this->get_options();
9830 $fs = get_file_storage();
9831 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9833 $current = $this->get_setting();
9834 $newhashes = null;
9835 if ($current) {
9836 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9837 if ($file = $fs->get_file_by_hash($hash)) {
9838 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9840 unset($file);
9843 if ($this->oldhashes === $newhashes) {
9844 $this->oldhashes = null;
9845 return false;
9847 $this->oldhashes = null;
9849 $callbackfunction = $this->updatedcallback;
9850 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9851 $callbackfunction($this->get_full_name());
9853 return true;
9856 public function output_html($data, $query = '') {
9857 global $PAGE, $CFG;
9859 $options = $this->get_options();
9860 $id = $this->get_id();
9861 $elname = $this->get_full_name();
9862 $draftitemid = file_get_submitted_draft_itemid($elname);
9863 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9864 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9866 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9867 require_once("$CFG->dirroot/lib/form/filemanager.php");
9869 $fmoptions = new stdClass();
9870 $fmoptions->mainfile = $options['mainfile'];
9871 $fmoptions->maxbytes = $options['maxbytes'];
9872 $fmoptions->maxfiles = $options['maxfiles'];
9873 $fmoptions->client_id = uniqid();
9874 $fmoptions->itemid = $draftitemid;
9875 $fmoptions->subdirs = $options['subdirs'];
9876 $fmoptions->target = $id;
9877 $fmoptions->accepted_types = $options['accepted_types'];
9878 $fmoptions->return_types = $options['return_types'];
9879 $fmoptions->context = $options['context'];
9880 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9882 $fm = new form_filemanager($fmoptions);
9883 $output = $PAGE->get_renderer('core', 'files');
9884 $html = $output->render($fm);
9886 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9887 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9889 return format_admin_setting($this, $this->visiblename,
9890 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
9891 $this->description, true, '', '', $query);
9897 * Administration interface for user specified regular expressions for device detection.
9899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9901 class admin_setting_devicedetectregex extends admin_setting {
9904 * Calls parent::__construct with specific args
9906 * @param string $name
9907 * @param string $visiblename
9908 * @param string $description
9909 * @param mixed $defaultsetting
9911 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9912 global $CFG;
9913 parent::__construct($name, $visiblename, $description, $defaultsetting);
9917 * Return the current setting(s)
9919 * @return array Current settings array
9921 public function get_setting() {
9922 global $CFG;
9924 $config = $this->config_read($this->name);
9925 if (is_null($config)) {
9926 return null;
9929 return $this->prepare_form_data($config);
9933 * Save selected settings
9935 * @param array $data Array of settings to save
9936 * @return bool
9938 public function write_setting($data) {
9939 if (empty($data)) {
9940 $data = array();
9943 if ($this->config_write($this->name, $this->process_form_data($data))) {
9944 return ''; // success
9945 } else {
9946 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9951 * Return XHTML field(s) for regexes
9953 * @param array $data Array of options to set in HTML
9954 * @return string XHTML string for the fields and wrapping div(s)
9956 public function output_html($data, $query='') {
9957 global $OUTPUT;
9959 $context = (object) [
9960 'expressions' => [],
9961 'name' => $this->get_full_name()
9964 if (empty($data)) {
9965 $looplimit = 1;
9966 } else {
9967 $looplimit = (count($data)/2)+1;
9970 for ($i=0; $i<$looplimit; $i++) {
9972 $expressionname = 'expression'.$i;
9974 if (!empty($data[$expressionname])){
9975 $expression = $data[$expressionname];
9976 } else {
9977 $expression = '';
9980 $valuename = 'value'.$i;
9982 if (!empty($data[$valuename])){
9983 $value = $data[$valuename];
9984 } else {
9985 $value= '';
9988 $context->expressions[] = [
9989 'index' => $i,
9990 'expression' => $expression,
9991 'value' => $value
9995 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
9997 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10001 * Converts the string of regexes
10003 * @see self::process_form_data()
10004 * @param $regexes string of regexes
10005 * @return array of form fields and their values
10007 protected function prepare_form_data($regexes) {
10009 $regexes = json_decode($regexes);
10011 $form = array();
10013 $i = 0;
10015 foreach ($regexes as $value => $regex) {
10016 $expressionname = 'expression'.$i;
10017 $valuename = 'value'.$i;
10019 $form[$expressionname] = $regex;
10020 $form[$valuename] = $value;
10021 $i++;
10024 return $form;
10028 * Converts the data from admin settings form into a string of regexes
10030 * @see self::prepare_form_data()
10031 * @param array $data array of admin form fields and values
10032 * @return false|string of regexes
10034 protected function process_form_data(array $form) {
10036 $count = count($form); // number of form field values
10038 if ($count % 2) {
10039 // we must get five fields per expression
10040 return false;
10043 $regexes = array();
10044 for ($i = 0; $i < $count / 2; $i++) {
10045 $expressionname = "expression".$i;
10046 $valuename = "value".$i;
10048 $expression = trim($form['expression'.$i]);
10049 $value = trim($form['value'.$i]);
10051 if (empty($expression)){
10052 continue;
10055 $regexes[$value] = $expression;
10058 $regexes = json_encode($regexes);
10060 return $regexes;
10066 * Multiselect for current modules
10068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10070 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10071 private $excludesystem;
10074 * Calls parent::__construct - note array $choices is not required
10076 * @param string $name setting name
10077 * @param string $visiblename localised setting name
10078 * @param string $description setting description
10079 * @param array $defaultsetting a plain array of default module ids
10080 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10082 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10083 $excludesystem = true) {
10084 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10085 $this->excludesystem = $excludesystem;
10089 * Loads an array of current module choices
10091 * @return bool always return true
10093 public function load_choices() {
10094 if (is_array($this->choices)) {
10095 return true;
10097 $this->choices = array();
10099 global $CFG, $DB;
10100 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10101 foreach ($records as $record) {
10102 // Exclude modules if the code doesn't exist
10103 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10104 // Also exclude system modules (if specified)
10105 if (!($this->excludesystem &&
10106 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10107 MOD_ARCHETYPE_SYSTEM)) {
10108 $this->choices[$record->id] = $record->name;
10112 return true;
10117 * Admin setting to show if a php extension is enabled or not.
10119 * @copyright 2013 Damyon Wiese
10120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10122 class admin_setting_php_extension_enabled extends admin_setting {
10124 /** @var string The name of the extension to check for */
10125 private $extension;
10128 * Calls parent::__construct with specific arguments
10130 public function __construct($name, $visiblename, $description, $extension) {
10131 $this->extension = $extension;
10132 $this->nosave = true;
10133 parent::__construct($name, $visiblename, $description, '');
10137 * Always returns true, does nothing
10139 * @return true
10141 public function get_setting() {
10142 return true;
10146 * Always returns true, does nothing
10148 * @return true
10150 public function get_defaultsetting() {
10151 return true;
10155 * Always returns '', does not write anything
10157 * @return string Always returns ''
10159 public function write_setting($data) {
10160 // Do not write any setting.
10161 return '';
10165 * Outputs the html for this setting.
10166 * @return string Returns an XHTML string
10168 public function output_html($data, $query='') {
10169 global $OUTPUT;
10171 $o = '';
10172 if (!extension_loaded($this->extension)) {
10173 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10175 $o .= format_admin_setting($this, $this->visiblename, $warning);
10177 return $o;
10182 * Server timezone setting.
10184 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10186 * @author Petr Skoda <petr.skoda@totaralms.com>
10188 class admin_setting_servertimezone extends admin_setting_configselect {
10190 * Constructor.
10192 public function __construct() {
10193 $default = core_date::get_default_php_timezone();
10194 if ($default === 'UTC') {
10195 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10196 $default = 'Europe/London';
10199 parent::__construct('timezone',
10200 new lang_string('timezone', 'core_admin'),
10201 new lang_string('configtimezone', 'core_admin'), $default, null);
10205 * Lazy load timezone options.
10206 * @return bool true if loaded, false if error
10208 public function load_choices() {
10209 global $CFG;
10210 if (is_array($this->choices)) {
10211 return true;
10214 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10215 $this->choices = core_date::get_list_of_timezones($current, false);
10216 if ($current == 99) {
10217 // Do not show 99 unless it is current value, we want to get rid of it over time.
10218 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10219 core_date::get_default_php_timezone());
10222 return true;
10227 * Forced user timezone setting.
10229 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10230 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10231 * @author Petr Skoda <petr.skoda@totaralms.com>
10233 class admin_setting_forcetimezone extends admin_setting_configselect {
10235 * Constructor.
10237 public function __construct() {
10238 parent::__construct('forcetimezone',
10239 new lang_string('forcetimezone', 'core_admin'),
10240 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10244 * Lazy load timezone options.
10245 * @return bool true if loaded, false if error
10247 public function load_choices() {
10248 global $CFG;
10249 if (is_array($this->choices)) {
10250 return true;
10253 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10254 $this->choices = core_date::get_list_of_timezones($current, true);
10255 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10257 return true;
10263 * Search setup steps info.
10265 * @package core
10266 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10267 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10269 class admin_setting_searchsetupinfo extends admin_setting {
10272 * Calls parent::__construct with specific arguments
10274 public function __construct() {
10275 $this->nosave = true;
10276 parent::__construct('searchsetupinfo', '', '', '');
10280 * Always returns true, does nothing
10282 * @return true
10284 public function get_setting() {
10285 return true;
10289 * Always returns true, does nothing
10291 * @return true
10293 public function get_defaultsetting() {
10294 return true;
10298 * Always returns '', does not write anything
10300 * @param array $data
10301 * @return string Always returns ''
10303 public function write_setting($data) {
10304 // Do not write any setting.
10305 return '';
10309 * Builds the HTML to display the control
10311 * @param string $data Unused
10312 * @param string $query
10313 * @return string
10315 public function output_html($data, $query='') {
10316 global $CFG, $OUTPUT;
10318 $return = '';
10319 $brtag = html_writer::empty_tag('br');
10321 $searchareas = \core_search\manager::get_search_areas_list();
10322 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10323 $anyindexed = false;
10324 foreach ($searchareas as $areaid => $searcharea) {
10325 list($componentname, $varname) = $searcharea->get_config_var_name();
10326 if (get_config($componentname, $varname . '_indexingstart')) {
10327 $anyindexed = true;
10328 break;
10332 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10334 $table = new html_table();
10335 $table->head = array(get_string('step', 'search'), get_string('status'));
10336 $table->colclasses = array('leftalign step', 'leftalign status');
10337 $table->id = 'searchsetup';
10338 $table->attributes['class'] = 'admintable generaltable';
10339 $table->data = array();
10341 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10343 // Select a search engine.
10344 $row = array();
10345 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10346 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10347 array('href' => $url));
10349 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10350 if (!empty($CFG->searchengine)) {
10351 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
10352 array('class' => 'statusok'));
10355 $row[1] = $status;
10356 $table->data[] = $row;
10358 // Available areas.
10359 $row = array();
10360 $url = new moodle_url('/admin/searchareas.php');
10361 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
10362 array('href' => $url));
10364 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10365 if ($anyenabled) {
10366 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10369 $row[1] = $status;
10370 $table->data[] = $row;
10372 // Setup search engine.
10373 $row = array();
10374 if (empty($CFG->searchengine)) {
10375 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
10376 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10377 } else {
10378 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
10379 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
10380 array('href' => $url));
10381 // Check the engine status.
10382 $searchengine = \core_search\manager::search_engine_instance();
10383 try {
10384 $serverstatus = $searchengine->is_server_ready();
10385 } catch (\moodle_exception $e) {
10386 $serverstatus = $e->getMessage();
10388 if ($serverstatus === true) {
10389 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10390 } else {
10391 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
10393 $row[1] = $status;
10395 $table->data[] = $row;
10397 // Indexed data.
10398 $row = array();
10399 $url = new moodle_url('/admin/searchareas.php');
10400 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
10401 if ($anyindexed) {
10402 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10403 } else {
10404 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10406 $row[1] = $status;
10407 $table->data[] = $row;
10409 // Enable global search.
10410 $row = array();
10411 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
10412 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
10413 array('href' => $url));
10414 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10415 if (\core_search\manager::is_global_search_enabled()) {
10416 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10418 $row[1] = $status;
10419 $table->data[] = $row;
10421 $return .= html_writer::table($table);
10423 return highlight($query, $return);
10429 * Used to validate the contents of SCSS code and ensuring they are parsable.
10431 * It does not attempt to detect undefined SCSS variables because it is designed
10432 * to be used without knowledge of other config/scss included.
10434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10435 * @copyright 2016 Dan Poltawski <dan@moodle.com>
10437 class admin_setting_scsscode extends admin_setting_configtextarea {
10440 * Validate the contents of the SCSS to ensure its parsable. Does not
10441 * attempt to detect undefined scss variables.
10443 * @param string $data The scss code from text field.
10444 * @return mixed bool true for success or string:error on failure.
10446 public function validate($data) {
10447 if (empty($data)) {
10448 return true;
10451 $scss = new core_scss();
10452 try {
10453 $scss->compile($data);
10454 } catch (Leafo\ScssPhp\Exception\ParserException $e) {
10455 return get_string('scssinvalid', 'admin', $e->getMessage());
10456 } catch (Leafo\ScssPhp\Exception\CompilerException $e) {
10457 // Silently ignore this - it could be a scss variable defined from somewhere
10458 // else which we are not examining here.
10459 return true;
10462 return true;
10468 * Administration setting to define a list of file types.
10470 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
10471 * @copyright 2017 David Mudrák <david@moodle.com>
10472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10474 class admin_setting_filetypes extends admin_setting_configtext {
10476 /** @var array Allow selection from these file types only. */
10477 protected $onlytypes = [];
10479 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
10480 protected $allowall = true;
10482 /** @var core_form\filetypes_util instance to use as a helper. */
10483 protected $util = null;
10486 * Constructor.
10488 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
10489 * @param string $visiblename Localised label of the setting
10490 * @param string $description Localised description of the setting
10491 * @param string $defaultsetting Default setting value.
10492 * @param array $options Setting widget options, an array with optional keys:
10493 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
10494 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
10496 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
10498 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
10500 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
10501 $this->onlytypes = $options['onlytypes'];
10504 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
10505 $this->allowall = (bool)$options['allowall'];
10508 $this->util = new \core_form\filetypes_util();
10512 * Normalize the user's input and write it to the database as comma separated list.
10514 * Comma separated list as a text representation of the array was chosen to
10515 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
10517 * @param string $data Value submitted by the admin.
10518 * @return string Epty string if all good, error message otherwise.
10520 public function write_setting($data) {
10521 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
10525 * Validate data before storage
10527 * @param string $data The setting values provided by the admin
10528 * @return bool|string True if ok, the string if error found
10530 public function validate($data) {
10532 // No need to call parent's validation here as we are PARAM_RAW.
10534 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
10535 return true;
10537 } else {
10538 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
10539 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
10544 * Return an HTML string for the setting element.
10546 * @param string $data The current setting value
10547 * @param string $query Admin search query to be highlighted
10548 * @return string HTML to be displayed
10550 public function output_html($data, $query='') {
10551 global $OUTPUT, $PAGE;
10553 $default = $this->get_defaultsetting();
10554 $context = (object) [
10555 'id' => $this->get_id(),
10556 'name' => $this->get_full_name(),
10557 'value' => $data,
10558 'descriptions' => $this->util->describe_file_types($data),
10560 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
10562 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
10563 $this->get_id(),
10564 $this->visiblename->out(),
10565 $this->onlytypes,
10566 $this->allowall,
10569 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
10573 * Should the values be always displayed in LTR mode?
10575 * We always return true here because these values are not RTL compatible.
10577 * @return bool True because these values are not RTL compatible.
10579 public function get_force_ltr() {
10580 return true;
10585 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
10587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10588 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
10590 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
10593 * Constructor.
10595 * @param string $name
10596 * @param string $visiblename
10597 * @param string $description
10598 * @param mixed $defaultsetting string or array
10599 * @param mixed $paramtype
10600 * @param string $cols
10601 * @param string $rows
10603 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
10604 $cols = '60', $rows = '8') {
10605 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
10606 // Pre-set force LTR to false.
10607 $this->set_force_ltr(false);
10611 * Validate the content and format of the age of digital consent map to ensure it is parsable.
10613 * @param string $data The age of digital consent map from text field.
10614 * @return mixed bool true for success or string:error on failure.
10616 public function validate($data) {
10617 if (empty($data)) {
10618 return true;
10621 try {
10622 \core_auth\digital_consent::parse_age_digital_consent_map($data);
10623 } catch (\moodle_exception $e) {
10624 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
10627 return true;
10632 * Selection of plugins that can work as site policy handlers
10634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10635 * @copyright 2018 Marina Glancy
10637 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
10640 * Constructor
10641 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
10642 * for ones in config_plugins.
10643 * @param string $visiblename localised
10644 * @param string $description long localised info
10645 * @param string $defaultsetting
10647 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10648 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10652 * Lazy-load the available choices for the select box
10654 public function load_choices() {
10655 if (during_initial_install()) {
10656 return false;
10658 if (is_array($this->choices)) {
10659 return true;
10662 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
10663 $manager = new \core_privacy\local\sitepolicy\manager();
10664 $plugins = $manager->get_all_handlers();
10665 foreach ($plugins as $pname => $unused) {
10666 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
10667 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
10670 return true;