Merge branch 'MDL-60070-master' of git://github.com/lameze/moodle
[moodle.git] / lib / adminlib.php
blob903da8da535163395c9ae24b3692fac981e955e8
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 function_exists($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 foreach ($choices as $key => $val) {
2964 if (is_array($val)) {
2965 $this->optgroups[$key] = $val;
2966 $this->choices = array_merge($this->choices, $val);
2967 } else {
2968 $this->choices[$key] = $val;
2973 parent::__construct($name, $visiblename, $description, $defaultsetting);
2977 * This function may be used in ancestors for lazy loading of choices
2979 * Override this method if loading of choices is expensive, such
2980 * as when it requires multiple db requests.
2982 * @return bool true if loaded, false if error
2984 public function load_choices() {
2986 if (is_array($this->choices)) {
2987 return true;
2989 .... load choices here
2991 return true;
2995 * Check if this is $query is related to a choice
2997 * @param string $query
2998 * @return bool true if related, false if not
3000 public function is_related($query) {
3001 if (parent::is_related($query)) {
3002 return true;
3004 if (!$this->load_choices()) {
3005 return false;
3007 foreach ($this->choices as $key=>$value) {
3008 if (strpos(core_text::strtolower($key), $query) !== false) {
3009 return true;
3011 if (strpos(core_text::strtolower($value), $query) !== false) {
3012 return true;
3015 return false;
3019 * Return the setting
3021 * @return mixed returns config if successful else null
3023 public function get_setting() {
3024 return $this->config_read($this->name);
3028 * Save a setting
3030 * @param string $data
3031 * @return string empty of error string
3033 public function write_setting($data) {
3034 if (!$this->load_choices() or empty($this->choices)) {
3035 return '';
3037 if (!array_key_exists($data, $this->choices)) {
3038 return ''; // ignore it
3041 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3045 * Returns XHTML select field
3047 * Ensure the options are loaded, and generate the XHTML for the select
3048 * element and any warning message. Separating this out from output_html
3049 * makes it easier to subclass this class.
3051 * @param string $data the option to show as selected.
3052 * @param string $current the currently selected option in the database, null if none.
3053 * @param string $default the default selected option.
3054 * @return array the HTML for the select element, and a warning message.
3055 * @deprecated since Moodle 3.2
3057 public function output_select_html($data, $current, $default, $extraname = '') {
3058 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3062 * Returns XHTML select field and wrapping div(s)
3064 * @see output_select_html()
3066 * @param string $data the option to show as selected
3067 * @param string $query
3068 * @return string XHTML field and wrapping div
3070 public function output_html($data, $query='') {
3071 global $OUTPUT;
3073 $default = $this->get_defaultsetting();
3074 $current = $this->get_setting();
3076 if (!$this->load_choices() || empty($this->choices)) {
3077 return '';
3080 $context = (object) [
3081 'id' => $this->get_id(),
3082 'name' => $this->get_full_name(),
3085 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3086 $defaultinfo = $this->choices[$default];
3087 } else {
3088 $defaultinfo = NULL;
3091 // Warnings.
3092 $warning = '';
3093 if ($current === null) {
3094 // First run.
3095 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3096 // No warning.
3097 } else if (!array_key_exists($current, $this->choices)) {
3098 $warning = get_string('warningcurrentsetting', 'admin', $current);
3099 if (!is_null($default) && $data == $current) {
3100 $data = $default; // Use default instead of first value when showing the form.
3104 $options = [];
3105 $template = 'core_admin/setting_configselect';
3107 if (!empty($this->optgroups)) {
3108 $optgroups = [];
3109 foreach ($this->optgroups as $label => $choices) {
3110 $optgroup = array('label' => $label, 'options' => []);
3111 foreach ($choices as $value => $name) {
3112 $optgroup['options'][] = [
3113 'value' => $value,
3114 'name' => $name,
3115 'selected' => (string) $value == $data
3117 unset($this->choices[$value]);
3119 $optgroups[] = $optgroup;
3121 $context->options = $options;
3122 $context->optgroups = $optgroups;
3123 $template = 'core_admin/setting_configselect_optgroup';
3126 foreach ($this->choices as $value => $name) {
3127 $options[] = [
3128 'value' => $value,
3129 'name' => $name,
3130 'selected' => (string) $value == $data
3133 $context->options = $options;
3135 $element = $OUTPUT->render_from_template($template, $context);
3137 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3143 * Select multiple items from list
3145 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3147 class admin_setting_configmultiselect extends admin_setting_configselect {
3149 * Constructor
3150 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3151 * @param string $visiblename localised
3152 * @param string $description long localised info
3153 * @param array $defaultsetting array of selected items
3154 * @param array $choices array of $value=>$label for each list item
3156 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3157 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3161 * Returns the select setting(s)
3163 * @return mixed null or array. Null if no settings else array of setting(s)
3165 public function get_setting() {
3166 $result = $this->config_read($this->name);
3167 if (is_null($result)) {
3168 return NULL;
3170 if ($result === '') {
3171 return array();
3173 return explode(',', $result);
3177 * Saves setting(s) provided through $data
3179 * Potential bug in the works should anyone call with this function
3180 * using a vartype that is not an array
3182 * @param array $data
3184 public function write_setting($data) {
3185 if (!is_array($data)) {
3186 return ''; //ignore it
3188 if (!$this->load_choices() or empty($this->choices)) {
3189 return '';
3192 unset($data['xxxxx']);
3194 $save = array();
3195 foreach ($data as $value) {
3196 if (!array_key_exists($value, $this->choices)) {
3197 continue; // ignore it
3199 $save[] = $value;
3202 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3206 * Is setting related to query text - used when searching
3208 * @param string $query
3209 * @return bool true if related, false if not
3211 public function is_related($query) {
3212 if (!$this->load_choices() or empty($this->choices)) {
3213 return false;
3215 if (parent::is_related($query)) {
3216 return true;
3219 foreach ($this->choices as $desc) {
3220 if (strpos(core_text::strtolower($desc), $query) !== false) {
3221 return true;
3224 return false;
3228 * Returns XHTML multi-select field
3230 * @todo Add vartype handling to ensure $data is an array
3231 * @param array $data Array of values to select by default
3232 * @param string $query
3233 * @return string XHTML multi-select field
3235 public function output_html($data, $query='') {
3236 global $OUTPUT;
3238 if (!$this->load_choices() or empty($this->choices)) {
3239 return '';
3242 $default = $this->get_defaultsetting();
3243 if (is_null($default)) {
3244 $default = array();
3246 if (is_null($data)) {
3247 $data = array();
3250 $context = (object) [
3251 'id' => $this->get_id(),
3252 'name' => $this->get_full_name(),
3253 'size' => min(10, count($this->choices))
3256 $defaults = [];
3257 $options = [];
3258 $template = 'core_admin/setting_configmultiselect';
3260 if (!empty($this->optgroups)) {
3261 $optgroups = [];
3262 foreach ($this->optgroups as $label => $choices) {
3263 $optgroup = array('label' => $label, 'options' => []);
3264 foreach ($choices as $value => $name) {
3265 if (in_array($value, $default)) {
3266 $defaults[] = $name;
3268 $optgroup['options'][] = [
3269 'value' => $value,
3270 'name' => $name,
3271 'selected' => in_array($value, $data)
3273 unset($this->choices[$value]);
3275 $optgroups[] = $optgroup;
3277 $context->optgroups = $optgroups;
3278 $template = 'core_admin/setting_configmultiselect_optgroup';
3281 foreach ($this->choices as $value => $name) {
3282 if (in_array($value, $default)) {
3283 $defaults[] = $name;
3285 $options[] = [
3286 'value' => $value,
3287 'name' => $name,
3288 'selected' => in_array($value, $data)
3291 $context->options = $options;
3293 if (is_null($default)) {
3294 $defaultinfo = NULL;
3295 } if (!empty($defaults)) {
3296 $defaultinfo = implode(', ', $defaults);
3297 } else {
3298 $defaultinfo = get_string('none');
3301 $element = $OUTPUT->render_from_template($template, $context);
3303 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3308 * Time selector
3310 * This is a liiitle bit messy. we're using two selects, but we're returning
3311 * them as an array named after $name (so we only use $name2 internally for the setting)
3313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3315 class admin_setting_configtime extends admin_setting {
3316 /** @var string Used for setting second select (minutes) */
3317 public $name2;
3320 * Constructor
3321 * @param string $hoursname setting for hours
3322 * @param string $minutesname setting for hours
3323 * @param string $visiblename localised
3324 * @param string $description long localised info
3325 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3327 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3328 $this->name2 = $minutesname;
3329 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3333 * Get the selected time
3335 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3337 public function get_setting() {
3338 $result1 = $this->config_read($this->name);
3339 $result2 = $this->config_read($this->name2);
3340 if (is_null($result1) or is_null($result2)) {
3341 return NULL;
3344 return array('h' => $result1, 'm' => $result2);
3348 * Store the time (hours and minutes)
3350 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3351 * @return bool true if success, false if not
3353 public function write_setting($data) {
3354 if (!is_array($data)) {
3355 return '';
3358 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3359 return ($result ? '' : get_string('errorsetting', 'admin'));
3363 * Returns XHTML time select fields
3365 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3366 * @param string $query
3367 * @return string XHTML time select fields and wrapping div(s)
3369 public function output_html($data, $query='') {
3370 global $OUTPUT;
3372 $default = $this->get_defaultsetting();
3373 if (is_array($default)) {
3374 $defaultinfo = $default['h'].':'.$default['m'];
3375 } else {
3376 $defaultinfo = NULL;
3379 $context = (object) [
3380 'id' => $this->get_id(),
3381 'name' => $this->get_full_name(),
3382 'hours' => array_map(function($i) use ($data) {
3383 return [
3384 'value' => $i,
3385 'name' => $i,
3386 'selected' => $i == $data['h']
3388 }, range(0, 23)),
3389 'minutes' => array_map(function($i) use ($data) {
3390 return [
3391 'value' => $i,
3392 'name' => $i,
3393 'selected' => $i == $data['m']
3395 }, range(0, 59, 5))
3398 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3400 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3401 $this->get_id() . 'h', '', $defaultinfo, $query);
3408 * Seconds duration setting.
3410 * @copyright 2012 Petr Skoda (http://skodak.org)
3411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3413 class admin_setting_configduration extends admin_setting {
3415 /** @var int default duration unit */
3416 protected $defaultunit;
3419 * Constructor
3420 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3421 * or 'myplugin/mysetting' for ones in config_plugins.
3422 * @param string $visiblename localised name
3423 * @param string $description localised long description
3424 * @param mixed $defaultsetting string or array depending on implementation
3425 * @param int $defaultunit - day, week, etc. (in seconds)
3427 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3428 if (is_number($defaultsetting)) {
3429 $defaultsetting = self::parse_seconds($defaultsetting);
3431 $units = self::get_units();
3432 if (isset($units[$defaultunit])) {
3433 $this->defaultunit = $defaultunit;
3434 } else {
3435 $this->defaultunit = 86400;
3437 parent::__construct($name, $visiblename, $description, $defaultsetting);
3441 * Returns selectable units.
3442 * @static
3443 * @return array
3445 protected static function get_units() {
3446 return array(
3447 604800 => get_string('weeks'),
3448 86400 => get_string('days'),
3449 3600 => get_string('hours'),
3450 60 => get_string('minutes'),
3451 1 => get_string('seconds'),
3456 * Converts seconds to some more user friendly string.
3457 * @static
3458 * @param int $seconds
3459 * @return string
3461 protected static function get_duration_text($seconds) {
3462 if (empty($seconds)) {
3463 return get_string('none');
3465 $data = self::parse_seconds($seconds);
3466 switch ($data['u']) {
3467 case (60*60*24*7):
3468 return get_string('numweeks', '', $data['v']);
3469 case (60*60*24):
3470 return get_string('numdays', '', $data['v']);
3471 case (60*60):
3472 return get_string('numhours', '', $data['v']);
3473 case (60):
3474 return get_string('numminutes', '', $data['v']);
3475 default:
3476 return get_string('numseconds', '', $data['v']*$data['u']);
3481 * Finds suitable units for given duration.
3482 * @static
3483 * @param int $seconds
3484 * @return array
3486 protected static function parse_seconds($seconds) {
3487 foreach (self::get_units() as $unit => $unused) {
3488 if ($seconds % $unit === 0) {
3489 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3492 return array('v'=>(int)$seconds, 'u'=>1);
3496 * Get the selected duration as array.
3498 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3500 public function get_setting() {
3501 $seconds = $this->config_read($this->name);
3502 if (is_null($seconds)) {
3503 return null;
3506 return self::parse_seconds($seconds);
3510 * Store the duration as seconds.
3512 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3513 * @return bool true if success, false if not
3515 public function write_setting($data) {
3516 if (!is_array($data)) {
3517 return '';
3520 $seconds = (int)($data['v']*$data['u']);
3521 if ($seconds < 0) {
3522 return get_string('errorsetting', 'admin');
3525 $result = $this->config_write($this->name, $seconds);
3526 return ($result ? '' : get_string('errorsetting', 'admin'));
3530 * Returns duration text+select fields.
3532 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3533 * @param string $query
3534 * @return string duration text+select fields and wrapping div(s)
3536 public function output_html($data, $query='') {
3537 global $OUTPUT;
3539 $default = $this->get_defaultsetting();
3540 if (is_number($default)) {
3541 $defaultinfo = self::get_duration_text($default);
3542 } else if (is_array($default)) {
3543 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3544 } else {
3545 $defaultinfo = null;
3548 $inputid = $this->get_id() . 'v';
3549 $units = self::get_units();
3550 $defaultunit = $this->defaultunit;
3552 $context = (object) [
3553 'id' => $this->get_id(),
3554 'name' => $this->get_full_name(),
3555 'value' => $data['v'],
3556 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3557 return [
3558 'value' => $unit,
3559 'name' => $units[$unit],
3560 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3562 }, array_keys($units))
3565 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3567 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3573 * Seconds duration setting with an advanced checkbox, that controls a additional
3574 * $name.'_adv' setting.
3576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3577 * @copyright 2014 The Open University
3579 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3581 * Constructor
3582 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3583 * or 'myplugin/mysetting' for ones in config_plugins.
3584 * @param string $visiblename localised name
3585 * @param string $description localised long description
3586 * @param array $defaultsetting array of int value, and bool whether it is
3587 * is advanced by default.
3588 * @param int $defaultunit - day, week, etc. (in seconds)
3590 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3591 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3592 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3598 * Used to validate a textarea used for ip addresses
3600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3601 * @copyright 2011 Petr Skoda (http://skodak.org)
3603 class admin_setting_configiplist extends admin_setting_configtextarea {
3606 * Validate the contents of the textarea as IP addresses
3608 * Used to validate a new line separated list of IP addresses collected from
3609 * a textarea control
3611 * @param string $data A list of IP Addresses separated by new lines
3612 * @return mixed bool true for success or string:error on failure
3614 public function validate($data) {
3615 if(!empty($data)) {
3616 $ips = explode("\n", $data);
3617 } else {
3618 return true;
3620 $result = true;
3621 $badips = array();
3622 foreach($ips as $ip) {
3623 $ip = trim($ip);
3624 if (empty($ip)) {
3625 continue;
3627 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3628 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3629 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3630 } else {
3631 $result = false;
3632 $badips[] = $ip;
3635 if($result) {
3636 return true;
3637 } else {
3638 return get_string('validateiperror', 'admin', join(', ', $badips));
3644 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3647 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3649 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3652 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3653 * Used to validate a new line separated list of entries collected from a textarea control.
3655 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3656 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3657 * via the get_setting() method, which has been overriden.
3659 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3660 * @return mixed bool true for success or string:error on failure
3662 public function validate($data) {
3663 if (empty($data)) {
3664 return true;
3666 $entries = explode("\n", $data);
3667 $badentries = [];
3669 foreach ($entries as $key => $entry) {
3670 $entry = trim($entry);
3671 if (empty($entry)) {
3672 return get_string('validateemptylineerror', 'admin');
3675 // Validate each string entry against the supported formats.
3676 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3677 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3678 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3679 continue;
3682 // Otherwise, the entry is invalid.
3683 $badentries[] = $entry;
3686 if ($badentries) {
3687 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3689 return true;
3693 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3695 * @param string $data the setting data, as sent from the web form.
3696 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3698 protected function ace_encode($data) {
3699 if (empty($data)) {
3700 return $data;
3702 $entries = explode("\n", $data);
3703 foreach ($entries as $key => $entry) {
3704 $entry = trim($entry);
3705 // This regex matches any string which:
3706 // a) contains at least one non-ascii unicode character AND
3707 // b) starts with a-zA-Z0-9 or any non-ascii unicode character AND
3708 // c) ends with a-zA-Z0-9 or any non-ascii unicode character
3709 // d) contains a-zA-Z0-9, hyphen, dot or any non-ascii unicode characters in the middle.
3710 if (preg_match('/^(?=[^\x00-\x7f])([^\x00-\x7f]|[a-zA-Z0-9])([^\x00-\x7f]|[a-zA-Z0-9-.])*([^\x00-\x7f]|[a-zA-Z0-9])$/',
3711 $entry)) {
3712 // If we can convert the unicode string to an idn, do so.
3713 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3714 $val = idn_to_ascii($entry);
3715 $entries[$key] = $val ? $val : $entry;
3718 return implode("\n", $entries);
3722 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
3724 * @param string $data the setting data, as found in the database.
3725 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
3727 protected function ace_decode($data) {
3728 $entries = explode("\n", $data);
3729 foreach ($entries as $key => $entry) {
3730 $entry = trim($entry);
3731 if (strpos($entry, 'xn--') !== false) {
3732 $entries[$key] = idn_to_utf8($entry);
3735 return implode("\n", $entries);
3739 * Override, providing utf8-decoding for ascii-encoded IDN strings.
3741 * @return mixed returns punycode-converted setting string if successful, else null.
3743 public function get_setting() {
3744 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
3745 $data = $this->config_read($this->name);
3746 if (function_exists('idn_to_utf8') && !is_null($data)) {
3747 $data = $this->ace_decode($data);
3749 return $data;
3753 * Override, providing ascii-encoding for utf8 (native) IDN strings.
3755 * @param string $data
3756 * @return string
3758 public function write_setting($data) {
3759 if ($this->paramtype === PARAM_INT and $data === '') {
3760 // Do not complain if '' used instead of 0.
3761 $data = 0;
3764 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
3765 if (function_exists('idn_to_ascii')) {
3766 $data = $this->ace_encode($data);
3769 $validated = $this->validate($data);
3770 if ($validated !== true) {
3771 return $validated;
3773 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3778 * Used to validate a textarea used for port numbers.
3780 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3781 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3783 class admin_setting_configportlist extends admin_setting_configtextarea {
3786 * Validate the contents of the textarea as port numbers.
3787 * Used to validate a new line separated list of ports collected from a textarea control.
3789 * @param string $data A list of ports separated by new lines
3790 * @return mixed bool true for success or string:error on failure
3792 public function validate($data) {
3793 if (empty($data)) {
3794 return true;
3796 $ports = explode("\n", $data);
3797 $badentries = [];
3798 foreach ($ports as $port) {
3799 $port = trim($port);
3800 if (empty($port)) {
3801 return get_string('validateemptylineerror', 'admin');
3804 // Is the string a valid integer number?
3805 if (strval(intval($port)) !== $port || intval($port) <= 0) {
3806 $badentries[] = $port;
3809 if ($badentries) {
3810 return get_string('validateerrorlist', 'admin', $badentries);
3812 return true;
3818 * An admin setting for selecting one or more users who have a capability
3819 * in the system context
3821 * An admin setting for selecting one or more users, who have a particular capability
3822 * in the system context. Warning, make sure the list will never be too long. There is
3823 * no paging or searching of this list.
3825 * To correctly get a list of users from this config setting, you need to call the
3826 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3830 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3831 /** @var string The capabilities name */
3832 protected $capability;
3833 /** @var int include admin users too */
3834 protected $includeadmins;
3837 * Constructor.
3839 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3840 * @param string $visiblename localised name
3841 * @param string $description localised long description
3842 * @param array $defaultsetting array of usernames
3843 * @param string $capability string capability name.
3844 * @param bool $includeadmins include administrators
3846 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3847 $this->capability = $capability;
3848 $this->includeadmins = $includeadmins;
3849 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3853 * Load all of the uses who have the capability into choice array
3855 * @return bool Always returns true
3857 function load_choices() {
3858 if (is_array($this->choices)) {
3859 return true;
3861 list($sort, $sortparams) = users_order_by_sql('u');
3862 if (!empty($sortparams)) {
3863 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3864 'This is unexpected, and a problem because there is no way to pass these ' .
3865 'parameters to get_users_by_capability. See MDL-34657.');
3867 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3868 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3869 $this->choices = array(
3870 '$@NONE@$' => get_string('nobody'),
3871 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3873 if ($this->includeadmins) {
3874 $admins = get_admins();
3875 foreach ($admins as $user) {
3876 $this->choices[$user->id] = fullname($user);
3879 if (is_array($users)) {
3880 foreach ($users as $user) {
3881 $this->choices[$user->id] = fullname($user);
3884 return true;
3888 * Returns the default setting for class
3890 * @return mixed Array, or string. Empty string if no default
3892 public function get_defaultsetting() {
3893 $this->load_choices();
3894 $defaultsetting = parent::get_defaultsetting();
3895 if (empty($defaultsetting)) {
3896 return array('$@NONE@$');
3897 } else if (array_key_exists($defaultsetting, $this->choices)) {
3898 return $defaultsetting;
3899 } else {
3900 return '';
3905 * Returns the current setting
3907 * @return mixed array or string
3909 public function get_setting() {
3910 $result = parent::get_setting();
3911 if ($result === null) {
3912 // this is necessary for settings upgrade
3913 return null;
3915 if (empty($result)) {
3916 $result = array('$@NONE@$');
3918 return $result;
3922 * Save the chosen setting provided as $data
3924 * @param array $data
3925 * @return mixed string or array
3927 public function write_setting($data) {
3928 // If all is selected, remove any explicit options.
3929 if (in_array('$@ALL@$', $data)) {
3930 $data = array('$@ALL@$');
3932 // None never needs to be written to the DB.
3933 if (in_array('$@NONE@$', $data)) {
3934 unset($data[array_search('$@NONE@$', $data)]);
3936 return parent::write_setting($data);
3942 * Special checkbox for calendar - resets SESSION vars.
3944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3946 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3948 * Calls the parent::__construct with default values
3950 * name => calendar_adminseesall
3951 * visiblename => get_string('adminseesall', 'admin')
3952 * description => get_string('helpadminseesall', 'admin')
3953 * defaultsetting => 0
3955 public function __construct() {
3956 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3957 get_string('helpadminseesall', 'admin'), '0');
3961 * Stores the setting passed in $data
3963 * @param mixed gets converted to string for comparison
3964 * @return string empty string or error message
3966 public function write_setting($data) {
3967 global $SESSION;
3968 return parent::write_setting($data);
3973 * Special select for settings that are altered in setup.php and can not be altered on the fly
3975 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3977 class admin_setting_special_selectsetup extends admin_setting_configselect {
3979 * Reads the setting directly from the database
3981 * @return mixed
3983 public function get_setting() {
3984 // read directly from db!
3985 return get_config(NULL, $this->name);
3989 * Save the setting passed in $data
3991 * @param string $data The setting to save
3992 * @return string empty or error message
3994 public function write_setting($data) {
3995 global $CFG;
3996 // do not change active CFG setting!
3997 $current = $CFG->{$this->name};
3998 $result = parent::write_setting($data);
3999 $CFG->{$this->name} = $current;
4000 return $result;
4006 * Special select for frontpage - stores data in course table
4008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4010 class admin_setting_sitesetselect extends admin_setting_configselect {
4012 * Returns the site name for the selected site
4014 * @see get_site()
4015 * @return string The site name of the selected site
4017 public function get_setting() {
4018 $site = course_get_format(get_site())->get_course();
4019 return $site->{$this->name};
4023 * Updates the database and save the setting
4025 * @param string data
4026 * @return string empty or error message
4028 public function write_setting($data) {
4029 global $DB, $SITE, $COURSE;
4030 if (!in_array($data, array_keys($this->choices))) {
4031 return get_string('errorsetting', 'admin');
4033 $record = new stdClass();
4034 $record->id = SITEID;
4035 $temp = $this->name;
4036 $record->$temp = $data;
4037 $record->timemodified = time();
4039 course_get_format($SITE)->update_course_format_options($record);
4040 $DB->update_record('course', $record);
4042 // Reset caches.
4043 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4044 if ($SITE->id == $COURSE->id) {
4045 $COURSE = $SITE;
4047 format_base::reset_course_cache($SITE->id);
4049 return '';
4056 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4057 * block to hidden.
4059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4061 class admin_setting_bloglevel extends admin_setting_configselect {
4063 * Updates the database and save the setting
4065 * @param string data
4066 * @return string empty or error message
4068 public function write_setting($data) {
4069 global $DB, $CFG;
4070 if ($data == 0) {
4071 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4072 foreach ($blogblocks as $block) {
4073 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4075 } else {
4076 // reenable all blocks only when switching from disabled blogs
4077 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4078 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4079 foreach ($blogblocks as $block) {
4080 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4084 return parent::write_setting($data);
4090 * Special select - lists on the frontpage - hacky
4092 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4094 class admin_setting_courselist_frontpage extends admin_setting {
4095 /** @var array Array of choices value=>label */
4096 public $choices;
4099 * Construct override, requires one param
4101 * @param bool $loggedin Is the user logged in
4103 public function __construct($loggedin) {
4104 global $CFG;
4105 require_once($CFG->dirroot.'/course/lib.php');
4106 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4107 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4108 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4109 $defaults = array(FRONTPAGEALLCOURSELIST);
4110 parent::__construct($name, $visiblename, $description, $defaults);
4114 * Loads the choices available
4116 * @return bool always returns true
4118 public function load_choices() {
4119 if (is_array($this->choices)) {
4120 return true;
4122 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4123 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4124 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4125 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4126 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4127 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4128 'none' => get_string('none'));
4129 if ($this->name === 'frontpage') {
4130 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4132 return true;
4136 * Returns the selected settings
4138 * @param mixed array or setting or null
4140 public function get_setting() {
4141 $result = $this->config_read($this->name);
4142 if (is_null($result)) {
4143 return NULL;
4145 if ($result === '') {
4146 return array();
4148 return explode(',', $result);
4152 * Save the selected options
4154 * @param array $data
4155 * @return mixed empty string (data is not an array) or bool true=success false=failure
4157 public function write_setting($data) {
4158 if (!is_array($data)) {
4159 return '';
4161 $this->load_choices();
4162 $save = array();
4163 foreach($data as $datum) {
4164 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4165 continue;
4167 $save[$datum] = $datum; // no duplicates
4169 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4173 * Return XHTML select field and wrapping div
4175 * @todo Add vartype handling to make sure $data is an array
4176 * @param array $data Array of elements to select by default
4177 * @return string XHTML select field and wrapping div
4179 public function output_html($data, $query='') {
4180 global $OUTPUT;
4182 $this->load_choices();
4183 $currentsetting = array();
4184 foreach ($data as $key) {
4185 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4186 $currentsetting[] = $key; // already selected first
4190 $context = (object) [
4191 'id' => $this->get_id(),
4192 'name' => $this->get_full_name(),
4195 $options = $this->choices;
4196 $selects = [];
4197 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4198 if (!array_key_exists($i, $currentsetting)) {
4199 $currentsetting[$i] = 'none';
4201 $selects[] = [
4202 'key' => $i,
4203 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4204 return [
4205 'name' => $options[$option],
4206 'value' => $option,
4207 'selected' => $currentsetting[$i] == $option
4209 }, array_keys($options))
4212 $context->selects = $selects;
4214 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4216 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4222 * Special checkbox for frontpage - stores data in course table
4224 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4226 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4228 * Returns the current sites name
4230 * @return string
4232 public function get_setting() {
4233 $site = course_get_format(get_site())->get_course();
4234 return $site->{$this->name};
4238 * Save the selected setting
4240 * @param string $data The selected site
4241 * @return string empty string or error message
4243 public function write_setting($data) {
4244 global $DB, $SITE, $COURSE;
4245 $record = new stdClass();
4246 $record->id = $SITE->id;
4247 $record->{$this->name} = ($data == '1' ? 1 : 0);
4248 $record->timemodified = time();
4250 course_get_format($SITE)->update_course_format_options($record);
4251 $DB->update_record('course', $record);
4253 // Reset caches.
4254 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4255 if ($SITE->id == $COURSE->id) {
4256 $COURSE = $SITE;
4258 format_base::reset_course_cache($SITE->id);
4260 return '';
4265 * Special text for frontpage - stores data in course table.
4266 * Empty string means not set here. Manual setting is required.
4268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4270 class admin_setting_sitesettext extends admin_setting_configtext {
4273 * Constructor.
4275 public function __construct() {
4276 call_user_func_array(['parent', '__construct'], func_get_args());
4277 $this->set_force_ltr(false);
4281 * Return the current setting
4283 * @return mixed string or null
4285 public function get_setting() {
4286 $site = course_get_format(get_site())->get_course();
4287 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4291 * Validate the selected data
4293 * @param string $data The selected value to validate
4294 * @return mixed true or message string
4296 public function validate($data) {
4297 global $DB, $SITE;
4298 $cleaned = clean_param($data, PARAM_TEXT);
4299 if ($cleaned === '') {
4300 return get_string('required');
4302 if ($this->name ==='shortname' &&
4303 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4304 return get_string('shortnametaken', 'error', $data);
4306 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4307 return true;
4308 } else {
4309 return get_string('validateerror', 'admin');
4314 * Save the selected setting
4316 * @param string $data The selected value
4317 * @return string empty or error message
4319 public function write_setting($data) {
4320 global $DB, $SITE, $COURSE;
4321 $data = trim($data);
4322 $validated = $this->validate($data);
4323 if ($validated !== true) {
4324 return $validated;
4327 $record = new stdClass();
4328 $record->id = $SITE->id;
4329 $record->{$this->name} = $data;
4330 $record->timemodified = time();
4332 course_get_format($SITE)->update_course_format_options($record);
4333 $DB->update_record('course', $record);
4335 // Reset caches.
4336 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4337 if ($SITE->id == $COURSE->id) {
4338 $COURSE = $SITE;
4340 format_base::reset_course_cache($SITE->id);
4342 return '';
4348 * Special text editor for site description.
4350 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4352 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4355 * Calls parent::__construct with specific arguments
4357 public function __construct() {
4358 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4359 PARAM_RAW, 60, 15);
4363 * Return the current setting
4364 * @return string The current setting
4366 public function get_setting() {
4367 $site = course_get_format(get_site())->get_course();
4368 return $site->{$this->name};
4372 * Save the new setting
4374 * @param string $data The new value to save
4375 * @return string empty or error message
4377 public function write_setting($data) {
4378 global $DB, $SITE, $COURSE;
4379 $record = new stdClass();
4380 $record->id = $SITE->id;
4381 $record->{$this->name} = $data;
4382 $record->timemodified = time();
4384 course_get_format($SITE)->update_course_format_options($record);
4385 $DB->update_record('course', $record);
4387 // Reset caches.
4388 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4389 if ($SITE->id == $COURSE->id) {
4390 $COURSE = $SITE;
4392 format_base::reset_course_cache($SITE->id);
4394 return '';
4400 * Administration interface for emoticon_manager settings.
4402 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4404 class admin_setting_emoticons extends admin_setting {
4407 * Calls parent::__construct with specific args
4409 public function __construct() {
4410 global $CFG;
4412 $manager = get_emoticon_manager();
4413 $defaults = $this->prepare_form_data($manager->default_emoticons());
4414 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4418 * Return the current setting(s)
4420 * @return array Current settings array
4422 public function get_setting() {
4423 global $CFG;
4425 $manager = get_emoticon_manager();
4427 $config = $this->config_read($this->name);
4428 if (is_null($config)) {
4429 return null;
4432 $config = $manager->decode_stored_config($config);
4433 if (is_null($config)) {
4434 return null;
4437 return $this->prepare_form_data($config);
4441 * Save selected settings
4443 * @param array $data Array of settings to save
4444 * @return bool
4446 public function write_setting($data) {
4448 $manager = get_emoticon_manager();
4449 $emoticons = $this->process_form_data($data);
4451 if ($emoticons === false) {
4452 return false;
4455 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4456 return ''; // success
4457 } else {
4458 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4463 * Return XHTML field(s) for options
4465 * @param array $data Array of options to set in HTML
4466 * @return string XHTML string for the fields and wrapping div(s)
4468 public function output_html($data, $query='') {
4469 global $OUTPUT;
4471 $context = (object) [
4472 'name' => $this->get_full_name(),
4473 'emoticons' => [],
4474 'forceltr' => true,
4477 $i = 0;
4478 foreach ($data as $field => $value) {
4480 // When $i == 0: text.
4481 // When $i == 1: imagename.
4482 // When $i == 2: imagecomponent.
4483 // When $i == 3: altidentifier.
4484 // When $i == 4: altcomponent.
4485 $fields[$i] = (object) [
4486 'field' => $field,
4487 'value' => $value,
4488 'index' => $i
4490 $i++;
4492 if ($i > 4) {
4493 $icon = null;
4494 if (!empty($fields[1]->value)) {
4495 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4496 $alt = get_string($fields[3]->value, $fields[4]->value);
4497 } else {
4498 $alt = $fields[0]->value;
4500 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4502 $context->emoticons[] = [
4503 'fields' => $fields,
4504 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4506 $fields = [];
4507 $i = 0;
4511 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4512 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4513 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4517 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4519 * @see self::process_form_data()
4520 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4521 * @return array of form fields and their values
4523 protected function prepare_form_data(array $emoticons) {
4525 $form = array();
4526 $i = 0;
4527 foreach ($emoticons as $emoticon) {
4528 $form['text'.$i] = $emoticon->text;
4529 $form['imagename'.$i] = $emoticon->imagename;
4530 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4531 $form['altidentifier'.$i] = $emoticon->altidentifier;
4532 $form['altcomponent'.$i] = $emoticon->altcomponent;
4533 $i++;
4535 // add one more blank field set for new object
4536 $form['text'.$i] = '';
4537 $form['imagename'.$i] = '';
4538 $form['imagecomponent'.$i] = '';
4539 $form['altidentifier'.$i] = '';
4540 $form['altcomponent'.$i] = '';
4542 return $form;
4546 * Converts the data from admin settings form into an array of emoticon objects
4548 * @see self::prepare_form_data()
4549 * @param array $data array of admin form fields and values
4550 * @return false|array of emoticon objects
4552 protected function process_form_data(array $form) {
4554 $count = count($form); // number of form field values
4556 if ($count % 5) {
4557 // we must get five fields per emoticon object
4558 return false;
4561 $emoticons = array();
4562 for ($i = 0; $i < $count / 5; $i++) {
4563 $emoticon = new stdClass();
4564 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4565 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4566 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4567 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4568 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4570 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4571 // prevent from breaking http://url.addresses by accident
4572 $emoticon->text = '';
4575 if (strlen($emoticon->text) < 2) {
4576 // do not allow single character emoticons
4577 $emoticon->text = '';
4580 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4581 // emoticon text must contain some non-alphanumeric character to prevent
4582 // breaking HTML tags
4583 $emoticon->text = '';
4586 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4587 $emoticons[] = $emoticon;
4590 return $emoticons;
4597 * Special setting for limiting of the list of available languages.
4599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4601 class admin_setting_langlist extends admin_setting_configtext {
4603 * Calls parent::__construct with specific arguments
4605 public function __construct() {
4606 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4610 * Save the new setting
4612 * @param string $data The new setting
4613 * @return bool
4615 public function write_setting($data) {
4616 $return = parent::write_setting($data);
4617 get_string_manager()->reset_caches();
4618 return $return;
4624 * Selection of one of the recognised countries using the list
4625 * returned by {@link get_list_of_countries()}.
4627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4629 class admin_settings_country_select extends admin_setting_configselect {
4630 protected $includeall;
4631 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4632 $this->includeall = $includeall;
4633 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4637 * Lazy-load the available choices for the select box
4639 public function load_choices() {
4640 global $CFG;
4641 if (is_array($this->choices)) {
4642 return true;
4644 $this->choices = array_merge(
4645 array('0' => get_string('choosedots')),
4646 get_string_manager()->get_list_of_countries($this->includeall));
4647 return true;
4653 * admin_setting_configselect for the default number of sections in a course,
4654 * simply so we can lazy-load the choices.
4656 * @copyright 2011 The Open University
4657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4659 class admin_settings_num_course_sections extends admin_setting_configselect {
4660 public function __construct($name, $visiblename, $description, $defaultsetting) {
4661 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4664 /** Lazy-load the available choices for the select box */
4665 public function load_choices() {
4666 $max = get_config('moodlecourse', 'maxsections');
4667 if (!isset($max) || !is_numeric($max)) {
4668 $max = 52;
4670 for ($i = 0; $i <= $max; $i++) {
4671 $this->choices[$i] = "$i";
4673 return true;
4679 * Course category selection
4681 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4683 class admin_settings_coursecat_select extends admin_setting_configselect {
4685 * Calls parent::__construct with specific arguments
4687 public function __construct($name, $visiblename, $description, $defaultsetting) {
4688 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4692 * Load the available choices for the select box
4694 * @return bool
4696 public function load_choices() {
4697 global $CFG;
4698 require_once($CFG->dirroot.'/course/lib.php');
4699 if (is_array($this->choices)) {
4700 return true;
4702 $this->choices = make_categories_options();
4703 return true;
4709 * Special control for selecting days to backup
4711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4713 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4715 * Calls parent::__construct with specific arguments
4717 public function __construct() {
4718 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4719 $this->plugin = 'backup';
4723 * Load the available choices for the select box
4725 * @return bool Always returns true
4727 public function load_choices() {
4728 if (is_array($this->choices)) {
4729 return true;
4731 $this->choices = array();
4732 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4733 foreach ($days as $day) {
4734 $this->choices[$day] = get_string($day, 'calendar');
4736 return true;
4741 * Special setting for backup auto destination.
4743 * @package core
4744 * @subpackage admin
4745 * @copyright 2014 Frédéric Massart - FMCorz.net
4746 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4748 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4751 * Calls parent::__construct with specific arguments.
4753 public function __construct() {
4754 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4758 * Check if the directory must be set, depending on backup/backup_auto_storage.
4760 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4761 * there will be conflicts if this validation happens before the other one.
4763 * @param string $data Form data.
4764 * @return string Empty when no errors.
4766 public function write_setting($data) {
4767 $storage = (int) get_config('backup', 'backup_auto_storage');
4768 if ($storage !== 0) {
4769 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4770 // The directory must exist and be writable.
4771 return get_string('backuperrorinvaliddestination');
4774 return parent::write_setting($data);
4780 * Special debug setting
4782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4784 class admin_setting_special_debug extends admin_setting_configselect {
4786 * Calls parent::__construct with specific arguments
4788 public function __construct() {
4789 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4793 * Load the available choices for the select box
4795 * @return bool
4797 public function load_choices() {
4798 if (is_array($this->choices)) {
4799 return true;
4801 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4802 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4803 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4804 DEBUG_ALL => get_string('debugall', 'admin'),
4805 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4806 return true;
4812 * Special admin control
4814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4816 class admin_setting_special_calendar_weekend extends admin_setting {
4818 * Calls parent::__construct with specific arguments
4820 public function __construct() {
4821 $name = 'calendar_weekend';
4822 $visiblename = get_string('calendar_weekend', 'admin');
4823 $description = get_string('helpweekenddays', 'admin');
4824 $default = array ('0', '6'); // Saturdays and Sundays
4825 parent::__construct($name, $visiblename, $description, $default);
4829 * Gets the current settings as an array
4831 * @return mixed Null if none, else array of settings
4833 public function get_setting() {
4834 $result = $this->config_read($this->name);
4835 if (is_null($result)) {
4836 return NULL;
4838 if ($result === '') {
4839 return array();
4841 $settings = array();
4842 for ($i=0; $i<7; $i++) {
4843 if ($result & (1 << $i)) {
4844 $settings[] = $i;
4847 return $settings;
4851 * Save the new settings
4853 * @param array $data Array of new settings
4854 * @return bool
4856 public function write_setting($data) {
4857 if (!is_array($data)) {
4858 return '';
4860 unset($data['xxxxx']);
4861 $result = 0;
4862 foreach($data as $index) {
4863 $result |= 1 << $index;
4865 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4869 * Return XHTML to display the control
4871 * @param array $data array of selected days
4872 * @param string $query
4873 * @return string XHTML for display (field + wrapping div(s)
4875 public function output_html($data, $query='') {
4876 global $OUTPUT;
4878 // The order matters very much because of the implied numeric keys.
4879 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4880 $context = (object) [
4881 'name' => $this->get_full_name(),
4882 'id' => $this->get_id(),
4883 'days' => array_map(function($index) use ($days, $data) {
4884 return [
4885 'index' => $index,
4886 'label' => get_string($days[$index], 'calendar'),
4887 'checked' => in_array($index, $data)
4889 }, array_keys($days))
4892 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
4894 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4901 * Admin setting that allows a user to pick a behaviour.
4903 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4905 class admin_setting_question_behaviour extends admin_setting_configselect {
4907 * @param string $name name of config variable
4908 * @param string $visiblename display name
4909 * @param string $description description
4910 * @param string $default default.
4912 public function __construct($name, $visiblename, $description, $default) {
4913 parent::__construct($name, $visiblename, $description, $default, null);
4917 * Load list of behaviours as choices
4918 * @return bool true => success, false => error.
4920 public function load_choices() {
4921 global $CFG;
4922 require_once($CFG->dirroot . '/question/engine/lib.php');
4923 $this->choices = question_engine::get_behaviour_options('');
4924 return true;
4930 * Admin setting that allows a user to pick appropriate roles for something.
4932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4934 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4935 /** @var array Array of capabilities which identify roles */
4936 private $types;
4939 * @param string $name Name of config variable
4940 * @param string $visiblename Display name
4941 * @param string $description Description
4942 * @param array $types Array of archetypes which identify
4943 * roles that will be enabled by default.
4945 public function __construct($name, $visiblename, $description, $types) {
4946 parent::__construct($name, $visiblename, $description, NULL, NULL);
4947 $this->types = $types;
4951 * Load roles as choices
4953 * @return bool true=>success, false=>error
4955 public function load_choices() {
4956 global $CFG, $DB;
4957 if (during_initial_install()) {
4958 return false;
4960 if (is_array($this->choices)) {
4961 return true;
4963 if ($roles = get_all_roles()) {
4964 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4965 return true;
4966 } else {
4967 return false;
4972 * Return the default setting for this control
4974 * @return array Array of default settings
4976 public function get_defaultsetting() {
4977 global $CFG;
4979 if (during_initial_install()) {
4980 return null;
4982 $result = array();
4983 foreach($this->types as $archetype) {
4984 if ($caproles = get_archetype_roles($archetype)) {
4985 foreach ($caproles as $caprole) {
4986 $result[$caprole->id] = 1;
4990 return $result;
4996 * Admin setting that is a list of installed filter plugins.
4998 * @copyright 2015 The Open University
4999 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5001 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5004 * Constructor
5006 * @param string $name unique ascii name, either 'mysetting' for settings
5007 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5008 * @param string $visiblename localised name
5009 * @param string $description localised long description
5010 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5012 public function __construct($name, $visiblename, $description, $default) {
5013 if (empty($default)) {
5014 $default = array();
5016 $this->load_choices();
5017 foreach ($default as $plugin) {
5018 if (!isset($this->choices[$plugin])) {
5019 unset($default[$plugin]);
5022 parent::__construct($name, $visiblename, $description, $default, null);
5025 public function load_choices() {
5026 if (is_array($this->choices)) {
5027 return true;
5029 $this->choices = array();
5031 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5032 $this->choices[$plugin] = filter_get_name($plugin);
5034 return true;
5040 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5044 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5046 * Constructor
5047 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5048 * @param string $visiblename localised
5049 * @param string $description long localised info
5050 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5051 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5052 * @param int $size default field size
5054 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5055 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5056 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5062 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5064 * @copyright 2009 Petr Skoda (http://skodak.org)
5065 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5067 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5070 * Constructor
5071 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5072 * @param string $visiblename localised
5073 * @param string $description long localised info
5074 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5075 * @param string $yes value used when checked
5076 * @param string $no value used when not checked
5078 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5079 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5080 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5087 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5089 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5091 * @copyright 2010 Sam Hemelryk
5092 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5094 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5096 * Constructor
5097 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5098 * @param string $visiblename localised
5099 * @param string $description long localised info
5100 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5101 * @param string $yes value used when checked
5102 * @param string $no value used when not checked
5104 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5105 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5106 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5113 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5117 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5119 * Calls parent::__construct with specific arguments
5121 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5122 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5123 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5129 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5131 * @copyright 2017 Marina Glancy
5132 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5134 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5136 * Constructor
5137 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5138 * or 'myplugin/mysetting' for ones in config_plugins.
5139 * @param string $visiblename localised
5140 * @param string $description long localised info
5141 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5142 * @param array $choices array of $value=>$label for each selection
5144 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5145 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5146 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5152 * Graded roles in gradebook
5154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5156 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5158 * Calls parent::__construct with specific arguments
5160 public function __construct() {
5161 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5162 get_string('configgradebookroles', 'admin'),
5163 array('student'));
5170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5172 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5174 * Saves the new settings passed in $data
5176 * @param string $data
5177 * @return mixed string or Array
5179 public function write_setting($data) {
5180 global $CFG, $DB;
5182 $oldvalue = $this->config_read($this->name);
5183 $return = parent::write_setting($data);
5184 $newvalue = $this->config_read($this->name);
5186 if ($oldvalue !== $newvalue) {
5187 // force full regrading
5188 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5191 return $return;
5197 * Which roles to show on course description page
5199 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5201 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5203 * Calls parent::__construct with specific arguments
5205 public function __construct() {
5206 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5207 get_string('coursecontact_desc', 'admin'),
5208 array('editingteacher'));
5209 $this->set_updatedcallback(create_function('',
5210 "cache::make('core', 'coursecontacts')->purge();"));
5217 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5219 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5221 * Calls parent::__construct with specific arguments
5223 public function __construct() {
5224 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5225 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5229 * Old syntax of class constructor. Deprecated in PHP7.
5231 * @deprecated since Moodle 3.1
5233 public function admin_setting_special_gradelimiting() {
5234 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5235 self::__construct();
5239 * Force site regrading
5241 function regrade_all() {
5242 global $CFG;
5243 require_once("$CFG->libdir/gradelib.php");
5244 grade_force_site_regrading();
5248 * Saves the new settings
5250 * @param mixed $data
5251 * @return string empty string or error message
5253 function write_setting($data) {
5254 $previous = $this->get_setting();
5256 if ($previous === null) {
5257 if ($data) {
5258 $this->regrade_all();
5260 } else {
5261 if ($data != $previous) {
5262 $this->regrade_all();
5265 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5271 * Special setting for $CFG->grade_minmaxtouse.
5273 * @package core
5274 * @copyright 2015 Frédéric Massart - FMCorz.net
5275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5277 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5280 * Constructor.
5282 public function __construct() {
5283 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5284 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5285 array(
5286 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5287 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5293 * Saves the new setting.
5295 * @param mixed $data
5296 * @return string empty string or error message
5298 function write_setting($data) {
5299 global $CFG;
5301 $previous = $this->get_setting();
5302 $result = parent::write_setting($data);
5304 // If saved and the value has changed.
5305 if (empty($result) && $previous != $data) {
5306 require_once($CFG->libdir . '/gradelib.php');
5307 grade_force_site_regrading();
5310 return $result;
5317 * Primary grade export plugin - has state tracking.
5319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5321 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5323 * Calls parent::__construct with specific arguments
5325 public function __construct() {
5326 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5327 get_string('configgradeexport', 'admin'), array(), NULL);
5331 * Load the available choices for the multicheckbox
5333 * @return bool always returns true
5335 public function load_choices() {
5336 if (is_array($this->choices)) {
5337 return true;
5339 $this->choices = array();
5341 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5342 foreach($plugins as $plugin => $unused) {
5343 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5346 return true;
5352 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5356 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5358 * Config gradepointmax constructor
5360 * @param string $name Overidden by "gradepointmax"
5361 * @param string $visiblename Overridden by "gradepointmax" language string.
5362 * @param string $description Overridden by "gradepointmax_help" language string.
5363 * @param string $defaultsetting Not used, overridden by 100.
5364 * @param mixed $paramtype Overridden by PARAM_INT.
5365 * @param int $size Overridden by 5.
5367 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5368 $name = 'gradepointdefault';
5369 $visiblename = get_string('gradepointdefault', 'grades');
5370 $description = get_string('gradepointdefault_help', 'grades');
5371 $defaultsetting = 100;
5372 $paramtype = PARAM_INT;
5373 $size = 5;
5374 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5378 * Validate data before storage
5379 * @param string $data The submitted data
5380 * @return bool|string true if ok, string if error found
5382 public function validate($data) {
5383 global $CFG;
5384 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5385 return true;
5386 } else {
5387 return get_string('gradepointdefault_validateerror', 'grades');
5394 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5398 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5401 * Config gradepointmax constructor
5403 * @param string $name Overidden by "gradepointmax"
5404 * @param string $visiblename Overridden by "gradepointmax" language string.
5405 * @param string $description Overridden by "gradepointmax_help" language string.
5406 * @param string $defaultsetting Not used, overridden by 100.
5407 * @param mixed $paramtype Overridden by PARAM_INT.
5408 * @param int $size Overridden by 5.
5410 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5411 $name = 'gradepointmax';
5412 $visiblename = get_string('gradepointmax', 'grades');
5413 $description = get_string('gradepointmax_help', 'grades');
5414 $defaultsetting = 100;
5415 $paramtype = PARAM_INT;
5416 $size = 5;
5417 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5421 * Save the selected setting
5423 * @param string $data The selected site
5424 * @return string empty string or error message
5426 public function write_setting($data) {
5427 if ($data === '') {
5428 $data = (int)$this->defaultsetting;
5429 } else {
5430 $data = $data;
5432 return parent::write_setting($data);
5436 * Validate data before storage
5437 * @param string $data The submitted data
5438 * @return bool|string true if ok, string if error found
5440 public function validate($data) {
5441 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5442 return true;
5443 } else {
5444 return get_string('gradepointmax_validateerror', 'grades');
5449 * Return an XHTML string for the setting
5450 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5451 * @param string $query search query to be highlighted
5452 * @return string XHTML to display control
5454 public function output_html($data, $query = '') {
5455 global $OUTPUT;
5457 $default = $this->get_defaultsetting();
5458 $context = (object) [
5459 'size' => $this->size,
5460 'id' => $this->get_id(),
5461 'name' => $this->get_full_name(),
5462 'value' => $data,
5463 'attributes' => [
5464 'maxlength' => 5
5466 'forceltr' => $this->get_force_ltr()
5468 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5470 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5476 * Grade category settings
5478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5480 class admin_setting_gradecat_combo extends admin_setting {
5481 /** @var array Array of choices */
5482 public $choices;
5485 * Sets choices and calls parent::__construct with passed arguments
5486 * @param string $name
5487 * @param string $visiblename
5488 * @param string $description
5489 * @param mixed $defaultsetting string or array depending on implementation
5490 * @param array $choices An array of choices for the control
5492 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5493 $this->choices = $choices;
5494 parent::__construct($name, $visiblename, $description, $defaultsetting);
5498 * Return the current setting(s) array
5500 * @return array Array of value=>xx, forced=>xx, adv=>xx
5502 public function get_setting() {
5503 global $CFG;
5505 $value = $this->config_read($this->name);
5506 $flag = $this->config_read($this->name.'_flag');
5508 if (is_null($value) or is_null($flag)) {
5509 return NULL;
5512 $flag = (int)$flag;
5513 $forced = (boolean)(1 & $flag); // first bit
5514 $adv = (boolean)(2 & $flag); // second bit
5516 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5520 * Save the new settings passed in $data
5522 * @todo Add vartype handling to ensure $data is array
5523 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5524 * @return string empty or error message
5526 public function write_setting($data) {
5527 global $CFG;
5529 $value = $data['value'];
5530 $forced = empty($data['forced']) ? 0 : 1;
5531 $adv = empty($data['adv']) ? 0 : 2;
5532 $flag = ($forced | $adv); //bitwise or
5534 if (!in_array($value, array_keys($this->choices))) {
5535 return 'Error setting ';
5538 $oldvalue = $this->config_read($this->name);
5539 $oldflag = (int)$this->config_read($this->name.'_flag');
5540 $oldforced = (1 & $oldflag); // first bit
5542 $result1 = $this->config_write($this->name, $value);
5543 $result2 = $this->config_write($this->name.'_flag', $flag);
5545 // force regrade if needed
5546 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5547 require_once($CFG->libdir.'/gradelib.php');
5548 grade_category::updated_forced_settings();
5551 if ($result1 and $result2) {
5552 return '';
5553 } else {
5554 return get_string('errorsetting', 'admin');
5559 * Return XHTML to display the field and wrapping div
5561 * @todo Add vartype handling to ensure $data is array
5562 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5563 * @param string $query
5564 * @return string XHTML to display control
5566 public function output_html($data, $query='') {
5567 global $OUTPUT;
5569 $value = $data['value'];
5571 $default = $this->get_defaultsetting();
5572 if (!is_null($default)) {
5573 $defaultinfo = array();
5574 if (isset($this->choices[$default['value']])) {
5575 $defaultinfo[] = $this->choices[$default['value']];
5577 if (!empty($default['forced'])) {
5578 $defaultinfo[] = get_string('force');
5580 if (!empty($default['adv'])) {
5581 $defaultinfo[] = get_string('advanced');
5583 $defaultinfo = implode(', ', $defaultinfo);
5585 } else {
5586 $defaultinfo = NULL;
5589 $options = $this->choices;
5590 $context = (object) [
5591 'id' => $this->get_id(),
5592 'name' => $this->get_full_name(),
5593 'forced' => !empty($data['forced']),
5594 'advanced' => !empty($data['adv']),
5595 'options' => array_map(function($option) use ($options, $value) {
5596 return [
5597 'value' => $option,
5598 'name' => $options[$option],
5599 'selected' => $option == $value
5601 }, array_keys($options)),
5604 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5606 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5612 * Selection of grade report in user profiles
5614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5616 class admin_setting_grade_profilereport extends admin_setting_configselect {
5618 * Calls parent::__construct with specific arguments
5620 public function __construct() {
5621 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5625 * Loads an array of choices for the configselect control
5627 * @return bool always return true
5629 public function load_choices() {
5630 if (is_array($this->choices)) {
5631 return true;
5633 $this->choices = array();
5635 global $CFG;
5636 require_once($CFG->libdir.'/gradelib.php');
5638 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5639 if (file_exists($plugindir.'/lib.php')) {
5640 require_once($plugindir.'/lib.php');
5641 $functionname = 'grade_report_'.$plugin.'_profilereport';
5642 if (function_exists($functionname)) {
5643 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5647 return true;
5652 * Provides a selection of grade reports to be used for "grades".
5654 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5655 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5657 class admin_setting_my_grades_report extends admin_setting_configselect {
5660 * Calls parent::__construct with specific arguments.
5662 public function __construct() {
5663 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5664 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5668 * Loads an array of choices for the configselect control.
5670 * @return bool always returns true.
5672 public function load_choices() {
5673 global $CFG; // Remove this line and behold the horror of behat test failures!
5674 $this->choices = array();
5675 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5676 if (file_exists($plugindir . '/lib.php')) {
5677 require_once($plugindir . '/lib.php');
5678 // Check to see if the class exists. Check the correct plugin convention first.
5679 if (class_exists('gradereport_' . $plugin)) {
5680 $classname = 'gradereport_' . $plugin;
5681 } else if (class_exists('grade_report_' . $plugin)) {
5682 // We are using the old plugin naming convention.
5683 $classname = 'grade_report_' . $plugin;
5684 } else {
5685 continue;
5687 if ($classname::supports_mygrades()) {
5688 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5692 // Add an option to specify an external url.
5693 $this->choices['external'] = get_string('externalurl', 'grades');
5694 return true;
5699 * Special class for register auth selection
5701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5703 class admin_setting_special_registerauth extends admin_setting_configselect {
5705 * Calls parent::__construct with specific arguments
5707 public function __construct() {
5708 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5712 * Returns the default option
5714 * @return string empty or default option
5716 public function get_defaultsetting() {
5717 $this->load_choices();
5718 $defaultsetting = parent::get_defaultsetting();
5719 if (array_key_exists($defaultsetting, $this->choices)) {
5720 return $defaultsetting;
5721 } else {
5722 return '';
5727 * Loads the possible choices for the array
5729 * @return bool always returns true
5731 public function load_choices() {
5732 global $CFG;
5734 if (is_array($this->choices)) {
5735 return true;
5737 $this->choices = array();
5738 $this->choices[''] = get_string('disable');
5740 $authsenabled = get_enabled_auth_plugins(true);
5742 foreach ($authsenabled as $auth) {
5743 $authplugin = get_auth_plugin($auth);
5744 if (!$authplugin->can_signup()) {
5745 continue;
5747 // Get the auth title (from core or own auth lang files)
5748 $authtitle = $authplugin->get_title();
5749 $this->choices[$auth] = $authtitle;
5751 return true;
5757 * General plugins manager
5759 class admin_page_pluginsoverview extends admin_externalpage {
5762 * Sets basic information about the external page
5764 public function __construct() {
5765 global $CFG;
5766 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5767 "$CFG->wwwroot/$CFG->admin/plugins.php");
5772 * Module manage page
5774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5776 class admin_page_managemods extends admin_externalpage {
5778 * Calls parent::__construct with specific arguments
5780 public function __construct() {
5781 global $CFG;
5782 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5786 * Try to find the specified module
5788 * @param string $query The module to search for
5789 * @return array
5791 public function search($query) {
5792 global $CFG, $DB;
5793 if ($result = parent::search($query)) {
5794 return $result;
5797 $found = false;
5798 if ($modules = $DB->get_records('modules')) {
5799 foreach ($modules as $module) {
5800 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5801 continue;
5803 if (strpos($module->name, $query) !== false) {
5804 $found = true;
5805 break;
5807 $strmodulename = get_string('modulename', $module->name);
5808 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5809 $found = true;
5810 break;
5814 if ($found) {
5815 $result = new stdClass();
5816 $result->page = $this;
5817 $result->settings = array();
5818 return array($this->name => $result);
5819 } else {
5820 return array();
5827 * Special class for enrol plugins management.
5829 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5832 class admin_setting_manageenrols extends admin_setting {
5834 * Calls parent::__construct with specific arguments
5836 public function __construct() {
5837 $this->nosave = true;
5838 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5842 * Always returns true, does nothing
5844 * @return true
5846 public function get_setting() {
5847 return true;
5851 * Always returns true, does nothing
5853 * @return true
5855 public function get_defaultsetting() {
5856 return true;
5860 * Always returns '', does not write anything
5862 * @return string Always returns ''
5864 public function write_setting($data) {
5865 // do not write any setting
5866 return '';
5870 * Checks if $query is one of the available enrol plugins
5872 * @param string $query The string to search for
5873 * @return bool Returns true if found, false if not
5875 public function is_related($query) {
5876 if (parent::is_related($query)) {
5877 return true;
5880 $query = core_text::strtolower($query);
5881 $enrols = enrol_get_plugins(false);
5882 foreach ($enrols as $name=>$enrol) {
5883 $localised = get_string('pluginname', 'enrol_'.$name);
5884 if (strpos(core_text::strtolower($name), $query) !== false) {
5885 return true;
5887 if (strpos(core_text::strtolower($localised), $query) !== false) {
5888 return true;
5891 return false;
5895 * Builds the XHTML to display the control
5897 * @param string $data Unused
5898 * @param string $query
5899 * @return string
5901 public function output_html($data, $query='') {
5902 global $CFG, $OUTPUT, $DB, $PAGE;
5904 // Display strings.
5905 $strup = get_string('up');
5906 $strdown = get_string('down');
5907 $strsettings = get_string('settings');
5908 $strenable = get_string('enable');
5909 $strdisable = get_string('disable');
5910 $struninstall = get_string('uninstallplugin', 'core_admin');
5911 $strusage = get_string('enrolusage', 'enrol');
5912 $strversion = get_string('version');
5913 $strtest = get_string('testsettings', 'core_enrol');
5915 $pluginmanager = core_plugin_manager::instance();
5917 $enrols_available = enrol_get_plugins(false);
5918 $active_enrols = enrol_get_plugins(true);
5920 $allenrols = array();
5921 foreach ($active_enrols as $key=>$enrol) {
5922 $allenrols[$key] = true;
5924 foreach ($enrols_available as $key=>$enrol) {
5925 $allenrols[$key] = true;
5927 // Now find all borked plugins and at least allow then to uninstall.
5928 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5929 foreach ($condidates as $candidate) {
5930 if (empty($allenrols[$candidate])) {
5931 $allenrols[$candidate] = true;
5935 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5936 $return .= $OUTPUT->box_start('generalbox enrolsui');
5938 $table = new html_table();
5939 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5940 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5941 $table->id = 'courseenrolmentplugins';
5942 $table->attributes['class'] = 'admintable generaltable';
5943 $table->data = array();
5945 // Iterate through enrol plugins and add to the display table.
5946 $updowncount = 1;
5947 $enrolcount = count($active_enrols);
5948 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5949 $printed = array();
5950 foreach($allenrols as $enrol => $unused) {
5951 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5952 $version = get_config('enrol_'.$enrol, 'version');
5953 if ($version === false) {
5954 $version = '';
5957 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5958 $name = get_string('pluginname', 'enrol_'.$enrol);
5959 } else {
5960 $name = $enrol;
5962 // Usage.
5963 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5964 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5965 $usage = "$ci / $cp";
5967 // Hide/show links.
5968 $class = '';
5969 if (isset($active_enrols[$enrol])) {
5970 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5971 $hideshow = "<a href=\"$aurl\">";
5972 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
5973 $enabled = true;
5974 $displayname = $name;
5975 } else if (isset($enrols_available[$enrol])) {
5976 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5977 $hideshow = "<a href=\"$aurl\">";
5978 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
5979 $enabled = false;
5980 $displayname = $name;
5981 $class = 'dimmed_text';
5982 } else {
5983 $hideshow = '';
5984 $enabled = false;
5985 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5987 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5988 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5989 } else {
5990 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5993 // Up/down link (only if enrol is enabled).
5994 $updown = '';
5995 if ($enabled) {
5996 if ($updowncount > 1) {
5997 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5998 $updown .= "<a href=\"$aurl\">";
5999 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
6000 } else {
6001 $updown .= $OUTPUT->spacer() . '&nbsp;';
6003 if ($updowncount < $enrolcount) {
6004 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6005 $updown .= "<a href=\"$aurl\">";
6006 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6007 } else {
6008 $updown .= $OUTPUT->spacer() . '&nbsp;';
6010 ++$updowncount;
6013 // Add settings link.
6014 if (!$version) {
6015 $settings = '';
6016 } else if ($surl = $plugininfo->get_settings_url()) {
6017 $settings = html_writer::link($surl, $strsettings);
6018 } else {
6019 $settings = '';
6022 // Add uninstall info.
6023 $uninstall = '';
6024 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6025 $uninstall = html_writer::link($uninstallurl, $struninstall);
6028 $test = '';
6029 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6030 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6031 $test = html_writer::link($testsettingsurl, $strtest);
6034 // Add a row to the table.
6035 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6036 if ($class) {
6037 $row->attributes['class'] = $class;
6039 $table->data[] = $row;
6041 $printed[$enrol] = true;
6044 $return .= html_writer::table($table);
6045 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6046 $return .= $OUTPUT->box_end();
6047 return highlight($query, $return);
6053 * Blocks manage page
6055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6057 class admin_page_manageblocks extends admin_externalpage {
6059 * Calls parent::__construct with specific arguments
6061 public function __construct() {
6062 global $CFG;
6063 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6067 * Search for a specific block
6069 * @param string $query The string to search for
6070 * @return array
6072 public function search($query) {
6073 global $CFG, $DB;
6074 if ($result = parent::search($query)) {
6075 return $result;
6078 $found = false;
6079 if ($blocks = $DB->get_records('block')) {
6080 foreach ($blocks as $block) {
6081 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6082 continue;
6084 if (strpos($block->name, $query) !== false) {
6085 $found = true;
6086 break;
6088 $strblockname = get_string('pluginname', 'block_'.$block->name);
6089 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6090 $found = true;
6091 break;
6095 if ($found) {
6096 $result = new stdClass();
6097 $result->page = $this;
6098 $result->settings = array();
6099 return array($this->name => $result);
6100 } else {
6101 return array();
6107 * Message outputs configuration
6109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6111 class admin_page_managemessageoutputs extends admin_externalpage {
6113 * Calls parent::__construct with specific arguments
6115 public function __construct() {
6116 global $CFG;
6117 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
6121 * Search for a specific message processor
6123 * @param string $query The string to search for
6124 * @return array
6126 public function search($query) {
6127 global $CFG, $DB;
6128 if ($result = parent::search($query)) {
6129 return $result;
6132 $found = false;
6133 if ($processors = get_message_processors()) {
6134 foreach ($processors as $processor) {
6135 if (!$processor->available) {
6136 continue;
6138 if (strpos($processor->name, $query) !== false) {
6139 $found = true;
6140 break;
6142 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6143 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6144 $found = true;
6145 break;
6149 if ($found) {
6150 $result = new stdClass();
6151 $result->page = $this;
6152 $result->settings = array();
6153 return array($this->name => $result);
6154 } else {
6155 return array();
6161 * Default message outputs configuration
6163 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6165 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6167 * Calls parent::__construct with specific arguments
6169 public function __construct() {
6170 global $CFG;
6171 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6177 * Manage question behaviours page
6179 * @copyright 2011 The Open University
6180 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6182 class admin_page_manageqbehaviours extends admin_externalpage {
6184 * Constructor
6186 public function __construct() {
6187 global $CFG;
6188 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6189 new moodle_url('/admin/qbehaviours.php'));
6193 * Search question behaviours for the specified string
6195 * @param string $query The string to search for in question behaviours
6196 * @return array
6198 public function search($query) {
6199 global $CFG;
6200 if ($result = parent::search($query)) {
6201 return $result;
6204 $found = false;
6205 require_once($CFG->dirroot . '/question/engine/lib.php');
6206 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6207 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6208 $query) !== false) {
6209 $found = true;
6210 break;
6213 if ($found) {
6214 $result = new stdClass();
6215 $result->page = $this;
6216 $result->settings = array();
6217 return array($this->name => $result);
6218 } else {
6219 return array();
6226 * Question type manage page
6228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6230 class admin_page_manageqtypes extends admin_externalpage {
6232 * Calls parent::__construct with specific arguments
6234 public function __construct() {
6235 global $CFG;
6236 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6237 new moodle_url('/admin/qtypes.php'));
6241 * Search question types for the specified string
6243 * @param string $query The string to search for in question types
6244 * @return array
6246 public function search($query) {
6247 global $CFG;
6248 if ($result = parent::search($query)) {
6249 return $result;
6252 $found = false;
6253 require_once($CFG->dirroot . '/question/engine/bank.php');
6254 foreach (question_bank::get_all_qtypes() as $qtype) {
6255 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6256 $found = true;
6257 break;
6260 if ($found) {
6261 $result = new stdClass();
6262 $result->page = $this;
6263 $result->settings = array();
6264 return array($this->name => $result);
6265 } else {
6266 return array();
6272 class admin_page_manageportfolios extends admin_externalpage {
6274 * Calls parent::__construct with specific arguments
6276 public function __construct() {
6277 global $CFG;
6278 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6279 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6283 * Searches page for the specified string.
6284 * @param string $query The string to search for
6285 * @return bool True if it is found on this page
6287 public function search($query) {
6288 global $CFG;
6289 if ($result = parent::search($query)) {
6290 return $result;
6293 $found = false;
6294 $portfolios = core_component::get_plugin_list('portfolio');
6295 foreach ($portfolios as $p => $dir) {
6296 if (strpos($p, $query) !== false) {
6297 $found = true;
6298 break;
6301 if (!$found) {
6302 foreach (portfolio_instances(false, false) as $instance) {
6303 $title = $instance->get('name');
6304 if (strpos(core_text::strtolower($title), $query) !== false) {
6305 $found = true;
6306 break;
6311 if ($found) {
6312 $result = new stdClass();
6313 $result->page = $this;
6314 $result->settings = array();
6315 return array($this->name => $result);
6316 } else {
6317 return array();
6323 class admin_page_managerepositories extends admin_externalpage {
6325 * Calls parent::__construct with specific arguments
6327 public function __construct() {
6328 global $CFG;
6329 parent::__construct('managerepositories', get_string('manage',
6330 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6334 * Searches page for the specified string.
6335 * @param string $query The string to search for
6336 * @return bool True if it is found on this page
6338 public function search($query) {
6339 global $CFG;
6340 if ($result = parent::search($query)) {
6341 return $result;
6344 $found = false;
6345 $repositories= core_component::get_plugin_list('repository');
6346 foreach ($repositories as $p => $dir) {
6347 if (strpos($p, $query) !== false) {
6348 $found = true;
6349 break;
6352 if (!$found) {
6353 foreach (repository::get_types() as $instance) {
6354 $title = $instance->get_typename();
6355 if (strpos(core_text::strtolower($title), $query) !== false) {
6356 $found = true;
6357 break;
6362 if ($found) {
6363 $result = new stdClass();
6364 $result->page = $this;
6365 $result->settings = array();
6366 return array($this->name => $result);
6367 } else {
6368 return array();
6375 * Special class for authentication administration.
6377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6379 class admin_setting_manageauths extends admin_setting {
6381 * Calls parent::__construct with specific arguments
6383 public function __construct() {
6384 $this->nosave = true;
6385 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6389 * Always returns true
6391 * @return true
6393 public function get_setting() {
6394 return true;
6398 * Always returns true
6400 * @return true
6402 public function get_defaultsetting() {
6403 return true;
6407 * Always returns '' and doesn't write anything
6409 * @return string Always returns ''
6411 public function write_setting($data) {
6412 // do not write any setting
6413 return '';
6417 * Search to find if Query is related to auth plugin
6419 * @param string $query The string to search for
6420 * @return bool true for related false for not
6422 public function is_related($query) {
6423 if (parent::is_related($query)) {
6424 return true;
6427 $authsavailable = core_component::get_plugin_list('auth');
6428 foreach ($authsavailable as $auth => $dir) {
6429 if (strpos($auth, $query) !== false) {
6430 return true;
6432 $authplugin = get_auth_plugin($auth);
6433 $authtitle = $authplugin->get_title();
6434 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6435 return true;
6438 return false;
6442 * Return XHTML to display control
6444 * @param mixed $data Unused
6445 * @param string $query
6446 * @return string highlight
6448 public function output_html($data, $query='') {
6449 global $CFG, $OUTPUT, $DB;
6451 // display strings
6452 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6453 'settings', 'edit', 'name', 'enable', 'disable',
6454 'up', 'down', 'none', 'users'));
6455 $txt->updown = "$txt->up/$txt->down";
6456 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6457 $txt->testsettings = get_string('testsettings', 'core_auth');
6459 $authsavailable = core_component::get_plugin_list('auth');
6460 get_enabled_auth_plugins(true); // fix the list of enabled auths
6461 if (empty($CFG->auth)) {
6462 $authsenabled = array();
6463 } else {
6464 $authsenabled = explode(',', $CFG->auth);
6467 // construct the display array, with enabled auth plugins at the top, in order
6468 $displayauths = array();
6469 $registrationauths = array();
6470 $registrationauths[''] = $txt->disable;
6471 $authplugins = array();
6472 foreach ($authsenabled as $auth) {
6473 $authplugin = get_auth_plugin($auth);
6474 $authplugins[$auth] = $authplugin;
6475 /// Get the auth title (from core or own auth lang files)
6476 $authtitle = $authplugin->get_title();
6477 /// Apply titles
6478 $displayauths[$auth] = $authtitle;
6479 if ($authplugin->can_signup()) {
6480 $registrationauths[$auth] = $authtitle;
6484 foreach ($authsavailable as $auth => $dir) {
6485 if (array_key_exists($auth, $displayauths)) {
6486 continue; //already in the list
6488 $authplugin = get_auth_plugin($auth);
6489 $authplugins[$auth] = $authplugin;
6490 /// Get the auth title (from core or own auth lang files)
6491 $authtitle = $authplugin->get_title();
6492 /// Apply titles
6493 $displayauths[$auth] = $authtitle;
6494 if ($authplugin->can_signup()) {
6495 $registrationauths[$auth] = $authtitle;
6499 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6500 $return .= $OUTPUT->box_start('generalbox authsui');
6502 $table = new html_table();
6503 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6504 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6505 $table->data = array();
6506 $table->attributes['class'] = 'admintable generaltable';
6507 $table->id = 'manageauthtable';
6509 //add always enabled plugins first
6510 $displayname = $displayauths['manual'];
6511 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6512 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6513 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6514 $displayname = $displayauths['nologin'];
6515 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6516 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6519 // iterate through auth plugins and add to the display table
6520 $updowncount = 1;
6521 $authcount = count($authsenabled);
6522 $url = "auth.php?sesskey=" . sesskey();
6523 foreach ($displayauths as $auth => $name) {
6524 if ($auth == 'manual' or $auth == 'nologin') {
6525 continue;
6527 $class = '';
6528 // hide/show link
6529 if (in_array($auth, $authsenabled)) {
6530 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6531 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6532 $enabled = true;
6533 $displayname = $name;
6535 else {
6536 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6537 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6538 $enabled = false;
6539 $displayname = $name;
6540 $class = 'dimmed_text';
6543 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6545 // up/down link (only if auth is enabled)
6546 $updown = '';
6547 if ($enabled) {
6548 if ($updowncount > 1) {
6549 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6550 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6552 else {
6553 $updown .= $OUTPUT->spacer() . '&nbsp;';
6555 if ($updowncount < $authcount) {
6556 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6557 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6559 else {
6560 $updown .= $OUTPUT->spacer() . '&nbsp;';
6562 ++ $updowncount;
6565 // settings link
6566 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6567 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6568 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6569 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6570 } else {
6571 $settings = '';
6574 // Uninstall link.
6575 $uninstall = '';
6576 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6577 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6580 $test = '';
6581 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6582 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6583 $test = html_writer::link($testurl, $txt->testsettings);
6586 // Add a row to the table.
6587 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6588 if ($class) {
6589 $row->attributes['class'] = $class;
6591 $table->data[] = $row;
6593 $return .= html_writer::table($table);
6594 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6595 $return .= $OUTPUT->box_end();
6596 return highlight($query, $return);
6602 * Special class for authentication administration.
6604 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6606 class admin_setting_manageeditors extends admin_setting {
6608 * Calls parent::__construct with specific arguments
6610 public function __construct() {
6611 $this->nosave = true;
6612 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6616 * Always returns true, does nothing
6618 * @return true
6620 public function get_setting() {
6621 return true;
6625 * Always returns true, does nothing
6627 * @return true
6629 public function get_defaultsetting() {
6630 return true;
6634 * Always returns '', does not write anything
6636 * @return string Always returns ''
6638 public function write_setting($data) {
6639 // do not write any setting
6640 return '';
6644 * Checks if $query is one of the available editors
6646 * @param string $query The string to search for
6647 * @return bool Returns true if found, false if not
6649 public function is_related($query) {
6650 if (parent::is_related($query)) {
6651 return true;
6654 $editors_available = editors_get_available();
6655 foreach ($editors_available as $editor=>$editorstr) {
6656 if (strpos($editor, $query) !== false) {
6657 return true;
6659 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6660 return true;
6663 return false;
6667 * Builds the XHTML to display the control
6669 * @param string $data Unused
6670 * @param string $query
6671 * @return string
6673 public function output_html($data, $query='') {
6674 global $CFG, $OUTPUT;
6676 // display strings
6677 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6678 'up', 'down', 'none'));
6679 $struninstall = get_string('uninstallplugin', 'core_admin');
6681 $txt->updown = "$txt->up/$txt->down";
6683 $editors_available = editors_get_available();
6684 $active_editors = explode(',', $CFG->texteditors);
6686 $active_editors = array_reverse($active_editors);
6687 foreach ($active_editors as $key=>$editor) {
6688 if (empty($editors_available[$editor])) {
6689 unset($active_editors[$key]);
6690 } else {
6691 $name = $editors_available[$editor];
6692 unset($editors_available[$editor]);
6693 $editors_available[$editor] = $name;
6696 if (empty($active_editors)) {
6697 //$active_editors = array('textarea');
6699 $editors_available = array_reverse($editors_available, true);
6700 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6701 $return .= $OUTPUT->box_start('generalbox editorsui');
6703 $table = new html_table();
6704 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6705 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6706 $table->id = 'editormanagement';
6707 $table->attributes['class'] = 'admintable generaltable';
6708 $table->data = array();
6710 // iterate through auth plugins and add to the display table
6711 $updowncount = 1;
6712 $editorcount = count($active_editors);
6713 $url = "editors.php?sesskey=" . sesskey();
6714 foreach ($editors_available as $editor => $name) {
6715 // hide/show link
6716 $class = '';
6717 if (in_array($editor, $active_editors)) {
6718 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6719 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6720 $enabled = true;
6721 $displayname = $name;
6723 else {
6724 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6725 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6726 $enabled = false;
6727 $displayname = $name;
6728 $class = 'dimmed_text';
6731 // up/down link (only if auth is enabled)
6732 $updown = '';
6733 if ($enabled) {
6734 if ($updowncount > 1) {
6735 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6736 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6738 else {
6739 $updown .= $OUTPUT->spacer() . '&nbsp;';
6741 if ($updowncount < $editorcount) {
6742 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6743 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6745 else {
6746 $updown .= $OUTPUT->spacer() . '&nbsp;';
6748 ++ $updowncount;
6751 // settings link
6752 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6753 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6754 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6755 } else {
6756 $settings = '';
6759 $uninstall = '';
6760 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6761 $uninstall = html_writer::link($uninstallurl, $struninstall);
6764 // Add a row to the table.
6765 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6766 if ($class) {
6767 $row->attributes['class'] = $class;
6769 $table->data[] = $row;
6771 $return .= html_writer::table($table);
6772 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6773 $return .= $OUTPUT->box_end();
6774 return highlight($query, $return);
6779 * Special class for antiviruses administration.
6781 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6784 class admin_setting_manageantiviruses extends admin_setting {
6786 * Calls parent::__construct with specific arguments
6788 public function __construct() {
6789 $this->nosave = true;
6790 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6794 * Always returns true, does nothing
6796 * @return true
6798 public function get_setting() {
6799 return true;
6803 * Always returns true, does nothing
6805 * @return true
6807 public function get_defaultsetting() {
6808 return true;
6812 * Always returns '', does not write anything
6814 * @param string $data Unused
6815 * @return string Always returns ''
6817 public function write_setting($data) {
6818 // Do not write any setting.
6819 return '';
6823 * Checks if $query is one of the available editors
6825 * @param string $query The string to search for
6826 * @return bool Returns true if found, false if not
6828 public function is_related($query) {
6829 if (parent::is_related($query)) {
6830 return true;
6833 $antivirusesavailable = \core\antivirus\manager::get_available();
6834 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6835 if (strpos($antivirus, $query) !== false) {
6836 return true;
6838 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6839 return true;
6842 return false;
6846 * Builds the XHTML to display the control
6848 * @param string $data Unused
6849 * @param string $query
6850 * @return string
6852 public function output_html($data, $query='') {
6853 global $CFG, $OUTPUT;
6855 // Display strings.
6856 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6857 'up', 'down', 'none'));
6858 $struninstall = get_string('uninstallplugin', 'core_admin');
6860 $txt->updown = "$txt->up/$txt->down";
6862 $antivirusesavailable = \core\antivirus\manager::get_available();
6863 $activeantiviruses = explode(',', $CFG->antiviruses);
6865 $activeantiviruses = array_reverse($activeantiviruses);
6866 foreach ($activeantiviruses as $key => $antivirus) {
6867 if (empty($antivirusesavailable[$antivirus])) {
6868 unset($activeantiviruses[$key]);
6869 } else {
6870 $name = $antivirusesavailable[$antivirus];
6871 unset($antivirusesavailable[$antivirus]);
6872 $antivirusesavailable[$antivirus] = $name;
6875 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6876 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6877 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6879 $table = new html_table();
6880 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6881 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6882 $table->id = 'antivirusmanagement';
6883 $table->attributes['class'] = 'admintable generaltable';
6884 $table->data = array();
6886 // Iterate through auth plugins and add to the display table.
6887 $updowncount = 1;
6888 $antiviruscount = count($activeantiviruses);
6889 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6890 foreach ($antivirusesavailable as $antivirus => $name) {
6891 // Hide/show link.
6892 $class = '';
6893 if (in_array($antivirus, $activeantiviruses)) {
6894 $hideshowurl = $baseurl;
6895 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6896 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
6897 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6898 $enabled = true;
6899 $displayname = $name;
6900 } else {
6901 $hideshowurl = $baseurl;
6902 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6903 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
6904 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6905 $enabled = false;
6906 $displayname = $name;
6907 $class = 'dimmed_text';
6910 // Up/down link.
6911 $updown = '';
6912 if ($enabled) {
6913 if ($updowncount > 1) {
6914 $updownurl = $baseurl;
6915 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6916 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
6917 $updown = html_writer::link($updownurl, $updownimg);
6918 } else {
6919 $updownimg = $OUTPUT->spacer();
6921 if ($updowncount < $antiviruscount) {
6922 $updownurl = $baseurl;
6923 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6924 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
6925 $updown = html_writer::link($updownurl, $updownimg);
6926 } else {
6927 $updownimg = $OUTPUT->spacer();
6929 ++ $updowncount;
6932 // Settings link.
6933 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6934 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6935 $settings = html_writer::link($eurl, $txt->settings);
6936 } else {
6937 $settings = '';
6940 $uninstall = '';
6941 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6942 $uninstall = html_writer::link($uninstallurl, $struninstall);
6945 // Add a row to the table.
6946 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6947 if ($class) {
6948 $row->attributes['class'] = $class;
6950 $table->data[] = $row;
6952 $return .= html_writer::table($table);
6953 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6954 $return .= $OUTPUT->box_end();
6955 return highlight($query, $return);
6960 * Special class for license administration.
6962 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6964 class admin_setting_managelicenses extends admin_setting {
6966 * Calls parent::__construct with specific arguments
6968 public function __construct() {
6969 $this->nosave = true;
6970 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6974 * Always returns true, does nothing
6976 * @return true
6978 public function get_setting() {
6979 return true;
6983 * Always returns true, does nothing
6985 * @return true
6987 public function get_defaultsetting() {
6988 return true;
6992 * Always returns '', does not write anything
6994 * @return string Always returns ''
6996 public function write_setting($data) {
6997 // do not write any setting
6998 return '';
7002 * Builds the XHTML to display the control
7004 * @param string $data Unused
7005 * @param string $query
7006 * @return string
7008 public function output_html($data, $query='') {
7009 global $CFG, $OUTPUT;
7010 require_once($CFG->libdir . '/licenselib.php');
7011 $url = "licenses.php?sesskey=" . sesskey();
7013 // display strings
7014 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
7015 $licenses = license_manager::get_licenses();
7017 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
7019 $return .= $OUTPUT->box_start('generalbox editorsui');
7021 $table = new html_table();
7022 $table->head = array($txt->name, $txt->enable);
7023 $table->colclasses = array('leftalign', 'centeralign');
7024 $table->id = 'availablelicenses';
7025 $table->attributes['class'] = 'admintable generaltable';
7026 $table->data = array();
7028 foreach ($licenses as $value) {
7029 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
7031 if ($value->enabled == 1) {
7032 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
7033 $OUTPUT->pix_icon('t/hide', get_string('disable')));
7034 } else {
7035 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
7036 $OUTPUT->pix_icon('t/show', get_string('enable')));
7039 if ($value->shortname == $CFG->sitedefaultlicense) {
7040 $displayname .= ' '.$OUTPUT->pix_icon('t/locked', get_string('default'));
7041 $hideshow = '';
7044 $enabled = true;
7046 $table->data[] =array($displayname, $hideshow);
7048 $return .= html_writer::table($table);
7049 $return .= $OUTPUT->box_end();
7050 return highlight($query, $return);
7055 * Course formats manager. Allows to enable/disable formats and jump to settings
7057 class admin_setting_manageformats extends admin_setting {
7060 * Calls parent::__construct with specific arguments
7062 public function __construct() {
7063 $this->nosave = true;
7064 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7068 * Always returns true
7070 * @return true
7072 public function get_setting() {
7073 return true;
7077 * Always returns true
7079 * @return true
7081 public function get_defaultsetting() {
7082 return true;
7086 * Always returns '' and doesn't write anything
7088 * @param mixed $data string or array, must not be NULL
7089 * @return string Always returns ''
7091 public function write_setting($data) {
7092 // do not write any setting
7093 return '';
7097 * Search to find if Query is related to format plugin
7099 * @param string $query The string to search for
7100 * @return bool true for related false for not
7102 public function is_related($query) {
7103 if (parent::is_related($query)) {
7104 return true;
7106 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7107 foreach ($formats as $format) {
7108 if (strpos($format->component, $query) !== false ||
7109 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7110 return true;
7113 return false;
7117 * Return XHTML to display control
7119 * @param mixed $data Unused
7120 * @param string $query
7121 * @return string highlight
7123 public function output_html($data, $query='') {
7124 global $CFG, $OUTPUT;
7125 $return = '';
7126 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7127 $return .= $OUTPUT->box_start('generalbox formatsui');
7129 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7131 // display strings
7132 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7133 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7134 $txt->updown = "$txt->up/$txt->down";
7136 $table = new html_table();
7137 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7138 $table->align = array('left', 'center', 'center', 'center', 'center');
7139 $table->attributes['class'] = 'manageformattable generaltable admintable';
7140 $table->data = array();
7142 $cnt = 0;
7143 $defaultformat = get_config('moodlecourse', 'format');
7144 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7145 foreach ($formats as $format) {
7146 $url = new moodle_url('/admin/courseformats.php',
7147 array('sesskey' => sesskey(), 'format' => $format->name));
7148 $isdefault = '';
7149 $class = '';
7150 if ($format->is_enabled()) {
7151 $strformatname = $format->displayname;
7152 if ($defaultformat === $format->name) {
7153 $hideshow = $txt->default;
7154 } else {
7155 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7156 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7158 } else {
7159 $strformatname = $format->displayname;
7160 $class = 'dimmed_text';
7161 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7162 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7164 $updown = '';
7165 if ($cnt) {
7166 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7167 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7168 } else {
7169 $updown .= $spacer;
7171 if ($cnt < count($formats) - 1) {
7172 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7173 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7174 } else {
7175 $updown .= $spacer;
7177 $cnt++;
7178 $settings = '';
7179 if ($format->get_settings_url()) {
7180 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7182 $uninstall = '';
7183 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7184 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7186 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7187 if ($class) {
7188 $row->attributes['class'] = $class;
7190 $table->data[] = $row;
7192 $return .= html_writer::table($table);
7193 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7194 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7195 $return .= $OUTPUT->box_end();
7196 return highlight($query, $return);
7201 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7203 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7206 class admin_setting_managedataformats extends admin_setting {
7209 * Calls parent::__construct with specific arguments
7211 public function __construct() {
7212 $this->nosave = true;
7213 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7217 * Always returns true
7219 * @return true
7221 public function get_setting() {
7222 return true;
7226 * Always returns true
7228 * @return true
7230 public function get_defaultsetting() {
7231 return true;
7235 * Always returns '' and doesn't write anything
7237 * @param mixed $data string or array, must not be NULL
7238 * @return string Always returns ''
7240 public function write_setting($data) {
7241 // Do not write any setting.
7242 return '';
7246 * Search to find if Query is related to format plugin
7248 * @param string $query The string to search for
7249 * @return bool true for related false for not
7251 public function is_related($query) {
7252 if (parent::is_related($query)) {
7253 return true;
7255 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7256 foreach ($formats as $format) {
7257 if (strpos($format->component, $query) !== false ||
7258 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7259 return true;
7262 return false;
7266 * Return XHTML to display control
7268 * @param mixed $data Unused
7269 * @param string $query
7270 * @return string highlight
7272 public function output_html($data, $query='') {
7273 global $CFG, $OUTPUT;
7274 $return = '';
7276 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7278 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7279 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7280 $txt->updown = "$txt->up/$txt->down";
7282 $table = new html_table();
7283 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7284 $table->align = array('left', 'center', 'center', 'center', 'center');
7285 $table->attributes['class'] = 'manageformattable generaltable admintable';
7286 $table->data = array();
7288 $cnt = 0;
7289 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7290 $totalenabled = 0;
7291 foreach ($formats as $format) {
7292 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7293 $totalenabled++;
7296 foreach ($formats as $format) {
7297 $status = $format->get_status();
7298 $url = new moodle_url('/admin/dataformats.php',
7299 array('sesskey' => sesskey(), 'name' => $format->name));
7301 $class = '';
7302 if ($format->is_enabled()) {
7303 $strformatname = $format->displayname;
7304 if ($totalenabled == 1&& $format->is_enabled()) {
7305 $hideshow = '';
7306 } else {
7307 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7308 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7310 } else {
7311 $class = 'dimmed_text';
7312 $strformatname = $format->displayname;
7313 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7314 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7317 $updown = '';
7318 if ($cnt) {
7319 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7320 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7321 } else {
7322 $updown .= $spacer;
7324 if ($cnt < count($formats) - 1) {
7325 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7326 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7327 } else {
7328 $updown .= $spacer;
7331 $uninstall = '';
7332 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7333 $uninstall = get_string('status_missing', 'core_plugin');
7334 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7335 $uninstall = get_string('status_new', 'core_plugin');
7336 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7337 if ($totalenabled != 1 || !$format->is_enabled()) {
7338 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7342 $settings = '';
7343 if ($format->get_settings_url()) {
7344 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7347 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7348 if ($class) {
7349 $row->attributes['class'] = $class;
7351 $table->data[] = $row;
7352 $cnt++;
7354 $return .= html_writer::table($table);
7355 return highlight($query, $return);
7360 * Special class for filter administration.
7362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7364 class admin_page_managefilters extends admin_externalpage {
7366 * Calls parent::__construct with specific arguments
7368 public function __construct() {
7369 global $CFG;
7370 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7374 * Searches all installed filters for specified filter
7376 * @param string $query The filter(string) to search for
7377 * @param string $query
7379 public function search($query) {
7380 global $CFG;
7381 if ($result = parent::search($query)) {
7382 return $result;
7385 $found = false;
7386 $filternames = filter_get_all_installed();
7387 foreach ($filternames as $path => $strfiltername) {
7388 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7389 $found = true;
7390 break;
7392 if (strpos($path, $query) !== false) {
7393 $found = true;
7394 break;
7398 if ($found) {
7399 $result = new stdClass;
7400 $result->page = $this;
7401 $result->settings = array();
7402 return array($this->name => $result);
7403 } else {
7404 return array();
7410 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7411 * Requires a get_rank method on the plugininfo class for sorting.
7413 * @copyright 2017 Damyon Wiese
7414 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7416 abstract class admin_setting_manage_plugins extends admin_setting {
7419 * Get the admin settings section name (just a unique string)
7421 * @return string
7423 public function get_section_name() {
7424 return 'manage' . $this->get_plugin_type() . 'plugins';
7428 * Get the admin settings section title (use get_string).
7430 * @return string
7432 abstract public function get_section_title();
7435 * Get the type of plugin to manage.
7437 * @return string
7439 abstract public function get_plugin_type();
7442 * Get the name of the second column.
7444 * @return string
7446 public function get_info_column_name() {
7447 return '';
7451 * Get the type of plugin to manage.
7453 * @param plugininfo The plugin info class.
7454 * @return string
7456 abstract public function get_info_column($plugininfo);
7459 * Calls parent::__construct with specific arguments
7461 public function __construct() {
7462 $this->nosave = true;
7463 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7467 * Always returns true, does nothing
7469 * @return true
7471 public function get_setting() {
7472 return true;
7476 * Always returns true, does nothing
7478 * @return true
7480 public function get_defaultsetting() {
7481 return true;
7485 * Always returns '', does not write anything
7487 * @param mixed $data
7488 * @return string Always returns ''
7490 public function write_setting($data) {
7491 // Do not write any setting.
7492 return '';
7496 * Checks if $query is one of the available plugins of this type
7498 * @param string $query The string to search for
7499 * @return bool Returns true if found, false if not
7501 public function is_related($query) {
7502 if (parent::is_related($query)) {
7503 return true;
7506 $query = core_text::strtolower($query);
7507 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7508 foreach ($plugins as $name => $plugin) {
7509 $localised = $plugin->displayname;
7510 if (strpos(core_text::strtolower($name), $query) !== false) {
7511 return true;
7513 if (strpos(core_text::strtolower($localised), $query) !== false) {
7514 return true;
7517 return false;
7521 * The URL for the management page for this plugintype.
7523 * @return moodle_url
7525 protected function get_manage_url() {
7526 return new moodle_url('/admin/updatesetting.php');
7530 * Builds the HTML to display the control.
7532 * @param string $data Unused
7533 * @param string $query
7534 * @return string
7536 public function output_html($data, $query = '') {
7537 global $CFG, $OUTPUT, $DB, $PAGE;
7539 $context = (object) [
7540 'manageurl' => new moodle_url($this->get_manage_url(), [
7541 'type' => $this->get_plugin_type(),
7542 'sesskey' => sesskey(),
7544 'infocolumnname' => $this->get_info_column_name(),
7545 'plugins' => [],
7548 $pluginmanager = core_plugin_manager::instance();
7549 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7550 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7551 $plugins = array_merge($enabled, $allplugins);
7552 foreach ($plugins as $key => $plugin) {
7553 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7555 $pluginkey = (object) [
7556 'plugin' => $plugin->displayname,
7557 'enabled' => $plugin->is_enabled(),
7558 'togglelink' => '',
7559 'moveuplink' => '',
7560 'movedownlink' => '',
7561 'settingslink' => $plugin->get_settings_url(),
7562 'uninstalllink' => '',
7563 'info' => '',
7566 // Enable/Disable link.
7567 $togglelink = new moodle_url($pluginlink);
7568 if ($plugin->is_enabled()) {
7569 $toggletarget = false;
7570 $togglelink->param('action', 'disable');
7572 if (count($context->plugins)) {
7573 // This is not the first plugin.
7574 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7577 if (count($enabled) > count($context->plugins) + 1) {
7578 // This is not the last plugin.
7579 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7582 $pluginkey->info = $this->get_info_column($plugin);
7583 } else {
7584 $toggletarget = true;
7585 $togglelink->param('action', 'enable');
7588 $pluginkey->toggletarget = $toggletarget;
7589 $pluginkey->togglelink = $togglelink;
7591 $frankenstyle = $plugin->type . '_' . $plugin->name;
7592 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
7593 // This plugin supports uninstallation.
7594 $pluginkey->uninstalllink = $uninstalllink;
7597 if (!empty($this->get_info_column_name())) {
7598 // This plugintype has an info column.
7599 $pluginkey->info = $this->get_info_column($plugin);
7602 $context->plugins[] = $pluginkey;
7605 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
7606 return highlight($query, $str);
7611 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7612 * Requires a get_rank method on the plugininfo class for sorting.
7614 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
7615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7617 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
7618 public function get_section_title() {
7619 return get_string('type_fileconverter_plural', 'plugin');
7622 public function get_plugin_type() {
7623 return 'fileconverter';
7626 public function get_info_column_name() {
7627 return get_string('supportedconversions', 'plugin');
7630 public function get_info_column($plugininfo) {
7631 return $plugininfo->get_supported_conversions();
7636 * Special class for media player plugins management.
7638 * @copyright 2016 Marina Glancy
7639 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7641 class admin_setting_managemediaplayers extends admin_setting {
7643 * Calls parent::__construct with specific arguments
7645 public function __construct() {
7646 $this->nosave = true;
7647 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
7651 * Always returns true, does nothing
7653 * @return true
7655 public function get_setting() {
7656 return true;
7660 * Always returns true, does nothing
7662 * @return true
7664 public function get_defaultsetting() {
7665 return true;
7669 * Always returns '', does not write anything
7671 * @param mixed $data
7672 * @return string Always returns ''
7674 public function write_setting($data) {
7675 // Do not write any setting.
7676 return '';
7680 * Checks if $query is one of the available enrol plugins
7682 * @param string $query The string to search for
7683 * @return bool Returns true if found, false if not
7685 public function is_related($query) {
7686 if (parent::is_related($query)) {
7687 return true;
7690 $query = core_text::strtolower($query);
7691 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
7692 foreach ($plugins as $name => $plugin) {
7693 $localised = $plugin->displayname;
7694 if (strpos(core_text::strtolower($name), $query) !== false) {
7695 return true;
7697 if (strpos(core_text::strtolower($localised), $query) !== false) {
7698 return true;
7701 return false;
7705 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7706 * @return \core\plugininfo\media[]
7708 protected function get_sorted_plugins() {
7709 $pluginmanager = core_plugin_manager::instance();
7711 $plugins = $pluginmanager->get_plugins_of_type('media');
7712 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7714 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7715 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
7717 $order = array_values($enabledplugins);
7718 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
7720 $sortedplugins = array();
7721 foreach ($order as $name) {
7722 $sortedplugins[$name] = $plugins[$name];
7725 return $sortedplugins;
7729 * Builds the XHTML to display the control
7731 * @param string $data Unused
7732 * @param string $query
7733 * @return string
7735 public function output_html($data, $query='') {
7736 global $CFG, $OUTPUT, $DB, $PAGE;
7738 // Display strings.
7739 $strup = get_string('up');
7740 $strdown = get_string('down');
7741 $strsettings = get_string('settings');
7742 $strenable = get_string('enable');
7743 $strdisable = get_string('disable');
7744 $struninstall = get_string('uninstallplugin', 'core_admin');
7745 $strversion = get_string('version');
7746 $strname = get_string('name');
7747 $strsupports = get_string('supports', 'core_media');
7749 $pluginmanager = core_plugin_manager::instance();
7751 $plugins = $this->get_sorted_plugins();
7752 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7754 $return = $OUTPUT->box_start('generalbox mediaplayersui');
7756 $table = new html_table();
7757 $table->head = array($strname, $strsupports, $strversion,
7758 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
7759 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
7760 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7761 $table->id = 'mediaplayerplugins';
7762 $table->attributes['class'] = 'admintable generaltable';
7763 $table->data = array();
7765 // Iterate through media plugins and add to the display table.
7766 $updowncount = 1;
7767 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
7768 $printed = array();
7769 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7771 $usedextensions = [];
7772 foreach ($plugins as $name => $plugin) {
7773 $url->param('media', $name);
7774 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
7775 $version = $plugininfo->versiondb;
7776 $supports = $plugininfo->supports($usedextensions);
7778 // Hide/show links.
7779 $class = '';
7780 if (!$plugininfo->is_installed_and_upgraded()) {
7781 $hideshow = '';
7782 $enabled = false;
7783 $displayname = '<span class="notifyproblem">'.$name.'</span>';
7784 } else {
7785 $enabled = $plugininfo->is_enabled();
7786 if ($enabled) {
7787 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
7788 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
7789 } else {
7790 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
7791 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
7792 $class = 'dimmed_text';
7794 $displayname = $plugin->displayname;
7795 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
7796 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
7799 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
7800 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
7801 } else {
7802 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
7805 // Up/down link (only if enrol is enabled).
7806 $updown = '';
7807 if ($enabled) {
7808 if ($updowncount > 1) {
7809 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
7810 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
7811 } else {
7812 $updown = $spacer;
7814 if ($updowncount < count($enabledplugins)) {
7815 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
7816 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
7817 } else {
7818 $updown .= $spacer;
7820 ++$updowncount;
7823 $uninstall = '';
7824 $status = $plugininfo->get_status();
7825 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7826 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
7828 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7829 $uninstall = get_string('status_new', 'core_plugin');
7830 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
7831 $uninstall .= html_writer::link($uninstallurl, $struninstall);
7834 $settings = '';
7835 if ($plugininfo->get_settings_url()) {
7836 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
7839 // Add a row to the table.
7840 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
7841 if ($class) {
7842 $row->attributes['class'] = $class;
7844 $table->data[] = $row;
7846 $printed[$name] = true;
7849 $return .= html_writer::table($table);
7850 $return .= $OUTPUT->box_end();
7851 return highlight($query, $return);
7856 * Initialise admin page - this function does require login and permission
7857 * checks specified in page definition.
7859 * This function must be called on each admin page before other code.
7861 * @global moodle_page $PAGE
7863 * @param string $section name of page
7864 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7865 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7866 * added to the turn blocks editing on/off form, so this page reloads correctly.
7867 * @param string $actualurl if the actual page being viewed is not the normal one for this
7868 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7869 * @param array $options Additional options that can be specified for page setup.
7870 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7872 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7873 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7875 $PAGE->set_context(null); // hack - set context to something, by default to system context
7877 $site = get_site();
7878 require_login();
7880 if (!empty($options['pagelayout'])) {
7881 // A specific page layout has been requested.
7882 $PAGE->set_pagelayout($options['pagelayout']);
7883 } else if ($section === 'upgradesettings') {
7884 $PAGE->set_pagelayout('maintenance');
7885 } else {
7886 $PAGE->set_pagelayout('admin');
7889 $adminroot = admin_get_root(false, false); // settings not required for external pages
7890 $extpage = $adminroot->locate($section, true);
7892 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7893 // The requested section isn't in the admin tree
7894 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7895 if (!has_capability('moodle/site:config', context_system::instance())) {
7896 // The requested section could depend on a different capability
7897 // but most likely the user has inadequate capabilities
7898 print_error('accessdenied', 'admin');
7899 } else {
7900 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7904 // this eliminates our need to authenticate on the actual pages
7905 if (!$extpage->check_access()) {
7906 print_error('accessdenied', 'admin');
7907 die;
7910 navigation_node::require_admin_tree();
7912 // $PAGE->set_extra_button($extrabutton); TODO
7914 if (!$actualurl) {
7915 $actualurl = $extpage->url;
7918 $PAGE->set_url($actualurl, $extraurlparams);
7919 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7920 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7923 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7924 // During initial install.
7925 $strinstallation = get_string('installation', 'install');
7926 $strsettings = get_string('settings');
7927 $PAGE->navbar->add($strsettings);
7928 $PAGE->set_title($strinstallation);
7929 $PAGE->set_heading($strinstallation);
7930 $PAGE->set_cacheable(false);
7931 return;
7934 // Locate the current item on the navigation and make it active when found.
7935 $path = $extpage->path;
7936 $node = $PAGE->settingsnav;
7937 while ($node && count($path) > 0) {
7938 $node = $node->get(array_pop($path));
7940 if ($node) {
7941 $node->make_active();
7944 // Normal case.
7945 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7946 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7947 $USER->editing = $adminediting;
7950 $visiblepathtosection = array_reverse($extpage->visiblepath);
7952 if ($PAGE->user_allowed_editing()) {
7953 if ($PAGE->user_is_editing()) {
7954 $caption = get_string('blockseditoff');
7955 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7956 } else {
7957 $caption = get_string('blocksediton');
7958 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7960 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7963 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7964 $PAGE->set_heading($SITE->fullname);
7966 // prevent caching in nav block
7967 $PAGE->navigation->clear_cache();
7971 * Returns the reference to admin tree root
7973 * @return object admin_root object
7975 function admin_get_root($reload=false, $requirefulltree=true) {
7976 global $CFG, $DB, $OUTPUT;
7978 static $ADMIN = NULL;
7980 if (is_null($ADMIN)) {
7981 // create the admin tree!
7982 $ADMIN = new admin_root($requirefulltree);
7985 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7986 $ADMIN->purge_children($requirefulltree);
7989 if (!$ADMIN->loaded) {
7990 // we process this file first to create categories first and in correct order
7991 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7993 // now we process all other files in admin/settings to build the admin tree
7994 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7995 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7996 continue;
7998 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7999 // plugins are loaded last - they may insert pages anywhere
8000 continue;
8002 require($file);
8004 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8006 $ADMIN->loaded = true;
8009 return $ADMIN;
8012 /// settings utility functions
8015 * This function applies default settings.
8017 * @param object $node, NULL means complete tree, null by default
8018 * @param bool $unconditional if true overrides all values with defaults, null buy default
8020 function admin_apply_default_settings($node=NULL, $unconditional=true) {
8021 global $CFG;
8023 if (is_null($node)) {
8024 core_plugin_manager::reset_caches();
8025 $node = admin_get_root(true, true);
8028 if ($node instanceof admin_category) {
8029 $entries = array_keys($node->children);
8030 foreach ($entries as $entry) {
8031 admin_apply_default_settings($node->children[$entry], $unconditional);
8034 } else if ($node instanceof admin_settingpage) {
8035 foreach ($node->settings as $setting) {
8036 if (!$unconditional and !is_null($setting->get_setting())) {
8037 //do not override existing defaults
8038 continue;
8040 $defaultsetting = $setting->get_defaultsetting();
8041 if (is_null($defaultsetting)) {
8042 // no value yet - default maybe applied after admin user creation or in upgradesettings
8043 continue;
8045 $setting->write_setting($defaultsetting);
8046 $setting->write_setting_flags(null);
8049 // Just in case somebody modifies the list of active plugins directly.
8050 core_plugin_manager::reset_caches();
8054 * Store changed settings, this function updates the errors variable in $ADMIN
8056 * @param object $formdata from form
8057 * @return int number of changed settings
8059 function admin_write_settings($formdata) {
8060 global $CFG, $SITE, $DB;
8062 $olddbsessions = !empty($CFG->dbsessions);
8063 $formdata = (array)$formdata;
8065 $data = array();
8066 foreach ($formdata as $fullname=>$value) {
8067 if (strpos($fullname, 's_') !== 0) {
8068 continue; // not a config value
8070 $data[$fullname] = $value;
8073 $adminroot = admin_get_root();
8074 $settings = admin_find_write_settings($adminroot, $data);
8076 $count = 0;
8077 foreach ($settings as $fullname=>$setting) {
8078 /** @var $setting admin_setting */
8079 $original = $setting->get_setting();
8080 $error = $setting->write_setting($data[$fullname]);
8081 if ($error !== '') {
8082 $adminroot->errors[$fullname] = new stdClass();
8083 $adminroot->errors[$fullname]->data = $data[$fullname];
8084 $adminroot->errors[$fullname]->id = $setting->get_id();
8085 $adminroot->errors[$fullname]->error = $error;
8086 } else {
8087 $setting->write_setting_flags($data);
8089 if ($setting->post_write_settings($original)) {
8090 $count++;
8094 if ($olddbsessions != !empty($CFG->dbsessions)) {
8095 require_logout();
8098 // Now update $SITE - just update the fields, in case other people have a
8099 // a reference to it (e.g. $PAGE, $COURSE).
8100 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8101 foreach (get_object_vars($newsite) as $field => $value) {
8102 $SITE->$field = $value;
8105 // now reload all settings - some of them might depend on the changed
8106 admin_get_root(true);
8107 return $count;
8111 * Internal recursive function - finds all settings from submitted form
8113 * @param object $node Instance of admin_category, or admin_settingpage
8114 * @param array $data
8115 * @return array
8117 function admin_find_write_settings($node, $data) {
8118 $return = array();
8120 if (empty($data)) {
8121 return $return;
8124 if ($node instanceof admin_category) {
8125 if ($node->check_access()) {
8126 $entries = array_keys($node->children);
8127 foreach ($entries as $entry) {
8128 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8132 } else if ($node instanceof admin_settingpage) {
8133 if ($node->check_access()) {
8134 foreach ($node->settings as $setting) {
8135 $fullname = $setting->get_full_name();
8136 if (array_key_exists($fullname, $data)) {
8137 $return[$fullname] = $setting;
8144 return $return;
8148 * Internal function - prints the search results
8150 * @param string $query String to search for
8151 * @return string empty or XHTML
8153 function admin_search_settings_html($query) {
8154 global $CFG, $OUTPUT, $PAGE;
8156 if (core_text::strlen($query) < 2) {
8157 return '';
8159 $query = core_text::strtolower($query);
8161 $adminroot = admin_get_root();
8162 $findings = $adminroot->search($query);
8163 $savebutton = false;
8165 $tpldata = (object) [
8166 'actionurl' => $PAGE->url->out(false),
8167 'results' => [],
8168 'sesskey' => sesskey(),
8171 foreach ($findings as $found) {
8172 $page = $found->page;
8173 $settings = $found->settings;
8174 if ($page->is_hidden()) {
8175 // hidden pages are not displayed in search results
8176 continue;
8179 $heading = highlight($query, $page->visiblename);
8180 $headingurl = null;
8181 if ($page instanceof admin_externalpage) {
8182 $headingurl = new moodle_url($page->url);
8183 } else if ($page instanceof admin_settingpage) {
8184 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8185 } else {
8186 continue;
8189 $sectionsettings = [];
8190 if (!empty($settings)) {
8191 foreach ($settings as $setting) {
8192 if (empty($setting->nosave)) {
8193 $savebutton = true;
8195 $fullname = $setting->get_full_name();
8196 if (array_key_exists($fullname, $adminroot->errors)) {
8197 $data = $adminroot->errors[$fullname]->data;
8198 } else {
8199 $data = $setting->get_setting();
8200 // do not use defaults if settings not available - upgradesettings handles the defaults!
8202 $sectionsettings[] = $setting->output_html($data, $query);
8206 $tpldata->results[] = (object) [
8207 'title' => $heading,
8208 'url' => $headingurl->out(false),
8209 'settings' => $sectionsettings
8213 $tpldata->showsave = $savebutton;
8214 $tpldata->hasresults = !empty($tpldata->results);
8216 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8220 * Internal function - returns arrays of html pages with uninitialised settings
8222 * @param object $node Instance of admin_category or admin_settingpage
8223 * @return array
8225 function admin_output_new_settings_by_page($node) {
8226 global $OUTPUT;
8227 $return = array();
8229 if ($node instanceof admin_category) {
8230 $entries = array_keys($node->children);
8231 foreach ($entries as $entry) {
8232 $return += admin_output_new_settings_by_page($node->children[$entry]);
8235 } else if ($node instanceof admin_settingpage) {
8236 $newsettings = array();
8237 foreach ($node->settings as $setting) {
8238 if (is_null($setting->get_setting())) {
8239 $newsettings[] = $setting;
8242 if (count($newsettings) > 0) {
8243 $adminroot = admin_get_root();
8244 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8245 $page .= '<fieldset class="adminsettings">'."\n";
8246 foreach ($newsettings as $setting) {
8247 $fullname = $setting->get_full_name();
8248 if (array_key_exists($fullname, $adminroot->errors)) {
8249 $data = $adminroot->errors[$fullname]->data;
8250 } else {
8251 $data = $setting->get_setting();
8252 if (is_null($data)) {
8253 $data = $setting->get_defaultsetting();
8256 $page .= '<div class="clearer"><!-- --></div>'."\n";
8257 $page .= $setting->output_html($data);
8259 $page .= '</fieldset>';
8260 $return[$node->name] = $page;
8264 return $return;
8268 * Format admin settings
8270 * @param object $setting
8271 * @param string $title label element
8272 * @param string $form form fragment, html code - not highlighted automatically
8273 * @param string $description
8274 * @param mixed $label link label to id, true by default or string being the label to connect it to
8275 * @param string $warning warning text
8276 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8277 * @param string $query search query to be highlighted
8278 * @return string XHTML
8280 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8281 global $CFG, $OUTPUT;
8283 $context = (object) [
8284 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8285 'fullname' => $setting->get_full_name(),
8288 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8289 if ($label === true) {
8290 $context->labelfor = $setting->get_id();
8291 } else if ($label === false) {
8292 $context->labelfor = '';
8293 } else {
8294 $context->labelfor = $label;
8297 $form .= $setting->output_setting_flags();
8299 $context->warning = $warning;
8300 $context->override = '';
8301 if (empty($setting->plugin)) {
8302 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8303 $context->override = get_string('configoverride', 'admin');
8305 } else {
8306 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8307 $context->override = get_string('configoverride', 'admin');
8311 $defaults = array();
8312 if (!is_null($defaultinfo)) {
8313 if ($defaultinfo === '') {
8314 $defaultinfo = get_string('emptysettingvalue', 'admin');
8316 $defaults[] = $defaultinfo;
8319 $context->default = null;
8320 $setting->get_setting_flag_defaults($defaults);
8321 if (!empty($defaults)) {
8322 $defaultinfo = implode(', ', $defaults);
8323 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8324 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8328 $context->error = '';
8329 $adminroot = admin_get_root();
8330 if (array_key_exists($context->fullname, $adminroot->errors)) {
8331 $context->error = $adminroot->errors[$context->fullname]->error;
8334 $context->id = 'admin-' . $setting->name;
8335 $context->title = highlightfast($query, $title);
8336 $context->name = highlightfast($query, $context->name);
8337 $context->description = highlight($query, markdown_to_html($description));
8338 $context->element = $form;
8339 $context->forceltr = $setting->get_force_ltr();
8341 return $OUTPUT->render_from_template('core_admin/setting', $context);
8345 * Based on find_new_settings{@link ()} in upgradesettings.php
8346 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8348 * @param object $node Instance of admin_category, or admin_settingpage
8349 * @return boolean true if any settings haven't been initialised, false if they all have
8351 function any_new_admin_settings($node) {
8353 if ($node instanceof admin_category) {
8354 $entries = array_keys($node->children);
8355 foreach ($entries as $entry) {
8356 if (any_new_admin_settings($node->children[$entry])) {
8357 return true;
8361 } else if ($node instanceof admin_settingpage) {
8362 foreach ($node->settings as $setting) {
8363 if ($setting->get_setting() === NULL) {
8364 return true;
8369 return false;
8373 * Moved from admin/replace.php so that we can use this in cron
8375 * @param string $search string to look for
8376 * @param string $replace string to replace
8377 * @return bool success or fail
8379 function db_replace($search, $replace) {
8380 global $DB, $CFG, $OUTPUT;
8382 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8383 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
8384 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
8385 'block_instances', '');
8387 // Turn off time limits, sometimes upgrades can be slow.
8388 core_php_time_limit::raise();
8390 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
8391 return false;
8393 foreach ($tables as $table) {
8395 if (in_array($table, $skiptables)) { // Don't process these
8396 continue;
8399 if ($columns = $DB->get_columns($table)) {
8400 $DB->set_debug(true);
8401 foreach ($columns as $column) {
8402 $DB->replace_all_text($table, $column, $search, $replace);
8404 $DB->set_debug(false);
8408 // delete modinfo caches
8409 rebuild_course_cache(0, true);
8411 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
8412 $blocks = core_component::get_plugin_list('block');
8413 foreach ($blocks as $blockname=>$fullblock) {
8414 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8415 continue;
8418 if (!is_readable($fullblock.'/lib.php')) {
8419 continue;
8422 $function = 'block_'.$blockname.'_global_db_replace';
8423 include_once($fullblock.'/lib.php');
8424 if (!function_exists($function)) {
8425 continue;
8428 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
8429 $function($search, $replace);
8430 echo $OUTPUT->notification("...finished", 'notifysuccess');
8433 purge_all_caches();
8435 return true;
8439 * Manage repository settings
8441 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8443 class admin_setting_managerepository extends admin_setting {
8444 /** @var string */
8445 private $baseurl;
8448 * calls parent::__construct with specific arguments
8450 public function __construct() {
8451 global $CFG;
8452 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
8453 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
8457 * Always returns true, does nothing
8459 * @return true
8461 public function get_setting() {
8462 return true;
8466 * Always returns true does nothing
8468 * @return true
8470 public function get_defaultsetting() {
8471 return true;
8475 * Always returns s_managerepository
8477 * @return string Always return 's_managerepository'
8479 public function get_full_name() {
8480 return 's_managerepository';
8484 * Always returns '' doesn't do anything
8486 public function write_setting($data) {
8487 $url = $this->baseurl . '&amp;new=' . $data;
8488 return '';
8489 // TODO
8490 // Should not use redirect and exit here
8491 // Find a better way to do this.
8492 // redirect($url);
8493 // exit;
8497 * Searches repository plugins for one that matches $query
8499 * @param string $query The string to search for
8500 * @return bool true if found, false if not
8502 public function is_related($query) {
8503 if (parent::is_related($query)) {
8504 return true;
8507 $repositories= core_component::get_plugin_list('repository');
8508 foreach ($repositories as $p => $dir) {
8509 if (strpos($p, $query) !== false) {
8510 return true;
8513 foreach (repository::get_types() as $instance) {
8514 $title = $instance->get_typename();
8515 if (strpos(core_text::strtolower($title), $query) !== false) {
8516 return true;
8519 return false;
8523 * Helper function that generates a moodle_url object
8524 * relevant to the repository
8527 function repository_action_url($repository) {
8528 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
8532 * Builds XHTML to display the control
8534 * @param string $data Unused
8535 * @param string $query
8536 * @return string XHTML
8538 public function output_html($data, $query='') {
8539 global $CFG, $USER, $OUTPUT;
8541 // Get strings that are used
8542 $strshow = get_string('on', 'repository');
8543 $strhide = get_string('off', 'repository');
8544 $strdelete = get_string('disabled', 'repository');
8546 $actionchoicesforexisting = array(
8547 'show' => $strshow,
8548 'hide' => $strhide,
8549 'delete' => $strdelete
8552 $actionchoicesfornew = array(
8553 'newon' => $strshow,
8554 'newoff' => $strhide,
8555 'delete' => $strdelete
8558 $return = '';
8559 $return .= $OUTPUT->box_start('generalbox');
8561 // Set strings that are used multiple times
8562 $settingsstr = get_string('settings');
8563 $disablestr = get_string('disable');
8565 // Table to list plug-ins
8566 $table = new html_table();
8567 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
8568 $table->align = array('left', 'center', 'center', 'center', 'center');
8569 $table->data = array();
8571 // Get list of used plug-ins
8572 $repositorytypes = repository::get_types();
8573 if (!empty($repositorytypes)) {
8574 // Array to store plugins being used
8575 $alreadyplugins = array();
8576 $totalrepositorytypes = count($repositorytypes);
8577 $updowncount = 1;
8578 foreach ($repositorytypes as $i) {
8579 $settings = '';
8580 $typename = $i->get_typename();
8581 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
8582 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
8583 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
8585 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
8586 // Calculate number of instances in order to display them for the Moodle administrator
8587 if (!empty($instanceoptionnames)) {
8588 $params = array();
8589 $params['context'] = array(context_system::instance());
8590 $params['onlyvisible'] = false;
8591 $params['type'] = $typename;
8592 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
8593 // site instances
8594 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
8595 $params['context'] = array();
8596 $instances = repository::static_function($typename, 'get_instances', $params);
8597 $courseinstances = array();
8598 $userinstances = array();
8600 foreach ($instances as $instance) {
8601 $repocontext = context::instance_by_id($instance->instance->contextid);
8602 if ($repocontext->contextlevel == CONTEXT_COURSE) {
8603 $courseinstances[] = $instance;
8604 } else if ($repocontext->contextlevel == CONTEXT_USER) {
8605 $userinstances[] = $instance;
8608 // course instances
8609 $instancenumber = count($courseinstances);
8610 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
8612 // user private instances
8613 $instancenumber = count($userinstances);
8614 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
8615 } else {
8616 $admininstancenumbertext = "";
8617 $courseinstancenumbertext = "";
8618 $userinstancenumbertext = "";
8621 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
8623 $settings .= $OUTPUT->container_start('mdl-left');
8624 $settings .= '<br/>';
8625 $settings .= $admininstancenumbertext;
8626 $settings .= '<br/>';
8627 $settings .= $courseinstancenumbertext;
8628 $settings .= '<br/>';
8629 $settings .= $userinstancenumbertext;
8630 $settings .= $OUTPUT->container_end();
8632 // Get the current visibility
8633 if ($i->get_visible()) {
8634 $currentaction = 'show';
8635 } else {
8636 $currentaction = 'hide';
8639 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
8641 // Display up/down link
8642 $updown = '';
8643 // Should be done with CSS instead.
8644 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
8646 if ($updowncount > 1) {
8647 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
8648 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
8650 else {
8651 $updown .= $spacer;
8653 if ($updowncount < $totalrepositorytypes) {
8654 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
8655 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
8657 else {
8658 $updown .= $spacer;
8661 $updowncount++;
8663 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
8665 if (!in_array($typename, $alreadyplugins)) {
8666 $alreadyplugins[] = $typename;
8671 // Get all the plugins that exist on disk
8672 $plugins = core_component::get_plugin_list('repository');
8673 if (!empty($plugins)) {
8674 foreach ($plugins as $plugin => $dir) {
8675 // Check that it has not already been listed
8676 if (!in_array($plugin, $alreadyplugins)) {
8677 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
8678 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
8683 $return .= html_writer::table($table);
8684 $return .= $OUTPUT->box_end();
8685 return highlight($query, $return);
8690 * Special checkbox for enable mobile web service
8691 * If enable then we store the service id of the mobile service into config table
8692 * If disable then we unstore the service id from the config table
8694 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
8696 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
8697 private $restuse;
8700 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
8702 * @return boolean
8704 private function is_protocol_cap_allowed() {
8705 global $DB, $CFG;
8707 // If the $this->restuse variable is not set, it needs to be set.
8708 if (empty($this->restuse) and $this->restuse!==false) {
8709 $params = array();
8710 $params['permission'] = CAP_ALLOW;
8711 $params['roleid'] = $CFG->defaultuserroleid;
8712 $params['capability'] = 'webservice/rest:use';
8713 $this->restuse = $DB->record_exists('role_capabilities', $params);
8716 return $this->restuse;
8720 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
8721 * @param type $status true to allow, false to not set
8723 private function set_protocol_cap($status) {
8724 global $CFG;
8725 if ($status and !$this->is_protocol_cap_allowed()) {
8726 //need to allow the cap
8727 $permission = CAP_ALLOW;
8728 $assign = true;
8729 } else if (!$status and $this->is_protocol_cap_allowed()){
8730 //need to disallow the cap
8731 $permission = CAP_INHERIT;
8732 $assign = true;
8734 if (!empty($assign)) {
8735 $systemcontext = context_system::instance();
8736 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8741 * Builds XHTML to display the control.
8742 * The main purpose of this overloading is to display a warning when https
8743 * is not supported by the server
8744 * @param string $data Unused
8745 * @param string $query
8746 * @return string XHTML
8748 public function output_html($data, $query='') {
8749 global $CFG, $OUTPUT;
8750 $html = parent::output_html($data, $query);
8752 if ((string)$data === $this->yes) {
8753 require_once($CFG->dirroot . "/lib/filelib.php");
8754 $curl = new curl();
8755 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
8756 $curl->head($httpswwwroot . "/login/index.php");
8757 $info = $curl->get_info();
8758 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
8759 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
8763 return $html;
8767 * Retrieves the current setting using the objects name
8769 * @return string
8771 public function get_setting() {
8772 global $CFG;
8774 // First check if is not set.
8775 $result = $this->config_read($this->name);
8776 if (is_null($result)) {
8777 return null;
8780 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8781 // Or if web services aren't enabled this can't be,
8782 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8783 return 0;
8786 require_once($CFG->dirroot . '/webservice/lib.php');
8787 $webservicemanager = new webservice();
8788 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8789 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8790 return $result;
8791 } else {
8792 return 0;
8797 * Save the selected setting
8799 * @param string $data The selected site
8800 * @return string empty string or error message
8802 public function write_setting($data) {
8803 global $DB, $CFG;
8805 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8806 if (empty($CFG->defaultuserroleid)) {
8807 return '';
8810 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8812 require_once($CFG->dirroot . '/webservice/lib.php');
8813 $webservicemanager = new webservice();
8815 $updateprotocol = false;
8816 if ((string)$data === $this->yes) {
8817 //code run when enable mobile web service
8818 //enable web service systeme if necessary
8819 set_config('enablewebservices', true);
8821 //enable mobile service
8822 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8823 $mobileservice->enabled = 1;
8824 $webservicemanager->update_external_service($mobileservice);
8826 // Enable REST server.
8827 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8829 if (!in_array('rest', $activeprotocols)) {
8830 $activeprotocols[] = 'rest';
8831 $updateprotocol = true;
8834 if ($updateprotocol) {
8835 set_config('webserviceprotocols', implode(',', $activeprotocols));
8838 // Allow rest:use capability for authenticated user.
8839 $this->set_protocol_cap(true);
8841 } else {
8842 //disable web service system if no other services are enabled
8843 $otherenabledservices = $DB->get_records_select('external_services',
8844 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8845 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8846 if (empty($otherenabledservices)) {
8847 set_config('enablewebservices', false);
8849 // Also disable REST server.
8850 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8852 $protocolkey = array_search('rest', $activeprotocols);
8853 if ($protocolkey !== false) {
8854 unset($activeprotocols[$protocolkey]);
8855 $updateprotocol = true;
8858 if ($updateprotocol) {
8859 set_config('webserviceprotocols', implode(',', $activeprotocols));
8862 // Disallow rest:use capability for authenticated user.
8863 $this->set_protocol_cap(false);
8866 //disable the mobile service
8867 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8868 $mobileservice->enabled = 0;
8869 $webservicemanager->update_external_service($mobileservice);
8872 return (parent::write_setting($data));
8877 * Special class for management of external services
8879 * @author Petr Skoda (skodak)
8881 class admin_setting_manageexternalservices extends admin_setting {
8883 * Calls parent::__construct with specific arguments
8885 public function __construct() {
8886 $this->nosave = true;
8887 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8891 * Always returns true, does nothing
8893 * @return true
8895 public function get_setting() {
8896 return true;
8900 * Always returns true, does nothing
8902 * @return true
8904 public function get_defaultsetting() {
8905 return true;
8909 * Always returns '', does not write anything
8911 * @return string Always returns ''
8913 public function write_setting($data) {
8914 // do not write any setting
8915 return '';
8919 * Checks if $query is one of the available external services
8921 * @param string $query The string to search for
8922 * @return bool Returns true if found, false if not
8924 public function is_related($query) {
8925 global $DB;
8927 if (parent::is_related($query)) {
8928 return true;
8931 $services = $DB->get_records('external_services', array(), 'id, name');
8932 foreach ($services as $service) {
8933 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8934 return true;
8937 return false;
8941 * Builds the XHTML to display the control
8943 * @param string $data Unused
8944 * @param string $query
8945 * @return string
8947 public function output_html($data, $query='') {
8948 global $CFG, $OUTPUT, $DB;
8950 // display strings
8951 $stradministration = get_string('administration');
8952 $stredit = get_string('edit');
8953 $strservice = get_string('externalservice', 'webservice');
8954 $strdelete = get_string('delete');
8955 $strplugin = get_string('plugin', 'admin');
8956 $stradd = get_string('add');
8957 $strfunctions = get_string('functions', 'webservice');
8958 $strusers = get_string('users');
8959 $strserviceusers = get_string('serviceusers', 'webservice');
8961 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8962 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8963 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8965 // built in services
8966 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8967 $return = "";
8968 if (!empty($services)) {
8969 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8973 $table = new html_table();
8974 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8975 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8976 $table->id = 'builtinservices';
8977 $table->attributes['class'] = 'admintable externalservices generaltable';
8978 $table->data = array();
8980 // iterate through auth plugins and add to the display table
8981 foreach ($services as $service) {
8982 $name = $service->name;
8984 // hide/show link
8985 if ($service->enabled) {
8986 $displayname = "<span>$name</span>";
8987 } else {
8988 $displayname = "<span class=\"dimmed_text\">$name</span>";
8991 $plugin = $service->component;
8993 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8995 if ($service->restrictedusers) {
8996 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8997 } else {
8998 $users = get_string('allusers', 'webservice');
9001 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9003 // add a row to the table
9004 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9006 $return .= html_writer::table($table);
9009 // Custom services
9010 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9011 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9013 $table = new html_table();
9014 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9015 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9016 $table->id = 'customservices';
9017 $table->attributes['class'] = 'admintable externalservices generaltable';
9018 $table->data = array();
9020 // iterate through auth plugins and add to the display table
9021 foreach ($services as $service) {
9022 $name = $service->name;
9024 // hide/show link
9025 if ($service->enabled) {
9026 $displayname = "<span>$name</span>";
9027 } else {
9028 $displayname = "<span class=\"dimmed_text\">$name</span>";
9031 // delete link
9032 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9034 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9036 if ($service->restrictedusers) {
9037 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9038 } else {
9039 $users = get_string('allusers', 'webservice');
9042 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9044 // add a row to the table
9045 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9047 // add new custom service option
9048 $return .= html_writer::table($table);
9050 $return .= '<br />';
9051 // add a token to the table
9052 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9054 return highlight($query, $return);
9059 * Special class for overview of external services
9061 * @author Jerome Mouneyrac
9063 class admin_setting_webservicesoverview extends admin_setting {
9066 * Calls parent::__construct with specific arguments
9068 public function __construct() {
9069 $this->nosave = true;
9070 parent::__construct('webservicesoverviewui',
9071 get_string('webservicesoverview', 'webservice'), '', '');
9075 * Always returns true, does nothing
9077 * @return true
9079 public function get_setting() {
9080 return true;
9084 * Always returns true, does nothing
9086 * @return true
9088 public function get_defaultsetting() {
9089 return true;
9093 * Always returns '', does not write anything
9095 * @return string Always returns ''
9097 public function write_setting($data) {
9098 // do not write any setting
9099 return '';
9103 * Builds the XHTML to display the control
9105 * @param string $data Unused
9106 * @param string $query
9107 * @return string
9109 public function output_html($data, $query='') {
9110 global $CFG, $OUTPUT;
9112 $return = "";
9113 $brtag = html_writer::empty_tag('br');
9115 /// One system controlling Moodle with Token
9116 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9117 $table = new html_table();
9118 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9119 get_string('description'));
9120 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9121 $table->id = 'onesystemcontrol';
9122 $table->attributes['class'] = 'admintable wsoverview generaltable';
9123 $table->data = array();
9125 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9126 . $brtag . $brtag;
9128 /// 1. Enable Web Services
9129 $row = array();
9130 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9131 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9132 array('href' => $url));
9133 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9134 if ($CFG->enablewebservices) {
9135 $status = get_string('yes');
9137 $row[1] = $status;
9138 $row[2] = get_string('enablewsdescription', 'webservice');
9139 $table->data[] = $row;
9141 /// 2. Enable protocols
9142 $row = array();
9143 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9144 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9145 array('href' => $url));
9146 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9147 //retrieve activated protocol
9148 $active_protocols = empty($CFG->webserviceprotocols) ?
9149 array() : explode(',', $CFG->webserviceprotocols);
9150 if (!empty($active_protocols)) {
9151 $status = "";
9152 foreach ($active_protocols as $protocol) {
9153 $status .= $protocol . $brtag;
9156 $row[1] = $status;
9157 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9158 $table->data[] = $row;
9160 /// 3. Create user account
9161 $row = array();
9162 $url = new moodle_url("/user/editadvanced.php?id=-1");
9163 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9164 array('href' => $url));
9165 $row[1] = "";
9166 $row[2] = get_string('createuserdescription', 'webservice');
9167 $table->data[] = $row;
9169 /// 4. Add capability to users
9170 $row = array();
9171 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9172 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9173 array('href' => $url));
9174 $row[1] = "";
9175 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9176 $table->data[] = $row;
9178 /// 5. Select a web service
9179 $row = array();
9180 $url = new moodle_url("/admin/settings.php?section=externalservices");
9181 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9182 array('href' => $url));
9183 $row[1] = "";
9184 $row[2] = get_string('createservicedescription', 'webservice');
9185 $table->data[] = $row;
9187 /// 6. Add functions
9188 $row = array();
9189 $url = new moodle_url("/admin/settings.php?section=externalservices");
9190 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9191 array('href' => $url));
9192 $row[1] = "";
9193 $row[2] = get_string('addfunctionsdescription', 'webservice');
9194 $table->data[] = $row;
9196 /// 7. Add the specific user
9197 $row = array();
9198 $url = new moodle_url("/admin/settings.php?section=externalservices");
9199 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9200 array('href' => $url));
9201 $row[1] = "";
9202 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9203 $table->data[] = $row;
9205 /// 8. Create token for the specific user
9206 $row = array();
9207 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9208 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9209 array('href' => $url));
9210 $row[1] = "";
9211 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9212 $table->data[] = $row;
9214 /// 9. Enable the documentation
9215 $row = array();
9216 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9217 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9218 array('href' => $url));
9219 $status = '<span class="warning">' . get_string('no') . '</span>';
9220 if ($CFG->enablewsdocumentation) {
9221 $status = get_string('yes');
9223 $row[1] = $status;
9224 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9225 $table->data[] = $row;
9227 /// 10. Test the service
9228 $row = array();
9229 $url = new moodle_url("/admin/webservice/testclient.php");
9230 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9231 array('href' => $url));
9232 $row[1] = "";
9233 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9234 $table->data[] = $row;
9236 $return .= html_writer::table($table);
9238 /// Users as clients with token
9239 $return .= $brtag . $brtag . $brtag;
9240 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9241 $table = new html_table();
9242 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9243 get_string('description'));
9244 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9245 $table->id = 'userasclients';
9246 $table->attributes['class'] = 'admintable wsoverview generaltable';
9247 $table->data = array();
9249 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9250 $brtag . $brtag;
9252 /// 1. Enable Web Services
9253 $row = array();
9254 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9255 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9256 array('href' => $url));
9257 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9258 if ($CFG->enablewebservices) {
9259 $status = get_string('yes');
9261 $row[1] = $status;
9262 $row[2] = get_string('enablewsdescription', 'webservice');
9263 $table->data[] = $row;
9265 /// 2. Enable protocols
9266 $row = array();
9267 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9268 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9269 array('href' => $url));
9270 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9271 //retrieve activated protocol
9272 $active_protocols = empty($CFG->webserviceprotocols) ?
9273 array() : explode(',', $CFG->webserviceprotocols);
9274 if (!empty($active_protocols)) {
9275 $status = "";
9276 foreach ($active_protocols as $protocol) {
9277 $status .= $protocol . $brtag;
9280 $row[1] = $status;
9281 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9282 $table->data[] = $row;
9285 /// 3. Select a web service
9286 $row = array();
9287 $url = new moodle_url("/admin/settings.php?section=externalservices");
9288 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9289 array('href' => $url));
9290 $row[1] = "";
9291 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9292 $table->data[] = $row;
9294 /// 4. Add functions
9295 $row = array();
9296 $url = new moodle_url("/admin/settings.php?section=externalservices");
9297 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9298 array('href' => $url));
9299 $row[1] = "";
9300 $row[2] = get_string('addfunctionsdescription', 'webservice');
9301 $table->data[] = $row;
9303 /// 5. Add capability to users
9304 $row = array();
9305 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9306 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9307 array('href' => $url));
9308 $row[1] = "";
9309 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9310 $table->data[] = $row;
9312 /// 6. Test the service
9313 $row = array();
9314 $url = new moodle_url("/admin/webservice/testclient.php");
9315 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9316 array('href' => $url));
9317 $row[1] = "";
9318 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9319 $table->data[] = $row;
9321 $return .= html_writer::table($table);
9323 return highlight($query, $return);
9330 * Special class for web service protocol administration.
9332 * @author Petr Skoda (skodak)
9334 class admin_setting_managewebserviceprotocols extends admin_setting {
9337 * Calls parent::__construct with specific arguments
9339 public function __construct() {
9340 $this->nosave = true;
9341 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9345 * Always returns true, does nothing
9347 * @return true
9349 public function get_setting() {
9350 return true;
9354 * Always returns true, does nothing
9356 * @return true
9358 public function get_defaultsetting() {
9359 return true;
9363 * Always returns '', does not write anything
9365 * @return string Always returns ''
9367 public function write_setting($data) {
9368 // do not write any setting
9369 return '';
9373 * Checks if $query is one of the available webservices
9375 * @param string $query The string to search for
9376 * @return bool Returns true if found, false if not
9378 public function is_related($query) {
9379 if (parent::is_related($query)) {
9380 return true;
9383 $protocols = core_component::get_plugin_list('webservice');
9384 foreach ($protocols as $protocol=>$location) {
9385 if (strpos($protocol, $query) !== false) {
9386 return true;
9388 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
9389 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
9390 return true;
9393 return false;
9397 * Builds the XHTML to display the control
9399 * @param string $data Unused
9400 * @param string $query
9401 * @return string
9403 public function output_html($data, $query='') {
9404 global $CFG, $OUTPUT;
9406 // display strings
9407 $stradministration = get_string('administration');
9408 $strsettings = get_string('settings');
9409 $stredit = get_string('edit');
9410 $strprotocol = get_string('protocol', 'webservice');
9411 $strenable = get_string('enable');
9412 $strdisable = get_string('disable');
9413 $strversion = get_string('version');
9415 $protocols_available = core_component::get_plugin_list('webservice');
9416 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9417 ksort($protocols_available);
9419 foreach ($active_protocols as $key=>$protocol) {
9420 if (empty($protocols_available[$protocol])) {
9421 unset($active_protocols[$key]);
9425 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
9426 $return .= $OUTPUT->box_start('generalbox webservicesui');
9428 $table = new html_table();
9429 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
9430 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
9431 $table->id = 'webserviceprotocols';
9432 $table->attributes['class'] = 'admintable generaltable';
9433 $table->data = array();
9435 // iterate through auth plugins and add to the display table
9436 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
9437 foreach ($protocols_available as $protocol => $location) {
9438 $name = get_string('pluginname', 'webservice_'.$protocol);
9440 $plugin = new stdClass();
9441 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
9442 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
9444 $version = isset($plugin->version) ? $plugin->version : '';
9446 // hide/show link
9447 if (in_array($protocol, $active_protocols)) {
9448 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
9449 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
9450 $displayname = "<span>$name</span>";
9451 } else {
9452 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
9453 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
9454 $displayname = "<span class=\"dimmed_text\">$name</span>";
9457 // settings link
9458 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
9459 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
9460 } else {
9461 $settings = '';
9464 // add a row to the table
9465 $table->data[] = array($displayname, $version, $hideshow, $settings);
9467 $return .= html_writer::table($table);
9468 $return .= get_string('configwebserviceplugins', 'webservice');
9469 $return .= $OUTPUT->box_end();
9471 return highlight($query, $return);
9477 * Special class for web service token administration.
9479 * @author Jerome Mouneyrac
9481 class admin_setting_managewebservicetokens extends admin_setting {
9484 * Calls parent::__construct with specific arguments
9486 public function __construct() {
9487 $this->nosave = true;
9488 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
9492 * Always returns true, does nothing
9494 * @return true
9496 public function get_setting() {
9497 return true;
9501 * Always returns true, does nothing
9503 * @return true
9505 public function get_defaultsetting() {
9506 return true;
9510 * Always returns '', does not write anything
9512 * @return string Always returns ''
9514 public function write_setting($data) {
9515 // do not write any setting
9516 return '';
9520 * Builds the XHTML to display the control
9522 * @param string $data Unused
9523 * @param string $query
9524 * @return string
9526 public function output_html($data, $query='') {
9527 global $CFG, $OUTPUT;
9529 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
9530 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
9532 $return = $OUTPUT->box_start('generalbox webservicestokenui');
9534 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
9535 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
9538 $table = new \webservice\token_table('webservicetokens');
9539 $table->define_baseurl($baseurl);
9540 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
9541 $table->data = array();
9542 ob_start();
9543 $table->out(10, false);
9544 $tablehtml = ob_get_contents();
9545 ob_end_clean();
9546 $return .= $tablehtml;
9548 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
9550 $return .= $OUTPUT->box_end();
9551 // add a token to the table
9552 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
9553 $return .= get_string('add')."</a>";
9555 return highlight($query, $return);
9561 * Colour picker
9563 * @copyright 2010 Sam Hemelryk
9564 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9566 class admin_setting_configcolourpicker extends admin_setting {
9569 * Information for previewing the colour
9571 * @var array|null
9573 protected $previewconfig = null;
9576 * Use default when empty.
9578 protected $usedefaultwhenempty = true;
9582 * @param string $name
9583 * @param string $visiblename
9584 * @param string $description
9585 * @param string $defaultsetting
9586 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
9588 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
9589 $usedefaultwhenempty = true) {
9590 $this->previewconfig = $previewconfig;
9591 $this->usedefaultwhenempty = $usedefaultwhenempty;
9592 parent::__construct($name, $visiblename, $description, $defaultsetting);
9593 $this->set_force_ltr(true);
9597 * Return the setting
9599 * @return mixed returns config if successful else null
9601 public function get_setting() {
9602 return $this->config_read($this->name);
9606 * Saves the setting
9608 * @param string $data
9609 * @return bool
9611 public function write_setting($data) {
9612 $data = $this->validate($data);
9613 if ($data === false) {
9614 return get_string('validateerror', 'admin');
9616 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
9620 * Validates the colour that was entered by the user
9622 * @param string $data
9623 * @return string|false
9625 protected function validate($data) {
9627 * List of valid HTML colour names
9629 * @var array
9631 $colornames = array(
9632 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
9633 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
9634 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
9635 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
9636 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
9637 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
9638 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
9639 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
9640 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
9641 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
9642 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
9643 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
9644 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
9645 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
9646 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
9647 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
9648 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
9649 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
9650 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
9651 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
9652 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
9653 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
9654 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
9655 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
9656 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
9657 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
9658 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
9659 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
9660 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
9661 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
9662 'whitesmoke', 'yellow', 'yellowgreen'
9665 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
9666 if (strpos($data, '#')!==0) {
9667 $data = '#'.$data;
9669 return $data;
9670 } else if (in_array(strtolower($data), $colornames)) {
9671 return $data;
9672 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9673 return $data;
9674 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9675 return $data;
9676 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9677 return $data;
9678 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9679 return $data;
9680 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9681 return $data;
9682 } else if (empty($data)) {
9683 if ($this->usedefaultwhenempty){
9684 return $this->defaultsetting;
9685 } else {
9686 return '';
9688 } else {
9689 return false;
9694 * Generates the HTML for the setting
9696 * @global moodle_page $PAGE
9697 * @global core_renderer $OUTPUT
9698 * @param string $data
9699 * @param string $query
9701 public function output_html($data, $query = '') {
9702 global $PAGE, $OUTPUT;
9704 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
9705 $context = (object) [
9706 'id' => $this->get_id(),
9707 'name' => $this->get_full_name(),
9708 'value' => $data,
9709 'icon' => $icon->export_for_template($OUTPUT),
9710 'haspreviewconfig' => !empty($this->previewconfig),
9711 'forceltr' => $this->get_force_ltr()
9714 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
9715 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9717 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
9718 $this->get_defaultsetting(), $query);
9725 * Class used for uploading of one file into file storage,
9726 * the file name is stored in config table.
9728 * Please note you need to implement your own '_pluginfile' callback function,
9729 * this setting only stores the file, it does not deal with file serving.
9731 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9734 class admin_setting_configstoredfile extends admin_setting {
9735 /** @var array file area options - should be one file only */
9736 protected $options;
9737 /** @var string name of the file area */
9738 protected $filearea;
9739 /** @var int intemid */
9740 protected $itemid;
9741 /** @var string used for detection of changes */
9742 protected $oldhashes;
9745 * Create new stored file setting.
9747 * @param string $name low level setting name
9748 * @param string $visiblename human readable setting name
9749 * @param string $description description of setting
9750 * @param mixed $filearea file area for file storage
9751 * @param int $itemid itemid for file storage
9752 * @param array $options file area options
9754 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9755 parent::__construct($name, $visiblename, $description, '');
9756 $this->filearea = $filearea;
9757 $this->itemid = $itemid;
9758 $this->options = (array)$options;
9762 * Applies defaults and returns all options.
9763 * @return array
9765 protected function get_options() {
9766 global $CFG;
9768 require_once("$CFG->libdir/filelib.php");
9769 require_once("$CFG->dirroot/repository/lib.php");
9770 $defaults = array(
9771 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9772 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9773 'context' => context_system::instance());
9774 foreach($this->options as $k => $v) {
9775 $defaults[$k] = $v;
9778 return $defaults;
9781 public function get_setting() {
9782 return $this->config_read($this->name);
9785 public function write_setting($data) {
9786 global $USER;
9788 // Let's not deal with validation here, this is for admins only.
9789 $current = $this->get_setting();
9790 if (empty($data) && $current === null) {
9791 // This will be the case when applying default settings (installation).
9792 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9793 } else if (!is_number($data)) {
9794 // Draft item id is expected here!
9795 return get_string('errorsetting', 'admin');
9798 $options = $this->get_options();
9799 $fs = get_file_storage();
9800 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9802 $this->oldhashes = null;
9803 if ($current) {
9804 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9805 if ($file = $fs->get_file_by_hash($hash)) {
9806 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9808 unset($file);
9811 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9812 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9813 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9814 // with an error because the draft area does not exist, as he did not use it.
9815 $usercontext = context_user::instance($USER->id);
9816 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9817 return get_string('errorsetting', 'admin');
9821 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9822 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9824 $filepath = '';
9825 if ($files) {
9826 /** @var stored_file $file */
9827 $file = reset($files);
9828 $filepath = $file->get_filepath().$file->get_filename();
9831 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9834 public function post_write_settings($original) {
9835 $options = $this->get_options();
9836 $fs = get_file_storage();
9837 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9839 $current = $this->get_setting();
9840 $newhashes = null;
9841 if ($current) {
9842 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9843 if ($file = $fs->get_file_by_hash($hash)) {
9844 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9846 unset($file);
9849 if ($this->oldhashes === $newhashes) {
9850 $this->oldhashes = null;
9851 return false;
9853 $this->oldhashes = null;
9855 $callbackfunction = $this->updatedcallback;
9856 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9857 $callbackfunction($this->get_full_name());
9859 return true;
9862 public function output_html($data, $query = '') {
9863 global $PAGE, $CFG;
9865 $options = $this->get_options();
9866 $id = $this->get_id();
9867 $elname = $this->get_full_name();
9868 $draftitemid = file_get_submitted_draft_itemid($elname);
9869 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9870 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9872 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9873 require_once("$CFG->dirroot/lib/form/filemanager.php");
9875 $fmoptions = new stdClass();
9876 $fmoptions->mainfile = $options['mainfile'];
9877 $fmoptions->maxbytes = $options['maxbytes'];
9878 $fmoptions->maxfiles = $options['maxfiles'];
9879 $fmoptions->client_id = uniqid();
9880 $fmoptions->itemid = $draftitemid;
9881 $fmoptions->subdirs = $options['subdirs'];
9882 $fmoptions->target = $id;
9883 $fmoptions->accepted_types = $options['accepted_types'];
9884 $fmoptions->return_types = $options['return_types'];
9885 $fmoptions->context = $options['context'];
9886 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9888 $fm = new form_filemanager($fmoptions);
9889 $output = $PAGE->get_renderer('core', 'files');
9890 $html = $output->render($fm);
9892 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9893 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9895 return format_admin_setting($this, $this->visiblename,
9896 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
9897 $this->description, true, '', '', $query);
9903 * Administration interface for user specified regular expressions for device detection.
9905 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9907 class admin_setting_devicedetectregex extends admin_setting {
9910 * Calls parent::__construct with specific args
9912 * @param string $name
9913 * @param string $visiblename
9914 * @param string $description
9915 * @param mixed $defaultsetting
9917 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9918 global $CFG;
9919 parent::__construct($name, $visiblename, $description, $defaultsetting);
9923 * Return the current setting(s)
9925 * @return array Current settings array
9927 public function get_setting() {
9928 global $CFG;
9930 $config = $this->config_read($this->name);
9931 if (is_null($config)) {
9932 return null;
9935 return $this->prepare_form_data($config);
9939 * Save selected settings
9941 * @param array $data Array of settings to save
9942 * @return bool
9944 public function write_setting($data) {
9945 if (empty($data)) {
9946 $data = array();
9949 if ($this->config_write($this->name, $this->process_form_data($data))) {
9950 return ''; // success
9951 } else {
9952 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9957 * Return XHTML field(s) for regexes
9959 * @param array $data Array of options to set in HTML
9960 * @return string XHTML string for the fields and wrapping div(s)
9962 public function output_html($data, $query='') {
9963 global $OUTPUT;
9965 $context = (object) [
9966 'expressions' => [],
9967 'name' => $this->get_full_name()
9970 if (empty($data)) {
9971 $looplimit = 1;
9972 } else {
9973 $looplimit = (count($data)/2)+1;
9976 for ($i=0; $i<$looplimit; $i++) {
9978 $expressionname = 'expression'.$i;
9980 if (!empty($data[$expressionname])){
9981 $expression = $data[$expressionname];
9982 } else {
9983 $expression = '';
9986 $valuename = 'value'.$i;
9988 if (!empty($data[$valuename])){
9989 $value = $data[$valuename];
9990 } else {
9991 $value= '';
9994 $context->expressions[] = [
9995 'index' => $i,
9996 'expression' => $expression,
9997 'value' => $value
10001 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
10003 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10007 * Converts the string of regexes
10009 * @see self::process_form_data()
10010 * @param $regexes string of regexes
10011 * @return array of form fields and their values
10013 protected function prepare_form_data($regexes) {
10015 $regexes = json_decode($regexes);
10017 $form = array();
10019 $i = 0;
10021 foreach ($regexes as $value => $regex) {
10022 $expressionname = 'expression'.$i;
10023 $valuename = 'value'.$i;
10025 $form[$expressionname] = $regex;
10026 $form[$valuename] = $value;
10027 $i++;
10030 return $form;
10034 * Converts the data from admin settings form into a string of regexes
10036 * @see self::prepare_form_data()
10037 * @param array $data array of admin form fields and values
10038 * @return false|string of regexes
10040 protected function process_form_data(array $form) {
10042 $count = count($form); // number of form field values
10044 if ($count % 2) {
10045 // we must get five fields per expression
10046 return false;
10049 $regexes = array();
10050 for ($i = 0; $i < $count / 2; $i++) {
10051 $expressionname = "expression".$i;
10052 $valuename = "value".$i;
10054 $expression = trim($form['expression'.$i]);
10055 $value = trim($form['value'.$i]);
10057 if (empty($expression)){
10058 continue;
10061 $regexes[$value] = $expression;
10064 $regexes = json_encode($regexes);
10066 return $regexes;
10072 * Multiselect for current modules
10074 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10076 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10077 private $excludesystem;
10080 * Calls parent::__construct - note array $choices is not required
10082 * @param string $name setting name
10083 * @param string $visiblename localised setting name
10084 * @param string $description setting description
10085 * @param array $defaultsetting a plain array of default module ids
10086 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10088 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10089 $excludesystem = true) {
10090 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10091 $this->excludesystem = $excludesystem;
10095 * Loads an array of current module choices
10097 * @return bool always return true
10099 public function load_choices() {
10100 if (is_array($this->choices)) {
10101 return true;
10103 $this->choices = array();
10105 global $CFG, $DB;
10106 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10107 foreach ($records as $record) {
10108 // Exclude modules if the code doesn't exist
10109 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10110 // Also exclude system modules (if specified)
10111 if (!($this->excludesystem &&
10112 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10113 MOD_ARCHETYPE_SYSTEM)) {
10114 $this->choices[$record->id] = $record->name;
10118 return true;
10123 * Admin setting to show if a php extension is enabled or not.
10125 * @copyright 2013 Damyon Wiese
10126 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10128 class admin_setting_php_extension_enabled extends admin_setting {
10130 /** @var string The name of the extension to check for */
10131 private $extension;
10134 * Calls parent::__construct with specific arguments
10136 public function __construct($name, $visiblename, $description, $extension) {
10137 $this->extension = $extension;
10138 $this->nosave = true;
10139 parent::__construct($name, $visiblename, $description, '');
10143 * Always returns true, does nothing
10145 * @return true
10147 public function get_setting() {
10148 return true;
10152 * Always returns true, does nothing
10154 * @return true
10156 public function get_defaultsetting() {
10157 return true;
10161 * Always returns '', does not write anything
10163 * @return string Always returns ''
10165 public function write_setting($data) {
10166 // Do not write any setting.
10167 return '';
10171 * Outputs the html for this setting.
10172 * @return string Returns an XHTML string
10174 public function output_html($data, $query='') {
10175 global $OUTPUT;
10177 $o = '';
10178 if (!extension_loaded($this->extension)) {
10179 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10181 $o .= format_admin_setting($this, $this->visiblename, $warning);
10183 return $o;
10188 * Server timezone setting.
10190 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10191 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10192 * @author Petr Skoda <petr.skoda@totaralms.com>
10194 class admin_setting_servertimezone extends admin_setting_configselect {
10196 * Constructor.
10198 public function __construct() {
10199 $default = core_date::get_default_php_timezone();
10200 if ($default === 'UTC') {
10201 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10202 $default = 'Europe/London';
10205 parent::__construct('timezone',
10206 new lang_string('timezone', 'core_admin'),
10207 new lang_string('configtimezone', 'core_admin'), $default, null);
10211 * Lazy load timezone options.
10212 * @return bool true if loaded, false if error
10214 public function load_choices() {
10215 global $CFG;
10216 if (is_array($this->choices)) {
10217 return true;
10220 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10221 $this->choices = core_date::get_list_of_timezones($current, false);
10222 if ($current == 99) {
10223 // Do not show 99 unless it is current value, we want to get rid of it over time.
10224 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10225 core_date::get_default_php_timezone());
10228 return true;
10233 * Forced user timezone setting.
10235 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10237 * @author Petr Skoda <petr.skoda@totaralms.com>
10239 class admin_setting_forcetimezone extends admin_setting_configselect {
10241 * Constructor.
10243 public function __construct() {
10244 parent::__construct('forcetimezone',
10245 new lang_string('forcetimezone', 'core_admin'),
10246 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10250 * Lazy load timezone options.
10251 * @return bool true if loaded, false if error
10253 public function load_choices() {
10254 global $CFG;
10255 if (is_array($this->choices)) {
10256 return true;
10259 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10260 $this->choices = core_date::get_list_of_timezones($current, true);
10261 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10263 return true;
10269 * Search setup steps info.
10271 * @package core
10272 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10275 class admin_setting_searchsetupinfo extends admin_setting {
10278 * Calls parent::__construct with specific arguments
10280 public function __construct() {
10281 $this->nosave = true;
10282 parent::__construct('searchsetupinfo', '', '', '');
10286 * Always returns true, does nothing
10288 * @return true
10290 public function get_setting() {
10291 return true;
10295 * Always returns true, does nothing
10297 * @return true
10299 public function get_defaultsetting() {
10300 return true;
10304 * Always returns '', does not write anything
10306 * @param array $data
10307 * @return string Always returns ''
10309 public function write_setting($data) {
10310 // Do not write any setting.
10311 return '';
10315 * Builds the HTML to display the control
10317 * @param string $data Unused
10318 * @param string $query
10319 * @return string
10321 public function output_html($data, $query='') {
10322 global $CFG, $OUTPUT;
10324 $return = '';
10325 $brtag = html_writer::empty_tag('br');
10327 $searchareas = \core_search\manager::get_search_areas_list();
10328 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10329 $anyindexed = false;
10330 foreach ($searchareas as $areaid => $searcharea) {
10331 list($componentname, $varname) = $searcharea->get_config_var_name();
10332 if (get_config($componentname, $varname . '_indexingstart')) {
10333 $anyindexed = true;
10334 break;
10338 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10340 $table = new html_table();
10341 $table->head = array(get_string('step', 'search'), get_string('status'));
10342 $table->colclasses = array('leftalign step', 'leftalign status');
10343 $table->id = 'searchsetup';
10344 $table->attributes['class'] = 'admintable generaltable';
10345 $table->data = array();
10347 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10349 // Select a search engine.
10350 $row = array();
10351 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10352 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10353 array('href' => $url));
10355 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10356 if (!empty($CFG->searchengine)) {
10357 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
10358 array('class' => 'statusok'));
10361 $row[1] = $status;
10362 $table->data[] = $row;
10364 // Available areas.
10365 $row = array();
10366 $url = new moodle_url('/admin/searchareas.php');
10367 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
10368 array('href' => $url));
10370 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10371 if ($anyenabled) {
10372 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10375 $row[1] = $status;
10376 $table->data[] = $row;
10378 // Setup search engine.
10379 $row = array();
10380 if (empty($CFG->searchengine)) {
10381 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
10382 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10383 } else {
10384 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
10385 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
10386 array('href' => $url));
10387 // Check the engine status.
10388 $searchengine = \core_search\manager::search_engine_instance();
10389 try {
10390 $serverstatus = $searchengine->is_server_ready();
10391 } catch (\moodle_exception $e) {
10392 $serverstatus = $e->getMessage();
10394 if ($serverstatus === true) {
10395 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10396 } else {
10397 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
10399 $row[1] = $status;
10401 $table->data[] = $row;
10403 // Indexed data.
10404 $row = array();
10405 $url = new moodle_url('/admin/searchareas.php');
10406 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
10407 if ($anyindexed) {
10408 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10409 } else {
10410 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10412 $row[1] = $status;
10413 $table->data[] = $row;
10415 // Enable global search.
10416 $row = array();
10417 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
10418 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
10419 array('href' => $url));
10420 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10421 if (\core_search\manager::is_global_search_enabled()) {
10422 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10424 $row[1] = $status;
10425 $table->data[] = $row;
10427 $return .= html_writer::table($table);
10429 return highlight($query, $return);
10435 * Used to validate the contents of SCSS code and ensuring they are parsable.
10437 * It does not attempt to detect undefined SCSS variables because it is designed
10438 * to be used without knowledge of other config/scss included.
10440 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10441 * @copyright 2016 Dan Poltawski <dan@moodle.com>
10443 class admin_setting_scsscode extends admin_setting_configtextarea {
10446 * Validate the contents of the SCSS to ensure its parsable. Does not
10447 * attempt to detect undefined scss variables.
10449 * @param string $data The scss code from text field.
10450 * @return mixed bool true for success or string:error on failure.
10452 public function validate($data) {
10453 if (empty($data)) {
10454 return true;
10457 $scss = new core_scss();
10458 try {
10459 $scss->compile($data);
10460 } catch (Leafo\ScssPhp\Exception\ParserException $e) {
10461 return get_string('scssinvalid', 'admin', $e->getMessage());
10462 } catch (Leafo\ScssPhp\Exception\CompilerException $e) {
10463 // Silently ignore this - it could be a scss variable defined from somewhere
10464 // else which we are not examining here.
10465 return true;
10468 return true;
10474 * Administration setting to define a list of file types.
10476 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
10477 * @copyright 2017 David Mudrák <david@moodle.com>
10478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10480 class admin_setting_filetypes extends admin_setting_configtext {
10482 /** @var array Allow selection from these file types only. */
10483 protected $onlytypes = [];
10485 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
10486 protected $allowall = true;
10488 /** @var core_form\filetypes_util instance to use as a helper. */
10489 protected $util = null;
10492 * Constructor.
10494 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
10495 * @param string $visiblename Localised label of the setting
10496 * @param string $description Localised description of the setting
10497 * @param string $defaultsetting Default setting value.
10498 * @param array $options Setting widget options, an array with optional keys:
10499 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
10500 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
10502 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
10504 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
10506 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
10507 $this->onlytypes = $options['onlytypes'];
10510 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
10511 $this->allowall = (bool)$options['allowall'];
10514 $this->util = new \core_form\filetypes_util();
10518 * Normalize the user's input and write it to the database as comma separated list.
10520 * Comma separated list as a text representation of the array was chosen to
10521 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
10523 * @param string $data Value submitted by the admin.
10524 * @return string Epty string if all good, error message otherwise.
10526 public function write_setting($data) {
10527 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
10531 * Validate data before storage
10533 * @param string $data The setting values provided by the admin
10534 * @return bool|string True if ok, the string if error found
10536 public function validate($data) {
10538 // No need to call parent's validation here as we are PARAM_RAW.
10540 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
10541 return true;
10543 } else {
10544 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
10545 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
10550 * Return an HTML string for the setting element.
10552 * @param string $data The current setting value
10553 * @param string $query Admin search query to be highlighted
10554 * @return string HTML to be displayed
10556 public function output_html($data, $query='') {
10557 global $OUTPUT, $PAGE;
10559 $default = $this->get_defaultsetting();
10560 $context = (object) [
10561 'id' => $this->get_id(),
10562 'name' => $this->get_full_name(),
10563 'value' => $data,
10564 'descriptions' => $this->util->describe_file_types($data),
10566 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
10568 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
10569 $this->get_id(),
10570 $this->visiblename->out(),
10571 $this->onlytypes,
10572 $this->allowall,
10575 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
10579 * Should the values be always displayed in LTR mode?
10581 * We always return true here because these values are not RTL compatible.
10583 * @return bool True because these values are not RTL compatible.
10585 public function get_force_ltr() {
10586 return true;