MDL-63050 cachestore_redis: Update hExists to check empty
[moodle.git] / lib / adminlib.php
blobc3e39cd1e1f3633ca4641af86743e743da42bcfd
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(__DIR__.'/../../config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag areas, collections and instances associated with this plugin.
170 core_tag_area::uninstall($component);
172 // Custom plugin uninstall.
173 $plugindirectory = core_component::get_plugin_directory($type, $name);
174 $uninstalllib = $plugindirectory . '/db/uninstall.php';
175 if (file_exists($uninstalllib)) {
176 require_once($uninstalllib);
177 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
178 if (function_exists($uninstallfunction)) {
179 // Do not verify result, let plugin complain if necessary.
180 $uninstallfunction();
184 // Specific plugin type cleanup.
185 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
186 if ($plugininfo) {
187 $plugininfo->uninstall_cleanup();
188 core_plugin_manager::reset_caches();
190 $plugininfo = null;
192 // perform clean-up task common for all the plugin/subplugin types
194 //delete the web service functions and pre-built services
195 require_once($CFG->dirroot.'/lib/externallib.php');
196 external_delete_descriptions($component);
198 // delete calendar events
199 $DB->delete_records('event', array('modulename' => $pluginname));
201 // Delete scheduled tasks.
202 $DB->delete_records('task_scheduled', array('component' => $component));
204 // Delete Inbound Message datakeys.
205 $DB->delete_records_select('messageinbound_datakeys',
206 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
208 // Delete Inbound Message handlers.
209 $DB->delete_records('messageinbound_handlers', array('component' => $component));
211 // delete all the logs
212 $DB->delete_records('log', array('module' => $pluginname));
214 // delete log_display information
215 $DB->delete_records('log_display', array('component' => $component));
217 // delete the module configuration records
218 unset_all_config_for_plugin($component);
219 if ($type === 'mod') {
220 unset_all_config_for_plugin($pluginname);
223 // delete message provider
224 message_provider_uninstall($component);
226 // delete the plugin tables
227 $xmldbfilepath = $plugindirectory . '/db/install.xml';
228 drop_plugin_tables($component, $xmldbfilepath, false);
229 if ($type === 'mod' or $type === 'block') {
230 // non-frankenstyle table prefixes
231 drop_plugin_tables($name, $xmldbfilepath, false);
234 // delete the capabilities that were defined by this module
235 capabilities_cleanup($component);
237 // remove event handlers and dequeue pending events
238 events_uninstall($component);
240 // Delete all remaining files in the filepool owned by the component.
241 $fs = get_file_storage();
242 $fs->delete_component_files($component);
244 // Finally purge all caches.
245 purge_all_caches();
247 // Invalidate the hash used for upgrade detections.
248 set_config('allversionshash', '');
250 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
254 * Returns the version of installed component
256 * @param string $component component name
257 * @param string $source either 'disk' or 'installed' - where to get the version information from
258 * @return string|bool version number or false if the component is not found
260 function get_component_version($component, $source='installed') {
261 global $CFG, $DB;
263 list($type, $name) = core_component::normalize_component($component);
265 // moodle core or a core subsystem
266 if ($type === 'core') {
267 if ($source === 'installed') {
268 if (empty($CFG->version)) {
269 return false;
270 } else {
271 return $CFG->version;
273 } else {
274 if (!is_readable($CFG->dirroot.'/version.php')) {
275 return false;
276 } else {
277 $version = null; //initialize variable for IDEs
278 include($CFG->dirroot.'/version.php');
279 return $version;
284 // activity module
285 if ($type === 'mod') {
286 if ($source === 'installed') {
287 if ($CFG->version < 2013092001.02) {
288 return $DB->get_field('modules', 'version', array('name'=>$name));
289 } else {
290 return get_config('mod_'.$name, 'version');
293 } else {
294 $mods = core_component::get_plugin_list('mod');
295 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
296 return false;
297 } else {
298 $plugin = new stdClass();
299 $plugin->version = null;
300 $module = $plugin;
301 include($mods[$name].'/version.php');
302 return $plugin->version;
307 // block
308 if ($type === 'block') {
309 if ($source === 'installed') {
310 if ($CFG->version < 2013092001.02) {
311 return $DB->get_field('block', 'version', array('name'=>$name));
312 } else {
313 return get_config('block_'.$name, 'version');
315 } else {
316 $blocks = core_component::get_plugin_list('block');
317 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
318 return false;
319 } else {
320 $plugin = new stdclass();
321 include($blocks[$name].'/version.php');
322 return $plugin->version;
327 // all other plugin types
328 if ($source === 'installed') {
329 return get_config($type.'_'.$name, 'version');
330 } else {
331 $plugins = core_component::get_plugin_list($type);
332 if (empty($plugins[$name])) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($plugins[$name].'/version.php');
337 return $plugin->version;
343 * Delete all plugin tables
345 * @param string $name Name of plugin, used as table prefix
346 * @param string $file Path to install.xml file
347 * @param bool $feedback defaults to true
348 * @return bool Always returns true
350 function drop_plugin_tables($name, $file, $feedback=true) {
351 global $CFG, $DB;
353 // first try normal delete
354 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
355 return true;
358 // then try to find all tables that start with name and are not in any xml file
359 $used_tables = get_used_table_names();
361 $tables = $DB->get_tables();
363 /// Iterate over, fixing id fields as necessary
364 foreach ($tables as $table) {
365 if (in_array($table, $used_tables)) {
366 continue;
369 if (strpos($table, $name) !== 0) {
370 continue;
373 // found orphan table --> delete it
374 if ($DB->get_manager()->table_exists($table)) {
375 $xmldb_table = new xmldb_table($table);
376 $DB->get_manager()->drop_table($xmldb_table);
380 return true;
384 * Returns names of all known tables == tables that moodle knows about.
386 * @return array Array of lowercase table names
388 function get_used_table_names() {
389 $table_names = array();
390 $dbdirs = get_db_directories();
392 foreach ($dbdirs as $dbdir) {
393 $file = $dbdir.'/install.xml';
395 $xmldb_file = new xmldb_file($file);
397 if (!$xmldb_file->fileExists()) {
398 continue;
401 $loaded = $xmldb_file->loadXMLStructure();
402 $structure = $xmldb_file->getStructure();
404 if ($loaded and $tables = $structure->getTables()) {
405 foreach($tables as $table) {
406 $table_names[] = strtolower($table->getName());
411 return $table_names;
415 * Returns list of all directories where we expect install.xml files
416 * @return array Array of paths
418 function get_db_directories() {
419 global $CFG;
421 $dbdirs = array();
423 /// First, the main one (lib/db)
424 $dbdirs[] = $CFG->libdir.'/db';
426 /// Then, all the ones defined by core_component::get_plugin_types()
427 $plugintypes = core_component::get_plugin_types();
428 foreach ($plugintypes as $plugintype => $pluginbasedir) {
429 if ($plugins = core_component::get_plugin_list($plugintype)) {
430 foreach ($plugins as $plugin => $plugindir) {
431 $dbdirs[] = $plugindir.'/db';
436 return $dbdirs;
440 * Try to obtain or release the cron lock.
441 * @param string $name name of lock
442 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
443 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
444 * @return bool true if lock obtained
446 function set_cron_lock($name, $until, $ignorecurrent=false) {
447 global $DB;
448 if (empty($name)) {
449 debugging("Tried to get a cron lock for a null fieldname");
450 return false;
453 // remove lock by force == remove from config table
454 if (is_null($until)) {
455 set_config($name, null);
456 return true;
459 if (!$ignorecurrent) {
460 // read value from db - other processes might have changed it
461 $value = $DB->get_field('config', 'value', array('name'=>$name));
463 if ($value and $value > time()) {
464 //lock active
465 return false;
469 set_config($name, $until);
470 return true;
474 * Test if and critical warnings are present
475 * @return bool
477 function admin_critical_warnings_present() {
478 global $SESSION;
480 if (!has_capability('moodle/site:config', context_system::instance())) {
481 return 0;
484 if (!isset($SESSION->admin_critical_warning)) {
485 $SESSION->admin_critical_warning = 0;
486 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
487 $SESSION->admin_critical_warning = 1;
491 return $SESSION->admin_critical_warning;
495 * Detects if float supports at least 10 decimal digits
497 * Detects if float supports at least 10 decimal digits
498 * and also if float-->string conversion works as expected.
500 * @return bool true if problem found
502 function is_float_problem() {
503 $num1 = 2009010200.01;
504 $num2 = 2009010200.02;
506 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
510 * Try to verify that dataroot is not accessible from web.
512 * Try to verify that dataroot is not accessible from web.
513 * It is not 100% correct but might help to reduce number of vulnerable sites.
514 * Protection from httpd.conf and .htaccess is not detected properly.
516 * @uses INSECURE_DATAROOT_WARNING
517 * @uses INSECURE_DATAROOT_ERROR
518 * @param bool $fetchtest try to test public access by fetching file, default false
519 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
521 function is_dataroot_insecure($fetchtest=false) {
522 global $CFG;
524 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
526 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
527 $rp = strrev(trim($rp, '/'));
528 $rp = explode('/', $rp);
529 foreach($rp as $r) {
530 if (strpos($siteroot, '/'.$r.'/') === 0) {
531 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
532 } else {
533 break; // probably alias root
537 $siteroot = strrev($siteroot);
538 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
540 if (strpos($dataroot, $siteroot) !== 0) {
541 return false;
544 if (!$fetchtest) {
545 return INSECURE_DATAROOT_WARNING;
548 // now try all methods to fetch a test file using http protocol
550 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
551 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
552 $httpdocroot = $matches[1];
553 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
554 make_upload_directory('diag');
555 $testfile = $CFG->dataroot.'/diag/public.txt';
556 if (!file_exists($testfile)) {
557 file_put_contents($testfile, 'test file, do not delete');
558 @chmod($testfile, $CFG->filepermissions);
560 $teststr = trim(file_get_contents($testfile));
561 if (empty($teststr)) {
562 // hmm, strange
563 return INSECURE_DATAROOT_WARNING;
566 $testurl = $datarooturl.'/diag/public.txt';
567 if (extension_loaded('curl') and
568 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
569 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
570 ($ch = @curl_init($testurl)) !== false) {
571 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
572 curl_setopt($ch, CURLOPT_HEADER, false);
573 $data = curl_exec($ch);
574 if (!curl_errno($ch)) {
575 $data = trim($data);
576 if ($data === $teststr) {
577 curl_close($ch);
578 return INSECURE_DATAROOT_ERROR;
581 curl_close($ch);
584 if ($data = @file_get_contents($testurl)) {
585 $data = trim($data);
586 if ($data === $teststr) {
587 return INSECURE_DATAROOT_ERROR;
591 preg_match('|https?://([^/]+)|i', $testurl, $matches);
592 $sitename = $matches[1];
593 $error = 0;
594 if ($fp = @fsockopen($sitename, 80, $error)) {
595 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
596 $localurl = $matches[1];
597 $out = "GET $localurl HTTP/1.1\r\n";
598 $out .= "Host: $sitename\r\n";
599 $out .= "Connection: Close\r\n\r\n";
600 fwrite($fp, $out);
601 $data = '';
602 $incoming = false;
603 while (!feof($fp)) {
604 if ($incoming) {
605 $data .= fgets($fp, 1024);
606 } else if (@fgets($fp, 1024) === "\r\n") {
607 $incoming = true;
610 fclose($fp);
611 $data = trim($data);
612 if ($data === $teststr) {
613 return INSECURE_DATAROOT_ERROR;
617 return INSECURE_DATAROOT_WARNING;
621 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
623 function enable_cli_maintenance_mode() {
624 global $CFG;
626 if (file_exists("$CFG->dataroot/climaintenance.html")) {
627 unlink("$CFG->dataroot/climaintenance.html");
630 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
631 $data = $CFG->maintenance_message;
632 $data = bootstrap_renderer::early_error_content($data, null, null, null);
633 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
635 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
636 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
638 } else {
639 $data = get_string('sitemaintenance', 'admin');
640 $data = bootstrap_renderer::early_error_content($data, null, null, null);
641 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
644 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
645 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
648 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
652 * Interface for anything appearing in the admin tree
654 * The interface that is implemented by anything that appears in the admin tree
655 * block. It forces inheriting classes to define a method for checking user permissions
656 * and methods for finding something in the admin tree.
658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
660 interface part_of_admin_tree {
663 * Finds a named part_of_admin_tree.
665 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
666 * and not parentable_part_of_admin_tree, then this function should only check if
667 * $this->name matches $name. If it does, it should return a reference to $this,
668 * otherwise, it should return a reference to NULL.
670 * If a class inherits parentable_part_of_admin_tree, this method should be called
671 * recursively on all child objects (assuming, of course, the parent object's name
672 * doesn't match the search criterion).
674 * @param string $name The internal name of the part_of_admin_tree we're searching for.
675 * @return mixed An object reference or a NULL reference.
677 public function locate($name);
680 * Removes named part_of_admin_tree.
682 * @param string $name The internal name of the part_of_admin_tree we want to remove.
683 * @return bool success.
685 public function prune($name);
688 * Search using query
689 * @param string $query
690 * @return mixed array-object structure of found settings and pages
692 public function search($query);
695 * Verifies current user's access to this part_of_admin_tree.
697 * Used to check if the current user has access to this part of the admin tree or
698 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
699 * then this method is usually just a call to has_capability() in the site context.
701 * If a class inherits parentable_part_of_admin_tree, this method should return the
702 * logical OR of the return of check_access() on all child objects.
704 * @return bool True if the user has access, false if she doesn't.
706 public function check_access();
709 * Mostly useful for removing of some parts of the tree in admin tree block.
711 * @return True is hidden from normal list view
713 public function is_hidden();
716 * Show we display Save button at the page bottom?
717 * @return bool
719 public function show_save();
724 * Interface implemented by any part_of_admin_tree that has children.
726 * The interface implemented by any part_of_admin_tree that can be a parent
727 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
728 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
729 * include an add method for adding other part_of_admin_tree objects as children.
731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 interface parentable_part_of_admin_tree extends part_of_admin_tree {
736 * Adds a part_of_admin_tree object to the admin tree.
738 * Used to add a part_of_admin_tree object to this object or a child of this
739 * object. $something should only be added if $destinationname matches
740 * $this->name. If it doesn't, add should be called on child objects that are
741 * also parentable_part_of_admin_tree's.
743 * $something should be appended as the last child in the $destinationname. If the
744 * $beforesibling is specified, $something should be prepended to it. If the given
745 * sibling is not found, $something should be appended to the end of $destinationname
746 * and a developer debugging message should be displayed.
748 * @param string $destinationname The internal name of the new parent for $something.
749 * @param part_of_admin_tree $something The object to be added.
750 * @return bool True on success, false on failure.
752 public function add($destinationname, $something, $beforesibling = null);
758 * The object used to represent folders (a.k.a. categories) in the admin tree block.
760 * Each admin_category object contains a number of part_of_admin_tree objects.
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class admin_category implements parentable_part_of_admin_tree {
766 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
767 protected $children;
768 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
769 public $name;
770 /** @var string The displayed name for this category. Usually obtained through get_string() */
771 public $visiblename;
772 /** @var bool Should this category be hidden in admin tree block? */
773 public $hidden;
774 /** @var mixed Either a string or an array or strings */
775 public $path;
776 /** @var mixed Either a string or an array or strings */
777 public $visiblepath;
779 /** @var array fast lookup category cache, all categories of one tree point to one cache */
780 protected $category_cache;
782 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
783 protected $sort = false;
784 /** @var bool If set to true children will be sorted in ascending order. */
785 protected $sortasc = true;
786 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
787 protected $sortsplit = true;
788 /** @var bool $sorted True if the children have been sorted and don't need resorting */
789 protected $sorted = false;
792 * Constructor for an empty admin category
794 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
795 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
796 * @param bool $hidden hide category in admin tree block, defaults to false
798 public function __construct($name, $visiblename, $hidden=false) {
799 $this->children = array();
800 $this->name = $name;
801 $this->visiblename = $visiblename;
802 $this->hidden = $hidden;
806 * Returns a reference to the part_of_admin_tree object with internal name $name.
808 * @param string $name The internal name of the object we want.
809 * @param bool $findpath initialize path and visiblepath arrays
810 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
811 * defaults to false
813 public function locate($name, $findpath=false) {
814 if (!isset($this->category_cache[$this->name])) {
815 // somebody much have purged the cache
816 $this->category_cache[$this->name] = $this;
819 if ($this->name == $name) {
820 if ($findpath) {
821 $this->visiblepath[] = $this->visiblename;
822 $this->path[] = $this->name;
824 return $this;
827 // quick category lookup
828 if (!$findpath and isset($this->category_cache[$name])) {
829 return $this->category_cache[$name];
832 $return = NULL;
833 foreach($this->children as $childid=>$unused) {
834 if ($return = $this->children[$childid]->locate($name, $findpath)) {
835 break;
839 if (!is_null($return) and $findpath) {
840 $return->visiblepath[] = $this->visiblename;
841 $return->path[] = $this->name;
844 return $return;
848 * Search using query
850 * @param string query
851 * @return mixed array-object structure of found settings and pages
853 public function search($query) {
854 $result = array();
855 foreach ($this->get_children() as $child) {
856 $subsearch = $child->search($query);
857 if (!is_array($subsearch)) {
858 debugging('Incorrect search result from '.$child->name);
859 continue;
861 $result = array_merge($result, $subsearch);
863 return $result;
867 * Removes part_of_admin_tree object with internal name $name.
869 * @param string $name The internal name of the object we want to remove.
870 * @return bool success
872 public function prune($name) {
874 if ($this->name == $name) {
875 return false; //can not remove itself
878 foreach($this->children as $precedence => $child) {
879 if ($child->name == $name) {
880 // clear cache and delete self
881 while($this->category_cache) {
882 // delete the cache, but keep the original array address
883 array_pop($this->category_cache);
885 unset($this->children[$precedence]);
886 return true;
887 } else if ($this->children[$precedence]->prune($name)) {
888 return true;
891 return false;
895 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
897 * By default the new part of the tree is appended as the last child of the parent. You
898 * can specify a sibling node that the new part should be prepended to. If the given
899 * sibling is not found, the part is appended to the end (as it would be by default) and
900 * a developer debugging message is displayed.
902 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
903 * @param string $destinationame The internal name of the immediate parent that we want for $something.
904 * @param mixed $something A part_of_admin_tree or setting instance to be added.
905 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
906 * @return bool True if successfully added, false if $something can not be added.
908 public function add($parentname, $something, $beforesibling = null) {
909 global $CFG;
911 $parent = $this->locate($parentname);
912 if (is_null($parent)) {
913 debugging('parent does not exist!');
914 return false;
917 if ($something instanceof part_of_admin_tree) {
918 if (!($parent instanceof parentable_part_of_admin_tree)) {
919 debugging('error - parts of tree can be inserted only into parentable parts');
920 return false;
922 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
923 // The name of the node is already used, simply warn the developer that this should not happen.
924 // It is intentional to check for the debug level before performing the check.
925 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
927 if (is_null($beforesibling)) {
928 // Append $something as the parent's last child.
929 $parent->children[] = $something;
930 } else {
931 if (!is_string($beforesibling) or trim($beforesibling) === '') {
932 throw new coding_exception('Unexpected value of the beforesibling parameter');
934 // Try to find the position of the sibling.
935 $siblingposition = null;
936 foreach ($parent->children as $childposition => $child) {
937 if ($child->name === $beforesibling) {
938 $siblingposition = $childposition;
939 break;
942 if (is_null($siblingposition)) {
943 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
944 $parent->children[] = $something;
945 } else {
946 $parent->children = array_merge(
947 array_slice($parent->children, 0, $siblingposition),
948 array($something),
949 array_slice($parent->children, $siblingposition)
953 if ($something instanceof admin_category) {
954 if (isset($this->category_cache[$something->name])) {
955 debugging('Duplicate admin category name: '.$something->name);
956 } else {
957 $this->category_cache[$something->name] = $something;
958 $something->category_cache =& $this->category_cache;
959 foreach ($something->children as $child) {
960 // just in case somebody already added subcategories
961 if ($child instanceof admin_category) {
962 if (isset($this->category_cache[$child->name])) {
963 debugging('Duplicate admin category name: '.$child->name);
964 } else {
965 $this->category_cache[$child->name] = $child;
966 $child->category_cache =& $this->category_cache;
972 return true;
974 } else {
975 debugging('error - can not add this element');
976 return false;
982 * Checks if the user has access to anything in this category.
984 * @return bool True if the user has access to at least one child in this category, false otherwise.
986 public function check_access() {
987 foreach ($this->children as $child) {
988 if ($child->check_access()) {
989 return true;
992 return false;
996 * Is this category hidden in admin tree block?
998 * @return bool True if hidden
1000 public function is_hidden() {
1001 return $this->hidden;
1005 * Show we display Save button at the page bottom?
1006 * @return bool
1008 public function show_save() {
1009 foreach ($this->children as $child) {
1010 if ($child->show_save()) {
1011 return true;
1014 return false;
1018 * Sets sorting on this category.
1020 * Please note this function doesn't actually do the sorting.
1021 * It can be called anytime.
1022 * Sorting occurs when the user calls get_children.
1023 * Code using the children array directly won't see the sorted results.
1025 * @param bool $sort If set to true children will be sorted, if false they won't be.
1026 * @param bool $asc If true sorting will be ascending, otherwise descending.
1027 * @param bool $split If true we sort pages and sub categories separately.
1029 public function set_sorting($sort, $asc = true, $split = true) {
1030 $this->sort = (bool)$sort;
1031 $this->sortasc = (bool)$asc;
1032 $this->sortsplit = (bool)$split;
1036 * Returns the children associated with this category.
1038 * @return part_of_admin_tree[]
1040 public function get_children() {
1041 // If we should sort and it hasn't already been sorted.
1042 if ($this->sort && !$this->sorted) {
1043 if ($this->sortsplit) {
1044 $categories = array();
1045 $pages = array();
1046 foreach ($this->children as $child) {
1047 if ($child instanceof admin_category) {
1048 $categories[] = $child;
1049 } else {
1050 $pages[] = $child;
1053 core_collator::asort_objects_by_property($categories, 'visiblename');
1054 core_collator::asort_objects_by_property($pages, 'visiblename');
1055 if (!$this->sortasc) {
1056 $categories = array_reverse($categories);
1057 $pages = array_reverse($pages);
1059 $this->children = array_merge($pages, $categories);
1060 } else {
1061 core_collator::asort_objects_by_property($this->children, 'visiblename');
1062 if (!$this->sortasc) {
1063 $this->children = array_reverse($this->children);
1066 $this->sorted = true;
1068 return $this->children;
1072 * Magically gets a property from this object.
1074 * @param $property
1075 * @return part_of_admin_tree[]
1076 * @throws coding_exception
1078 public function __get($property) {
1079 if ($property === 'children') {
1080 return $this->get_children();
1082 throw new coding_exception('Invalid property requested.');
1086 * Magically sets a property against this object.
1088 * @param string $property
1089 * @param mixed $value
1090 * @throws coding_exception
1092 public function __set($property, $value) {
1093 if ($property === 'children') {
1094 $this->sorted = false;
1095 $this->children = $value;
1096 } else {
1097 throw new coding_exception('Invalid property requested.');
1102 * Checks if an inaccessible property is set.
1104 * @param string $property
1105 * @return bool
1106 * @throws coding_exception
1108 public function __isset($property) {
1109 if ($property === 'children') {
1110 return isset($this->children);
1112 throw new coding_exception('Invalid property requested.');
1118 * Root of admin settings tree, does not have any parent.
1120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1122 class admin_root extends admin_category {
1123 /** @var array List of errors */
1124 public $errors;
1125 /** @var string search query */
1126 public $search;
1127 /** @var bool full tree flag - true means all settings required, false only pages required */
1128 public $fulltree;
1129 /** @var bool flag indicating loaded tree */
1130 public $loaded;
1131 /** @var mixed site custom defaults overriding defaults in settings files*/
1132 public $custom_defaults;
1135 * @param bool $fulltree true means all settings required,
1136 * false only pages required
1138 public function __construct($fulltree) {
1139 global $CFG;
1141 parent::__construct('root', get_string('administration'), false);
1142 $this->errors = array();
1143 $this->search = '';
1144 $this->fulltree = $fulltree;
1145 $this->loaded = false;
1147 $this->category_cache = array();
1149 // load custom defaults if found
1150 $this->custom_defaults = null;
1151 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1152 if (is_readable($defaultsfile)) {
1153 $defaults = array();
1154 include($defaultsfile);
1155 if (is_array($defaults) and count($defaults)) {
1156 $this->custom_defaults = $defaults;
1162 * Empties children array, and sets loaded to false
1164 * @param bool $requirefulltree
1166 public function purge_children($requirefulltree) {
1167 $this->children = array();
1168 $this->fulltree = ($requirefulltree || $this->fulltree);
1169 $this->loaded = false;
1170 //break circular dependencies - this helps PHP 5.2
1171 while($this->category_cache) {
1172 array_pop($this->category_cache);
1174 $this->category_cache = array();
1180 * Links external PHP pages into the admin tree.
1182 * See detailed usage example at the top of this document (adminlib.php)
1184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1186 class admin_externalpage implements part_of_admin_tree {
1188 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1189 public $name;
1191 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1192 public $visiblename;
1194 /** @var string The external URL that we should link to when someone requests this external page. */
1195 public $url;
1197 /** @var string The role capability/permission a user must have to access this external page. */
1198 public $req_capability;
1200 /** @var object The context in which capability/permission should be checked, default is site context. */
1201 public $context;
1203 /** @var bool hidden in admin tree block. */
1204 public $hidden;
1206 /** @var mixed either string or array of string */
1207 public $path;
1209 /** @var array list of visible names of page parents */
1210 public $visiblepath;
1213 * Constructor for adding an external page into the admin tree.
1215 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1216 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1217 * @param string $url The external URL that we should link to when someone requests this external page.
1218 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1219 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1220 * @param stdClass $context The context the page relates to. Not sure what happens
1221 * if you specify something other than system or front page. Defaults to system.
1223 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1224 $this->name = $name;
1225 $this->visiblename = $visiblename;
1226 $this->url = $url;
1227 if (is_array($req_capability)) {
1228 $this->req_capability = $req_capability;
1229 } else {
1230 $this->req_capability = array($req_capability);
1232 $this->hidden = $hidden;
1233 $this->context = $context;
1237 * Returns a reference to the part_of_admin_tree object with internal name $name.
1239 * @param string $name The internal name of the object we want.
1240 * @param bool $findpath defaults to false
1241 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1243 public function locate($name, $findpath=false) {
1244 if ($this->name == $name) {
1245 if ($findpath) {
1246 $this->visiblepath = array($this->visiblename);
1247 $this->path = array($this->name);
1249 return $this;
1250 } else {
1251 $return = NULL;
1252 return $return;
1257 * This function always returns false, required function by interface
1259 * @param string $name
1260 * @return false
1262 public function prune($name) {
1263 return false;
1267 * Search using query
1269 * @param string $query
1270 * @return mixed array-object structure of found settings and pages
1272 public function search($query) {
1273 $found = false;
1274 if (strpos(strtolower($this->name), $query) !== false) {
1275 $found = true;
1276 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1277 $found = true;
1279 if ($found) {
1280 $result = new stdClass();
1281 $result->page = $this;
1282 $result->settings = array();
1283 return array($this->name => $result);
1284 } else {
1285 return array();
1290 * Determines if the current user has access to this external page based on $this->req_capability.
1292 * @return bool True if user has access, false otherwise.
1294 public function check_access() {
1295 global $CFG;
1296 $context = empty($this->context) ? context_system::instance() : $this->context;
1297 foreach($this->req_capability as $cap) {
1298 if (has_capability($cap, $context)) {
1299 return true;
1302 return false;
1306 * Is this external page hidden in admin tree block?
1308 * @return bool True if hidden
1310 public function is_hidden() {
1311 return $this->hidden;
1315 * Show we display Save button at the page bottom?
1316 * @return bool
1318 public function show_save() {
1319 return false;
1325 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1329 class admin_settingpage implements part_of_admin_tree {
1331 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1332 public $name;
1334 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1335 public $visiblename;
1337 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1338 public $settings;
1340 /** @var string The role capability/permission a user must have to access this external page. */
1341 public $req_capability;
1343 /** @var object The context in which capability/permission should be checked, default is site context. */
1344 public $context;
1346 /** @var bool hidden in admin tree block. */
1347 public $hidden;
1349 /** @var mixed string of paths or array of strings of paths */
1350 public $path;
1352 /** @var array list of visible names of page parents */
1353 public $visiblepath;
1356 * see admin_settingpage for details of this function
1358 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1359 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1360 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1361 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1362 * @param stdClass $context The context the page relates to. Not sure what happens
1363 * if you specify something other than system or front page. Defaults to system.
1365 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1366 $this->settings = new stdClass();
1367 $this->name = $name;
1368 $this->visiblename = $visiblename;
1369 if (is_array($req_capability)) {
1370 $this->req_capability = $req_capability;
1371 } else {
1372 $this->req_capability = array($req_capability);
1374 $this->hidden = $hidden;
1375 $this->context = $context;
1379 * see admin_category
1381 * @param string $name
1382 * @param bool $findpath
1383 * @return mixed Object (this) if name == this->name, else returns null
1385 public function locate($name, $findpath=false) {
1386 if ($this->name == $name) {
1387 if ($findpath) {
1388 $this->visiblepath = array($this->visiblename);
1389 $this->path = array($this->name);
1391 return $this;
1392 } else {
1393 $return = NULL;
1394 return $return;
1399 * Search string in settings page.
1401 * @param string $query
1402 * @return array
1404 public function search($query) {
1405 $found = array();
1407 foreach ($this->settings as $setting) {
1408 if ($setting->is_related($query)) {
1409 $found[] = $setting;
1413 if ($found) {
1414 $result = new stdClass();
1415 $result->page = $this;
1416 $result->settings = $found;
1417 return array($this->name => $result);
1420 $found = false;
1421 if (strpos(strtolower($this->name), $query) !== false) {
1422 $found = true;
1423 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1424 $found = true;
1426 if ($found) {
1427 $result = new stdClass();
1428 $result->page = $this;
1429 $result->settings = array();
1430 return array($this->name => $result);
1431 } else {
1432 return array();
1437 * This function always returns false, required by interface
1439 * @param string $name
1440 * @return bool Always false
1442 public function prune($name) {
1443 return false;
1447 * adds an admin_setting to this admin_settingpage
1449 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1450 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1452 * @param object $setting is the admin_setting object you want to add
1453 * @return bool true if successful, false if not
1455 public function add($setting) {
1456 if (!($setting instanceof admin_setting)) {
1457 debugging('error - not a setting instance');
1458 return false;
1461 $name = $setting->name;
1462 if ($setting->plugin) {
1463 $name = $setting->plugin . $name;
1465 $this->settings->{$name} = $setting;
1466 return true;
1470 * see admin_externalpage
1472 * @return bool Returns true for yes false for no
1474 public function check_access() {
1475 global $CFG;
1476 $context = empty($this->context) ? context_system::instance() : $this->context;
1477 foreach($this->req_capability as $cap) {
1478 if (has_capability($cap, $context)) {
1479 return true;
1482 return false;
1486 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1487 * @return string Returns an XHTML string
1489 public function output_html() {
1490 $adminroot = admin_get_root();
1491 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1492 foreach($this->settings as $setting) {
1493 $fullname = $setting->get_full_name();
1494 if (array_key_exists($fullname, $adminroot->errors)) {
1495 $data = $adminroot->errors[$fullname]->data;
1496 } else {
1497 $data = $setting->get_setting();
1498 // do not use defaults if settings not available - upgrade settings handles the defaults!
1500 $return .= $setting->output_html($data);
1502 $return .= '</fieldset>';
1503 return $return;
1507 * Is this settings page hidden in admin tree block?
1509 * @return bool True if hidden
1511 public function is_hidden() {
1512 return $this->hidden;
1516 * Show we display Save button at the page bottom?
1517 * @return bool
1519 public function show_save() {
1520 foreach($this->settings as $setting) {
1521 if (empty($setting->nosave)) {
1522 return true;
1525 return false;
1531 * Admin settings class. Only exists on setting pages.
1532 * Read & write happens at this level; no authentication.
1534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1536 abstract class admin_setting {
1537 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1538 public $name;
1539 /** @var string localised name */
1540 public $visiblename;
1541 /** @var string localised long description in Markdown format */
1542 public $description;
1543 /** @var mixed Can be string or array of string */
1544 public $defaultsetting;
1545 /** @var string */
1546 public $updatedcallback;
1547 /** @var mixed can be String or Null. Null means main config table */
1548 public $plugin; // null means main config table
1549 /** @var bool true indicates this setting does not actually save anything, just information */
1550 public $nosave = false;
1551 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1552 public $affectsmodinfo = false;
1553 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1554 private $flags = array();
1555 /** @var bool Whether this field must be forced LTR. */
1556 private $forceltr = null;
1559 * Constructor
1560 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1561 * or 'myplugin/mysetting' for ones in config_plugins.
1562 * @param string $visiblename localised name
1563 * @param string $description localised long description
1564 * @param mixed $defaultsetting string or array depending on implementation
1566 public function __construct($name, $visiblename, $description, $defaultsetting) {
1567 $this->parse_setting_name($name);
1568 $this->visiblename = $visiblename;
1569 $this->description = $description;
1570 $this->defaultsetting = $defaultsetting;
1574 * Generic function to add a flag to this admin setting.
1576 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1577 * @param bool $default - The default for the flag
1578 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1579 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1581 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1582 if (empty($this->flags[$shortname])) {
1583 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1584 } else {
1585 $this->flags[$shortname]->set_options($enabled, $default);
1590 * Set the enabled options flag on this admin setting.
1592 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1593 * @param bool $default - The default for the flag
1595 public function set_enabled_flag_options($enabled, $default) {
1596 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1600 * Set the advanced options flag on this admin setting.
1602 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1603 * @param bool $default - The default for the flag
1605 public function set_advanced_flag_options($enabled, $default) {
1606 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1611 * Set the locked options flag on this admin setting.
1613 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1614 * @param bool $default - The default for the flag
1616 public function set_locked_flag_options($enabled, $default) {
1617 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1621 * Get the currently saved value for a setting flag
1623 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1624 * @return bool
1626 public function get_setting_flag_value(admin_setting_flag $flag) {
1627 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1628 if (!isset($value)) {
1629 $value = $flag->get_default();
1632 return !empty($value);
1636 * Get the list of defaults for the flags on this setting.
1638 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1640 public function get_setting_flag_defaults(& $defaults) {
1641 foreach ($this->flags as $flag) {
1642 if ($flag->is_enabled() && $flag->get_default()) {
1643 $defaults[] = $flag->get_displayname();
1649 * Output the input fields for the advanced and locked flags on this setting.
1651 * @param bool $adv - The current value of the advanced flag.
1652 * @param bool $locked - The current value of the locked flag.
1653 * @return string $output - The html for the flags.
1655 public function output_setting_flags() {
1656 $output = '';
1658 foreach ($this->flags as $flag) {
1659 if ($flag->is_enabled()) {
1660 $output .= $flag->output_setting_flag($this);
1664 if (!empty($output)) {
1665 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1667 return $output;
1671 * Write the values of the flags for this admin setting.
1673 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1674 * @return bool - true if successful.
1676 public function write_setting_flags($data) {
1677 $result = true;
1678 foreach ($this->flags as $flag) {
1679 $result = $result && $flag->write_setting_flag($this, $data);
1681 return $result;
1685 * Set up $this->name and potentially $this->plugin
1687 * Set up $this->name and possibly $this->plugin based on whether $name looks
1688 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1689 * on the names, that is, output a developer debug warning if the name
1690 * contains anything other than [a-zA-Z0-9_]+.
1692 * @param string $name the setting name passed in to the constructor.
1694 private function parse_setting_name($name) {
1695 $bits = explode('/', $name);
1696 if (count($bits) > 2) {
1697 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1699 $this->name = array_pop($bits);
1700 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1701 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1703 if (!empty($bits)) {
1704 $this->plugin = array_pop($bits);
1705 if ($this->plugin === 'moodle') {
1706 $this->plugin = null;
1707 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1708 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1714 * Returns the fullname prefixed by the plugin
1715 * @return string
1717 public function get_full_name() {
1718 return 's_'.$this->plugin.'_'.$this->name;
1722 * Returns the ID string based on plugin and name
1723 * @return string
1725 public function get_id() {
1726 return 'id_s_'.$this->plugin.'_'.$this->name;
1730 * @param bool $affectsmodinfo If true, changes to this setting will
1731 * cause the course cache to be rebuilt
1733 public function set_affects_modinfo($affectsmodinfo) {
1734 $this->affectsmodinfo = $affectsmodinfo;
1738 * Returns the config if possible
1740 * @return mixed returns config if successful else null
1742 public function config_read($name) {
1743 global $CFG;
1744 if (!empty($this->plugin)) {
1745 $value = get_config($this->plugin, $name);
1746 return $value === false ? NULL : $value;
1748 } else {
1749 if (isset($CFG->$name)) {
1750 return $CFG->$name;
1751 } else {
1752 return NULL;
1758 * Used to set a config pair and log change
1760 * @param string $name
1761 * @param mixed $value Gets converted to string if not null
1762 * @return bool Write setting to config table
1764 public function config_write($name, $value) {
1765 global $DB, $USER, $CFG;
1767 if ($this->nosave) {
1768 return true;
1771 // make sure it is a real change
1772 $oldvalue = get_config($this->plugin, $name);
1773 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1774 $value = is_null($value) ? null : (string)$value;
1776 if ($oldvalue === $value) {
1777 return true;
1780 // store change
1781 set_config($name, $value, $this->plugin);
1783 // Some admin settings affect course modinfo
1784 if ($this->affectsmodinfo) {
1785 // Clear course cache for all courses
1786 rebuild_course_cache(0, true);
1789 $this->add_to_config_log($name, $oldvalue, $value);
1791 return true; // BC only
1795 * Log config changes if necessary.
1796 * @param string $name
1797 * @param string $oldvalue
1798 * @param string $value
1800 protected function add_to_config_log($name, $oldvalue, $value) {
1801 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1805 * Returns current value of this setting
1806 * @return mixed array or string depending on instance, NULL means not set yet
1808 public abstract function get_setting();
1811 * Returns default setting if exists
1812 * @return mixed array or string depending on instance; NULL means no default, user must supply
1814 public function get_defaultsetting() {
1815 $adminroot = admin_get_root(false, false);
1816 if (!empty($adminroot->custom_defaults)) {
1817 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1818 if (isset($adminroot->custom_defaults[$plugin])) {
1819 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1820 return $adminroot->custom_defaults[$plugin][$this->name];
1824 return $this->defaultsetting;
1828 * Store new setting
1830 * @param mixed $data string or array, must not be NULL
1831 * @return string empty string if ok, string error message otherwise
1833 public abstract function write_setting($data);
1836 * Return part of form with setting
1837 * This function should always be overwritten
1839 * @param mixed $data array or string depending on setting
1840 * @param string $query
1841 * @return string
1843 public function output_html($data, $query='') {
1844 // should be overridden
1845 return;
1849 * Function called if setting updated - cleanup, cache reset, etc.
1850 * @param string $functionname Sets the function name
1851 * @return void
1853 public function set_updatedcallback($functionname) {
1854 $this->updatedcallback = $functionname;
1858 * Execute postupdatecallback if necessary.
1859 * @param mixed $original original value before write_setting()
1860 * @return bool true if changed, false if not.
1862 public function post_write_settings($original) {
1863 // Comparison must work for arrays too.
1864 if (serialize($original) === serialize($this->get_setting())) {
1865 return false;
1868 $callbackfunction = $this->updatedcallback;
1869 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
1870 $callbackfunction($this->get_full_name());
1872 return true;
1876 * Is setting related to query text - used when searching
1877 * @param string $query
1878 * @return bool
1880 public function is_related($query) {
1881 if (strpos(strtolower($this->name), $query) !== false) {
1882 return true;
1884 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1885 return true;
1887 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1888 return true;
1890 $current = $this->get_setting();
1891 if (!is_null($current)) {
1892 if (is_string($current)) {
1893 if (strpos(core_text::strtolower($current), $query) !== false) {
1894 return true;
1898 $default = $this->get_defaultsetting();
1899 if (!is_null($default)) {
1900 if (is_string($default)) {
1901 if (strpos(core_text::strtolower($default), $query) !== false) {
1902 return true;
1906 return false;
1910 * Get whether this should be displayed in LTR mode.
1912 * @return bool|null
1914 public function get_force_ltr() {
1915 return $this->forceltr;
1919 * Set whether to force LTR or not.
1921 * @param bool $value True when forced, false when not force, null when unknown.
1923 public function set_force_ltr($value) {
1924 $this->forceltr = $value;
1929 * An additional option that can be applied to an admin setting.
1930 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1934 class admin_setting_flag {
1935 /** @var bool Flag to indicate if this option can be toggled for this setting */
1936 private $enabled = false;
1937 /** @var bool Flag to indicate if this option defaults to true or false */
1938 private $default = false;
1939 /** @var string Short string used to create setting name - e.g. 'adv' */
1940 private $shortname = '';
1941 /** @var string String used as the label for this flag */
1942 private $displayname = '';
1943 /** @const Checkbox for this flag is displayed in admin page */
1944 const ENABLED = true;
1945 /** @const Checkbox for this flag is not displayed in admin page */
1946 const DISABLED = false;
1949 * Constructor
1951 * @param bool $enabled Can this option can be toggled.
1952 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1953 * @param bool $default The default checked state for this setting option.
1954 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1955 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1957 public function __construct($enabled, $default, $shortname, $displayname) {
1958 $this->shortname = $shortname;
1959 $this->displayname = $displayname;
1960 $this->set_options($enabled, $default);
1964 * Update the values of this setting options class
1966 * @param bool $enabled Can this option can be toggled.
1967 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1968 * @param bool $default The default checked state for this setting option.
1970 public function set_options($enabled, $default) {
1971 $this->enabled = $enabled;
1972 $this->default = $default;
1976 * Should this option appear in the interface and be toggleable?
1978 * @return bool Is it enabled?
1980 public function is_enabled() {
1981 return $this->enabled;
1985 * Should this option be checked by default?
1987 * @return bool Is it on by default?
1989 public function get_default() {
1990 return $this->default;
1994 * Return the short name for this flag. e.g. 'adv' or 'locked'
1996 * @return string
1998 public function get_shortname() {
1999 return $this->shortname;
2003 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2005 * @return string
2007 public function get_displayname() {
2008 return $this->displayname;
2012 * Save the submitted data for this flag - or set it to the default if $data is null.
2014 * @param admin_setting $setting - The admin setting for this flag
2015 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2016 * @return bool
2018 public function write_setting_flag(admin_setting $setting, $data) {
2019 $result = true;
2020 if ($this->is_enabled()) {
2021 if (!isset($data)) {
2022 $value = $this->get_default();
2023 } else {
2024 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2026 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2029 return $result;
2034 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2036 * @param admin_setting $setting - The admin setting for this flag
2037 * @return string - The html for the checkbox.
2039 public function output_setting_flag(admin_setting $setting) {
2040 global $OUTPUT;
2042 $value = $setting->get_setting_flag_value($this);
2044 $context = new stdClass();
2045 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2046 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2047 $context->value = 1;
2048 $context->checked = $value ? true : false;
2049 $context->label = $this->get_displayname();
2051 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2057 * No setting - just heading and text.
2059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2061 class admin_setting_heading extends admin_setting {
2064 * not a setting, just text
2065 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2066 * @param string $heading heading
2067 * @param string $information text in box
2069 public function __construct($name, $heading, $information) {
2070 $this->nosave = true;
2071 parent::__construct($name, $heading, $information, '');
2075 * Always returns true
2076 * @return bool Always returns true
2078 public function get_setting() {
2079 return true;
2083 * Always returns true
2084 * @return bool Always returns true
2086 public function get_defaultsetting() {
2087 return true;
2091 * Never write settings
2092 * @return string Always returns an empty string
2094 public function write_setting($data) {
2095 // do not write any setting
2096 return '';
2100 * Returns an HTML string
2101 * @return string Returns an HTML string
2103 public function output_html($data, $query='') {
2104 global $OUTPUT;
2105 $context = new stdClass();
2106 $context->title = $this->visiblename;
2107 $context->description = $this->description;
2108 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2109 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2115 * The most flexible setting, the user enters text.
2117 * This type of field should be used for config settings which are using
2118 * English words and are not localised (passwords, database name, list of values, ...).
2120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2122 class admin_setting_configtext extends admin_setting {
2124 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2125 public $paramtype;
2126 /** @var int default field size */
2127 public $size;
2130 * Config text constructor
2132 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2133 * @param string $visiblename localised
2134 * @param string $description long localised info
2135 * @param string $defaultsetting
2136 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2137 * @param int $size default field size
2139 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2140 $this->paramtype = $paramtype;
2141 if (!is_null($size)) {
2142 $this->size = $size;
2143 } else {
2144 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2146 parent::__construct($name, $visiblename, $description, $defaultsetting);
2150 * Get whether this should be displayed in LTR mode.
2152 * Try to guess from the PARAM type unless specifically set.
2154 public function get_force_ltr() {
2155 $forceltr = parent::get_force_ltr();
2156 if ($forceltr === null) {
2157 return !is_rtl_compatible($this->paramtype);
2159 return $forceltr;
2163 * Return the setting
2165 * @return mixed returns config if successful else null
2167 public function get_setting() {
2168 return $this->config_read($this->name);
2171 public function write_setting($data) {
2172 if ($this->paramtype === PARAM_INT and $data === '') {
2173 // do not complain if '' used instead of 0
2174 $data = 0;
2176 // $data is a string
2177 $validated = $this->validate($data);
2178 if ($validated !== true) {
2179 return $validated;
2181 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2185 * Validate data before storage
2186 * @param string data
2187 * @return mixed true if ok string if error found
2189 public function validate($data) {
2190 // allow paramtype to be a custom regex if it is the form of /pattern/
2191 if (preg_match('#^/.*/$#', $this->paramtype)) {
2192 if (preg_match($this->paramtype, $data)) {
2193 return true;
2194 } else {
2195 return get_string('validateerror', 'admin');
2198 } else if ($this->paramtype === PARAM_RAW) {
2199 return true;
2201 } else {
2202 $cleaned = clean_param($data, $this->paramtype);
2203 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2204 return true;
2205 } else {
2206 return get_string('validateerror', 'admin');
2212 * Return an XHTML string for the setting
2213 * @return string Returns an XHTML string
2215 public function output_html($data, $query='') {
2216 global $OUTPUT;
2218 $default = $this->get_defaultsetting();
2219 $context = (object) [
2220 'size' => $this->size,
2221 'id' => $this->get_id(),
2222 'name' => $this->get_full_name(),
2223 'value' => $data,
2224 'forceltr' => $this->get_force_ltr(),
2226 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2228 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2233 * Text input with a maximum length constraint.
2235 * @copyright 2015 onwards Ankit Agarwal
2236 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2238 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2240 /** @var int maximum number of chars allowed. */
2241 protected $maxlength;
2244 * Config text constructor
2246 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2247 * or 'myplugin/mysetting' for ones in config_plugins.
2248 * @param string $visiblename localised
2249 * @param string $description long localised info
2250 * @param string $defaultsetting
2251 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2252 * @param int $size default field size
2253 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2255 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2256 $size=null, $maxlength = 0) {
2257 $this->maxlength = $maxlength;
2258 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2262 * Validate data before storage
2264 * @param string $data data
2265 * @return mixed true if ok string if error found
2267 public function validate($data) {
2268 $parentvalidation = parent::validate($data);
2269 if ($parentvalidation === true) {
2270 if ($this->maxlength > 0) {
2271 // Max length check.
2272 $length = core_text::strlen($data);
2273 if ($length > $this->maxlength) {
2274 return get_string('maximumchars', 'moodle', $this->maxlength);
2276 return true;
2277 } else {
2278 return true; // No max length check needed.
2280 } else {
2281 return $parentvalidation;
2287 * General text area without html editor.
2289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2291 class admin_setting_configtextarea extends admin_setting_configtext {
2292 private $rows;
2293 private $cols;
2296 * @param string $name
2297 * @param string $visiblename
2298 * @param string $description
2299 * @param mixed $defaultsetting string or array
2300 * @param mixed $paramtype
2301 * @param string $cols The number of columns to make the editor
2302 * @param string $rows The number of rows to make the editor
2304 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2305 $this->rows = $rows;
2306 $this->cols = $cols;
2307 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2311 * Returns an XHTML string for the editor
2313 * @param string $data
2314 * @param string $query
2315 * @return string XHTML string for the editor
2317 public function output_html($data, $query='') {
2318 global $OUTPUT;
2320 $default = $this->get_defaultsetting();
2321 $defaultinfo = $default;
2322 if (!is_null($default) and $default !== '') {
2323 $defaultinfo = "\n".$default;
2326 $context = (object) [
2327 'cols' => $this->cols,
2328 'rows' => $this->rows,
2329 'id' => $this->get_id(),
2330 'name' => $this->get_full_name(),
2331 'value' => $data,
2332 'forceltr' => $this->get_force_ltr(),
2334 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2336 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2341 * General text area with html editor.
2343 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2346 * @param string $name
2347 * @param string $visiblename
2348 * @param string $description
2349 * @param mixed $defaultsetting string or array
2350 * @param mixed $paramtype
2352 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2353 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2354 $this->set_force_ltr(false);
2355 editors_head_setup();
2359 * Returns an XHTML string for the editor
2361 * @param string $data
2362 * @param string $query
2363 * @return string XHTML string for the editor
2365 public function output_html($data, $query='') {
2366 $editor = editors_get_preferred_editor(FORMAT_HTML);
2367 $editor->set_text($data);
2368 $editor->use_editor($this->get_id(), array('noclean'=>true));
2369 return parent::output_html($data, $query);
2375 * Password field, allows unmasking of password
2377 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2379 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2382 * Constructor
2383 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2384 * @param string $visiblename localised
2385 * @param string $description long localised info
2386 * @param string $defaultsetting default password
2388 public function __construct($name, $visiblename, $description, $defaultsetting) {
2389 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2393 * Log config changes if necessary.
2394 * @param string $name
2395 * @param string $oldvalue
2396 * @param string $value
2398 protected function add_to_config_log($name, $oldvalue, $value) {
2399 if ($value !== '') {
2400 $value = '********';
2402 if ($oldvalue !== '' and $oldvalue !== null) {
2403 $oldvalue = '********';
2405 parent::add_to_config_log($name, $oldvalue, $value);
2409 * Returns HTML for the field.
2411 * @param string $data Value for the field
2412 * @param string $query Passed as final argument for format_admin_setting
2413 * @return string Rendered HTML
2415 public function output_html($data, $query='') {
2416 global $OUTPUT;
2417 $context = (object) [
2418 'id' => $this->get_id(),
2419 'name' => $this->get_full_name(),
2420 'size' => $this->size,
2421 'value' => $data,
2422 'forceltr' => $this->get_force_ltr(),
2424 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2425 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2431 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2432 * Note: Only advanced makes sense right now - locked does not.
2434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2436 class admin_setting_configempty extends admin_setting_configtext {
2439 * @param string $name
2440 * @param string $visiblename
2441 * @param string $description
2443 public function __construct($name, $visiblename, $description) {
2444 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2448 * Returns an XHTML string for the hidden field
2450 * @param string $data
2451 * @param string $query
2452 * @return string XHTML string for the editor
2454 public function output_html($data, $query='') {
2455 global $OUTPUT;
2457 $context = (object) [
2458 'id' => $this->get_id(),
2459 'name' => $this->get_full_name()
2461 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2463 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2469 * Path to directory
2471 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2473 class admin_setting_configfile extends admin_setting_configtext {
2475 * Constructor
2476 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2477 * @param string $visiblename localised
2478 * @param string $description long localised info
2479 * @param string $defaultdirectory default directory location
2481 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2482 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2486 * Returns XHTML for the field
2488 * Returns XHTML for the field and also checks whether the file
2489 * specified in $data exists using file_exists()
2491 * @param string $data File name and path to use in value attr
2492 * @param string $query
2493 * @return string XHTML field
2495 public function output_html($data, $query='') {
2496 global $CFG, $OUTPUT;
2498 $default = $this->get_defaultsetting();
2499 $context = (object) [
2500 'id' => $this->get_id(),
2501 'name' => $this->get_full_name(),
2502 'size' => $this->size,
2503 'value' => $data,
2504 'showvalidity' => !empty($data),
2505 'valid' => $data && file_exists($data),
2506 'readonly' => !empty($CFG->preventexecpath),
2507 'forceltr' => $this->get_force_ltr(),
2510 if ($context->readonly) {
2511 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2514 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2516 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2520 * Checks if execpatch has been disabled in config.php
2522 public function write_setting($data) {
2523 global $CFG;
2524 if (!empty($CFG->preventexecpath)) {
2525 if ($this->get_setting() === null) {
2526 // Use default during installation.
2527 $data = $this->get_defaultsetting();
2528 if ($data === null) {
2529 $data = '';
2531 } else {
2532 return '';
2535 return parent::write_setting($data);
2542 * Path to executable file
2544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2546 class admin_setting_configexecutable extends admin_setting_configfile {
2549 * Returns an XHTML field
2551 * @param string $data This is the value for the field
2552 * @param string $query
2553 * @return string XHTML field
2555 public function output_html($data, $query='') {
2556 global $CFG, $OUTPUT;
2557 $default = $this->get_defaultsetting();
2558 require_once("$CFG->libdir/filelib.php");
2560 $context = (object) [
2561 'id' => $this->get_id(),
2562 'name' => $this->get_full_name(),
2563 'size' => $this->size,
2564 'value' => $data,
2565 'showvalidity' => !empty($data),
2566 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2567 'readonly' => !empty($CFG->preventexecpath),
2568 'forceltr' => $this->get_force_ltr()
2571 if (!empty($CFG->preventexecpath)) {
2572 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2575 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2577 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2583 * Path to directory
2585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2587 class admin_setting_configdirectory extends admin_setting_configfile {
2590 * Returns an XHTML field
2592 * @param string $data This is the value for the field
2593 * @param string $query
2594 * @return string XHTML
2596 public function output_html($data, $query='') {
2597 global $CFG, $OUTPUT;
2598 $default = $this->get_defaultsetting();
2600 $context = (object) [
2601 'id' => $this->get_id(),
2602 'name' => $this->get_full_name(),
2603 'size' => $this->size,
2604 'value' => $data,
2605 'showvalidity' => !empty($data),
2606 'valid' => $data && file_exists($data) && is_dir($data),
2607 'readonly' => !empty($CFG->preventexecpath),
2608 'forceltr' => $this->get_force_ltr()
2611 if (!empty($CFG->preventexecpath)) {
2612 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2615 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2617 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2623 * Checkbox
2625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2627 class admin_setting_configcheckbox extends admin_setting {
2628 /** @var string Value used when checked */
2629 public $yes;
2630 /** @var string Value used when not checked */
2631 public $no;
2634 * Constructor
2635 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2636 * @param string $visiblename localised
2637 * @param string $description long localised info
2638 * @param string $defaultsetting
2639 * @param string $yes value used when checked
2640 * @param string $no value used when not checked
2642 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2643 parent::__construct($name, $visiblename, $description, $defaultsetting);
2644 $this->yes = (string)$yes;
2645 $this->no = (string)$no;
2649 * Retrieves the current setting using the objects name
2651 * @return string
2653 public function get_setting() {
2654 return $this->config_read($this->name);
2658 * Sets the value for the setting
2660 * Sets the value for the setting to either the yes or no values
2661 * of the object by comparing $data to yes
2663 * @param mixed $data Gets converted to str for comparison against yes value
2664 * @return string empty string or error
2666 public function write_setting($data) {
2667 if ((string)$data === $this->yes) { // convert to strings before comparison
2668 $data = $this->yes;
2669 } else {
2670 $data = $this->no;
2672 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2676 * Returns an XHTML checkbox field
2678 * @param string $data If $data matches yes then checkbox is checked
2679 * @param string $query
2680 * @return string XHTML field
2682 public function output_html($data, $query='') {
2683 global $OUTPUT;
2685 $context = (object) [
2686 'id' => $this->get_id(),
2687 'name' => $this->get_full_name(),
2688 'no' => $this->no,
2689 'value' => $this->yes,
2690 'checked' => (string) $data === $this->yes,
2693 $default = $this->get_defaultsetting();
2694 if (!is_null($default)) {
2695 if ((string)$default === $this->yes) {
2696 $defaultinfo = get_string('checkboxyes', 'admin');
2697 } else {
2698 $defaultinfo = get_string('checkboxno', 'admin');
2700 } else {
2701 $defaultinfo = NULL;
2704 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2706 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2712 * Multiple checkboxes, each represents different value, stored in csv format
2714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2716 class admin_setting_configmulticheckbox extends admin_setting {
2717 /** @var array Array of choices value=>label */
2718 public $choices;
2721 * Constructor: uses parent::__construct
2723 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2724 * @param string $visiblename localised
2725 * @param string $description long localised info
2726 * @param array $defaultsetting array of selected
2727 * @param array $choices array of $value=>$label for each checkbox
2729 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2730 $this->choices = $choices;
2731 parent::__construct($name, $visiblename, $description, $defaultsetting);
2735 * This public function may be used in ancestors for lazy loading of choices
2737 * @todo Check if this function is still required content commented out only returns true
2738 * @return bool true if loaded, false if error
2740 public function load_choices() {
2742 if (is_array($this->choices)) {
2743 return true;
2745 .... load choices here
2747 return true;
2751 * Is setting related to query text - used when searching
2753 * @param string $query
2754 * @return bool true on related, false on not or failure
2756 public function is_related($query) {
2757 if (!$this->load_choices() or empty($this->choices)) {
2758 return false;
2760 if (parent::is_related($query)) {
2761 return true;
2764 foreach ($this->choices as $desc) {
2765 if (strpos(core_text::strtolower($desc), $query) !== false) {
2766 return true;
2769 return false;
2773 * Returns the current setting if it is set
2775 * @return mixed null if null, else an array
2777 public function get_setting() {
2778 $result = $this->config_read($this->name);
2780 if (is_null($result)) {
2781 return NULL;
2783 if ($result === '') {
2784 return array();
2786 $enabled = explode(',', $result);
2787 $setting = array();
2788 foreach ($enabled as $option) {
2789 $setting[$option] = 1;
2791 return $setting;
2795 * Saves the setting(s) provided in $data
2797 * @param array $data An array of data, if not array returns empty str
2798 * @return mixed empty string on useless data or bool true=success, false=failed
2800 public function write_setting($data) {
2801 if (!is_array($data)) {
2802 return ''; // ignore it
2804 if (!$this->load_choices() or empty($this->choices)) {
2805 return '';
2807 unset($data['xxxxx']);
2808 $result = array();
2809 foreach ($data as $key => $value) {
2810 if ($value and array_key_exists($key, $this->choices)) {
2811 $result[] = $key;
2814 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2818 * Returns XHTML field(s) as required by choices
2820 * Relies on data being an array should data ever be another valid vartype with
2821 * acceptable value this may cause a warning/error
2822 * if (!is_array($data)) would fix the problem
2824 * @todo Add vartype handling to ensure $data is an array
2826 * @param array $data An array of checked values
2827 * @param string $query
2828 * @return string XHTML field
2830 public function output_html($data, $query='') {
2831 global $OUTPUT;
2833 if (!$this->load_choices() or empty($this->choices)) {
2834 return '';
2837 $default = $this->get_defaultsetting();
2838 if (is_null($default)) {
2839 $default = array();
2841 if (is_null($data)) {
2842 $data = array();
2845 $context = (object) [
2846 'id' => $this->get_id(),
2847 'name' => $this->get_full_name(),
2850 $options = array();
2851 $defaults = array();
2852 foreach ($this->choices as $key => $description) {
2853 if (!empty($default[$key])) {
2854 $defaults[] = $description;
2857 $options[] = [
2858 'key' => $key,
2859 'checked' => !empty($data[$key]),
2860 'label' => highlightfast($query, $description)
2864 if (is_null($default)) {
2865 $defaultinfo = null;
2866 } else if (!empty($defaults)) {
2867 $defaultinfo = implode(', ', $defaults);
2868 } else {
2869 $defaultinfo = get_string('none');
2872 $context->options = $options;
2873 $context->hasoptions = !empty($options);
2875 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
2877 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
2884 * Multiple checkboxes 2, value stored as string 00101011
2886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2888 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2891 * Returns the setting if set
2893 * @return mixed null if not set, else an array of set settings
2895 public function get_setting() {
2896 $result = $this->config_read($this->name);
2897 if (is_null($result)) {
2898 return NULL;
2900 if (!$this->load_choices()) {
2901 return NULL;
2903 $result = str_pad($result, count($this->choices), '0');
2904 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2905 $setting = array();
2906 foreach ($this->choices as $key=>$unused) {
2907 $value = array_shift($result);
2908 if ($value) {
2909 $setting[$key] = 1;
2912 return $setting;
2916 * Save setting(s) provided in $data param
2918 * @param array $data An array of settings to save
2919 * @return mixed empty string for bad data or bool true=>success, false=>error
2921 public function write_setting($data) {
2922 if (!is_array($data)) {
2923 return ''; // ignore it
2925 if (!$this->load_choices() or empty($this->choices)) {
2926 return '';
2928 $result = '';
2929 foreach ($this->choices as $key=>$unused) {
2930 if (!empty($data[$key])) {
2931 $result .= '1';
2932 } else {
2933 $result .= '0';
2936 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2942 * Select one value from list
2944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2946 class admin_setting_configselect extends admin_setting {
2947 /** @var array Array of choices value=>label */
2948 public $choices;
2949 /** @var array Array of choices grouped using optgroups */
2950 public $optgroups;
2953 * Constructor
2954 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2955 * @param string $visiblename localised
2956 * @param string $description long localised info
2957 * @param string|int $defaultsetting
2958 * @param array $choices array of $value=>$label for each selection
2960 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2961 // Look for optgroup and single options.
2962 if (is_array($choices)) {
2963 $this->choices = [];
2964 foreach ($choices as $key => $val) {
2965 if (is_array($val)) {
2966 $this->optgroups[$key] = $val;
2967 $this->choices = array_merge($this->choices, $val);
2968 } else {
2969 $this->choices[$key] = $val;
2974 parent::__construct($name, $visiblename, $description, $defaultsetting);
2978 * This function may be used in ancestors for lazy loading of choices
2980 * Override this method if loading of choices is expensive, such
2981 * as when it requires multiple db requests.
2983 * @return bool true if loaded, false if error
2985 public function load_choices() {
2987 if (is_array($this->choices)) {
2988 return true;
2990 .... load choices here
2992 return true;
2996 * Check if this is $query is related to a choice
2998 * @param string $query
2999 * @return bool true if related, false if not
3001 public function is_related($query) {
3002 if (parent::is_related($query)) {
3003 return true;
3005 if (!$this->load_choices()) {
3006 return false;
3008 foreach ($this->choices as $key=>$value) {
3009 if (strpos(core_text::strtolower($key), $query) !== false) {
3010 return true;
3012 if (strpos(core_text::strtolower($value), $query) !== false) {
3013 return true;
3016 return false;
3020 * Return the setting
3022 * @return mixed returns config if successful else null
3024 public function get_setting() {
3025 return $this->config_read($this->name);
3029 * Save a setting
3031 * @param string $data
3032 * @return string empty of error string
3034 public function write_setting($data) {
3035 if (!$this->load_choices() or empty($this->choices)) {
3036 return '';
3038 if (!array_key_exists($data, $this->choices)) {
3039 return ''; // ignore it
3042 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3046 * Returns XHTML select field
3048 * Ensure the options are loaded, and generate the XHTML for the select
3049 * element and any warning message. Separating this out from output_html
3050 * makes it easier to subclass this class.
3052 * @param string $data the option to show as selected.
3053 * @param string $current the currently selected option in the database, null if none.
3054 * @param string $default the default selected option.
3055 * @return array the HTML for the select element, and a warning message.
3056 * @deprecated since Moodle 3.2
3058 public function output_select_html($data, $current, $default, $extraname = '') {
3059 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3063 * Returns XHTML select field and wrapping div(s)
3065 * @see output_select_html()
3067 * @param string $data the option to show as selected
3068 * @param string $query
3069 * @return string XHTML field and wrapping div
3071 public function output_html($data, $query='') {
3072 global $OUTPUT;
3074 $default = $this->get_defaultsetting();
3075 $current = $this->get_setting();
3077 if (!$this->load_choices() || empty($this->choices)) {
3078 return '';
3081 $context = (object) [
3082 'id' => $this->get_id(),
3083 'name' => $this->get_full_name(),
3086 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3087 $defaultinfo = $this->choices[$default];
3088 } else {
3089 $defaultinfo = NULL;
3092 // Warnings.
3093 $warning = '';
3094 if ($current === null) {
3095 // First run.
3096 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3097 // No warning.
3098 } else if (!array_key_exists($current, $this->choices)) {
3099 $warning = get_string('warningcurrentsetting', 'admin', $current);
3100 if (!is_null($default) && $data == $current) {
3101 $data = $default; // Use default instead of first value when showing the form.
3105 $options = [];
3106 $template = 'core_admin/setting_configselect';
3108 if (!empty($this->optgroups)) {
3109 $optgroups = [];
3110 foreach ($this->optgroups as $label => $choices) {
3111 $optgroup = array('label' => $label, 'options' => []);
3112 foreach ($choices as $value => $name) {
3113 $optgroup['options'][] = [
3114 'value' => $value,
3115 'name' => $name,
3116 'selected' => (string) $value == $data
3118 unset($this->choices[$value]);
3120 $optgroups[] = $optgroup;
3122 $context->options = $options;
3123 $context->optgroups = $optgroups;
3124 $template = 'core_admin/setting_configselect_optgroup';
3127 foreach ($this->choices as $value => $name) {
3128 $options[] = [
3129 'value' => $value,
3130 'name' => $name,
3131 'selected' => (string) $value == $data
3134 $context->options = $options;
3136 $element = $OUTPUT->render_from_template($template, $context);
3138 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3144 * Select multiple items from list
3146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3148 class admin_setting_configmultiselect extends admin_setting_configselect {
3150 * Constructor
3151 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3152 * @param string $visiblename localised
3153 * @param string $description long localised info
3154 * @param array $defaultsetting array of selected items
3155 * @param array $choices array of $value=>$label for each list item
3157 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3158 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3162 * Returns the select setting(s)
3164 * @return mixed null or array. Null if no settings else array of setting(s)
3166 public function get_setting() {
3167 $result = $this->config_read($this->name);
3168 if (is_null($result)) {
3169 return NULL;
3171 if ($result === '') {
3172 return array();
3174 return explode(',', $result);
3178 * Saves setting(s) provided through $data
3180 * Potential bug in the works should anyone call with this function
3181 * using a vartype that is not an array
3183 * @param array $data
3185 public function write_setting($data) {
3186 if (!is_array($data)) {
3187 return ''; //ignore it
3189 if (!$this->load_choices() or empty($this->choices)) {
3190 return '';
3193 unset($data['xxxxx']);
3195 $save = array();
3196 foreach ($data as $value) {
3197 if (!array_key_exists($value, $this->choices)) {
3198 continue; // ignore it
3200 $save[] = $value;
3203 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3207 * Is setting related to query text - used when searching
3209 * @param string $query
3210 * @return bool true if related, false if not
3212 public function is_related($query) {
3213 if (!$this->load_choices() or empty($this->choices)) {
3214 return false;
3216 if (parent::is_related($query)) {
3217 return true;
3220 foreach ($this->choices as $desc) {
3221 if (strpos(core_text::strtolower($desc), $query) !== false) {
3222 return true;
3225 return false;
3229 * Returns XHTML multi-select field
3231 * @todo Add vartype handling to ensure $data is an array
3232 * @param array $data Array of values to select by default
3233 * @param string $query
3234 * @return string XHTML multi-select field
3236 public function output_html($data, $query='') {
3237 global $OUTPUT;
3239 if (!$this->load_choices() or empty($this->choices)) {
3240 return '';
3243 $default = $this->get_defaultsetting();
3244 if (is_null($default)) {
3245 $default = array();
3247 if (is_null($data)) {
3248 $data = array();
3251 $context = (object) [
3252 'id' => $this->get_id(),
3253 'name' => $this->get_full_name(),
3254 'size' => min(10, count($this->choices))
3257 $defaults = [];
3258 $options = [];
3259 $template = 'core_admin/setting_configmultiselect';
3261 if (!empty($this->optgroups)) {
3262 $optgroups = [];
3263 foreach ($this->optgroups as $label => $choices) {
3264 $optgroup = array('label' => $label, 'options' => []);
3265 foreach ($choices as $value => $name) {
3266 if (in_array($value, $default)) {
3267 $defaults[] = $name;
3269 $optgroup['options'][] = [
3270 'value' => $value,
3271 'name' => $name,
3272 'selected' => in_array($value, $data)
3274 unset($this->choices[$value]);
3276 $optgroups[] = $optgroup;
3278 $context->optgroups = $optgroups;
3279 $template = 'core_admin/setting_configmultiselect_optgroup';
3282 foreach ($this->choices as $value => $name) {
3283 if (in_array($value, $default)) {
3284 $defaults[] = $name;
3286 $options[] = [
3287 'value' => $value,
3288 'name' => $name,
3289 'selected' => in_array($value, $data)
3292 $context->options = $options;
3294 if (is_null($default)) {
3295 $defaultinfo = NULL;
3296 } if (!empty($defaults)) {
3297 $defaultinfo = implode(', ', $defaults);
3298 } else {
3299 $defaultinfo = get_string('none');
3302 $element = $OUTPUT->render_from_template($template, $context);
3304 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3309 * Time selector
3311 * This is a liiitle bit messy. we're using two selects, but we're returning
3312 * them as an array named after $name (so we only use $name2 internally for the setting)
3314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3316 class admin_setting_configtime extends admin_setting {
3317 /** @var string Used for setting second select (minutes) */
3318 public $name2;
3321 * Constructor
3322 * @param string $hoursname setting for hours
3323 * @param string $minutesname setting for hours
3324 * @param string $visiblename localised
3325 * @param string $description long localised info
3326 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3328 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3329 $this->name2 = $minutesname;
3330 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3334 * Get the selected time
3336 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3338 public function get_setting() {
3339 $result1 = $this->config_read($this->name);
3340 $result2 = $this->config_read($this->name2);
3341 if (is_null($result1) or is_null($result2)) {
3342 return NULL;
3345 return array('h' => $result1, 'm' => $result2);
3349 * Store the time (hours and minutes)
3351 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3352 * @return bool true if success, false if not
3354 public function write_setting($data) {
3355 if (!is_array($data)) {
3356 return '';
3359 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3360 return ($result ? '' : get_string('errorsetting', 'admin'));
3364 * Returns XHTML time select fields
3366 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3367 * @param string $query
3368 * @return string XHTML time select fields and wrapping div(s)
3370 public function output_html($data, $query='') {
3371 global $OUTPUT;
3373 $default = $this->get_defaultsetting();
3374 if (is_array($default)) {
3375 $defaultinfo = $default['h'].':'.$default['m'];
3376 } else {
3377 $defaultinfo = NULL;
3380 $context = (object) [
3381 'id' => $this->get_id(),
3382 'name' => $this->get_full_name(),
3383 'hours' => array_map(function($i) use ($data) {
3384 return [
3385 'value' => $i,
3386 'name' => $i,
3387 'selected' => $i == $data['h']
3389 }, range(0, 23)),
3390 'minutes' => array_map(function($i) use ($data) {
3391 return [
3392 'value' => $i,
3393 'name' => $i,
3394 'selected' => $i == $data['m']
3396 }, range(0, 59, 5))
3399 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3401 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3402 $this->get_id() . 'h', '', $defaultinfo, $query);
3409 * Seconds duration setting.
3411 * @copyright 2012 Petr Skoda (http://skodak.org)
3412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3414 class admin_setting_configduration extends admin_setting {
3416 /** @var int default duration unit */
3417 protected $defaultunit;
3420 * Constructor
3421 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3422 * or 'myplugin/mysetting' for ones in config_plugins.
3423 * @param string $visiblename localised name
3424 * @param string $description localised long description
3425 * @param mixed $defaultsetting string or array depending on implementation
3426 * @param int $defaultunit - day, week, etc. (in seconds)
3428 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3429 if (is_number($defaultsetting)) {
3430 $defaultsetting = self::parse_seconds($defaultsetting);
3432 $units = self::get_units();
3433 if (isset($units[$defaultunit])) {
3434 $this->defaultunit = $defaultunit;
3435 } else {
3436 $this->defaultunit = 86400;
3438 parent::__construct($name, $visiblename, $description, $defaultsetting);
3442 * Returns selectable units.
3443 * @static
3444 * @return array
3446 protected static function get_units() {
3447 return array(
3448 604800 => get_string('weeks'),
3449 86400 => get_string('days'),
3450 3600 => get_string('hours'),
3451 60 => get_string('minutes'),
3452 1 => get_string('seconds'),
3457 * Converts seconds to some more user friendly string.
3458 * @static
3459 * @param int $seconds
3460 * @return string
3462 protected static function get_duration_text($seconds) {
3463 if (empty($seconds)) {
3464 return get_string('none');
3466 $data = self::parse_seconds($seconds);
3467 switch ($data['u']) {
3468 case (60*60*24*7):
3469 return get_string('numweeks', '', $data['v']);
3470 case (60*60*24):
3471 return get_string('numdays', '', $data['v']);
3472 case (60*60):
3473 return get_string('numhours', '', $data['v']);
3474 case (60):
3475 return get_string('numminutes', '', $data['v']);
3476 default:
3477 return get_string('numseconds', '', $data['v']*$data['u']);
3482 * Finds suitable units for given duration.
3483 * @static
3484 * @param int $seconds
3485 * @return array
3487 protected static function parse_seconds($seconds) {
3488 foreach (self::get_units() as $unit => $unused) {
3489 if ($seconds % $unit === 0) {
3490 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3493 return array('v'=>(int)$seconds, 'u'=>1);
3497 * Get the selected duration as array.
3499 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3501 public function get_setting() {
3502 $seconds = $this->config_read($this->name);
3503 if (is_null($seconds)) {
3504 return null;
3507 return self::parse_seconds($seconds);
3511 * Store the duration as seconds.
3513 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3514 * @return bool true if success, false if not
3516 public function write_setting($data) {
3517 if (!is_array($data)) {
3518 return '';
3521 $seconds = (int)($data['v']*$data['u']);
3522 if ($seconds < 0) {
3523 return get_string('errorsetting', 'admin');
3526 $result = $this->config_write($this->name, $seconds);
3527 return ($result ? '' : get_string('errorsetting', 'admin'));
3531 * Returns duration text+select fields.
3533 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3534 * @param string $query
3535 * @return string duration text+select fields and wrapping div(s)
3537 public function output_html($data, $query='') {
3538 global $OUTPUT;
3540 $default = $this->get_defaultsetting();
3541 if (is_number($default)) {
3542 $defaultinfo = self::get_duration_text($default);
3543 } else if (is_array($default)) {
3544 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3545 } else {
3546 $defaultinfo = null;
3549 $inputid = $this->get_id() . 'v';
3550 $units = self::get_units();
3551 $defaultunit = $this->defaultunit;
3553 $context = (object) [
3554 'id' => $this->get_id(),
3555 'name' => $this->get_full_name(),
3556 'value' => $data['v'],
3557 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3558 return [
3559 'value' => $unit,
3560 'name' => $units[$unit],
3561 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3563 }, array_keys($units))
3566 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3568 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3574 * Seconds duration setting with an advanced checkbox, that controls a additional
3575 * $name.'_adv' setting.
3577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3578 * @copyright 2014 The Open University
3580 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3582 * Constructor
3583 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3584 * or 'myplugin/mysetting' for ones in config_plugins.
3585 * @param string $visiblename localised name
3586 * @param string $description localised long description
3587 * @param array $defaultsetting array of int value, and bool whether it is
3588 * is advanced by default.
3589 * @param int $defaultunit - day, week, etc. (in seconds)
3591 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3592 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3593 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3599 * Used to validate a textarea used for ip addresses
3601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3602 * @copyright 2011 Petr Skoda (http://skodak.org)
3604 class admin_setting_configiplist extends admin_setting_configtextarea {
3607 * Validate the contents of the textarea as IP addresses
3609 * Used to validate a new line separated list of IP addresses collected from
3610 * a textarea control
3612 * @param string $data A list of IP Addresses separated by new lines
3613 * @return mixed bool true for success or string:error on failure
3615 public function validate($data) {
3616 if(!empty($data)) {
3617 $lines = explode("\n", $data);
3618 } else {
3619 return true;
3621 $result = true;
3622 $badips = array();
3623 foreach ($lines as $line) {
3624 $tokens = explode('#', $line);
3625 $ip = trim($tokens[0]);
3626 if (empty($ip)) {
3627 continue;
3629 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3630 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3631 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3632 } else {
3633 $result = false;
3634 $badips[] = $ip;
3637 if($result) {
3638 return true;
3639 } else {
3640 return get_string('validateiperror', 'admin', join(', ', $badips));
3646 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3649 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3651 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3654 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3655 * Used to validate a new line separated list of entries collected from a textarea control.
3657 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3658 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3659 * via the get_setting() method, which has been overriden.
3661 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3662 * @return mixed bool true for success or string:error on failure
3664 public function validate($data) {
3665 if (empty($data)) {
3666 return true;
3668 $entries = explode("\n", $data);
3669 $badentries = [];
3671 foreach ($entries as $key => $entry) {
3672 $entry = trim($entry);
3673 if (empty($entry)) {
3674 return get_string('validateemptylineerror', 'admin');
3677 // Validate each string entry against the supported formats.
3678 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3679 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3680 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3681 continue;
3684 // Otherwise, the entry is invalid.
3685 $badentries[] = $entry;
3688 if ($badentries) {
3689 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3691 return true;
3695 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3697 * @param string $data the setting data, as sent from the web form.
3698 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3700 protected function ace_encode($data) {
3701 if (empty($data)) {
3702 return $data;
3704 $entries = explode("\n", $data);
3705 foreach ($entries as $key => $entry) {
3706 $entry = trim($entry);
3707 // This regex matches any string that has non-ascii character.
3708 if (preg_match('/[^\x00-\x7f]/', $entry)) {
3709 // If we can convert the unicode string to an idn, do so.
3710 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3711 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3712 $entries[$key] = $val ? $val : $entry;
3715 return implode("\n", $entries);
3719 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
3721 * @param string $data the setting data, as found in the database.
3722 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
3724 protected function ace_decode($data) {
3725 $entries = explode("\n", $data);
3726 foreach ($entries as $key => $entry) {
3727 $entry = trim($entry);
3728 if (strpos($entry, 'xn--') !== false) {
3729 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3732 return implode("\n", $entries);
3736 * Override, providing utf8-decoding for ascii-encoded IDN strings.
3738 * @return mixed returns punycode-converted setting string if successful, else null.
3740 public function get_setting() {
3741 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
3742 $data = $this->config_read($this->name);
3743 if (function_exists('idn_to_utf8') && !is_null($data)) {
3744 $data = $this->ace_decode($data);
3746 return $data;
3750 * Override, providing ascii-encoding for utf8 (native) IDN strings.
3752 * @param string $data
3753 * @return string
3755 public function write_setting($data) {
3756 if ($this->paramtype === PARAM_INT and $data === '') {
3757 // Do not complain if '' used instead of 0.
3758 $data = 0;
3761 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
3762 if (function_exists('idn_to_ascii')) {
3763 $data = $this->ace_encode($data);
3766 $validated = $this->validate($data);
3767 if ($validated !== true) {
3768 return $validated;
3770 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3775 * Used to validate a textarea used for port numbers.
3777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3778 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3780 class admin_setting_configportlist extends admin_setting_configtextarea {
3783 * Validate the contents of the textarea as port numbers.
3784 * Used to validate a new line separated list of ports collected from a textarea control.
3786 * @param string $data A list of ports separated by new lines
3787 * @return mixed bool true for success or string:error on failure
3789 public function validate($data) {
3790 if (empty($data)) {
3791 return true;
3793 $ports = explode("\n", $data);
3794 $badentries = [];
3795 foreach ($ports as $port) {
3796 $port = trim($port);
3797 if (empty($port)) {
3798 return get_string('validateemptylineerror', 'admin');
3801 // Is the string a valid integer number?
3802 if (strval(intval($port)) !== $port || intval($port) <= 0) {
3803 $badentries[] = $port;
3806 if ($badentries) {
3807 return get_string('validateerrorlist', 'admin', $badentries);
3809 return true;
3815 * An admin setting for selecting one or more users who have a capability
3816 * in the system context
3818 * An admin setting for selecting one or more users, who have a particular capability
3819 * in the system context. Warning, make sure the list will never be too long. There is
3820 * no paging or searching of this list.
3822 * To correctly get a list of users from this config setting, you need to call the
3823 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3827 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3828 /** @var string The capabilities name */
3829 protected $capability;
3830 /** @var int include admin users too */
3831 protected $includeadmins;
3834 * Constructor.
3836 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3837 * @param string $visiblename localised name
3838 * @param string $description localised long description
3839 * @param array $defaultsetting array of usernames
3840 * @param string $capability string capability name.
3841 * @param bool $includeadmins include administrators
3843 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3844 $this->capability = $capability;
3845 $this->includeadmins = $includeadmins;
3846 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3850 * Load all of the uses who have the capability into choice array
3852 * @return bool Always returns true
3854 function load_choices() {
3855 if (is_array($this->choices)) {
3856 return true;
3858 list($sort, $sortparams) = users_order_by_sql('u');
3859 if (!empty($sortparams)) {
3860 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3861 'This is unexpected, and a problem because there is no way to pass these ' .
3862 'parameters to get_users_by_capability. See MDL-34657.');
3864 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3865 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3866 $this->choices = array(
3867 '$@NONE@$' => get_string('nobody'),
3868 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3870 if ($this->includeadmins) {
3871 $admins = get_admins();
3872 foreach ($admins as $user) {
3873 $this->choices[$user->id] = fullname($user);
3876 if (is_array($users)) {
3877 foreach ($users as $user) {
3878 $this->choices[$user->id] = fullname($user);
3881 return true;
3885 * Returns the default setting for class
3887 * @return mixed Array, or string. Empty string if no default
3889 public function get_defaultsetting() {
3890 $this->load_choices();
3891 $defaultsetting = parent::get_defaultsetting();
3892 if (empty($defaultsetting)) {
3893 return array('$@NONE@$');
3894 } else if (array_key_exists($defaultsetting, $this->choices)) {
3895 return $defaultsetting;
3896 } else {
3897 return '';
3902 * Returns the current setting
3904 * @return mixed array or string
3906 public function get_setting() {
3907 $result = parent::get_setting();
3908 if ($result === null) {
3909 // this is necessary for settings upgrade
3910 return null;
3912 if (empty($result)) {
3913 $result = array('$@NONE@$');
3915 return $result;
3919 * Save the chosen setting provided as $data
3921 * @param array $data
3922 * @return mixed string or array
3924 public function write_setting($data) {
3925 // If all is selected, remove any explicit options.
3926 if (in_array('$@ALL@$', $data)) {
3927 $data = array('$@ALL@$');
3929 // None never needs to be written to the DB.
3930 if (in_array('$@NONE@$', $data)) {
3931 unset($data[array_search('$@NONE@$', $data)]);
3933 return parent::write_setting($data);
3939 * Special checkbox for calendar - resets SESSION vars.
3941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3943 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3945 * Calls the parent::__construct with default values
3947 * name => calendar_adminseesall
3948 * visiblename => get_string('adminseesall', 'admin')
3949 * description => get_string('helpadminseesall', 'admin')
3950 * defaultsetting => 0
3952 public function __construct() {
3953 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3954 get_string('helpadminseesall', 'admin'), '0');
3958 * Stores the setting passed in $data
3960 * @param mixed gets converted to string for comparison
3961 * @return string empty string or error message
3963 public function write_setting($data) {
3964 global $SESSION;
3965 return parent::write_setting($data);
3970 * Special select for settings that are altered in setup.php and can not be altered on the fly
3972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3974 class admin_setting_special_selectsetup extends admin_setting_configselect {
3976 * Reads the setting directly from the database
3978 * @return mixed
3980 public function get_setting() {
3981 // read directly from db!
3982 return get_config(NULL, $this->name);
3986 * Save the setting passed in $data
3988 * @param string $data The setting to save
3989 * @return string empty or error message
3991 public function write_setting($data) {
3992 global $CFG;
3993 // do not change active CFG setting!
3994 $current = $CFG->{$this->name};
3995 $result = parent::write_setting($data);
3996 $CFG->{$this->name} = $current;
3997 return $result;
4003 * Special select for frontpage - stores data in course table
4005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4007 class admin_setting_sitesetselect extends admin_setting_configselect {
4009 * Returns the site name for the selected site
4011 * @see get_site()
4012 * @return string The site name of the selected site
4014 public function get_setting() {
4015 $site = course_get_format(get_site())->get_course();
4016 return $site->{$this->name};
4020 * Updates the database and save the setting
4022 * @param string data
4023 * @return string empty or error message
4025 public function write_setting($data) {
4026 global $DB, $SITE, $COURSE;
4027 if (!in_array($data, array_keys($this->choices))) {
4028 return get_string('errorsetting', 'admin');
4030 $record = new stdClass();
4031 $record->id = SITEID;
4032 $temp = $this->name;
4033 $record->$temp = $data;
4034 $record->timemodified = time();
4036 course_get_format($SITE)->update_course_format_options($record);
4037 $DB->update_record('course', $record);
4039 // Reset caches.
4040 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4041 if ($SITE->id == $COURSE->id) {
4042 $COURSE = $SITE;
4044 format_base::reset_course_cache($SITE->id);
4046 return '';
4053 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4054 * block to hidden.
4056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4058 class admin_setting_bloglevel extends admin_setting_configselect {
4060 * Updates the database and save the setting
4062 * @param string data
4063 * @return string empty or error message
4065 public function write_setting($data) {
4066 global $DB, $CFG;
4067 if ($data == 0) {
4068 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4069 foreach ($blogblocks as $block) {
4070 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4072 } else {
4073 // reenable all blocks only when switching from disabled blogs
4074 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4075 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4076 foreach ($blogblocks as $block) {
4077 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4081 return parent::write_setting($data);
4087 * Special select - lists on the frontpage - hacky
4089 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4091 class admin_setting_courselist_frontpage extends admin_setting {
4092 /** @var array Array of choices value=>label */
4093 public $choices;
4096 * Construct override, requires one param
4098 * @param bool $loggedin Is the user logged in
4100 public function __construct($loggedin) {
4101 global $CFG;
4102 require_once($CFG->dirroot.'/course/lib.php');
4103 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4104 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4105 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4106 $defaults = array(FRONTPAGEALLCOURSELIST);
4107 parent::__construct($name, $visiblename, $description, $defaults);
4111 * Loads the choices available
4113 * @return bool always returns true
4115 public function load_choices() {
4116 if (is_array($this->choices)) {
4117 return true;
4119 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4120 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4121 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4122 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4123 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4124 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4125 'none' => get_string('none'));
4126 if ($this->name === 'frontpage') {
4127 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4129 return true;
4133 * Returns the selected settings
4135 * @param mixed array or setting or null
4137 public function get_setting() {
4138 $result = $this->config_read($this->name);
4139 if (is_null($result)) {
4140 return NULL;
4142 if ($result === '') {
4143 return array();
4145 return explode(',', $result);
4149 * Save the selected options
4151 * @param array $data
4152 * @return mixed empty string (data is not an array) or bool true=success false=failure
4154 public function write_setting($data) {
4155 if (!is_array($data)) {
4156 return '';
4158 $this->load_choices();
4159 $save = array();
4160 foreach($data as $datum) {
4161 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4162 continue;
4164 $save[$datum] = $datum; // no duplicates
4166 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4170 * Return XHTML select field and wrapping div
4172 * @todo Add vartype handling to make sure $data is an array
4173 * @param array $data Array of elements to select by default
4174 * @return string XHTML select field and wrapping div
4176 public function output_html($data, $query='') {
4177 global $OUTPUT;
4179 $this->load_choices();
4180 $currentsetting = array();
4181 foreach ($data as $key) {
4182 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4183 $currentsetting[] = $key; // already selected first
4187 $context = (object) [
4188 'id' => $this->get_id(),
4189 'name' => $this->get_full_name(),
4192 $options = $this->choices;
4193 $selects = [];
4194 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4195 if (!array_key_exists($i, $currentsetting)) {
4196 $currentsetting[$i] = 'none';
4198 $selects[] = [
4199 'key' => $i,
4200 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4201 return [
4202 'name' => $options[$option],
4203 'value' => $option,
4204 'selected' => $currentsetting[$i] == $option
4206 }, array_keys($options))
4209 $context->selects = $selects;
4211 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4213 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4219 * Special checkbox for frontpage - stores data in course table
4221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4223 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4225 * Returns the current sites name
4227 * @return string
4229 public function get_setting() {
4230 $site = course_get_format(get_site())->get_course();
4231 return $site->{$this->name};
4235 * Save the selected setting
4237 * @param string $data The selected site
4238 * @return string empty string or error message
4240 public function write_setting($data) {
4241 global $DB, $SITE, $COURSE;
4242 $record = new stdClass();
4243 $record->id = $SITE->id;
4244 $record->{$this->name} = ($data == '1' ? 1 : 0);
4245 $record->timemodified = time();
4247 course_get_format($SITE)->update_course_format_options($record);
4248 $DB->update_record('course', $record);
4250 // Reset caches.
4251 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4252 if ($SITE->id == $COURSE->id) {
4253 $COURSE = $SITE;
4255 format_base::reset_course_cache($SITE->id);
4257 return '';
4262 * Special text for frontpage - stores data in course table.
4263 * Empty string means not set here. Manual setting is required.
4265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4267 class admin_setting_sitesettext extends admin_setting_configtext {
4270 * Constructor.
4272 public function __construct() {
4273 call_user_func_array(['parent', '__construct'], func_get_args());
4274 $this->set_force_ltr(false);
4278 * Return the current setting
4280 * @return mixed string or null
4282 public function get_setting() {
4283 $site = course_get_format(get_site())->get_course();
4284 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4288 * Validate the selected data
4290 * @param string $data The selected value to validate
4291 * @return mixed true or message string
4293 public function validate($data) {
4294 global $DB, $SITE;
4295 $cleaned = clean_param($data, PARAM_TEXT);
4296 if ($cleaned === '') {
4297 return get_string('required');
4299 if ($this->name ==='shortname' &&
4300 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4301 return get_string('shortnametaken', 'error', $data);
4303 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4304 return true;
4305 } else {
4306 return get_string('validateerror', 'admin');
4311 * Save the selected setting
4313 * @param string $data The selected value
4314 * @return string empty or error message
4316 public function write_setting($data) {
4317 global $DB, $SITE, $COURSE;
4318 $data = trim($data);
4319 $validated = $this->validate($data);
4320 if ($validated !== true) {
4321 return $validated;
4324 $record = new stdClass();
4325 $record->id = $SITE->id;
4326 $record->{$this->name} = $data;
4327 $record->timemodified = time();
4329 course_get_format($SITE)->update_course_format_options($record);
4330 $DB->update_record('course', $record);
4332 // Reset caches.
4333 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4334 if ($SITE->id == $COURSE->id) {
4335 $COURSE = $SITE;
4337 format_base::reset_course_cache($SITE->id);
4339 return '';
4345 * Special text editor for site description.
4347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4349 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4352 * Calls parent::__construct with specific arguments
4354 public function __construct() {
4355 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4356 PARAM_RAW, 60, 15);
4360 * Return the current setting
4361 * @return string The current setting
4363 public function get_setting() {
4364 $site = course_get_format(get_site())->get_course();
4365 return $site->{$this->name};
4369 * Save the new setting
4371 * @param string $data The new value to save
4372 * @return string empty or error message
4374 public function write_setting($data) {
4375 global $DB, $SITE, $COURSE;
4376 $record = new stdClass();
4377 $record->id = $SITE->id;
4378 $record->{$this->name} = $data;
4379 $record->timemodified = time();
4381 course_get_format($SITE)->update_course_format_options($record);
4382 $DB->update_record('course', $record);
4384 // Reset caches.
4385 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4386 if ($SITE->id == $COURSE->id) {
4387 $COURSE = $SITE;
4389 format_base::reset_course_cache($SITE->id);
4391 return '';
4397 * Administration interface for emoticon_manager settings.
4399 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4401 class admin_setting_emoticons extends admin_setting {
4404 * Calls parent::__construct with specific args
4406 public function __construct() {
4407 global $CFG;
4409 $manager = get_emoticon_manager();
4410 $defaults = $this->prepare_form_data($manager->default_emoticons());
4411 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4415 * Return the current setting(s)
4417 * @return array Current settings array
4419 public function get_setting() {
4420 global $CFG;
4422 $manager = get_emoticon_manager();
4424 $config = $this->config_read($this->name);
4425 if (is_null($config)) {
4426 return null;
4429 $config = $manager->decode_stored_config($config);
4430 if (is_null($config)) {
4431 return null;
4434 return $this->prepare_form_data($config);
4438 * Save selected settings
4440 * @param array $data Array of settings to save
4441 * @return bool
4443 public function write_setting($data) {
4445 $manager = get_emoticon_manager();
4446 $emoticons = $this->process_form_data($data);
4448 if ($emoticons === false) {
4449 return false;
4452 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4453 return ''; // success
4454 } else {
4455 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4460 * Return XHTML field(s) for options
4462 * @param array $data Array of options to set in HTML
4463 * @return string XHTML string for the fields and wrapping div(s)
4465 public function output_html($data, $query='') {
4466 global $OUTPUT;
4468 $context = (object) [
4469 'name' => $this->get_full_name(),
4470 'emoticons' => [],
4471 'forceltr' => true,
4474 $i = 0;
4475 foreach ($data as $field => $value) {
4477 // When $i == 0: text.
4478 // When $i == 1: imagename.
4479 // When $i == 2: imagecomponent.
4480 // When $i == 3: altidentifier.
4481 // When $i == 4: altcomponent.
4482 $fields[$i] = (object) [
4483 'field' => $field,
4484 'value' => $value,
4485 'index' => $i
4487 $i++;
4489 if ($i > 4) {
4490 $icon = null;
4491 if (!empty($fields[1]->value)) {
4492 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4493 $alt = get_string($fields[3]->value, $fields[4]->value);
4494 } else {
4495 $alt = $fields[0]->value;
4497 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4499 $context->emoticons[] = [
4500 'fields' => $fields,
4501 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4503 $fields = [];
4504 $i = 0;
4508 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4509 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4510 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4514 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4516 * @see self::process_form_data()
4517 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4518 * @return array of form fields and their values
4520 protected function prepare_form_data(array $emoticons) {
4522 $form = array();
4523 $i = 0;
4524 foreach ($emoticons as $emoticon) {
4525 $form['text'.$i] = $emoticon->text;
4526 $form['imagename'.$i] = $emoticon->imagename;
4527 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4528 $form['altidentifier'.$i] = $emoticon->altidentifier;
4529 $form['altcomponent'.$i] = $emoticon->altcomponent;
4530 $i++;
4532 // add one more blank field set for new object
4533 $form['text'.$i] = '';
4534 $form['imagename'.$i] = '';
4535 $form['imagecomponent'.$i] = '';
4536 $form['altidentifier'.$i] = '';
4537 $form['altcomponent'.$i] = '';
4539 return $form;
4543 * Converts the data from admin settings form into an array of emoticon objects
4545 * @see self::prepare_form_data()
4546 * @param array $data array of admin form fields and values
4547 * @return false|array of emoticon objects
4549 protected function process_form_data(array $form) {
4551 $count = count($form); // number of form field values
4553 if ($count % 5) {
4554 // we must get five fields per emoticon object
4555 return false;
4558 $emoticons = array();
4559 for ($i = 0; $i < $count / 5; $i++) {
4560 $emoticon = new stdClass();
4561 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4562 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4563 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4564 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4565 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4567 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4568 // prevent from breaking http://url.addresses by accident
4569 $emoticon->text = '';
4572 if (strlen($emoticon->text) < 2) {
4573 // do not allow single character emoticons
4574 $emoticon->text = '';
4577 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4578 // emoticon text must contain some non-alphanumeric character to prevent
4579 // breaking HTML tags
4580 $emoticon->text = '';
4583 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4584 $emoticons[] = $emoticon;
4587 return $emoticons;
4594 * Special setting for limiting of the list of available languages.
4596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4598 class admin_setting_langlist extends admin_setting_configtext {
4600 * Calls parent::__construct with specific arguments
4602 public function __construct() {
4603 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4607 * Save the new setting
4609 * @param string $data The new setting
4610 * @return bool
4612 public function write_setting($data) {
4613 $return = parent::write_setting($data);
4614 get_string_manager()->reset_caches();
4615 return $return;
4621 * Selection of one of the recognised countries using the list
4622 * returned by {@link get_list_of_countries()}.
4624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4626 class admin_settings_country_select extends admin_setting_configselect {
4627 protected $includeall;
4628 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4629 $this->includeall = $includeall;
4630 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4634 * Lazy-load the available choices for the select box
4636 public function load_choices() {
4637 global $CFG;
4638 if (is_array($this->choices)) {
4639 return true;
4641 $this->choices = array_merge(
4642 array('0' => get_string('choosedots')),
4643 get_string_manager()->get_list_of_countries($this->includeall));
4644 return true;
4650 * admin_setting_configselect for the default number of sections in a course,
4651 * simply so we can lazy-load the choices.
4653 * @copyright 2011 The Open University
4654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4656 class admin_settings_num_course_sections extends admin_setting_configselect {
4657 public function __construct($name, $visiblename, $description, $defaultsetting) {
4658 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4661 /** Lazy-load the available choices for the select box */
4662 public function load_choices() {
4663 $max = get_config('moodlecourse', 'maxsections');
4664 if (!isset($max) || !is_numeric($max)) {
4665 $max = 52;
4667 for ($i = 0; $i <= $max; $i++) {
4668 $this->choices[$i] = "$i";
4670 return true;
4676 * Course category selection
4678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4680 class admin_settings_coursecat_select extends admin_setting_configselect {
4682 * Calls parent::__construct with specific arguments
4684 public function __construct($name, $visiblename, $description, $defaultsetting) {
4685 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4689 * Load the available choices for the select box
4691 * @return bool
4693 public function load_choices() {
4694 global $CFG;
4695 require_once($CFG->dirroot.'/course/lib.php');
4696 if (is_array($this->choices)) {
4697 return true;
4699 $this->choices = make_categories_options();
4700 return true;
4706 * Special control for selecting days to backup
4708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4710 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4712 * Calls parent::__construct with specific arguments
4714 public function __construct() {
4715 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4716 $this->plugin = 'backup';
4720 * Load the available choices for the select box
4722 * @return bool Always returns true
4724 public function load_choices() {
4725 if (is_array($this->choices)) {
4726 return true;
4728 $this->choices = array();
4729 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4730 foreach ($days as $day) {
4731 $this->choices[$day] = get_string($day, 'calendar');
4733 return true;
4738 * Special setting for backup auto destination.
4740 * @package core
4741 * @subpackage admin
4742 * @copyright 2014 Frédéric Massart - FMCorz.net
4743 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4745 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4748 * Calls parent::__construct with specific arguments.
4750 public function __construct() {
4751 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4755 * Check if the directory must be set, depending on backup/backup_auto_storage.
4757 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4758 * there will be conflicts if this validation happens before the other one.
4760 * @param string $data Form data.
4761 * @return string Empty when no errors.
4763 public function write_setting($data) {
4764 $storage = (int) get_config('backup', 'backup_auto_storage');
4765 if ($storage !== 0) {
4766 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4767 // The directory must exist and be writable.
4768 return get_string('backuperrorinvaliddestination');
4771 return parent::write_setting($data);
4777 * Special debug setting
4779 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4781 class admin_setting_special_debug extends admin_setting_configselect {
4783 * Calls parent::__construct with specific arguments
4785 public function __construct() {
4786 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4790 * Load the available choices for the select box
4792 * @return bool
4794 public function load_choices() {
4795 if (is_array($this->choices)) {
4796 return true;
4798 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4799 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4800 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4801 DEBUG_ALL => get_string('debugall', 'admin'),
4802 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4803 return true;
4809 * Special admin control
4811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4813 class admin_setting_special_calendar_weekend extends admin_setting {
4815 * Calls parent::__construct with specific arguments
4817 public function __construct() {
4818 $name = 'calendar_weekend';
4819 $visiblename = get_string('calendar_weekend', 'admin');
4820 $description = get_string('helpweekenddays', 'admin');
4821 $default = array ('0', '6'); // Saturdays and Sundays
4822 parent::__construct($name, $visiblename, $description, $default);
4826 * Gets the current settings as an array
4828 * @return mixed Null if none, else array of settings
4830 public function get_setting() {
4831 $result = $this->config_read($this->name);
4832 if (is_null($result)) {
4833 return NULL;
4835 if ($result === '') {
4836 return array();
4838 $settings = array();
4839 for ($i=0; $i<7; $i++) {
4840 if ($result & (1 << $i)) {
4841 $settings[] = $i;
4844 return $settings;
4848 * Save the new settings
4850 * @param array $data Array of new settings
4851 * @return bool
4853 public function write_setting($data) {
4854 if (!is_array($data)) {
4855 return '';
4857 unset($data['xxxxx']);
4858 $result = 0;
4859 foreach($data as $index) {
4860 $result |= 1 << $index;
4862 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4866 * Return XHTML to display the control
4868 * @param array $data array of selected days
4869 * @param string $query
4870 * @return string XHTML for display (field + wrapping div(s)
4872 public function output_html($data, $query='') {
4873 global $OUTPUT;
4875 // The order matters very much because of the implied numeric keys.
4876 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4877 $context = (object) [
4878 'name' => $this->get_full_name(),
4879 'id' => $this->get_id(),
4880 'days' => array_map(function($index) use ($days, $data) {
4881 return [
4882 'index' => $index,
4883 'label' => get_string($days[$index], 'calendar'),
4884 'checked' => in_array($index, $data)
4886 }, array_keys($days))
4889 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
4891 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4898 * Admin setting that allows a user to pick a behaviour.
4900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4902 class admin_setting_question_behaviour extends admin_setting_configselect {
4904 * @param string $name name of config variable
4905 * @param string $visiblename display name
4906 * @param string $description description
4907 * @param string $default default.
4909 public function __construct($name, $visiblename, $description, $default) {
4910 parent::__construct($name, $visiblename, $description, $default, null);
4914 * Load list of behaviours as choices
4915 * @return bool true => success, false => error.
4917 public function load_choices() {
4918 global $CFG;
4919 require_once($CFG->dirroot . '/question/engine/lib.php');
4920 $this->choices = question_engine::get_behaviour_options('');
4921 return true;
4927 * Admin setting that allows a user to pick appropriate roles for something.
4929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4931 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4932 /** @var array Array of capabilities which identify roles */
4933 private $types;
4936 * @param string $name Name of config variable
4937 * @param string $visiblename Display name
4938 * @param string $description Description
4939 * @param array $types Array of archetypes which identify
4940 * roles that will be enabled by default.
4942 public function __construct($name, $visiblename, $description, $types) {
4943 parent::__construct($name, $visiblename, $description, NULL, NULL);
4944 $this->types = $types;
4948 * Load roles as choices
4950 * @return bool true=>success, false=>error
4952 public function load_choices() {
4953 global $CFG, $DB;
4954 if (during_initial_install()) {
4955 return false;
4957 if (is_array($this->choices)) {
4958 return true;
4960 if ($roles = get_all_roles()) {
4961 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4962 return true;
4963 } else {
4964 return false;
4969 * Return the default setting for this control
4971 * @return array Array of default settings
4973 public function get_defaultsetting() {
4974 global $CFG;
4976 if (during_initial_install()) {
4977 return null;
4979 $result = array();
4980 foreach($this->types as $archetype) {
4981 if ($caproles = get_archetype_roles($archetype)) {
4982 foreach ($caproles as $caprole) {
4983 $result[$caprole->id] = 1;
4987 return $result;
4993 * Admin setting that is a list of installed filter plugins.
4995 * @copyright 2015 The Open University
4996 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4998 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
5001 * Constructor
5003 * @param string $name unique ascii name, either 'mysetting' for settings
5004 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5005 * @param string $visiblename localised name
5006 * @param string $description localised long description
5007 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5009 public function __construct($name, $visiblename, $description, $default) {
5010 if (empty($default)) {
5011 $default = array();
5013 $this->load_choices();
5014 foreach ($default as $plugin) {
5015 if (!isset($this->choices[$plugin])) {
5016 unset($default[$plugin]);
5019 parent::__construct($name, $visiblename, $description, $default, null);
5022 public function load_choices() {
5023 if (is_array($this->choices)) {
5024 return true;
5026 $this->choices = array();
5028 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5029 $this->choices[$plugin] = filter_get_name($plugin);
5031 return true;
5037 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5041 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5043 * Constructor
5044 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5045 * @param string $visiblename localised
5046 * @param string $description long localised info
5047 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5048 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5049 * @param int $size default field size
5051 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5052 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5053 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5059 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5061 * @copyright 2009 Petr Skoda (http://skodak.org)
5062 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5064 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5067 * Constructor
5068 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5069 * @param string $visiblename localised
5070 * @param string $description long localised info
5071 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5072 * @param string $yes value used when checked
5073 * @param string $no value used when not checked
5075 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5076 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5077 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5084 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5086 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5088 * @copyright 2010 Sam Hemelryk
5089 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5091 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5093 * Constructor
5094 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5095 * @param string $visiblename localised
5096 * @param string $description long localised info
5097 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5098 * @param string $yes value used when checked
5099 * @param string $no value used when not checked
5101 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5102 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5103 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5110 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5114 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5116 * Calls parent::__construct with specific arguments
5118 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5119 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5120 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5126 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5128 * @copyright 2017 Marina Glancy
5129 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5131 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5133 * Constructor
5134 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5135 * or 'myplugin/mysetting' for ones in config_plugins.
5136 * @param string $visiblename localised
5137 * @param string $description long localised info
5138 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5139 * @param array $choices array of $value=>$label for each selection
5141 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5142 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5143 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5149 * Graded roles in gradebook
5151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5153 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5155 * Calls parent::__construct with specific arguments
5157 public function __construct() {
5158 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5159 get_string('configgradebookroles', 'admin'),
5160 array('student'));
5167 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5169 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5171 * Saves the new settings passed in $data
5173 * @param string $data
5174 * @return mixed string or Array
5176 public function write_setting($data) {
5177 global $CFG, $DB;
5179 $oldvalue = $this->config_read($this->name);
5180 $return = parent::write_setting($data);
5181 $newvalue = $this->config_read($this->name);
5183 if ($oldvalue !== $newvalue) {
5184 // force full regrading
5185 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5188 return $return;
5194 * Which roles to show on course description page
5196 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5198 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5200 * Calls parent::__construct with specific arguments
5202 public function __construct() {
5203 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5204 get_string('coursecontact_desc', 'admin'),
5205 array('editingteacher'));
5206 $this->set_updatedcallback(function (){
5207 cache::make('core', 'coursecontacts')->purge();
5215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5217 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5219 * Calls parent::__construct with specific arguments
5221 public function __construct() {
5222 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5223 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5227 * Old syntax of class constructor. Deprecated in PHP7.
5229 * @deprecated since Moodle 3.1
5231 public function admin_setting_special_gradelimiting() {
5232 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5233 self::__construct();
5237 * Force site regrading
5239 function regrade_all() {
5240 global $CFG;
5241 require_once("$CFG->libdir/gradelib.php");
5242 grade_force_site_regrading();
5246 * Saves the new settings
5248 * @param mixed $data
5249 * @return string empty string or error message
5251 function write_setting($data) {
5252 $previous = $this->get_setting();
5254 if ($previous === null) {
5255 if ($data) {
5256 $this->regrade_all();
5258 } else {
5259 if ($data != $previous) {
5260 $this->regrade_all();
5263 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5269 * Special setting for $CFG->grade_minmaxtouse.
5271 * @package core
5272 * @copyright 2015 Frédéric Massart - FMCorz.net
5273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5275 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5278 * Constructor.
5280 public function __construct() {
5281 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5282 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5283 array(
5284 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5285 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5291 * Saves the new setting.
5293 * @param mixed $data
5294 * @return string empty string or error message
5296 function write_setting($data) {
5297 global $CFG;
5299 $previous = $this->get_setting();
5300 $result = parent::write_setting($data);
5302 // If saved and the value has changed.
5303 if (empty($result) && $previous != $data) {
5304 require_once($CFG->libdir . '/gradelib.php');
5305 grade_force_site_regrading();
5308 return $result;
5315 * Primary grade export plugin - has state tracking.
5317 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5319 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5321 * Calls parent::__construct with specific arguments
5323 public function __construct() {
5324 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5325 get_string('configgradeexport', 'admin'), array(), NULL);
5329 * Load the available choices for the multicheckbox
5331 * @return bool always returns true
5333 public function load_choices() {
5334 if (is_array($this->choices)) {
5335 return true;
5337 $this->choices = array();
5339 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5340 foreach($plugins as $plugin => $unused) {
5341 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5344 return true;
5350 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5354 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5356 * Config gradepointmax constructor
5358 * @param string $name Overidden by "gradepointmax"
5359 * @param string $visiblename Overridden by "gradepointmax" language string.
5360 * @param string $description Overridden by "gradepointmax_help" language string.
5361 * @param string $defaultsetting Not used, overridden by 100.
5362 * @param mixed $paramtype Overridden by PARAM_INT.
5363 * @param int $size Overridden by 5.
5365 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5366 $name = 'gradepointdefault';
5367 $visiblename = get_string('gradepointdefault', 'grades');
5368 $description = get_string('gradepointdefault_help', 'grades');
5369 $defaultsetting = 100;
5370 $paramtype = PARAM_INT;
5371 $size = 5;
5372 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5376 * Validate data before storage
5377 * @param string $data The submitted data
5378 * @return bool|string true if ok, string if error found
5380 public function validate($data) {
5381 global $CFG;
5382 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5383 return true;
5384 } else {
5385 return get_string('gradepointdefault_validateerror', 'grades');
5392 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5394 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5396 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5399 * Config gradepointmax constructor
5401 * @param string $name Overidden by "gradepointmax"
5402 * @param string $visiblename Overridden by "gradepointmax" language string.
5403 * @param string $description Overridden by "gradepointmax_help" language string.
5404 * @param string $defaultsetting Not used, overridden by 100.
5405 * @param mixed $paramtype Overridden by PARAM_INT.
5406 * @param int $size Overridden by 5.
5408 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5409 $name = 'gradepointmax';
5410 $visiblename = get_string('gradepointmax', 'grades');
5411 $description = get_string('gradepointmax_help', 'grades');
5412 $defaultsetting = 100;
5413 $paramtype = PARAM_INT;
5414 $size = 5;
5415 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5419 * Save the selected setting
5421 * @param string $data The selected site
5422 * @return string empty string or error message
5424 public function write_setting($data) {
5425 if ($data === '') {
5426 $data = (int)$this->defaultsetting;
5427 } else {
5428 $data = $data;
5430 return parent::write_setting($data);
5434 * Validate data before storage
5435 * @param string $data The submitted data
5436 * @return bool|string true if ok, string if error found
5438 public function validate($data) {
5439 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5440 return true;
5441 } else {
5442 return get_string('gradepointmax_validateerror', 'grades');
5447 * Return an XHTML string for the setting
5448 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5449 * @param string $query search query to be highlighted
5450 * @return string XHTML to display control
5452 public function output_html($data, $query = '') {
5453 global $OUTPUT;
5455 $default = $this->get_defaultsetting();
5456 $context = (object) [
5457 'size' => $this->size,
5458 'id' => $this->get_id(),
5459 'name' => $this->get_full_name(),
5460 'value' => $data,
5461 'attributes' => [
5462 'maxlength' => 5
5464 'forceltr' => $this->get_force_ltr()
5466 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5468 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5474 * Grade category settings
5476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5478 class admin_setting_gradecat_combo extends admin_setting {
5479 /** @var array Array of choices */
5480 public $choices;
5483 * Sets choices and calls parent::__construct with passed arguments
5484 * @param string $name
5485 * @param string $visiblename
5486 * @param string $description
5487 * @param mixed $defaultsetting string or array depending on implementation
5488 * @param array $choices An array of choices for the control
5490 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5491 $this->choices = $choices;
5492 parent::__construct($name, $visiblename, $description, $defaultsetting);
5496 * Return the current setting(s) array
5498 * @return array Array of value=>xx, forced=>xx, adv=>xx
5500 public function get_setting() {
5501 global $CFG;
5503 $value = $this->config_read($this->name);
5504 $flag = $this->config_read($this->name.'_flag');
5506 if (is_null($value) or is_null($flag)) {
5507 return NULL;
5510 $flag = (int)$flag;
5511 $forced = (boolean)(1 & $flag); // first bit
5512 $adv = (boolean)(2 & $flag); // second bit
5514 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5518 * Save the new settings passed in $data
5520 * @todo Add vartype handling to ensure $data is array
5521 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5522 * @return string empty or error message
5524 public function write_setting($data) {
5525 global $CFG;
5527 $value = $data['value'];
5528 $forced = empty($data['forced']) ? 0 : 1;
5529 $adv = empty($data['adv']) ? 0 : 2;
5530 $flag = ($forced | $adv); //bitwise or
5532 if (!in_array($value, array_keys($this->choices))) {
5533 return 'Error setting ';
5536 $oldvalue = $this->config_read($this->name);
5537 $oldflag = (int)$this->config_read($this->name.'_flag');
5538 $oldforced = (1 & $oldflag); // first bit
5540 $result1 = $this->config_write($this->name, $value);
5541 $result2 = $this->config_write($this->name.'_flag', $flag);
5543 // force regrade if needed
5544 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5545 require_once($CFG->libdir.'/gradelib.php');
5546 grade_category::updated_forced_settings();
5549 if ($result1 and $result2) {
5550 return '';
5551 } else {
5552 return get_string('errorsetting', 'admin');
5557 * Return XHTML to display the field and wrapping div
5559 * @todo Add vartype handling to ensure $data is array
5560 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5561 * @param string $query
5562 * @return string XHTML to display control
5564 public function output_html($data, $query='') {
5565 global $OUTPUT;
5567 $value = $data['value'];
5569 $default = $this->get_defaultsetting();
5570 if (!is_null($default)) {
5571 $defaultinfo = array();
5572 if (isset($this->choices[$default['value']])) {
5573 $defaultinfo[] = $this->choices[$default['value']];
5575 if (!empty($default['forced'])) {
5576 $defaultinfo[] = get_string('force');
5578 if (!empty($default['adv'])) {
5579 $defaultinfo[] = get_string('advanced');
5581 $defaultinfo = implode(', ', $defaultinfo);
5583 } else {
5584 $defaultinfo = NULL;
5587 $options = $this->choices;
5588 $context = (object) [
5589 'id' => $this->get_id(),
5590 'name' => $this->get_full_name(),
5591 'forced' => !empty($data['forced']),
5592 'advanced' => !empty($data['adv']),
5593 'options' => array_map(function($option) use ($options, $value) {
5594 return [
5595 'value' => $option,
5596 'name' => $options[$option],
5597 'selected' => $option == $value
5599 }, array_keys($options)),
5602 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5604 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5610 * Selection of grade report in user profiles
5612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5614 class admin_setting_grade_profilereport extends admin_setting_configselect {
5616 * Calls parent::__construct with specific arguments
5618 public function __construct() {
5619 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5623 * Loads an array of choices for the configselect control
5625 * @return bool always return true
5627 public function load_choices() {
5628 if (is_array($this->choices)) {
5629 return true;
5631 $this->choices = array();
5633 global $CFG;
5634 require_once($CFG->libdir.'/gradelib.php');
5636 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5637 if (file_exists($plugindir.'/lib.php')) {
5638 require_once($plugindir.'/lib.php');
5639 $functionname = 'grade_report_'.$plugin.'_profilereport';
5640 if (function_exists($functionname)) {
5641 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5645 return true;
5650 * Provides a selection of grade reports to be used for "grades".
5652 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5653 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5655 class admin_setting_my_grades_report extends admin_setting_configselect {
5658 * Calls parent::__construct with specific arguments.
5660 public function __construct() {
5661 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5662 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5666 * Loads an array of choices for the configselect control.
5668 * @return bool always returns true.
5670 public function load_choices() {
5671 global $CFG; // Remove this line and behold the horror of behat test failures!
5672 $this->choices = array();
5673 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5674 if (file_exists($plugindir . '/lib.php')) {
5675 require_once($plugindir . '/lib.php');
5676 // Check to see if the class exists. Check the correct plugin convention first.
5677 if (class_exists('gradereport_' . $plugin)) {
5678 $classname = 'gradereport_' . $plugin;
5679 } else if (class_exists('grade_report_' . $plugin)) {
5680 // We are using the old plugin naming convention.
5681 $classname = 'grade_report_' . $plugin;
5682 } else {
5683 continue;
5685 if ($classname::supports_mygrades()) {
5686 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5690 // Add an option to specify an external url.
5691 $this->choices['external'] = get_string('externalurl', 'grades');
5692 return true;
5697 * Special class for register auth selection
5699 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5701 class admin_setting_special_registerauth extends admin_setting_configselect {
5703 * Calls parent::__construct with specific arguments
5705 public function __construct() {
5706 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5710 * Returns the default option
5712 * @return string empty or default option
5714 public function get_defaultsetting() {
5715 $this->load_choices();
5716 $defaultsetting = parent::get_defaultsetting();
5717 if (array_key_exists($defaultsetting, $this->choices)) {
5718 return $defaultsetting;
5719 } else {
5720 return '';
5725 * Loads the possible choices for the array
5727 * @return bool always returns true
5729 public function load_choices() {
5730 global $CFG;
5732 if (is_array($this->choices)) {
5733 return true;
5735 $this->choices = array();
5736 $this->choices[''] = get_string('disable');
5738 $authsenabled = get_enabled_auth_plugins(true);
5740 foreach ($authsenabled as $auth) {
5741 $authplugin = get_auth_plugin($auth);
5742 if (!$authplugin->can_signup()) {
5743 continue;
5745 // Get the auth title (from core or own auth lang files)
5746 $authtitle = $authplugin->get_title();
5747 $this->choices[$auth] = $authtitle;
5749 return true;
5755 * General plugins manager
5757 class admin_page_pluginsoverview extends admin_externalpage {
5760 * Sets basic information about the external page
5762 public function __construct() {
5763 global $CFG;
5764 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5765 "$CFG->wwwroot/$CFG->admin/plugins.php");
5770 * Module manage page
5772 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5774 class admin_page_managemods extends admin_externalpage {
5776 * Calls parent::__construct with specific arguments
5778 public function __construct() {
5779 global $CFG;
5780 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5784 * Try to find the specified module
5786 * @param string $query The module to search for
5787 * @return array
5789 public function search($query) {
5790 global $CFG, $DB;
5791 if ($result = parent::search($query)) {
5792 return $result;
5795 $found = false;
5796 if ($modules = $DB->get_records('modules')) {
5797 foreach ($modules as $module) {
5798 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5799 continue;
5801 if (strpos($module->name, $query) !== false) {
5802 $found = true;
5803 break;
5805 $strmodulename = get_string('modulename', $module->name);
5806 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5807 $found = true;
5808 break;
5812 if ($found) {
5813 $result = new stdClass();
5814 $result->page = $this;
5815 $result->settings = array();
5816 return array($this->name => $result);
5817 } else {
5818 return array();
5825 * Special class for enrol plugins management.
5827 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5830 class admin_setting_manageenrols extends admin_setting {
5832 * Calls parent::__construct with specific arguments
5834 public function __construct() {
5835 $this->nosave = true;
5836 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5840 * Always returns true, does nothing
5842 * @return true
5844 public function get_setting() {
5845 return true;
5849 * Always returns true, does nothing
5851 * @return true
5853 public function get_defaultsetting() {
5854 return true;
5858 * Always returns '', does not write anything
5860 * @return string Always returns ''
5862 public function write_setting($data) {
5863 // do not write any setting
5864 return '';
5868 * Checks if $query is one of the available enrol plugins
5870 * @param string $query The string to search for
5871 * @return bool Returns true if found, false if not
5873 public function is_related($query) {
5874 if (parent::is_related($query)) {
5875 return true;
5878 $query = core_text::strtolower($query);
5879 $enrols = enrol_get_plugins(false);
5880 foreach ($enrols as $name=>$enrol) {
5881 $localised = get_string('pluginname', 'enrol_'.$name);
5882 if (strpos(core_text::strtolower($name), $query) !== false) {
5883 return true;
5885 if (strpos(core_text::strtolower($localised), $query) !== false) {
5886 return true;
5889 return false;
5893 * Builds the XHTML to display the control
5895 * @param string $data Unused
5896 * @param string $query
5897 * @return string
5899 public function output_html($data, $query='') {
5900 global $CFG, $OUTPUT, $DB, $PAGE;
5902 // Display strings.
5903 $strup = get_string('up');
5904 $strdown = get_string('down');
5905 $strsettings = get_string('settings');
5906 $strenable = get_string('enable');
5907 $strdisable = get_string('disable');
5908 $struninstall = get_string('uninstallplugin', 'core_admin');
5909 $strusage = get_string('enrolusage', 'enrol');
5910 $strversion = get_string('version');
5911 $strtest = get_string('testsettings', 'core_enrol');
5913 $pluginmanager = core_plugin_manager::instance();
5915 $enrols_available = enrol_get_plugins(false);
5916 $active_enrols = enrol_get_plugins(true);
5918 $allenrols = array();
5919 foreach ($active_enrols as $key=>$enrol) {
5920 $allenrols[$key] = true;
5922 foreach ($enrols_available as $key=>$enrol) {
5923 $allenrols[$key] = true;
5925 // Now find all borked plugins and at least allow then to uninstall.
5926 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5927 foreach ($condidates as $candidate) {
5928 if (empty($allenrols[$candidate])) {
5929 $allenrols[$candidate] = true;
5933 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5934 $return .= $OUTPUT->box_start('generalbox enrolsui');
5936 $table = new html_table();
5937 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5938 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5939 $table->id = 'courseenrolmentplugins';
5940 $table->attributes['class'] = 'admintable generaltable';
5941 $table->data = array();
5943 // Iterate through enrol plugins and add to the display table.
5944 $updowncount = 1;
5945 $enrolcount = count($active_enrols);
5946 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5947 $printed = array();
5948 foreach($allenrols as $enrol => $unused) {
5949 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5950 $version = get_config('enrol_'.$enrol, 'version');
5951 if ($version === false) {
5952 $version = '';
5955 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5956 $name = get_string('pluginname', 'enrol_'.$enrol);
5957 } else {
5958 $name = $enrol;
5960 // Usage.
5961 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5962 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5963 $usage = "$ci / $cp";
5965 // Hide/show links.
5966 $class = '';
5967 if (isset($active_enrols[$enrol])) {
5968 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5969 $hideshow = "<a href=\"$aurl\">";
5970 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
5971 $enabled = true;
5972 $displayname = $name;
5973 } else if (isset($enrols_available[$enrol])) {
5974 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5975 $hideshow = "<a href=\"$aurl\">";
5976 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
5977 $enabled = false;
5978 $displayname = $name;
5979 $class = 'dimmed_text';
5980 } else {
5981 $hideshow = '';
5982 $enabled = false;
5983 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5985 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5986 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5987 } else {
5988 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5991 // Up/down link (only if enrol is enabled).
5992 $updown = '';
5993 if ($enabled) {
5994 if ($updowncount > 1) {
5995 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5996 $updown .= "<a href=\"$aurl\">";
5997 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
5998 } else {
5999 $updown .= $OUTPUT->spacer() . '&nbsp;';
6001 if ($updowncount < $enrolcount) {
6002 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6003 $updown .= "<a href=\"$aurl\">";
6004 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6005 } else {
6006 $updown .= $OUTPUT->spacer() . '&nbsp;';
6008 ++$updowncount;
6011 // Add settings link.
6012 if (!$version) {
6013 $settings = '';
6014 } else if ($surl = $plugininfo->get_settings_url()) {
6015 $settings = html_writer::link($surl, $strsettings);
6016 } else {
6017 $settings = '';
6020 // Add uninstall info.
6021 $uninstall = '';
6022 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6023 $uninstall = html_writer::link($uninstallurl, $struninstall);
6026 $test = '';
6027 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6028 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6029 $test = html_writer::link($testsettingsurl, $strtest);
6032 // Add a row to the table.
6033 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6034 if ($class) {
6035 $row->attributes['class'] = $class;
6037 $table->data[] = $row;
6039 $printed[$enrol] = true;
6042 $return .= html_writer::table($table);
6043 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6044 $return .= $OUTPUT->box_end();
6045 return highlight($query, $return);
6051 * Blocks manage page
6053 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6055 class admin_page_manageblocks extends admin_externalpage {
6057 * Calls parent::__construct with specific arguments
6059 public function __construct() {
6060 global $CFG;
6061 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6065 * Search for a specific block
6067 * @param string $query The string to search for
6068 * @return array
6070 public function search($query) {
6071 global $CFG, $DB;
6072 if ($result = parent::search($query)) {
6073 return $result;
6076 $found = false;
6077 if ($blocks = $DB->get_records('block')) {
6078 foreach ($blocks as $block) {
6079 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6080 continue;
6082 if (strpos($block->name, $query) !== false) {
6083 $found = true;
6084 break;
6086 $strblockname = get_string('pluginname', 'block_'.$block->name);
6087 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6088 $found = true;
6089 break;
6093 if ($found) {
6094 $result = new stdClass();
6095 $result->page = $this;
6096 $result->settings = array();
6097 return array($this->name => $result);
6098 } else {
6099 return array();
6105 * Message outputs configuration
6107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6109 class admin_page_managemessageoutputs extends admin_externalpage {
6111 * Calls parent::__construct with specific arguments
6113 public function __construct() {
6114 global $CFG;
6115 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
6119 * Search for a specific message processor
6121 * @param string $query The string to search for
6122 * @return array
6124 public function search($query) {
6125 global $CFG, $DB;
6126 if ($result = parent::search($query)) {
6127 return $result;
6130 $found = false;
6131 if ($processors = get_message_processors()) {
6132 foreach ($processors as $processor) {
6133 if (!$processor->available) {
6134 continue;
6136 if (strpos($processor->name, $query) !== false) {
6137 $found = true;
6138 break;
6140 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6141 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6142 $found = true;
6143 break;
6147 if ($found) {
6148 $result = new stdClass();
6149 $result->page = $this;
6150 $result->settings = array();
6151 return array($this->name => $result);
6152 } else {
6153 return array();
6159 * Default message outputs configuration
6161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6163 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6165 * Calls parent::__construct with specific arguments
6167 public function __construct() {
6168 global $CFG;
6169 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6175 * Manage question behaviours page
6177 * @copyright 2011 The Open University
6178 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6180 class admin_page_manageqbehaviours extends admin_externalpage {
6182 * Constructor
6184 public function __construct() {
6185 global $CFG;
6186 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6187 new moodle_url('/admin/qbehaviours.php'));
6191 * Search question behaviours for the specified string
6193 * @param string $query The string to search for in question behaviours
6194 * @return array
6196 public function search($query) {
6197 global $CFG;
6198 if ($result = parent::search($query)) {
6199 return $result;
6202 $found = false;
6203 require_once($CFG->dirroot . '/question/engine/lib.php');
6204 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6205 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6206 $query) !== false) {
6207 $found = true;
6208 break;
6211 if ($found) {
6212 $result = new stdClass();
6213 $result->page = $this;
6214 $result->settings = array();
6215 return array($this->name => $result);
6216 } else {
6217 return array();
6224 * Question type manage page
6226 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6228 class admin_page_manageqtypes extends admin_externalpage {
6230 * Calls parent::__construct with specific arguments
6232 public function __construct() {
6233 global $CFG;
6234 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6235 new moodle_url('/admin/qtypes.php'));
6239 * Search question types for the specified string
6241 * @param string $query The string to search for in question types
6242 * @return array
6244 public function search($query) {
6245 global $CFG;
6246 if ($result = parent::search($query)) {
6247 return $result;
6250 $found = false;
6251 require_once($CFG->dirroot . '/question/engine/bank.php');
6252 foreach (question_bank::get_all_qtypes() as $qtype) {
6253 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6254 $found = true;
6255 break;
6258 if ($found) {
6259 $result = new stdClass();
6260 $result->page = $this;
6261 $result->settings = array();
6262 return array($this->name => $result);
6263 } else {
6264 return array();
6270 class admin_page_manageportfolios extends admin_externalpage {
6272 * Calls parent::__construct with specific arguments
6274 public function __construct() {
6275 global $CFG;
6276 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6277 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6281 * Searches page for the specified string.
6282 * @param string $query The string to search for
6283 * @return bool True if it is found on this page
6285 public function search($query) {
6286 global $CFG;
6287 if ($result = parent::search($query)) {
6288 return $result;
6291 $found = false;
6292 $portfolios = core_component::get_plugin_list('portfolio');
6293 foreach ($portfolios as $p => $dir) {
6294 if (strpos($p, $query) !== false) {
6295 $found = true;
6296 break;
6299 if (!$found) {
6300 foreach (portfolio_instances(false, false) as $instance) {
6301 $title = $instance->get('name');
6302 if (strpos(core_text::strtolower($title), $query) !== false) {
6303 $found = true;
6304 break;
6309 if ($found) {
6310 $result = new stdClass();
6311 $result->page = $this;
6312 $result->settings = array();
6313 return array($this->name => $result);
6314 } else {
6315 return array();
6321 class admin_page_managerepositories extends admin_externalpage {
6323 * Calls parent::__construct with specific arguments
6325 public function __construct() {
6326 global $CFG;
6327 parent::__construct('managerepositories', get_string('manage',
6328 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6332 * Searches page for the specified string.
6333 * @param string $query The string to search for
6334 * @return bool True if it is found on this page
6336 public function search($query) {
6337 global $CFG;
6338 if ($result = parent::search($query)) {
6339 return $result;
6342 $found = false;
6343 $repositories= core_component::get_plugin_list('repository');
6344 foreach ($repositories as $p => $dir) {
6345 if (strpos($p, $query) !== false) {
6346 $found = true;
6347 break;
6350 if (!$found) {
6351 foreach (repository::get_types() as $instance) {
6352 $title = $instance->get_typename();
6353 if (strpos(core_text::strtolower($title), $query) !== false) {
6354 $found = true;
6355 break;
6360 if ($found) {
6361 $result = new stdClass();
6362 $result->page = $this;
6363 $result->settings = array();
6364 return array($this->name => $result);
6365 } else {
6366 return array();
6373 * Special class for authentication administration.
6375 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6377 class admin_setting_manageauths extends admin_setting {
6379 * Calls parent::__construct with specific arguments
6381 public function __construct() {
6382 $this->nosave = true;
6383 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6387 * Always returns true
6389 * @return true
6391 public function get_setting() {
6392 return true;
6396 * Always returns true
6398 * @return true
6400 public function get_defaultsetting() {
6401 return true;
6405 * Always returns '' and doesn't write anything
6407 * @return string Always returns ''
6409 public function write_setting($data) {
6410 // do not write any setting
6411 return '';
6415 * Search to find if Query is related to auth plugin
6417 * @param string $query The string to search for
6418 * @return bool true for related false for not
6420 public function is_related($query) {
6421 if (parent::is_related($query)) {
6422 return true;
6425 $authsavailable = core_component::get_plugin_list('auth');
6426 foreach ($authsavailable as $auth => $dir) {
6427 if (strpos($auth, $query) !== false) {
6428 return true;
6430 $authplugin = get_auth_plugin($auth);
6431 $authtitle = $authplugin->get_title();
6432 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6433 return true;
6436 return false;
6440 * Return XHTML to display control
6442 * @param mixed $data Unused
6443 * @param string $query
6444 * @return string highlight
6446 public function output_html($data, $query='') {
6447 global $CFG, $OUTPUT, $DB;
6449 // display strings
6450 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6451 'settings', 'edit', 'name', 'enable', 'disable',
6452 'up', 'down', 'none', 'users'));
6453 $txt->updown = "$txt->up/$txt->down";
6454 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6455 $txt->testsettings = get_string('testsettings', 'core_auth');
6457 $authsavailable = core_component::get_plugin_list('auth');
6458 get_enabled_auth_plugins(true); // fix the list of enabled auths
6459 if (empty($CFG->auth)) {
6460 $authsenabled = array();
6461 } else {
6462 $authsenabled = explode(',', $CFG->auth);
6465 // construct the display array, with enabled auth plugins at the top, in order
6466 $displayauths = array();
6467 $registrationauths = array();
6468 $registrationauths[''] = $txt->disable;
6469 $authplugins = array();
6470 foreach ($authsenabled as $auth) {
6471 $authplugin = get_auth_plugin($auth);
6472 $authplugins[$auth] = $authplugin;
6473 /// Get the auth title (from core or own auth lang files)
6474 $authtitle = $authplugin->get_title();
6475 /// Apply titles
6476 $displayauths[$auth] = $authtitle;
6477 if ($authplugin->can_signup()) {
6478 $registrationauths[$auth] = $authtitle;
6482 foreach ($authsavailable as $auth => $dir) {
6483 if (array_key_exists($auth, $displayauths)) {
6484 continue; //already in the list
6486 $authplugin = get_auth_plugin($auth);
6487 $authplugins[$auth] = $authplugin;
6488 /// Get the auth title (from core or own auth lang files)
6489 $authtitle = $authplugin->get_title();
6490 /// Apply titles
6491 $displayauths[$auth] = $authtitle;
6492 if ($authplugin->can_signup()) {
6493 $registrationauths[$auth] = $authtitle;
6497 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6498 $return .= $OUTPUT->box_start('generalbox authsui');
6500 $table = new html_table();
6501 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6502 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6503 $table->data = array();
6504 $table->attributes['class'] = 'admintable generaltable';
6505 $table->id = 'manageauthtable';
6507 //add always enabled plugins first
6508 $displayname = $displayauths['manual'];
6509 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6510 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6511 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6512 $displayname = $displayauths['nologin'];
6513 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6514 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6517 // iterate through auth plugins and add to the display table
6518 $updowncount = 1;
6519 $authcount = count($authsenabled);
6520 $url = "auth.php?sesskey=" . sesskey();
6521 foreach ($displayauths as $auth => $name) {
6522 if ($auth == 'manual' or $auth == 'nologin') {
6523 continue;
6525 $class = '';
6526 // hide/show link
6527 if (in_array($auth, $authsenabled)) {
6528 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6529 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6530 $enabled = true;
6531 $displayname = $name;
6533 else {
6534 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6535 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6536 $enabled = false;
6537 $displayname = $name;
6538 $class = 'dimmed_text';
6541 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6543 // up/down link (only if auth is enabled)
6544 $updown = '';
6545 if ($enabled) {
6546 if ($updowncount > 1) {
6547 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6548 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6550 else {
6551 $updown .= $OUTPUT->spacer() . '&nbsp;';
6553 if ($updowncount < $authcount) {
6554 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6555 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6557 else {
6558 $updown .= $OUTPUT->spacer() . '&nbsp;';
6560 ++ $updowncount;
6563 // settings link
6564 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6565 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6566 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6567 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6568 } else {
6569 $settings = '';
6572 // Uninstall link.
6573 $uninstall = '';
6574 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6575 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6578 $test = '';
6579 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6580 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6581 $test = html_writer::link($testurl, $txt->testsettings);
6584 // Add a row to the table.
6585 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6586 if ($class) {
6587 $row->attributes['class'] = $class;
6589 $table->data[] = $row;
6591 $return .= html_writer::table($table);
6592 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6593 $return .= $OUTPUT->box_end();
6594 return highlight($query, $return);
6600 * Special class for authentication administration.
6602 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6604 class admin_setting_manageeditors extends admin_setting {
6606 * Calls parent::__construct with specific arguments
6608 public function __construct() {
6609 $this->nosave = true;
6610 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6614 * Always returns true, does nothing
6616 * @return true
6618 public function get_setting() {
6619 return true;
6623 * Always returns true, does nothing
6625 * @return true
6627 public function get_defaultsetting() {
6628 return true;
6632 * Always returns '', does not write anything
6634 * @return string Always returns ''
6636 public function write_setting($data) {
6637 // do not write any setting
6638 return '';
6642 * Checks if $query is one of the available editors
6644 * @param string $query The string to search for
6645 * @return bool Returns true if found, false if not
6647 public function is_related($query) {
6648 if (parent::is_related($query)) {
6649 return true;
6652 $editors_available = editors_get_available();
6653 foreach ($editors_available as $editor=>$editorstr) {
6654 if (strpos($editor, $query) !== false) {
6655 return true;
6657 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6658 return true;
6661 return false;
6665 * Builds the XHTML to display the control
6667 * @param string $data Unused
6668 * @param string $query
6669 * @return string
6671 public function output_html($data, $query='') {
6672 global $CFG, $OUTPUT;
6674 // display strings
6675 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6676 'up', 'down', 'none'));
6677 $struninstall = get_string('uninstallplugin', 'core_admin');
6679 $txt->updown = "$txt->up/$txt->down";
6681 $editors_available = editors_get_available();
6682 $active_editors = explode(',', $CFG->texteditors);
6684 $active_editors = array_reverse($active_editors);
6685 foreach ($active_editors as $key=>$editor) {
6686 if (empty($editors_available[$editor])) {
6687 unset($active_editors[$key]);
6688 } else {
6689 $name = $editors_available[$editor];
6690 unset($editors_available[$editor]);
6691 $editors_available[$editor] = $name;
6694 if (empty($active_editors)) {
6695 //$active_editors = array('textarea');
6697 $editors_available = array_reverse($editors_available, true);
6698 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6699 $return .= $OUTPUT->box_start('generalbox editorsui');
6701 $table = new html_table();
6702 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6703 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6704 $table->id = 'editormanagement';
6705 $table->attributes['class'] = 'admintable generaltable';
6706 $table->data = array();
6708 // iterate through auth plugins and add to the display table
6709 $updowncount = 1;
6710 $editorcount = count($active_editors);
6711 $url = "editors.php?sesskey=" . sesskey();
6712 foreach ($editors_available as $editor => $name) {
6713 // hide/show link
6714 $class = '';
6715 if (in_array($editor, $active_editors)) {
6716 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6717 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6718 $enabled = true;
6719 $displayname = $name;
6721 else {
6722 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6723 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6724 $enabled = false;
6725 $displayname = $name;
6726 $class = 'dimmed_text';
6729 // up/down link (only if auth is enabled)
6730 $updown = '';
6731 if ($enabled) {
6732 if ($updowncount > 1) {
6733 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6734 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6736 else {
6737 $updown .= $OUTPUT->spacer() . '&nbsp;';
6739 if ($updowncount < $editorcount) {
6740 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6741 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6743 else {
6744 $updown .= $OUTPUT->spacer() . '&nbsp;';
6746 ++ $updowncount;
6749 // settings link
6750 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6751 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6752 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6753 } else {
6754 $settings = '';
6757 $uninstall = '';
6758 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6759 $uninstall = html_writer::link($uninstallurl, $struninstall);
6762 // Add a row to the table.
6763 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6764 if ($class) {
6765 $row->attributes['class'] = $class;
6767 $table->data[] = $row;
6769 $return .= html_writer::table($table);
6770 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6771 $return .= $OUTPUT->box_end();
6772 return highlight($query, $return);
6777 * Special class for antiviruses administration.
6779 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6780 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6782 class admin_setting_manageantiviruses extends admin_setting {
6784 * Calls parent::__construct with specific arguments
6786 public function __construct() {
6787 $this->nosave = true;
6788 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6792 * Always returns true, does nothing
6794 * @return true
6796 public function get_setting() {
6797 return true;
6801 * Always returns true, does nothing
6803 * @return true
6805 public function get_defaultsetting() {
6806 return true;
6810 * Always returns '', does not write anything
6812 * @param string $data Unused
6813 * @return string Always returns ''
6815 public function write_setting($data) {
6816 // Do not write any setting.
6817 return '';
6821 * Checks if $query is one of the available editors
6823 * @param string $query The string to search for
6824 * @return bool Returns true if found, false if not
6826 public function is_related($query) {
6827 if (parent::is_related($query)) {
6828 return true;
6831 $antivirusesavailable = \core\antivirus\manager::get_available();
6832 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6833 if (strpos($antivirus, $query) !== false) {
6834 return true;
6836 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6837 return true;
6840 return false;
6844 * Builds the XHTML to display the control
6846 * @param string $data Unused
6847 * @param string $query
6848 * @return string
6850 public function output_html($data, $query='') {
6851 global $CFG, $OUTPUT;
6853 // Display strings.
6854 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6855 'up', 'down', 'none'));
6856 $struninstall = get_string('uninstallplugin', 'core_admin');
6858 $txt->updown = "$txt->up/$txt->down";
6860 $antivirusesavailable = \core\antivirus\manager::get_available();
6861 $activeantiviruses = explode(',', $CFG->antiviruses);
6863 $activeantiviruses = array_reverse($activeantiviruses);
6864 foreach ($activeantiviruses as $key => $antivirus) {
6865 if (empty($antivirusesavailable[$antivirus])) {
6866 unset($activeantiviruses[$key]);
6867 } else {
6868 $name = $antivirusesavailable[$antivirus];
6869 unset($antivirusesavailable[$antivirus]);
6870 $antivirusesavailable[$antivirus] = $name;
6873 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6874 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6875 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6877 $table = new html_table();
6878 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6879 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6880 $table->id = 'antivirusmanagement';
6881 $table->attributes['class'] = 'admintable generaltable';
6882 $table->data = array();
6884 // Iterate through auth plugins and add to the display table.
6885 $updowncount = 1;
6886 $antiviruscount = count($activeantiviruses);
6887 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6888 foreach ($antivirusesavailable as $antivirus => $name) {
6889 // Hide/show link.
6890 $class = '';
6891 if (in_array($antivirus, $activeantiviruses)) {
6892 $hideshowurl = $baseurl;
6893 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6894 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
6895 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6896 $enabled = true;
6897 $displayname = $name;
6898 } else {
6899 $hideshowurl = $baseurl;
6900 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6901 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
6902 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6903 $enabled = false;
6904 $displayname = $name;
6905 $class = 'dimmed_text';
6908 // Up/down link.
6909 $updown = '';
6910 if ($enabled) {
6911 if ($updowncount > 1) {
6912 $updownurl = $baseurl;
6913 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6914 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
6915 $updown = html_writer::link($updownurl, $updownimg);
6916 } else {
6917 $updownimg = $OUTPUT->spacer();
6919 if ($updowncount < $antiviruscount) {
6920 $updownurl = $baseurl;
6921 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6922 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
6923 $updown = html_writer::link($updownurl, $updownimg);
6924 } else {
6925 $updownimg = $OUTPUT->spacer();
6927 ++ $updowncount;
6930 // Settings link.
6931 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6932 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6933 $settings = html_writer::link($eurl, $txt->settings);
6934 } else {
6935 $settings = '';
6938 $uninstall = '';
6939 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6940 $uninstall = html_writer::link($uninstallurl, $struninstall);
6943 // Add a row to the table.
6944 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6945 if ($class) {
6946 $row->attributes['class'] = $class;
6948 $table->data[] = $row;
6950 $return .= html_writer::table($table);
6951 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6952 $return .= $OUTPUT->box_end();
6953 return highlight($query, $return);
6958 * Special class for license administration.
6960 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6962 class admin_setting_managelicenses extends admin_setting {
6964 * Calls parent::__construct with specific arguments
6966 public function __construct() {
6967 $this->nosave = true;
6968 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6972 * Always returns true, does nothing
6974 * @return true
6976 public function get_setting() {
6977 return true;
6981 * Always returns true, does nothing
6983 * @return true
6985 public function get_defaultsetting() {
6986 return true;
6990 * Always returns '', does not write anything
6992 * @return string Always returns ''
6994 public function write_setting($data) {
6995 // do not write any setting
6996 return '';
7000 * Builds the XHTML to display the control
7002 * @param string $data Unused
7003 * @param string $query
7004 * @return string
7006 public function output_html($data, $query='') {
7007 global $CFG, $OUTPUT;
7008 require_once($CFG->libdir . '/licenselib.php');
7009 $url = "licenses.php?sesskey=" . sesskey();
7011 // display strings
7012 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
7013 $licenses = license_manager::get_licenses();
7015 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
7017 $return .= $OUTPUT->box_start('generalbox editorsui');
7019 $table = new html_table();
7020 $table->head = array($txt->name, $txt->enable);
7021 $table->colclasses = array('leftalign', 'centeralign');
7022 $table->id = 'availablelicenses';
7023 $table->attributes['class'] = 'admintable generaltable';
7024 $table->data = array();
7026 foreach ($licenses as $value) {
7027 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
7029 if ($value->enabled == 1) {
7030 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
7031 $OUTPUT->pix_icon('t/hide', get_string('disable')));
7032 } else {
7033 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
7034 $OUTPUT->pix_icon('t/show', get_string('enable')));
7037 if ($value->shortname == $CFG->sitedefaultlicense) {
7038 $displayname .= ' '.$OUTPUT->pix_icon('t/locked', get_string('default'));
7039 $hideshow = '';
7042 $enabled = true;
7044 $table->data[] =array($displayname, $hideshow);
7046 $return .= html_writer::table($table);
7047 $return .= $OUTPUT->box_end();
7048 return highlight($query, $return);
7053 * Course formats manager. Allows to enable/disable formats and jump to settings
7055 class admin_setting_manageformats extends admin_setting {
7058 * Calls parent::__construct with specific arguments
7060 public function __construct() {
7061 $this->nosave = true;
7062 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7066 * Always returns true
7068 * @return true
7070 public function get_setting() {
7071 return true;
7075 * Always returns true
7077 * @return true
7079 public function get_defaultsetting() {
7080 return true;
7084 * Always returns '' and doesn't write anything
7086 * @param mixed $data string or array, must not be NULL
7087 * @return string Always returns ''
7089 public function write_setting($data) {
7090 // do not write any setting
7091 return '';
7095 * Search to find if Query is related to format plugin
7097 * @param string $query The string to search for
7098 * @return bool true for related false for not
7100 public function is_related($query) {
7101 if (parent::is_related($query)) {
7102 return true;
7104 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7105 foreach ($formats as $format) {
7106 if (strpos($format->component, $query) !== false ||
7107 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7108 return true;
7111 return false;
7115 * Return XHTML to display control
7117 * @param mixed $data Unused
7118 * @param string $query
7119 * @return string highlight
7121 public function output_html($data, $query='') {
7122 global $CFG, $OUTPUT;
7123 $return = '';
7124 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7125 $return .= $OUTPUT->box_start('generalbox formatsui');
7127 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7129 // display strings
7130 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7131 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7132 $txt->updown = "$txt->up/$txt->down";
7134 $table = new html_table();
7135 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7136 $table->align = array('left', 'center', 'center', 'center', 'center');
7137 $table->attributes['class'] = 'manageformattable generaltable admintable';
7138 $table->data = array();
7140 $cnt = 0;
7141 $defaultformat = get_config('moodlecourse', 'format');
7142 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7143 foreach ($formats as $format) {
7144 $url = new moodle_url('/admin/courseformats.php',
7145 array('sesskey' => sesskey(), 'format' => $format->name));
7146 $isdefault = '';
7147 $class = '';
7148 if ($format->is_enabled()) {
7149 $strformatname = $format->displayname;
7150 if ($defaultformat === $format->name) {
7151 $hideshow = $txt->default;
7152 } else {
7153 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7154 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7156 } else {
7157 $strformatname = $format->displayname;
7158 $class = 'dimmed_text';
7159 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7160 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7162 $updown = '';
7163 if ($cnt) {
7164 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7165 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7166 } else {
7167 $updown .= $spacer;
7169 if ($cnt < count($formats) - 1) {
7170 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7171 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7172 } else {
7173 $updown .= $spacer;
7175 $cnt++;
7176 $settings = '';
7177 if ($format->get_settings_url()) {
7178 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7180 $uninstall = '';
7181 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7182 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7184 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7185 if ($class) {
7186 $row->attributes['class'] = $class;
7188 $table->data[] = $row;
7190 $return .= html_writer::table($table);
7191 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7192 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7193 $return .= $OUTPUT->box_end();
7194 return highlight($query, $return);
7199 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7201 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7202 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7204 class admin_setting_managedataformats extends admin_setting {
7207 * Calls parent::__construct with specific arguments
7209 public function __construct() {
7210 $this->nosave = true;
7211 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7215 * Always returns true
7217 * @return true
7219 public function get_setting() {
7220 return true;
7224 * Always returns true
7226 * @return true
7228 public function get_defaultsetting() {
7229 return true;
7233 * Always returns '' and doesn't write anything
7235 * @param mixed $data string or array, must not be NULL
7236 * @return string Always returns ''
7238 public function write_setting($data) {
7239 // Do not write any setting.
7240 return '';
7244 * Search to find if Query is related to format plugin
7246 * @param string $query The string to search for
7247 * @return bool true for related false for not
7249 public function is_related($query) {
7250 if (parent::is_related($query)) {
7251 return true;
7253 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7254 foreach ($formats as $format) {
7255 if (strpos($format->component, $query) !== false ||
7256 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7257 return true;
7260 return false;
7264 * Return XHTML to display control
7266 * @param mixed $data Unused
7267 * @param string $query
7268 * @return string highlight
7270 public function output_html($data, $query='') {
7271 global $CFG, $OUTPUT;
7272 $return = '';
7274 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7276 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7277 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7278 $txt->updown = "$txt->up/$txt->down";
7280 $table = new html_table();
7281 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7282 $table->align = array('left', 'center', 'center', 'center', 'center');
7283 $table->attributes['class'] = 'manageformattable generaltable admintable';
7284 $table->data = array();
7286 $cnt = 0;
7287 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7288 $totalenabled = 0;
7289 foreach ($formats as $format) {
7290 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7291 $totalenabled++;
7294 foreach ($formats as $format) {
7295 $status = $format->get_status();
7296 $url = new moodle_url('/admin/dataformats.php',
7297 array('sesskey' => sesskey(), 'name' => $format->name));
7299 $class = '';
7300 if ($format->is_enabled()) {
7301 $strformatname = $format->displayname;
7302 if ($totalenabled == 1&& $format->is_enabled()) {
7303 $hideshow = '';
7304 } else {
7305 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7306 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7308 } else {
7309 $class = 'dimmed_text';
7310 $strformatname = $format->displayname;
7311 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7312 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7315 $updown = '';
7316 if ($cnt) {
7317 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7318 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7319 } else {
7320 $updown .= $spacer;
7322 if ($cnt < count($formats) - 1) {
7323 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7324 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7325 } else {
7326 $updown .= $spacer;
7329 $uninstall = '';
7330 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7331 $uninstall = get_string('status_missing', 'core_plugin');
7332 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7333 $uninstall = get_string('status_new', 'core_plugin');
7334 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7335 if ($totalenabled != 1 || !$format->is_enabled()) {
7336 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7340 $settings = '';
7341 if ($format->get_settings_url()) {
7342 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7345 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7346 if ($class) {
7347 $row->attributes['class'] = $class;
7349 $table->data[] = $row;
7350 $cnt++;
7352 $return .= html_writer::table($table);
7353 return highlight($query, $return);
7358 * Special class for filter administration.
7360 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7362 class admin_page_managefilters extends admin_externalpage {
7364 * Calls parent::__construct with specific arguments
7366 public function __construct() {
7367 global $CFG;
7368 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7372 * Searches all installed filters for specified filter
7374 * @param string $query The filter(string) to search for
7375 * @param string $query
7377 public function search($query) {
7378 global $CFG;
7379 if ($result = parent::search($query)) {
7380 return $result;
7383 $found = false;
7384 $filternames = filter_get_all_installed();
7385 foreach ($filternames as $path => $strfiltername) {
7386 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7387 $found = true;
7388 break;
7390 if (strpos($path, $query) !== false) {
7391 $found = true;
7392 break;
7396 if ($found) {
7397 $result = new stdClass;
7398 $result->page = $this;
7399 $result->settings = array();
7400 return array($this->name => $result);
7401 } else {
7402 return array();
7408 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7409 * Requires a get_rank method on the plugininfo class for sorting.
7411 * @copyright 2017 Damyon Wiese
7412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7414 abstract class admin_setting_manage_plugins extends admin_setting {
7417 * Get the admin settings section name (just a unique string)
7419 * @return string
7421 public function get_section_name() {
7422 return 'manage' . $this->get_plugin_type() . 'plugins';
7426 * Get the admin settings section title (use get_string).
7428 * @return string
7430 abstract public function get_section_title();
7433 * Get the type of plugin to manage.
7435 * @return string
7437 abstract public function get_plugin_type();
7440 * Get the name of the second column.
7442 * @return string
7444 public function get_info_column_name() {
7445 return '';
7449 * Get the type of plugin to manage.
7451 * @param plugininfo The plugin info class.
7452 * @return string
7454 abstract public function get_info_column($plugininfo);
7457 * Calls parent::__construct with specific arguments
7459 public function __construct() {
7460 $this->nosave = true;
7461 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7465 * Always returns true, does nothing
7467 * @return true
7469 public function get_setting() {
7470 return true;
7474 * Always returns true, does nothing
7476 * @return true
7478 public function get_defaultsetting() {
7479 return true;
7483 * Always returns '', does not write anything
7485 * @param mixed $data
7486 * @return string Always returns ''
7488 public function write_setting($data) {
7489 // Do not write any setting.
7490 return '';
7494 * Checks if $query is one of the available plugins of this type
7496 * @param string $query The string to search for
7497 * @return bool Returns true if found, false if not
7499 public function is_related($query) {
7500 if (parent::is_related($query)) {
7501 return true;
7504 $query = core_text::strtolower($query);
7505 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7506 foreach ($plugins as $name => $plugin) {
7507 $localised = $plugin->displayname;
7508 if (strpos(core_text::strtolower($name), $query) !== false) {
7509 return true;
7511 if (strpos(core_text::strtolower($localised), $query) !== false) {
7512 return true;
7515 return false;
7519 * The URL for the management page for this plugintype.
7521 * @return moodle_url
7523 protected function get_manage_url() {
7524 return new moodle_url('/admin/updatesetting.php');
7528 * Builds the HTML to display the control.
7530 * @param string $data Unused
7531 * @param string $query
7532 * @return string
7534 public function output_html($data, $query = '') {
7535 global $CFG, $OUTPUT, $DB, $PAGE;
7537 $context = (object) [
7538 'manageurl' => new moodle_url($this->get_manage_url(), [
7539 'type' => $this->get_plugin_type(),
7540 'sesskey' => sesskey(),
7542 'infocolumnname' => $this->get_info_column_name(),
7543 'plugins' => [],
7546 $pluginmanager = core_plugin_manager::instance();
7547 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7548 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7549 $plugins = array_merge($enabled, $allplugins);
7550 foreach ($plugins as $key => $plugin) {
7551 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7553 $pluginkey = (object) [
7554 'plugin' => $plugin->displayname,
7555 'enabled' => $plugin->is_enabled(),
7556 'togglelink' => '',
7557 'moveuplink' => '',
7558 'movedownlink' => '',
7559 'settingslink' => $plugin->get_settings_url(),
7560 'uninstalllink' => '',
7561 'info' => '',
7564 // Enable/Disable link.
7565 $togglelink = new moodle_url($pluginlink);
7566 if ($plugin->is_enabled()) {
7567 $toggletarget = false;
7568 $togglelink->param('action', 'disable');
7570 if (count($context->plugins)) {
7571 // This is not the first plugin.
7572 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7575 if (count($enabled) > count($context->plugins) + 1) {
7576 // This is not the last plugin.
7577 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7580 $pluginkey->info = $this->get_info_column($plugin);
7581 } else {
7582 $toggletarget = true;
7583 $togglelink->param('action', 'enable');
7586 $pluginkey->toggletarget = $toggletarget;
7587 $pluginkey->togglelink = $togglelink;
7589 $frankenstyle = $plugin->type . '_' . $plugin->name;
7590 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
7591 // This plugin supports uninstallation.
7592 $pluginkey->uninstalllink = $uninstalllink;
7595 if (!empty($this->get_info_column_name())) {
7596 // This plugintype has an info column.
7597 $pluginkey->info = $this->get_info_column($plugin);
7600 $context->plugins[] = $pluginkey;
7603 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
7604 return highlight($query, $str);
7609 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7610 * Requires a get_rank method on the plugininfo class for sorting.
7612 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
7613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7615 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
7616 public function get_section_title() {
7617 return get_string('type_fileconverter_plural', 'plugin');
7620 public function get_plugin_type() {
7621 return 'fileconverter';
7624 public function get_info_column_name() {
7625 return get_string('supportedconversions', 'plugin');
7628 public function get_info_column($plugininfo) {
7629 return $plugininfo->get_supported_conversions();
7634 * Special class for media player plugins management.
7636 * @copyright 2016 Marina Glancy
7637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7639 class admin_setting_managemediaplayers extends admin_setting {
7641 * Calls parent::__construct with specific arguments
7643 public function __construct() {
7644 $this->nosave = true;
7645 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
7649 * Always returns true, does nothing
7651 * @return true
7653 public function get_setting() {
7654 return true;
7658 * Always returns true, does nothing
7660 * @return true
7662 public function get_defaultsetting() {
7663 return true;
7667 * Always returns '', does not write anything
7669 * @param mixed $data
7670 * @return string Always returns ''
7672 public function write_setting($data) {
7673 // Do not write any setting.
7674 return '';
7678 * Checks if $query is one of the available enrol plugins
7680 * @param string $query The string to search for
7681 * @return bool Returns true if found, false if not
7683 public function is_related($query) {
7684 if (parent::is_related($query)) {
7685 return true;
7688 $query = core_text::strtolower($query);
7689 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
7690 foreach ($plugins as $name => $plugin) {
7691 $localised = $plugin->displayname;
7692 if (strpos(core_text::strtolower($name), $query) !== false) {
7693 return true;
7695 if (strpos(core_text::strtolower($localised), $query) !== false) {
7696 return true;
7699 return false;
7703 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7704 * @return \core\plugininfo\media[]
7706 protected function get_sorted_plugins() {
7707 $pluginmanager = core_plugin_manager::instance();
7709 $plugins = $pluginmanager->get_plugins_of_type('media');
7710 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7712 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7713 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
7715 $order = array_values($enabledplugins);
7716 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
7718 $sortedplugins = array();
7719 foreach ($order as $name) {
7720 $sortedplugins[$name] = $plugins[$name];
7723 return $sortedplugins;
7727 * Builds the XHTML to display the control
7729 * @param string $data Unused
7730 * @param string $query
7731 * @return string
7733 public function output_html($data, $query='') {
7734 global $CFG, $OUTPUT, $DB, $PAGE;
7736 // Display strings.
7737 $strup = get_string('up');
7738 $strdown = get_string('down');
7739 $strsettings = get_string('settings');
7740 $strenable = get_string('enable');
7741 $strdisable = get_string('disable');
7742 $struninstall = get_string('uninstallplugin', 'core_admin');
7743 $strversion = get_string('version');
7744 $strname = get_string('name');
7745 $strsupports = get_string('supports', 'core_media');
7747 $pluginmanager = core_plugin_manager::instance();
7749 $plugins = $this->get_sorted_plugins();
7750 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7752 $return = $OUTPUT->box_start('generalbox mediaplayersui');
7754 $table = new html_table();
7755 $table->head = array($strname, $strsupports, $strversion,
7756 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
7757 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
7758 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7759 $table->id = 'mediaplayerplugins';
7760 $table->attributes['class'] = 'admintable generaltable';
7761 $table->data = array();
7763 // Iterate through media plugins and add to the display table.
7764 $updowncount = 1;
7765 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
7766 $printed = array();
7767 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7769 $usedextensions = [];
7770 foreach ($plugins as $name => $plugin) {
7771 $url->param('media', $name);
7772 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
7773 $version = $plugininfo->versiondb;
7774 $supports = $plugininfo->supports($usedextensions);
7776 // Hide/show links.
7777 $class = '';
7778 if (!$plugininfo->is_installed_and_upgraded()) {
7779 $hideshow = '';
7780 $enabled = false;
7781 $displayname = '<span class="notifyproblem">'.$name.'</span>';
7782 } else {
7783 $enabled = $plugininfo->is_enabled();
7784 if ($enabled) {
7785 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
7786 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
7787 } else {
7788 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
7789 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
7790 $class = 'dimmed_text';
7792 $displayname = $plugin->displayname;
7793 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
7794 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
7797 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
7798 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
7799 } else {
7800 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
7803 // Up/down link (only if enrol is enabled).
7804 $updown = '';
7805 if ($enabled) {
7806 if ($updowncount > 1) {
7807 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
7808 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
7809 } else {
7810 $updown = $spacer;
7812 if ($updowncount < count($enabledplugins)) {
7813 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
7814 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
7815 } else {
7816 $updown .= $spacer;
7818 ++$updowncount;
7821 $uninstall = '';
7822 $status = $plugininfo->get_status();
7823 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7824 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
7826 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7827 $uninstall = get_string('status_new', 'core_plugin');
7828 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
7829 $uninstall .= html_writer::link($uninstallurl, $struninstall);
7832 $settings = '';
7833 if ($plugininfo->get_settings_url()) {
7834 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
7837 // Add a row to the table.
7838 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
7839 if ($class) {
7840 $row->attributes['class'] = $class;
7842 $table->data[] = $row;
7844 $printed[$name] = true;
7847 $return .= html_writer::table($table);
7848 $return .= $OUTPUT->box_end();
7849 return highlight($query, $return);
7854 * Initialise admin page - this function does require login and permission
7855 * checks specified in page definition.
7857 * This function must be called on each admin page before other code.
7859 * @global moodle_page $PAGE
7861 * @param string $section name of page
7862 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7863 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7864 * added to the turn blocks editing on/off form, so this page reloads correctly.
7865 * @param string $actualurl if the actual page being viewed is not the normal one for this
7866 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7867 * @param array $options Additional options that can be specified for page setup.
7868 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7870 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7871 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7873 $PAGE->set_context(null); // hack - set context to something, by default to system context
7875 $site = get_site();
7876 require_login();
7878 if (!empty($options['pagelayout'])) {
7879 // A specific page layout has been requested.
7880 $PAGE->set_pagelayout($options['pagelayout']);
7881 } else if ($section === 'upgradesettings') {
7882 $PAGE->set_pagelayout('maintenance');
7883 } else {
7884 $PAGE->set_pagelayout('admin');
7887 $adminroot = admin_get_root(false, false); // settings not required for external pages
7888 $extpage = $adminroot->locate($section, true);
7890 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7891 // The requested section isn't in the admin tree
7892 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7893 if (!has_capability('moodle/site:config', context_system::instance())) {
7894 // The requested section could depend on a different capability
7895 // but most likely the user has inadequate capabilities
7896 print_error('accessdenied', 'admin');
7897 } else {
7898 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7902 // this eliminates our need to authenticate on the actual pages
7903 if (!$extpage->check_access()) {
7904 print_error('accessdenied', 'admin');
7905 die;
7908 navigation_node::require_admin_tree();
7910 // $PAGE->set_extra_button($extrabutton); TODO
7912 if (!$actualurl) {
7913 $actualurl = $extpage->url;
7916 $PAGE->set_url($actualurl, $extraurlparams);
7917 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7918 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7921 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7922 // During initial install.
7923 $strinstallation = get_string('installation', 'install');
7924 $strsettings = get_string('settings');
7925 $PAGE->navbar->add($strsettings);
7926 $PAGE->set_title($strinstallation);
7927 $PAGE->set_heading($strinstallation);
7928 $PAGE->set_cacheable(false);
7929 return;
7932 // Locate the current item on the navigation and make it active when found.
7933 $path = $extpage->path;
7934 $node = $PAGE->settingsnav;
7935 while ($node && count($path) > 0) {
7936 $node = $node->get(array_pop($path));
7938 if ($node) {
7939 $node->make_active();
7942 // Normal case.
7943 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7944 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7945 $USER->editing = $adminediting;
7948 $visiblepathtosection = array_reverse($extpage->visiblepath);
7950 if ($PAGE->user_allowed_editing()) {
7951 if ($PAGE->user_is_editing()) {
7952 $caption = get_string('blockseditoff');
7953 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7954 } else {
7955 $caption = get_string('blocksediton');
7956 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7958 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7961 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7962 $PAGE->set_heading($SITE->fullname);
7964 // prevent caching in nav block
7965 $PAGE->navigation->clear_cache();
7969 * Returns the reference to admin tree root
7971 * @return object admin_root object
7973 function admin_get_root($reload=false, $requirefulltree=true) {
7974 global $CFG, $DB, $OUTPUT;
7976 static $ADMIN = NULL;
7978 if (is_null($ADMIN)) {
7979 // create the admin tree!
7980 $ADMIN = new admin_root($requirefulltree);
7983 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7984 $ADMIN->purge_children($requirefulltree);
7987 if (!$ADMIN->loaded) {
7988 // we process this file first to create categories first and in correct order
7989 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7991 // now we process all other files in admin/settings to build the admin tree
7992 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7993 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7994 continue;
7996 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7997 // plugins are loaded last - they may insert pages anywhere
7998 continue;
8000 require($file);
8002 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8004 $ADMIN->loaded = true;
8007 return $ADMIN;
8010 /// settings utility functions
8013 * This function applies default settings.
8015 * @param object $node, NULL means complete tree, null by default
8016 * @param bool $unconditional if true overrides all values with defaults, null buy default
8018 function admin_apply_default_settings($node=NULL, $unconditional=true) {
8019 global $CFG;
8021 if (is_null($node)) {
8022 core_plugin_manager::reset_caches();
8023 $node = admin_get_root(true, true);
8026 if ($node instanceof admin_category) {
8027 $entries = array_keys($node->children);
8028 foreach ($entries as $entry) {
8029 admin_apply_default_settings($node->children[$entry], $unconditional);
8032 } else if ($node instanceof admin_settingpage) {
8033 foreach ($node->settings as $setting) {
8034 if (!$unconditional and !is_null($setting->get_setting())) {
8035 //do not override existing defaults
8036 continue;
8038 $defaultsetting = $setting->get_defaultsetting();
8039 if (is_null($defaultsetting)) {
8040 // no value yet - default maybe applied after admin user creation or in upgradesettings
8041 continue;
8043 $setting->write_setting($defaultsetting);
8044 $setting->write_setting_flags(null);
8047 // Just in case somebody modifies the list of active plugins directly.
8048 core_plugin_manager::reset_caches();
8052 * Store changed settings, this function updates the errors variable in $ADMIN
8054 * @param object $formdata from form
8055 * @return int number of changed settings
8057 function admin_write_settings($formdata) {
8058 global $CFG, $SITE, $DB;
8060 $olddbsessions = !empty($CFG->dbsessions);
8061 $formdata = (array)$formdata;
8063 $data = array();
8064 foreach ($formdata as $fullname=>$value) {
8065 if (strpos($fullname, 's_') !== 0) {
8066 continue; // not a config value
8068 $data[$fullname] = $value;
8071 $adminroot = admin_get_root();
8072 $settings = admin_find_write_settings($adminroot, $data);
8074 $count = 0;
8075 foreach ($settings as $fullname=>$setting) {
8076 /** @var $setting admin_setting */
8077 $original = $setting->get_setting();
8078 $error = $setting->write_setting($data[$fullname]);
8079 if ($error !== '') {
8080 $adminroot->errors[$fullname] = new stdClass();
8081 $adminroot->errors[$fullname]->data = $data[$fullname];
8082 $adminroot->errors[$fullname]->id = $setting->get_id();
8083 $adminroot->errors[$fullname]->error = $error;
8084 } else {
8085 $setting->write_setting_flags($data);
8087 if ($setting->post_write_settings($original)) {
8088 $count++;
8092 if ($olddbsessions != !empty($CFG->dbsessions)) {
8093 require_logout();
8096 // Now update $SITE - just update the fields, in case other people have a
8097 // a reference to it (e.g. $PAGE, $COURSE).
8098 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8099 foreach (get_object_vars($newsite) as $field => $value) {
8100 $SITE->$field = $value;
8103 // now reload all settings - some of them might depend on the changed
8104 admin_get_root(true);
8105 return $count;
8109 * Internal recursive function - finds all settings from submitted form
8111 * @param object $node Instance of admin_category, or admin_settingpage
8112 * @param array $data
8113 * @return array
8115 function admin_find_write_settings($node, $data) {
8116 $return = array();
8118 if (empty($data)) {
8119 return $return;
8122 if ($node instanceof admin_category) {
8123 if ($node->check_access()) {
8124 $entries = array_keys($node->children);
8125 foreach ($entries as $entry) {
8126 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8130 } else if ($node instanceof admin_settingpage) {
8131 if ($node->check_access()) {
8132 foreach ($node->settings as $setting) {
8133 $fullname = $setting->get_full_name();
8134 if (array_key_exists($fullname, $data)) {
8135 $return[$fullname] = $setting;
8142 return $return;
8146 * Internal function - prints the search results
8148 * @param string $query String to search for
8149 * @return string empty or XHTML
8151 function admin_search_settings_html($query) {
8152 global $CFG, $OUTPUT, $PAGE;
8154 if (core_text::strlen($query) < 2) {
8155 return '';
8157 $query = core_text::strtolower($query);
8159 $adminroot = admin_get_root();
8160 $findings = $adminroot->search($query);
8161 $savebutton = false;
8163 $tpldata = (object) [
8164 'actionurl' => $PAGE->url->out(false),
8165 'results' => [],
8166 'sesskey' => sesskey(),
8169 foreach ($findings as $found) {
8170 $page = $found->page;
8171 $settings = $found->settings;
8172 if ($page->is_hidden()) {
8173 // hidden pages are not displayed in search results
8174 continue;
8177 $heading = highlight($query, $page->visiblename);
8178 $headingurl = null;
8179 if ($page instanceof admin_externalpage) {
8180 $headingurl = new moodle_url($page->url);
8181 } else if ($page instanceof admin_settingpage) {
8182 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8183 } else {
8184 continue;
8187 $sectionsettings = [];
8188 if (!empty($settings)) {
8189 foreach ($settings as $setting) {
8190 if (empty($setting->nosave)) {
8191 $savebutton = true;
8193 $fullname = $setting->get_full_name();
8194 if (array_key_exists($fullname, $adminroot->errors)) {
8195 $data = $adminroot->errors[$fullname]->data;
8196 } else {
8197 $data = $setting->get_setting();
8198 // do not use defaults if settings not available - upgradesettings handles the defaults!
8200 $sectionsettings[] = $setting->output_html($data, $query);
8204 $tpldata->results[] = (object) [
8205 'title' => $heading,
8206 'url' => $headingurl->out(false),
8207 'settings' => $sectionsettings
8211 $tpldata->showsave = $savebutton;
8212 $tpldata->hasresults = !empty($tpldata->results);
8214 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8218 * Internal function - returns arrays of html pages with uninitialised settings
8220 * @param object $node Instance of admin_category or admin_settingpage
8221 * @return array
8223 function admin_output_new_settings_by_page($node) {
8224 global $OUTPUT;
8225 $return = array();
8227 if ($node instanceof admin_category) {
8228 $entries = array_keys($node->children);
8229 foreach ($entries as $entry) {
8230 $return += admin_output_new_settings_by_page($node->children[$entry]);
8233 } else if ($node instanceof admin_settingpage) {
8234 $newsettings = array();
8235 foreach ($node->settings as $setting) {
8236 if (is_null($setting->get_setting())) {
8237 $newsettings[] = $setting;
8240 if (count($newsettings) > 0) {
8241 $adminroot = admin_get_root();
8242 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8243 $page .= '<fieldset class="adminsettings">'."\n";
8244 foreach ($newsettings as $setting) {
8245 $fullname = $setting->get_full_name();
8246 if (array_key_exists($fullname, $adminroot->errors)) {
8247 $data = $adminroot->errors[$fullname]->data;
8248 } else {
8249 $data = $setting->get_setting();
8250 if (is_null($data)) {
8251 $data = $setting->get_defaultsetting();
8254 $page .= '<div class="clearer"><!-- --></div>'."\n";
8255 $page .= $setting->output_html($data);
8257 $page .= '</fieldset>';
8258 $return[$node->name] = $page;
8262 return $return;
8266 * Format admin settings
8268 * @param object $setting
8269 * @param string $title label element
8270 * @param string $form form fragment, html code - not highlighted automatically
8271 * @param string $description
8272 * @param mixed $label link label to id, true by default or string being the label to connect it to
8273 * @param string $warning warning text
8274 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8275 * @param string $query search query to be highlighted
8276 * @return string XHTML
8278 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8279 global $CFG, $OUTPUT;
8281 $context = (object) [
8282 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8283 'fullname' => $setting->get_full_name(),
8286 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8287 if ($label === true) {
8288 $context->labelfor = $setting->get_id();
8289 } else if ($label === false) {
8290 $context->labelfor = '';
8291 } else {
8292 $context->labelfor = $label;
8295 $form .= $setting->output_setting_flags();
8297 $context->warning = $warning;
8298 $context->override = '';
8299 if (empty($setting->plugin)) {
8300 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8301 $context->override = get_string('configoverride', 'admin');
8303 } else {
8304 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8305 $context->override = get_string('configoverride', 'admin');
8309 $defaults = array();
8310 if (!is_null($defaultinfo)) {
8311 if ($defaultinfo === '') {
8312 $defaultinfo = get_string('emptysettingvalue', 'admin');
8314 $defaults[] = $defaultinfo;
8317 $context->default = null;
8318 $setting->get_setting_flag_defaults($defaults);
8319 if (!empty($defaults)) {
8320 $defaultinfo = implode(', ', $defaults);
8321 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8322 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8326 $context->error = '';
8327 $adminroot = admin_get_root();
8328 if (array_key_exists($context->fullname, $adminroot->errors)) {
8329 $context->error = $adminroot->errors[$context->fullname]->error;
8332 $context->id = 'admin-' . $setting->name;
8333 $context->title = highlightfast($query, $title);
8334 $context->name = highlightfast($query, $context->name);
8335 $context->description = highlight($query, markdown_to_html($description));
8336 $context->element = $form;
8337 $context->forceltr = $setting->get_force_ltr();
8339 return $OUTPUT->render_from_template('core_admin/setting', $context);
8343 * Based on find_new_settings{@link ()} in upgradesettings.php
8344 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8346 * @param object $node Instance of admin_category, or admin_settingpage
8347 * @return boolean true if any settings haven't been initialised, false if they all have
8349 function any_new_admin_settings($node) {
8351 if ($node instanceof admin_category) {
8352 $entries = array_keys($node->children);
8353 foreach ($entries as $entry) {
8354 if (any_new_admin_settings($node->children[$entry])) {
8355 return true;
8359 } else if ($node instanceof admin_settingpage) {
8360 foreach ($node->settings as $setting) {
8361 if ($setting->get_setting() === NULL) {
8362 return true;
8367 return false;
8371 * Moved from admin/replace.php so that we can use this in cron
8373 * @param string $search string to look for
8374 * @param string $replace string to replace
8375 * @return bool success or fail
8377 function db_replace($search, $replace) {
8378 global $DB, $CFG, $OUTPUT;
8380 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8381 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
8382 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
8383 'block_instances', '');
8385 // Turn off time limits, sometimes upgrades can be slow.
8386 core_php_time_limit::raise();
8388 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
8389 return false;
8391 foreach ($tables as $table) {
8393 if (in_array($table, $skiptables)) { // Don't process these
8394 continue;
8397 if ($columns = $DB->get_columns($table)) {
8398 $DB->set_debug(true);
8399 foreach ($columns as $column) {
8400 $DB->replace_all_text($table, $column, $search, $replace);
8402 $DB->set_debug(false);
8406 // delete modinfo caches
8407 rebuild_course_cache(0, true);
8409 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
8410 $blocks = core_component::get_plugin_list('block');
8411 foreach ($blocks as $blockname=>$fullblock) {
8412 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8413 continue;
8416 if (!is_readable($fullblock.'/lib.php')) {
8417 continue;
8420 $function = 'block_'.$blockname.'_global_db_replace';
8421 include_once($fullblock.'/lib.php');
8422 if (!function_exists($function)) {
8423 continue;
8426 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
8427 $function($search, $replace);
8428 echo $OUTPUT->notification("...finished", 'notifysuccess');
8431 purge_all_caches();
8433 return true;
8437 * Manage repository settings
8439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8441 class admin_setting_managerepository extends admin_setting {
8442 /** @var string */
8443 private $baseurl;
8446 * calls parent::__construct with specific arguments
8448 public function __construct() {
8449 global $CFG;
8450 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
8451 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
8455 * Always returns true, does nothing
8457 * @return true
8459 public function get_setting() {
8460 return true;
8464 * Always returns true does nothing
8466 * @return true
8468 public function get_defaultsetting() {
8469 return true;
8473 * Always returns s_managerepository
8475 * @return string Always return 's_managerepository'
8477 public function get_full_name() {
8478 return 's_managerepository';
8482 * Always returns '' doesn't do anything
8484 public function write_setting($data) {
8485 $url = $this->baseurl . '&amp;new=' . $data;
8486 return '';
8487 // TODO
8488 // Should not use redirect and exit here
8489 // Find a better way to do this.
8490 // redirect($url);
8491 // exit;
8495 * Searches repository plugins for one that matches $query
8497 * @param string $query The string to search for
8498 * @return bool true if found, false if not
8500 public function is_related($query) {
8501 if (parent::is_related($query)) {
8502 return true;
8505 $repositories= core_component::get_plugin_list('repository');
8506 foreach ($repositories as $p => $dir) {
8507 if (strpos($p, $query) !== false) {
8508 return true;
8511 foreach (repository::get_types() as $instance) {
8512 $title = $instance->get_typename();
8513 if (strpos(core_text::strtolower($title), $query) !== false) {
8514 return true;
8517 return false;
8521 * Helper function that generates a moodle_url object
8522 * relevant to the repository
8525 function repository_action_url($repository) {
8526 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
8530 * Builds XHTML to display the control
8532 * @param string $data Unused
8533 * @param string $query
8534 * @return string XHTML
8536 public function output_html($data, $query='') {
8537 global $CFG, $USER, $OUTPUT;
8539 // Get strings that are used
8540 $strshow = get_string('on', 'repository');
8541 $strhide = get_string('off', 'repository');
8542 $strdelete = get_string('disabled', 'repository');
8544 $actionchoicesforexisting = array(
8545 'show' => $strshow,
8546 'hide' => $strhide,
8547 'delete' => $strdelete
8550 $actionchoicesfornew = array(
8551 'newon' => $strshow,
8552 'newoff' => $strhide,
8553 'delete' => $strdelete
8556 $return = '';
8557 $return .= $OUTPUT->box_start('generalbox');
8559 // Set strings that are used multiple times
8560 $settingsstr = get_string('settings');
8561 $disablestr = get_string('disable');
8563 // Table to list plug-ins
8564 $table = new html_table();
8565 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
8566 $table->align = array('left', 'center', 'center', 'center', 'center');
8567 $table->data = array();
8569 // Get list of used plug-ins
8570 $repositorytypes = repository::get_types();
8571 if (!empty($repositorytypes)) {
8572 // Array to store plugins being used
8573 $alreadyplugins = array();
8574 $totalrepositorytypes = count($repositorytypes);
8575 $updowncount = 1;
8576 foreach ($repositorytypes as $i) {
8577 $settings = '';
8578 $typename = $i->get_typename();
8579 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
8580 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
8581 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
8583 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
8584 // Calculate number of instances in order to display them for the Moodle administrator
8585 if (!empty($instanceoptionnames)) {
8586 $params = array();
8587 $params['context'] = array(context_system::instance());
8588 $params['onlyvisible'] = false;
8589 $params['type'] = $typename;
8590 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
8591 // site instances
8592 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
8593 $params['context'] = array();
8594 $instances = repository::static_function($typename, 'get_instances', $params);
8595 $courseinstances = array();
8596 $userinstances = array();
8598 foreach ($instances as $instance) {
8599 $repocontext = context::instance_by_id($instance->instance->contextid);
8600 if ($repocontext->contextlevel == CONTEXT_COURSE) {
8601 $courseinstances[] = $instance;
8602 } else if ($repocontext->contextlevel == CONTEXT_USER) {
8603 $userinstances[] = $instance;
8606 // course instances
8607 $instancenumber = count($courseinstances);
8608 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
8610 // user private instances
8611 $instancenumber = count($userinstances);
8612 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
8613 } else {
8614 $admininstancenumbertext = "";
8615 $courseinstancenumbertext = "";
8616 $userinstancenumbertext = "";
8619 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
8621 $settings .= $OUTPUT->container_start('mdl-left');
8622 $settings .= '<br/>';
8623 $settings .= $admininstancenumbertext;
8624 $settings .= '<br/>';
8625 $settings .= $courseinstancenumbertext;
8626 $settings .= '<br/>';
8627 $settings .= $userinstancenumbertext;
8628 $settings .= $OUTPUT->container_end();
8630 // Get the current visibility
8631 if ($i->get_visible()) {
8632 $currentaction = 'show';
8633 } else {
8634 $currentaction = 'hide';
8637 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
8639 // Display up/down link
8640 $updown = '';
8641 // Should be done with CSS instead.
8642 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
8644 if ($updowncount > 1) {
8645 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
8646 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
8648 else {
8649 $updown .= $spacer;
8651 if ($updowncount < $totalrepositorytypes) {
8652 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
8653 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
8655 else {
8656 $updown .= $spacer;
8659 $updowncount++;
8661 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
8663 if (!in_array($typename, $alreadyplugins)) {
8664 $alreadyplugins[] = $typename;
8669 // Get all the plugins that exist on disk
8670 $plugins = core_component::get_plugin_list('repository');
8671 if (!empty($plugins)) {
8672 foreach ($plugins as $plugin => $dir) {
8673 // Check that it has not already been listed
8674 if (!in_array($plugin, $alreadyplugins)) {
8675 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
8676 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
8681 $return .= html_writer::table($table);
8682 $return .= $OUTPUT->box_end();
8683 return highlight($query, $return);
8688 * Special checkbox for enable mobile web service
8689 * If enable then we store the service id of the mobile service into config table
8690 * If disable then we unstore the service id from the config table
8692 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
8694 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
8695 private $restuse;
8698 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
8700 * @return boolean
8702 private function is_protocol_cap_allowed() {
8703 global $DB, $CFG;
8705 // If the $this->restuse variable is not set, it needs to be set.
8706 if (empty($this->restuse) and $this->restuse!==false) {
8707 $params = array();
8708 $params['permission'] = CAP_ALLOW;
8709 $params['roleid'] = $CFG->defaultuserroleid;
8710 $params['capability'] = 'webservice/rest:use';
8711 $this->restuse = $DB->record_exists('role_capabilities', $params);
8714 return $this->restuse;
8718 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
8719 * @param type $status true to allow, false to not set
8721 private function set_protocol_cap($status) {
8722 global $CFG;
8723 if ($status and !$this->is_protocol_cap_allowed()) {
8724 //need to allow the cap
8725 $permission = CAP_ALLOW;
8726 $assign = true;
8727 } else if (!$status and $this->is_protocol_cap_allowed()){
8728 //need to disallow the cap
8729 $permission = CAP_INHERIT;
8730 $assign = true;
8732 if (!empty($assign)) {
8733 $systemcontext = context_system::instance();
8734 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8739 * Builds XHTML to display the control.
8740 * The main purpose of this overloading is to display a warning when https
8741 * is not supported by the server
8742 * @param string $data Unused
8743 * @param string $query
8744 * @return string XHTML
8746 public function output_html($data, $query='') {
8747 global $OUTPUT;
8748 $html = parent::output_html($data, $query);
8750 if ((string)$data === $this->yes) {
8751 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
8752 foreach ($notifications as $notification) {
8753 $message = get_string($notification[0], $notification[1]);
8754 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
8758 return $html;
8762 * Retrieves the current setting using the objects name
8764 * @return string
8766 public function get_setting() {
8767 global $CFG;
8769 // First check if is not set.
8770 $result = $this->config_read($this->name);
8771 if (is_null($result)) {
8772 return null;
8775 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8776 // Or if web services aren't enabled this can't be,
8777 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8778 return 0;
8781 require_once($CFG->dirroot . '/webservice/lib.php');
8782 $webservicemanager = new webservice();
8783 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8784 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8785 return $result;
8786 } else {
8787 return 0;
8792 * Save the selected setting
8794 * @param string $data The selected site
8795 * @return string empty string or error message
8797 public function write_setting($data) {
8798 global $DB, $CFG;
8800 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8801 if (empty($CFG->defaultuserroleid)) {
8802 return '';
8805 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8807 require_once($CFG->dirroot . '/webservice/lib.php');
8808 $webservicemanager = new webservice();
8810 $updateprotocol = false;
8811 if ((string)$data === $this->yes) {
8812 //code run when enable mobile web service
8813 //enable web service systeme if necessary
8814 set_config('enablewebservices', true);
8816 //enable mobile service
8817 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8818 $mobileservice->enabled = 1;
8819 $webservicemanager->update_external_service($mobileservice);
8821 // Enable REST server.
8822 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8824 if (!in_array('rest', $activeprotocols)) {
8825 $activeprotocols[] = 'rest';
8826 $updateprotocol = true;
8829 if ($updateprotocol) {
8830 set_config('webserviceprotocols', implode(',', $activeprotocols));
8833 // Allow rest:use capability for authenticated user.
8834 $this->set_protocol_cap(true);
8836 } else {
8837 //disable web service system if no other services are enabled
8838 $otherenabledservices = $DB->get_records_select('external_services',
8839 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8840 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8841 if (empty($otherenabledservices)) {
8842 set_config('enablewebservices', false);
8844 // Also disable REST server.
8845 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8847 $protocolkey = array_search('rest', $activeprotocols);
8848 if ($protocolkey !== false) {
8849 unset($activeprotocols[$protocolkey]);
8850 $updateprotocol = true;
8853 if ($updateprotocol) {
8854 set_config('webserviceprotocols', implode(',', $activeprotocols));
8857 // Disallow rest:use capability for authenticated user.
8858 $this->set_protocol_cap(false);
8861 //disable the mobile service
8862 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8863 $mobileservice->enabled = 0;
8864 $webservicemanager->update_external_service($mobileservice);
8867 return (parent::write_setting($data));
8872 * Special class for management of external services
8874 * @author Petr Skoda (skodak)
8876 class admin_setting_manageexternalservices extends admin_setting {
8878 * Calls parent::__construct with specific arguments
8880 public function __construct() {
8881 $this->nosave = true;
8882 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8886 * Always returns true, does nothing
8888 * @return true
8890 public function get_setting() {
8891 return true;
8895 * Always returns true, does nothing
8897 * @return true
8899 public function get_defaultsetting() {
8900 return true;
8904 * Always returns '', does not write anything
8906 * @return string Always returns ''
8908 public function write_setting($data) {
8909 // do not write any setting
8910 return '';
8914 * Checks if $query is one of the available external services
8916 * @param string $query The string to search for
8917 * @return bool Returns true if found, false if not
8919 public function is_related($query) {
8920 global $DB;
8922 if (parent::is_related($query)) {
8923 return true;
8926 $services = $DB->get_records('external_services', array(), 'id, name');
8927 foreach ($services as $service) {
8928 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8929 return true;
8932 return false;
8936 * Builds the XHTML to display the control
8938 * @param string $data Unused
8939 * @param string $query
8940 * @return string
8942 public function output_html($data, $query='') {
8943 global $CFG, $OUTPUT, $DB;
8945 // display strings
8946 $stradministration = get_string('administration');
8947 $stredit = get_string('edit');
8948 $strservice = get_string('externalservice', 'webservice');
8949 $strdelete = get_string('delete');
8950 $strplugin = get_string('plugin', 'admin');
8951 $stradd = get_string('add');
8952 $strfunctions = get_string('functions', 'webservice');
8953 $strusers = get_string('users');
8954 $strserviceusers = get_string('serviceusers', 'webservice');
8956 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8957 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8958 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8960 // built in services
8961 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8962 $return = "";
8963 if (!empty($services)) {
8964 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8968 $table = new html_table();
8969 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8970 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8971 $table->id = 'builtinservices';
8972 $table->attributes['class'] = 'admintable externalservices generaltable';
8973 $table->data = array();
8975 // iterate through auth plugins and add to the display table
8976 foreach ($services as $service) {
8977 $name = $service->name;
8979 // hide/show link
8980 if ($service->enabled) {
8981 $displayname = "<span>$name</span>";
8982 } else {
8983 $displayname = "<span class=\"dimmed_text\">$name</span>";
8986 $plugin = $service->component;
8988 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8990 if ($service->restrictedusers) {
8991 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8992 } else {
8993 $users = get_string('allusers', 'webservice');
8996 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8998 // add a row to the table
8999 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
9001 $return .= html_writer::table($table);
9004 // Custom services
9005 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9006 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9008 $table = new html_table();
9009 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9010 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9011 $table->id = 'customservices';
9012 $table->attributes['class'] = 'admintable externalservices generaltable';
9013 $table->data = array();
9015 // iterate through auth plugins and add to the display table
9016 foreach ($services as $service) {
9017 $name = $service->name;
9019 // hide/show link
9020 if ($service->enabled) {
9021 $displayname = "<span>$name</span>";
9022 } else {
9023 $displayname = "<span class=\"dimmed_text\">$name</span>";
9026 // delete link
9027 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9029 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9031 if ($service->restrictedusers) {
9032 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9033 } else {
9034 $users = get_string('allusers', 'webservice');
9037 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9039 // add a row to the table
9040 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9042 // add new custom service option
9043 $return .= html_writer::table($table);
9045 $return .= '<br />';
9046 // add a token to the table
9047 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9049 return highlight($query, $return);
9054 * Special class for overview of external services
9056 * @author Jerome Mouneyrac
9058 class admin_setting_webservicesoverview extends admin_setting {
9061 * Calls parent::__construct with specific arguments
9063 public function __construct() {
9064 $this->nosave = true;
9065 parent::__construct('webservicesoverviewui',
9066 get_string('webservicesoverview', 'webservice'), '', '');
9070 * Always returns true, does nothing
9072 * @return true
9074 public function get_setting() {
9075 return true;
9079 * Always returns true, does nothing
9081 * @return true
9083 public function get_defaultsetting() {
9084 return true;
9088 * Always returns '', does not write anything
9090 * @return string Always returns ''
9092 public function write_setting($data) {
9093 // do not write any setting
9094 return '';
9098 * Builds the XHTML to display the control
9100 * @param string $data Unused
9101 * @param string $query
9102 * @return string
9104 public function output_html($data, $query='') {
9105 global $CFG, $OUTPUT;
9107 $return = "";
9108 $brtag = html_writer::empty_tag('br');
9110 /// One system controlling Moodle with Token
9111 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9112 $table = new html_table();
9113 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9114 get_string('description'));
9115 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9116 $table->id = 'onesystemcontrol';
9117 $table->attributes['class'] = 'admintable wsoverview generaltable';
9118 $table->data = array();
9120 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9121 . $brtag . $brtag;
9123 /// 1. Enable Web Services
9124 $row = array();
9125 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9126 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9127 array('href' => $url));
9128 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9129 if ($CFG->enablewebservices) {
9130 $status = get_string('yes');
9132 $row[1] = $status;
9133 $row[2] = get_string('enablewsdescription', 'webservice');
9134 $table->data[] = $row;
9136 /// 2. Enable protocols
9137 $row = array();
9138 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9139 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9140 array('href' => $url));
9141 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9142 //retrieve activated protocol
9143 $active_protocols = empty($CFG->webserviceprotocols) ?
9144 array() : explode(',', $CFG->webserviceprotocols);
9145 if (!empty($active_protocols)) {
9146 $status = "";
9147 foreach ($active_protocols as $protocol) {
9148 $status .= $protocol . $brtag;
9151 $row[1] = $status;
9152 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9153 $table->data[] = $row;
9155 /// 3. Create user account
9156 $row = array();
9157 $url = new moodle_url("/user/editadvanced.php?id=-1");
9158 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9159 array('href' => $url));
9160 $row[1] = "";
9161 $row[2] = get_string('createuserdescription', 'webservice');
9162 $table->data[] = $row;
9164 /// 4. Add capability to users
9165 $row = array();
9166 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9167 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9168 array('href' => $url));
9169 $row[1] = "";
9170 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9171 $table->data[] = $row;
9173 /// 5. Select a web service
9174 $row = array();
9175 $url = new moodle_url("/admin/settings.php?section=externalservices");
9176 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9177 array('href' => $url));
9178 $row[1] = "";
9179 $row[2] = get_string('createservicedescription', 'webservice');
9180 $table->data[] = $row;
9182 /// 6. Add functions
9183 $row = array();
9184 $url = new moodle_url("/admin/settings.php?section=externalservices");
9185 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9186 array('href' => $url));
9187 $row[1] = "";
9188 $row[2] = get_string('addfunctionsdescription', 'webservice');
9189 $table->data[] = $row;
9191 /// 7. Add the specific user
9192 $row = array();
9193 $url = new moodle_url("/admin/settings.php?section=externalservices");
9194 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9195 array('href' => $url));
9196 $row[1] = "";
9197 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9198 $table->data[] = $row;
9200 /// 8. Create token for the specific user
9201 $row = array();
9202 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9203 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9204 array('href' => $url));
9205 $row[1] = "";
9206 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9207 $table->data[] = $row;
9209 /// 9. Enable the documentation
9210 $row = array();
9211 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9212 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9213 array('href' => $url));
9214 $status = '<span class="warning">' . get_string('no') . '</span>';
9215 if ($CFG->enablewsdocumentation) {
9216 $status = get_string('yes');
9218 $row[1] = $status;
9219 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9220 $table->data[] = $row;
9222 /// 10. Test the service
9223 $row = array();
9224 $url = new moodle_url("/admin/webservice/testclient.php");
9225 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9226 array('href' => $url));
9227 $row[1] = "";
9228 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9229 $table->data[] = $row;
9231 $return .= html_writer::table($table);
9233 /// Users as clients with token
9234 $return .= $brtag . $brtag . $brtag;
9235 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9236 $table = new html_table();
9237 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9238 get_string('description'));
9239 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9240 $table->id = 'userasclients';
9241 $table->attributes['class'] = 'admintable wsoverview generaltable';
9242 $table->data = array();
9244 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9245 $brtag . $brtag;
9247 /// 1. Enable Web Services
9248 $row = array();
9249 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9250 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9251 array('href' => $url));
9252 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9253 if ($CFG->enablewebservices) {
9254 $status = get_string('yes');
9256 $row[1] = $status;
9257 $row[2] = get_string('enablewsdescription', 'webservice');
9258 $table->data[] = $row;
9260 /// 2. Enable protocols
9261 $row = array();
9262 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9263 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9264 array('href' => $url));
9265 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9266 //retrieve activated protocol
9267 $active_protocols = empty($CFG->webserviceprotocols) ?
9268 array() : explode(',', $CFG->webserviceprotocols);
9269 if (!empty($active_protocols)) {
9270 $status = "";
9271 foreach ($active_protocols as $protocol) {
9272 $status .= $protocol . $brtag;
9275 $row[1] = $status;
9276 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9277 $table->data[] = $row;
9280 /// 3. Select a web service
9281 $row = array();
9282 $url = new moodle_url("/admin/settings.php?section=externalservices");
9283 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9284 array('href' => $url));
9285 $row[1] = "";
9286 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9287 $table->data[] = $row;
9289 /// 4. Add functions
9290 $row = array();
9291 $url = new moodle_url("/admin/settings.php?section=externalservices");
9292 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9293 array('href' => $url));
9294 $row[1] = "";
9295 $row[2] = get_string('addfunctionsdescription', 'webservice');
9296 $table->data[] = $row;
9298 /// 5. Add capability to users
9299 $row = array();
9300 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9301 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9302 array('href' => $url));
9303 $row[1] = "";
9304 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9305 $table->data[] = $row;
9307 /// 6. Test the service
9308 $row = array();
9309 $url = new moodle_url("/admin/webservice/testclient.php");
9310 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9311 array('href' => $url));
9312 $row[1] = "";
9313 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9314 $table->data[] = $row;
9316 $return .= html_writer::table($table);
9318 return highlight($query, $return);
9325 * Special class for web service protocol administration.
9327 * @author Petr Skoda (skodak)
9329 class admin_setting_managewebserviceprotocols extends admin_setting {
9332 * Calls parent::__construct with specific arguments
9334 public function __construct() {
9335 $this->nosave = true;
9336 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9340 * Always returns true, does nothing
9342 * @return true
9344 public function get_setting() {
9345 return true;
9349 * Always returns true, does nothing
9351 * @return true
9353 public function get_defaultsetting() {
9354 return true;
9358 * Always returns '', does not write anything
9360 * @return string Always returns ''
9362 public function write_setting($data) {
9363 // do not write any setting
9364 return '';
9368 * Checks if $query is one of the available webservices
9370 * @param string $query The string to search for
9371 * @return bool Returns true if found, false if not
9373 public function is_related($query) {
9374 if (parent::is_related($query)) {
9375 return true;
9378 $protocols = core_component::get_plugin_list('webservice');
9379 foreach ($protocols as $protocol=>$location) {
9380 if (strpos($protocol, $query) !== false) {
9381 return true;
9383 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
9384 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
9385 return true;
9388 return false;
9392 * Builds the XHTML to display the control
9394 * @param string $data Unused
9395 * @param string $query
9396 * @return string
9398 public function output_html($data, $query='') {
9399 global $CFG, $OUTPUT;
9401 // display strings
9402 $stradministration = get_string('administration');
9403 $strsettings = get_string('settings');
9404 $stredit = get_string('edit');
9405 $strprotocol = get_string('protocol', 'webservice');
9406 $strenable = get_string('enable');
9407 $strdisable = get_string('disable');
9408 $strversion = get_string('version');
9410 $protocols_available = core_component::get_plugin_list('webservice');
9411 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9412 ksort($protocols_available);
9414 foreach ($active_protocols as $key=>$protocol) {
9415 if (empty($protocols_available[$protocol])) {
9416 unset($active_protocols[$key]);
9420 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
9421 $return .= $OUTPUT->box_start('generalbox webservicesui');
9423 $table = new html_table();
9424 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
9425 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
9426 $table->id = 'webserviceprotocols';
9427 $table->attributes['class'] = 'admintable generaltable';
9428 $table->data = array();
9430 // iterate through auth plugins and add to the display table
9431 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
9432 foreach ($protocols_available as $protocol => $location) {
9433 $name = get_string('pluginname', 'webservice_'.$protocol);
9435 $plugin = new stdClass();
9436 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
9437 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
9439 $version = isset($plugin->version) ? $plugin->version : '';
9441 // hide/show link
9442 if (in_array($protocol, $active_protocols)) {
9443 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
9444 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
9445 $displayname = "<span>$name</span>";
9446 } else {
9447 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
9448 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
9449 $displayname = "<span class=\"dimmed_text\">$name</span>";
9452 // settings link
9453 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
9454 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
9455 } else {
9456 $settings = '';
9459 // add a row to the table
9460 $table->data[] = array($displayname, $version, $hideshow, $settings);
9462 $return .= html_writer::table($table);
9463 $return .= get_string('configwebserviceplugins', 'webservice');
9464 $return .= $OUTPUT->box_end();
9466 return highlight($query, $return);
9472 * Special class for web service token administration.
9474 * @author Jerome Mouneyrac
9476 class admin_setting_managewebservicetokens extends admin_setting {
9479 * Calls parent::__construct with specific arguments
9481 public function __construct() {
9482 $this->nosave = true;
9483 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
9487 * Always returns true, does nothing
9489 * @return true
9491 public function get_setting() {
9492 return true;
9496 * Always returns true, does nothing
9498 * @return true
9500 public function get_defaultsetting() {
9501 return true;
9505 * Always returns '', does not write anything
9507 * @return string Always returns ''
9509 public function write_setting($data) {
9510 // do not write any setting
9511 return '';
9515 * Builds the XHTML to display the control
9517 * @param string $data Unused
9518 * @param string $query
9519 * @return string
9521 public function output_html($data, $query='') {
9522 global $CFG, $OUTPUT;
9524 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
9525 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
9527 $return = $OUTPUT->box_start('generalbox webservicestokenui');
9529 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
9530 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
9533 $table = new \webservice\token_table('webservicetokens');
9534 $table->define_baseurl($baseurl);
9535 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
9536 $table->data = array();
9537 ob_start();
9538 $table->out(10, false);
9539 $tablehtml = ob_get_contents();
9540 ob_end_clean();
9541 $return .= $tablehtml;
9543 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
9545 $return .= $OUTPUT->box_end();
9546 // add a token to the table
9547 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
9548 $return .= get_string('add')."</a>";
9550 return highlight($query, $return);
9556 * Colour picker
9558 * @copyright 2010 Sam Hemelryk
9559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9561 class admin_setting_configcolourpicker extends admin_setting {
9564 * Information for previewing the colour
9566 * @var array|null
9568 protected $previewconfig = null;
9571 * Use default when empty.
9573 protected $usedefaultwhenempty = true;
9577 * @param string $name
9578 * @param string $visiblename
9579 * @param string $description
9580 * @param string $defaultsetting
9581 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
9583 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
9584 $usedefaultwhenempty = true) {
9585 $this->previewconfig = $previewconfig;
9586 $this->usedefaultwhenempty = $usedefaultwhenempty;
9587 parent::__construct($name, $visiblename, $description, $defaultsetting);
9588 $this->set_force_ltr(true);
9592 * Return the setting
9594 * @return mixed returns config if successful else null
9596 public function get_setting() {
9597 return $this->config_read($this->name);
9601 * Saves the setting
9603 * @param string $data
9604 * @return bool
9606 public function write_setting($data) {
9607 $data = $this->validate($data);
9608 if ($data === false) {
9609 return get_string('validateerror', 'admin');
9611 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
9615 * Validates the colour that was entered by the user
9617 * @param string $data
9618 * @return string|false
9620 protected function validate($data) {
9622 * List of valid HTML colour names
9624 * @var array
9626 $colornames = array(
9627 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
9628 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
9629 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
9630 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
9631 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
9632 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
9633 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
9634 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
9635 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
9636 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
9637 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
9638 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
9639 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
9640 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
9641 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
9642 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
9643 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
9644 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
9645 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
9646 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
9647 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
9648 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
9649 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
9650 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
9651 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
9652 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
9653 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
9654 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
9655 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
9656 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
9657 'whitesmoke', 'yellow', 'yellowgreen'
9660 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
9661 if (strpos($data, '#')!==0) {
9662 $data = '#'.$data;
9664 return $data;
9665 } else if (in_array(strtolower($data), $colornames)) {
9666 return $data;
9667 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9668 return $data;
9669 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9670 return $data;
9671 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9672 return $data;
9673 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9674 return $data;
9675 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9676 return $data;
9677 } else if (empty($data)) {
9678 if ($this->usedefaultwhenempty){
9679 return $this->defaultsetting;
9680 } else {
9681 return '';
9683 } else {
9684 return false;
9689 * Generates the HTML for the setting
9691 * @global moodle_page $PAGE
9692 * @global core_renderer $OUTPUT
9693 * @param string $data
9694 * @param string $query
9696 public function output_html($data, $query = '') {
9697 global $PAGE, $OUTPUT;
9699 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
9700 $context = (object) [
9701 'id' => $this->get_id(),
9702 'name' => $this->get_full_name(),
9703 'value' => $data,
9704 'icon' => $icon->export_for_template($OUTPUT),
9705 'haspreviewconfig' => !empty($this->previewconfig),
9706 'forceltr' => $this->get_force_ltr()
9709 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
9710 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9712 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
9713 $this->get_defaultsetting(), $query);
9720 * Class used for uploading of one file into file storage,
9721 * the file name is stored in config table.
9723 * Please note you need to implement your own '_pluginfile' callback function,
9724 * this setting only stores the file, it does not deal with file serving.
9726 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9729 class admin_setting_configstoredfile extends admin_setting {
9730 /** @var array file area options - should be one file only */
9731 protected $options;
9732 /** @var string name of the file area */
9733 protected $filearea;
9734 /** @var int intemid */
9735 protected $itemid;
9736 /** @var string used for detection of changes */
9737 protected $oldhashes;
9740 * Create new stored file setting.
9742 * @param string $name low level setting name
9743 * @param string $visiblename human readable setting name
9744 * @param string $description description of setting
9745 * @param mixed $filearea file area for file storage
9746 * @param int $itemid itemid for file storage
9747 * @param array $options file area options
9749 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9750 parent::__construct($name, $visiblename, $description, '');
9751 $this->filearea = $filearea;
9752 $this->itemid = $itemid;
9753 $this->options = (array)$options;
9757 * Applies defaults and returns all options.
9758 * @return array
9760 protected function get_options() {
9761 global $CFG;
9763 require_once("$CFG->libdir/filelib.php");
9764 require_once("$CFG->dirroot/repository/lib.php");
9765 $defaults = array(
9766 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9767 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9768 'context' => context_system::instance());
9769 foreach($this->options as $k => $v) {
9770 $defaults[$k] = $v;
9773 return $defaults;
9776 public function get_setting() {
9777 return $this->config_read($this->name);
9780 public function write_setting($data) {
9781 global $USER;
9783 // Let's not deal with validation here, this is for admins only.
9784 $current = $this->get_setting();
9785 if (empty($data) && $current === null) {
9786 // This will be the case when applying default settings (installation).
9787 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9788 } else if (!is_number($data)) {
9789 // Draft item id is expected here!
9790 return get_string('errorsetting', 'admin');
9793 $options = $this->get_options();
9794 $fs = get_file_storage();
9795 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9797 $this->oldhashes = null;
9798 if ($current) {
9799 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9800 if ($file = $fs->get_file_by_hash($hash)) {
9801 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9803 unset($file);
9806 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9807 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9808 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9809 // with an error because the draft area does not exist, as he did not use it.
9810 $usercontext = context_user::instance($USER->id);
9811 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9812 return get_string('errorsetting', 'admin');
9816 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9817 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9819 $filepath = '';
9820 if ($files) {
9821 /** @var stored_file $file */
9822 $file = reset($files);
9823 $filepath = $file->get_filepath().$file->get_filename();
9826 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9829 public function post_write_settings($original) {
9830 $options = $this->get_options();
9831 $fs = get_file_storage();
9832 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9834 $current = $this->get_setting();
9835 $newhashes = null;
9836 if ($current) {
9837 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9838 if ($file = $fs->get_file_by_hash($hash)) {
9839 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9841 unset($file);
9844 if ($this->oldhashes === $newhashes) {
9845 $this->oldhashes = null;
9846 return false;
9848 $this->oldhashes = null;
9850 $callbackfunction = $this->updatedcallback;
9851 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9852 $callbackfunction($this->get_full_name());
9854 return true;
9857 public function output_html($data, $query = '') {
9858 global $PAGE, $CFG;
9860 $options = $this->get_options();
9861 $id = $this->get_id();
9862 $elname = $this->get_full_name();
9863 $draftitemid = file_get_submitted_draft_itemid($elname);
9864 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9865 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9867 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9868 require_once("$CFG->dirroot/lib/form/filemanager.php");
9870 $fmoptions = new stdClass();
9871 $fmoptions->mainfile = $options['mainfile'];
9872 $fmoptions->maxbytes = $options['maxbytes'];
9873 $fmoptions->maxfiles = $options['maxfiles'];
9874 $fmoptions->client_id = uniqid();
9875 $fmoptions->itemid = $draftitemid;
9876 $fmoptions->subdirs = $options['subdirs'];
9877 $fmoptions->target = $id;
9878 $fmoptions->accepted_types = $options['accepted_types'];
9879 $fmoptions->return_types = $options['return_types'];
9880 $fmoptions->context = $options['context'];
9881 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9883 $fm = new form_filemanager($fmoptions);
9884 $output = $PAGE->get_renderer('core', 'files');
9885 $html = $output->render($fm);
9887 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9888 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9890 return format_admin_setting($this, $this->visiblename,
9891 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
9892 $this->description, true, '', '', $query);
9898 * Administration interface for user specified regular expressions for device detection.
9900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9902 class admin_setting_devicedetectregex extends admin_setting {
9905 * Calls parent::__construct with specific args
9907 * @param string $name
9908 * @param string $visiblename
9909 * @param string $description
9910 * @param mixed $defaultsetting
9912 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9913 global $CFG;
9914 parent::__construct($name, $visiblename, $description, $defaultsetting);
9918 * Return the current setting(s)
9920 * @return array Current settings array
9922 public function get_setting() {
9923 global $CFG;
9925 $config = $this->config_read($this->name);
9926 if (is_null($config)) {
9927 return null;
9930 return $this->prepare_form_data($config);
9934 * Save selected settings
9936 * @param array $data Array of settings to save
9937 * @return bool
9939 public function write_setting($data) {
9940 if (empty($data)) {
9941 $data = array();
9944 if ($this->config_write($this->name, $this->process_form_data($data))) {
9945 return ''; // success
9946 } else {
9947 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9952 * Return XHTML field(s) for regexes
9954 * @param array $data Array of options to set in HTML
9955 * @return string XHTML string for the fields and wrapping div(s)
9957 public function output_html($data, $query='') {
9958 global $OUTPUT;
9960 $context = (object) [
9961 'expressions' => [],
9962 'name' => $this->get_full_name()
9965 if (empty($data)) {
9966 $looplimit = 1;
9967 } else {
9968 $looplimit = (count($data)/2)+1;
9971 for ($i=0; $i<$looplimit; $i++) {
9973 $expressionname = 'expression'.$i;
9975 if (!empty($data[$expressionname])){
9976 $expression = $data[$expressionname];
9977 } else {
9978 $expression = '';
9981 $valuename = 'value'.$i;
9983 if (!empty($data[$valuename])){
9984 $value = $data[$valuename];
9985 } else {
9986 $value= '';
9989 $context->expressions[] = [
9990 'index' => $i,
9991 'expression' => $expression,
9992 'value' => $value
9996 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
9998 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
10002 * Converts the string of regexes
10004 * @see self::process_form_data()
10005 * @param $regexes string of regexes
10006 * @return array of form fields and their values
10008 protected function prepare_form_data($regexes) {
10010 $regexes = json_decode($regexes);
10012 $form = array();
10014 $i = 0;
10016 foreach ($regexes as $value => $regex) {
10017 $expressionname = 'expression'.$i;
10018 $valuename = 'value'.$i;
10020 $form[$expressionname] = $regex;
10021 $form[$valuename] = $value;
10022 $i++;
10025 return $form;
10029 * Converts the data from admin settings form into a string of regexes
10031 * @see self::prepare_form_data()
10032 * @param array $data array of admin form fields and values
10033 * @return false|string of regexes
10035 protected function process_form_data(array $form) {
10037 $count = count($form); // number of form field values
10039 if ($count % 2) {
10040 // we must get five fields per expression
10041 return false;
10044 $regexes = array();
10045 for ($i = 0; $i < $count / 2; $i++) {
10046 $expressionname = "expression".$i;
10047 $valuename = "value".$i;
10049 $expression = trim($form['expression'.$i]);
10050 $value = trim($form['value'.$i]);
10052 if (empty($expression)){
10053 continue;
10056 $regexes[$value] = $expression;
10059 $regexes = json_encode($regexes);
10061 return $regexes;
10067 * Multiselect for current modules
10069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10071 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10072 private $excludesystem;
10075 * Calls parent::__construct - note array $choices is not required
10077 * @param string $name setting name
10078 * @param string $visiblename localised setting name
10079 * @param string $description setting description
10080 * @param array $defaultsetting a plain array of default module ids
10081 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10083 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10084 $excludesystem = true) {
10085 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10086 $this->excludesystem = $excludesystem;
10090 * Loads an array of current module choices
10092 * @return bool always return true
10094 public function load_choices() {
10095 if (is_array($this->choices)) {
10096 return true;
10098 $this->choices = array();
10100 global $CFG, $DB;
10101 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10102 foreach ($records as $record) {
10103 // Exclude modules if the code doesn't exist
10104 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10105 // Also exclude system modules (if specified)
10106 if (!($this->excludesystem &&
10107 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10108 MOD_ARCHETYPE_SYSTEM)) {
10109 $this->choices[$record->id] = $record->name;
10113 return true;
10118 * Admin setting to show if a php extension is enabled or not.
10120 * @copyright 2013 Damyon Wiese
10121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10123 class admin_setting_php_extension_enabled extends admin_setting {
10125 /** @var string The name of the extension to check for */
10126 private $extension;
10129 * Calls parent::__construct with specific arguments
10131 public function __construct($name, $visiblename, $description, $extension) {
10132 $this->extension = $extension;
10133 $this->nosave = true;
10134 parent::__construct($name, $visiblename, $description, '');
10138 * Always returns true, does nothing
10140 * @return true
10142 public function get_setting() {
10143 return true;
10147 * Always returns true, does nothing
10149 * @return true
10151 public function get_defaultsetting() {
10152 return true;
10156 * Always returns '', does not write anything
10158 * @return string Always returns ''
10160 public function write_setting($data) {
10161 // Do not write any setting.
10162 return '';
10166 * Outputs the html for this setting.
10167 * @return string Returns an XHTML string
10169 public function output_html($data, $query='') {
10170 global $OUTPUT;
10172 $o = '';
10173 if (!extension_loaded($this->extension)) {
10174 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10176 $o .= format_admin_setting($this, $this->visiblename, $warning);
10178 return $o;
10183 * Server timezone setting.
10185 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10187 * @author Petr Skoda <petr.skoda@totaralms.com>
10189 class admin_setting_servertimezone extends admin_setting_configselect {
10191 * Constructor.
10193 public function __construct() {
10194 $default = core_date::get_default_php_timezone();
10195 if ($default === 'UTC') {
10196 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10197 $default = 'Europe/London';
10200 parent::__construct('timezone',
10201 new lang_string('timezone', 'core_admin'),
10202 new lang_string('configtimezone', 'core_admin'), $default, null);
10206 * Lazy load timezone options.
10207 * @return bool true if loaded, false if error
10209 public function load_choices() {
10210 global $CFG;
10211 if (is_array($this->choices)) {
10212 return true;
10215 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10216 $this->choices = core_date::get_list_of_timezones($current, false);
10217 if ($current == 99) {
10218 // Do not show 99 unless it is current value, we want to get rid of it over time.
10219 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10220 core_date::get_default_php_timezone());
10223 return true;
10228 * Forced user timezone setting.
10230 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10231 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10232 * @author Petr Skoda <petr.skoda@totaralms.com>
10234 class admin_setting_forcetimezone extends admin_setting_configselect {
10236 * Constructor.
10238 public function __construct() {
10239 parent::__construct('forcetimezone',
10240 new lang_string('forcetimezone', 'core_admin'),
10241 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10245 * Lazy load timezone options.
10246 * @return bool true if loaded, false if error
10248 public function load_choices() {
10249 global $CFG;
10250 if (is_array($this->choices)) {
10251 return true;
10254 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10255 $this->choices = core_date::get_list_of_timezones($current, true);
10256 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10258 return true;
10264 * Search setup steps info.
10266 * @package core
10267 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10270 class admin_setting_searchsetupinfo extends admin_setting {
10273 * Calls parent::__construct with specific arguments
10275 public function __construct() {
10276 $this->nosave = true;
10277 parent::__construct('searchsetupinfo', '', '', '');
10281 * Always returns true, does nothing
10283 * @return true
10285 public function get_setting() {
10286 return true;
10290 * Always returns true, does nothing
10292 * @return true
10294 public function get_defaultsetting() {
10295 return true;
10299 * Always returns '', does not write anything
10301 * @param array $data
10302 * @return string Always returns ''
10304 public function write_setting($data) {
10305 // Do not write any setting.
10306 return '';
10310 * Builds the HTML to display the control
10312 * @param string $data Unused
10313 * @param string $query
10314 * @return string
10316 public function output_html($data, $query='') {
10317 global $CFG, $OUTPUT;
10319 $return = '';
10320 $brtag = html_writer::empty_tag('br');
10322 $searchareas = \core_search\manager::get_search_areas_list();
10323 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10324 $anyindexed = false;
10325 foreach ($searchareas as $areaid => $searcharea) {
10326 list($componentname, $varname) = $searcharea->get_config_var_name();
10327 if (get_config($componentname, $varname . '_indexingstart')) {
10328 $anyindexed = true;
10329 break;
10333 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10335 $table = new html_table();
10336 $table->head = array(get_string('step', 'search'), get_string('status'));
10337 $table->colclasses = array('leftalign step', 'leftalign status');
10338 $table->id = 'searchsetup';
10339 $table->attributes['class'] = 'admintable generaltable';
10340 $table->data = array();
10342 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10344 // Select a search engine.
10345 $row = array();
10346 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10347 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10348 array('href' => $url));
10350 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10351 if (!empty($CFG->searchengine)) {
10352 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
10353 array('class' => 'statusok'));
10356 $row[1] = $status;
10357 $table->data[] = $row;
10359 // Available areas.
10360 $row = array();
10361 $url = new moodle_url('/admin/searchareas.php');
10362 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
10363 array('href' => $url));
10365 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10366 if ($anyenabled) {
10367 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10370 $row[1] = $status;
10371 $table->data[] = $row;
10373 // Setup search engine.
10374 $row = array();
10375 if (empty($CFG->searchengine)) {
10376 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
10377 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10378 } else {
10379 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
10380 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
10381 array('href' => $url));
10382 // Check the engine status.
10383 $searchengine = \core_search\manager::search_engine_instance();
10384 try {
10385 $serverstatus = $searchengine->is_server_ready();
10386 } catch (\moodle_exception $e) {
10387 $serverstatus = $e->getMessage();
10389 if ($serverstatus === true) {
10390 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10391 } else {
10392 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
10394 $row[1] = $status;
10396 $table->data[] = $row;
10398 // Indexed data.
10399 $row = array();
10400 $url = new moodle_url('/admin/searchareas.php');
10401 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
10402 if ($anyindexed) {
10403 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10404 } else {
10405 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10407 $row[1] = $status;
10408 $table->data[] = $row;
10410 // Enable global search.
10411 $row = array();
10412 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
10413 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
10414 array('href' => $url));
10415 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10416 if (\core_search\manager::is_global_search_enabled()) {
10417 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10419 $row[1] = $status;
10420 $table->data[] = $row;
10422 $return .= html_writer::table($table);
10424 return highlight($query, $return);
10430 * Used to validate the contents of SCSS code and ensuring they are parsable.
10432 * It does not attempt to detect undefined SCSS variables because it is designed
10433 * to be used without knowledge of other config/scss included.
10435 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10436 * @copyright 2016 Dan Poltawski <dan@moodle.com>
10438 class admin_setting_scsscode extends admin_setting_configtextarea {
10441 * Validate the contents of the SCSS to ensure its parsable. Does not
10442 * attempt to detect undefined scss variables.
10444 * @param string $data The scss code from text field.
10445 * @return mixed bool true for success or string:error on failure.
10447 public function validate($data) {
10448 if (empty($data)) {
10449 return true;
10452 $scss = new core_scss();
10453 try {
10454 $scss->compile($data);
10455 } catch (Leafo\ScssPhp\Exception\ParserException $e) {
10456 return get_string('scssinvalid', 'admin', $e->getMessage());
10457 } catch (Leafo\ScssPhp\Exception\CompilerException $e) {
10458 // Silently ignore this - it could be a scss variable defined from somewhere
10459 // else which we are not examining here.
10460 return true;
10463 return true;
10469 * Administration setting to define a list of file types.
10471 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
10472 * @copyright 2017 David Mudrák <david@moodle.com>
10473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10475 class admin_setting_filetypes extends admin_setting_configtext {
10477 /** @var array Allow selection from these file types only. */
10478 protected $onlytypes = [];
10480 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
10481 protected $allowall = true;
10483 /** @var core_form\filetypes_util instance to use as a helper. */
10484 protected $util = null;
10487 * Constructor.
10489 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
10490 * @param string $visiblename Localised label of the setting
10491 * @param string $description Localised description of the setting
10492 * @param string $defaultsetting Default setting value.
10493 * @param array $options Setting widget options, an array with optional keys:
10494 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
10495 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
10497 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
10499 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
10501 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
10502 $this->onlytypes = $options['onlytypes'];
10505 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
10506 $this->allowall = (bool)$options['allowall'];
10509 $this->util = new \core_form\filetypes_util();
10513 * Normalize the user's input and write it to the database as comma separated list.
10515 * Comma separated list as a text representation of the array was chosen to
10516 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
10518 * @param string $data Value submitted by the admin.
10519 * @return string Epty string if all good, error message otherwise.
10521 public function write_setting($data) {
10522 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
10526 * Validate data before storage
10528 * @param string $data The setting values provided by the admin
10529 * @return bool|string True if ok, the string if error found
10531 public function validate($data) {
10533 // No need to call parent's validation here as we are PARAM_RAW.
10535 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
10536 return true;
10538 } else {
10539 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
10540 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
10545 * Return an HTML string for the setting element.
10547 * @param string $data The current setting value
10548 * @param string $query Admin search query to be highlighted
10549 * @return string HTML to be displayed
10551 public function output_html($data, $query='') {
10552 global $OUTPUT, $PAGE;
10554 $default = $this->get_defaultsetting();
10555 $context = (object) [
10556 'id' => $this->get_id(),
10557 'name' => $this->get_full_name(),
10558 'value' => $data,
10559 'descriptions' => $this->util->describe_file_types($data),
10561 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
10563 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
10564 $this->get_id(),
10565 $this->visiblename->out(),
10566 $this->onlytypes,
10567 $this->allowall,
10570 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
10574 * Should the values be always displayed in LTR mode?
10576 * We always return true here because these values are not RTL compatible.
10578 * @return bool True because these values are not RTL compatible.
10580 public function get_force_ltr() {
10581 return true;
10586 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
10588 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10589 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
10591 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
10594 * Constructor.
10596 * @param string $name
10597 * @param string $visiblename
10598 * @param string $description
10599 * @param mixed $defaultsetting string or array
10600 * @param mixed $paramtype
10601 * @param string $cols
10602 * @param string $rows
10604 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
10605 $cols = '60', $rows = '8') {
10606 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
10607 // Pre-set force LTR to false.
10608 $this->set_force_ltr(false);
10612 * Validate the content and format of the age of digital consent map to ensure it is parsable.
10614 * @param string $data The age of digital consent map from text field.
10615 * @return mixed bool true for success or string:error on failure.
10617 public function validate($data) {
10618 if (empty($data)) {
10619 return true;
10622 try {
10623 \core_auth\digital_consent::parse_age_digital_consent_map($data);
10624 } catch (\moodle_exception $e) {
10625 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
10628 return true;
10633 * Selection of plugins that can work as site policy handlers
10635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10636 * @copyright 2018 Marina Glancy
10638 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
10641 * Constructor
10642 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
10643 * for ones in config_plugins.
10644 * @param string $visiblename localised
10645 * @param string $description long localised info
10646 * @param string $defaultsetting
10648 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10649 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10653 * Lazy-load the available choices for the select box
10655 public function load_choices() {
10656 if (during_initial_install()) {
10657 return false;
10659 if (is_array($this->choices)) {
10660 return true;
10663 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
10664 $manager = new \core_privacy\local\sitepolicy\manager();
10665 $plugins = $manager->get_all_handlers();
10666 foreach ($plugins as $pname => $unused) {
10667 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
10668 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
10671 return true;