Merge branch 'MDL-61960-master' of git://github.com/farhan6318/moodle
[moodle.git] / lib / adminlib.php
blob0c7b15667da36c35ef45b5fbe0084b4723ed4731
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 // Delete all remaining files in the filepool owned by the component.
238 $fs = get_file_storage();
239 $fs->delete_component_files($component);
241 // Finally purge all caches.
242 purge_all_caches();
244 // Invalidate the hash used for upgrade detections.
245 set_config('allversionshash', '');
247 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
251 * Returns the version of installed component
253 * @param string $component component name
254 * @param string $source either 'disk' or 'installed' - where to get the version information from
255 * @return string|bool version number or false if the component is not found
257 function get_component_version($component, $source='installed') {
258 global $CFG, $DB;
260 list($type, $name) = core_component::normalize_component($component);
262 // moodle core or a core subsystem
263 if ($type === 'core') {
264 if ($source === 'installed') {
265 if (empty($CFG->version)) {
266 return false;
267 } else {
268 return $CFG->version;
270 } else {
271 if (!is_readable($CFG->dirroot.'/version.php')) {
272 return false;
273 } else {
274 $version = null; //initialize variable for IDEs
275 include($CFG->dirroot.'/version.php');
276 return $version;
281 // activity module
282 if ($type === 'mod') {
283 if ($source === 'installed') {
284 if ($CFG->version < 2013092001.02) {
285 return $DB->get_field('modules', 'version', array('name'=>$name));
286 } else {
287 return get_config('mod_'.$name, 'version');
290 } else {
291 $mods = core_component::get_plugin_list('mod');
292 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
293 return false;
294 } else {
295 $plugin = new stdClass();
296 $plugin->version = null;
297 $module = $plugin;
298 include($mods[$name].'/version.php');
299 return $plugin->version;
304 // block
305 if ($type === 'block') {
306 if ($source === 'installed') {
307 if ($CFG->version < 2013092001.02) {
308 return $DB->get_field('block', 'version', array('name'=>$name));
309 } else {
310 return get_config('block_'.$name, 'version');
312 } else {
313 $blocks = core_component::get_plugin_list('block');
314 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
315 return false;
316 } else {
317 $plugin = new stdclass();
318 include($blocks[$name].'/version.php');
319 return $plugin->version;
324 // all other plugin types
325 if ($source === 'installed') {
326 return get_config($type.'_'.$name, 'version');
327 } else {
328 $plugins = core_component::get_plugin_list($type);
329 if (empty($plugins[$name])) {
330 return false;
331 } else {
332 $plugin = new stdclass();
333 include($plugins[$name].'/version.php');
334 return $plugin->version;
340 * Delete all plugin tables
342 * @param string $name Name of plugin, used as table prefix
343 * @param string $file Path to install.xml file
344 * @param bool $feedback defaults to true
345 * @return bool Always returns true
347 function drop_plugin_tables($name, $file, $feedback=true) {
348 global $CFG, $DB;
350 // first try normal delete
351 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
352 return true;
355 // then try to find all tables that start with name and are not in any xml file
356 $used_tables = get_used_table_names();
358 $tables = $DB->get_tables();
360 /// Iterate over, fixing id fields as necessary
361 foreach ($tables as $table) {
362 if (in_array($table, $used_tables)) {
363 continue;
366 if (strpos($table, $name) !== 0) {
367 continue;
370 // found orphan table --> delete it
371 if ($DB->get_manager()->table_exists($table)) {
372 $xmldb_table = new xmldb_table($table);
373 $DB->get_manager()->drop_table($xmldb_table);
377 return true;
381 * Returns names of all known tables == tables that moodle knows about.
383 * @return array Array of lowercase table names
385 function get_used_table_names() {
386 $table_names = array();
387 $dbdirs = get_db_directories();
389 foreach ($dbdirs as $dbdir) {
390 $file = $dbdir.'/install.xml';
392 $xmldb_file = new xmldb_file($file);
394 if (!$xmldb_file->fileExists()) {
395 continue;
398 $loaded = $xmldb_file->loadXMLStructure();
399 $structure = $xmldb_file->getStructure();
401 if ($loaded and $tables = $structure->getTables()) {
402 foreach($tables as $table) {
403 $table_names[] = strtolower($table->getName());
408 return $table_names;
412 * Returns list of all directories where we expect install.xml files
413 * @return array Array of paths
415 function get_db_directories() {
416 global $CFG;
418 $dbdirs = array();
420 /// First, the main one (lib/db)
421 $dbdirs[] = $CFG->libdir.'/db';
423 /// Then, all the ones defined by core_component::get_plugin_types()
424 $plugintypes = core_component::get_plugin_types();
425 foreach ($plugintypes as $plugintype => $pluginbasedir) {
426 if ($plugins = core_component::get_plugin_list($plugintype)) {
427 foreach ($plugins as $plugin => $plugindir) {
428 $dbdirs[] = $plugindir.'/db';
433 return $dbdirs;
437 * Try to obtain or release the cron lock.
438 * @param string $name name of lock
439 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
440 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
441 * @return bool true if lock obtained
443 function set_cron_lock($name, $until, $ignorecurrent=false) {
444 global $DB;
445 if (empty($name)) {
446 debugging("Tried to get a cron lock for a null fieldname");
447 return false;
450 // remove lock by force == remove from config table
451 if (is_null($until)) {
452 set_config($name, null);
453 return true;
456 if (!$ignorecurrent) {
457 // read value from db - other processes might have changed it
458 $value = $DB->get_field('config', 'value', array('name'=>$name));
460 if ($value and $value > time()) {
461 //lock active
462 return false;
466 set_config($name, $until);
467 return true;
471 * Test if and critical warnings are present
472 * @return bool
474 function admin_critical_warnings_present() {
475 global $SESSION;
477 if (!has_capability('moodle/site:config', context_system::instance())) {
478 return 0;
481 if (!isset($SESSION->admin_critical_warning)) {
482 $SESSION->admin_critical_warning = 0;
483 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
484 $SESSION->admin_critical_warning = 1;
488 return $SESSION->admin_critical_warning;
492 * Detects if float supports at least 10 decimal digits
494 * Detects if float supports at least 10 decimal digits
495 * and also if float-->string conversion works as expected.
497 * @return bool true if problem found
499 function is_float_problem() {
500 $num1 = 2009010200.01;
501 $num2 = 2009010200.02;
503 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
507 * Try to verify that dataroot is not accessible from web.
509 * Try to verify that dataroot is not accessible from web.
510 * It is not 100% correct but might help to reduce number of vulnerable sites.
511 * Protection from httpd.conf and .htaccess is not detected properly.
513 * @uses INSECURE_DATAROOT_WARNING
514 * @uses INSECURE_DATAROOT_ERROR
515 * @param bool $fetchtest try to test public access by fetching file, default false
516 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
518 function is_dataroot_insecure($fetchtest=false) {
519 global $CFG;
521 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
523 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
524 $rp = strrev(trim($rp, '/'));
525 $rp = explode('/', $rp);
526 foreach($rp as $r) {
527 if (strpos($siteroot, '/'.$r.'/') === 0) {
528 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
529 } else {
530 break; // probably alias root
534 $siteroot = strrev($siteroot);
535 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
537 if (strpos($dataroot, $siteroot) !== 0) {
538 return false;
541 if (!$fetchtest) {
542 return INSECURE_DATAROOT_WARNING;
545 // now try all methods to fetch a test file using http protocol
547 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
548 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
549 $httpdocroot = $matches[1];
550 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
551 make_upload_directory('diag');
552 $testfile = $CFG->dataroot.'/diag/public.txt';
553 if (!file_exists($testfile)) {
554 file_put_contents($testfile, 'test file, do not delete');
555 @chmod($testfile, $CFG->filepermissions);
557 $teststr = trim(file_get_contents($testfile));
558 if (empty($teststr)) {
559 // hmm, strange
560 return INSECURE_DATAROOT_WARNING;
563 $testurl = $datarooturl.'/diag/public.txt';
564 if (extension_loaded('curl') and
565 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
566 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
567 ($ch = @curl_init($testurl)) !== false) {
568 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
569 curl_setopt($ch, CURLOPT_HEADER, false);
570 $data = curl_exec($ch);
571 if (!curl_errno($ch)) {
572 $data = trim($data);
573 if ($data === $teststr) {
574 curl_close($ch);
575 return INSECURE_DATAROOT_ERROR;
578 curl_close($ch);
581 if ($data = @file_get_contents($testurl)) {
582 $data = trim($data);
583 if ($data === $teststr) {
584 return INSECURE_DATAROOT_ERROR;
588 preg_match('|https?://([^/]+)|i', $testurl, $matches);
589 $sitename = $matches[1];
590 $error = 0;
591 if ($fp = @fsockopen($sitename, 80, $error)) {
592 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
593 $localurl = $matches[1];
594 $out = "GET $localurl HTTP/1.1\r\n";
595 $out .= "Host: $sitename\r\n";
596 $out .= "Connection: Close\r\n\r\n";
597 fwrite($fp, $out);
598 $data = '';
599 $incoming = false;
600 while (!feof($fp)) {
601 if ($incoming) {
602 $data .= fgets($fp, 1024);
603 } else if (@fgets($fp, 1024) === "\r\n") {
604 $incoming = true;
607 fclose($fp);
608 $data = trim($data);
609 if ($data === $teststr) {
610 return INSECURE_DATAROOT_ERROR;
614 return INSECURE_DATAROOT_WARNING;
618 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
620 function enable_cli_maintenance_mode() {
621 global $CFG;
623 if (file_exists("$CFG->dataroot/climaintenance.html")) {
624 unlink("$CFG->dataroot/climaintenance.html");
627 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
628 $data = $CFG->maintenance_message;
629 $data = bootstrap_renderer::early_error_content($data, null, null, null);
630 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
632 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
633 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
635 } else {
636 $data = get_string('sitemaintenance', 'admin');
637 $data = bootstrap_renderer::early_error_content($data, null, null, null);
638 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
641 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
642 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
645 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
649 * Interface for anything appearing in the admin tree
651 * The interface that is implemented by anything that appears in the admin tree
652 * block. It forces inheriting classes to define a method for checking user permissions
653 * and methods for finding something in the admin tree.
655 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
657 interface part_of_admin_tree {
660 * Finds a named part_of_admin_tree.
662 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
663 * and not parentable_part_of_admin_tree, then this function should only check if
664 * $this->name matches $name. If it does, it should return a reference to $this,
665 * otherwise, it should return a reference to NULL.
667 * If a class inherits parentable_part_of_admin_tree, this method should be called
668 * recursively on all child objects (assuming, of course, the parent object's name
669 * doesn't match the search criterion).
671 * @param string $name The internal name of the part_of_admin_tree we're searching for.
672 * @return mixed An object reference or a NULL reference.
674 public function locate($name);
677 * Removes named part_of_admin_tree.
679 * @param string $name The internal name of the part_of_admin_tree we want to remove.
680 * @return bool success.
682 public function prune($name);
685 * Search using query
686 * @param string $query
687 * @return mixed array-object structure of found settings and pages
689 public function search($query);
692 * Verifies current user's access to this part_of_admin_tree.
694 * Used to check if the current user has access to this part of the admin tree or
695 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
696 * then this method is usually just a call to has_capability() in the site context.
698 * If a class inherits parentable_part_of_admin_tree, this method should return the
699 * logical OR of the return of check_access() on all child objects.
701 * @return bool True if the user has access, false if she doesn't.
703 public function check_access();
706 * Mostly useful for removing of some parts of the tree in admin tree block.
708 * @return True is hidden from normal list view
710 public function is_hidden();
713 * Show we display Save button at the page bottom?
714 * @return bool
716 public function show_save();
721 * Interface implemented by any part_of_admin_tree that has children.
723 * The interface implemented by any part_of_admin_tree that can be a parent
724 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
725 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
726 * include an add method for adding other part_of_admin_tree objects as children.
728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
730 interface parentable_part_of_admin_tree extends part_of_admin_tree {
733 * Adds a part_of_admin_tree object to the admin tree.
735 * Used to add a part_of_admin_tree object to this object or a child of this
736 * object. $something should only be added if $destinationname matches
737 * $this->name. If it doesn't, add should be called on child objects that are
738 * also parentable_part_of_admin_tree's.
740 * $something should be appended as the last child in the $destinationname. If the
741 * $beforesibling is specified, $something should be prepended to it. If the given
742 * sibling is not found, $something should be appended to the end of $destinationname
743 * and a developer debugging message should be displayed.
745 * @param string $destinationname The internal name of the new parent for $something.
746 * @param part_of_admin_tree $something The object to be added.
747 * @return bool True on success, false on failure.
749 public function add($destinationname, $something, $beforesibling = null);
755 * The object used to represent folders (a.k.a. categories) in the admin tree block.
757 * Each admin_category object contains a number of part_of_admin_tree objects.
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
761 class admin_category implements parentable_part_of_admin_tree {
763 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
764 protected $children;
765 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
766 public $name;
767 /** @var string The displayed name for this category. Usually obtained through get_string() */
768 public $visiblename;
769 /** @var bool Should this category be hidden in admin tree block? */
770 public $hidden;
771 /** @var mixed Either a string or an array or strings */
772 public $path;
773 /** @var mixed Either a string or an array or strings */
774 public $visiblepath;
776 /** @var array fast lookup category cache, all categories of one tree point to one cache */
777 protected $category_cache;
779 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
780 protected $sort = false;
781 /** @var bool If set to true children will be sorted in ascending order. */
782 protected $sortasc = true;
783 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
784 protected $sortsplit = true;
785 /** @var bool $sorted True if the children have been sorted and don't need resorting */
786 protected $sorted = false;
789 * Constructor for an empty admin category
791 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
792 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
793 * @param bool $hidden hide category in admin tree block, defaults to false
795 public function __construct($name, $visiblename, $hidden=false) {
796 $this->children = array();
797 $this->name = $name;
798 $this->visiblename = $visiblename;
799 $this->hidden = $hidden;
803 * Returns a reference to the part_of_admin_tree object with internal name $name.
805 * @param string $name The internal name of the object we want.
806 * @param bool $findpath initialize path and visiblepath arrays
807 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
808 * defaults to false
810 public function locate($name, $findpath=false) {
811 if (!isset($this->category_cache[$this->name])) {
812 // somebody much have purged the cache
813 $this->category_cache[$this->name] = $this;
816 if ($this->name == $name) {
817 if ($findpath) {
818 $this->visiblepath[] = $this->visiblename;
819 $this->path[] = $this->name;
821 return $this;
824 // quick category lookup
825 if (!$findpath and isset($this->category_cache[$name])) {
826 return $this->category_cache[$name];
829 $return = NULL;
830 foreach($this->children as $childid=>$unused) {
831 if ($return = $this->children[$childid]->locate($name, $findpath)) {
832 break;
836 if (!is_null($return) and $findpath) {
837 $return->visiblepath[] = $this->visiblename;
838 $return->path[] = $this->name;
841 return $return;
845 * Search using query
847 * @param string query
848 * @return mixed array-object structure of found settings and pages
850 public function search($query) {
851 $result = array();
852 foreach ($this->get_children() as $child) {
853 $subsearch = $child->search($query);
854 if (!is_array($subsearch)) {
855 debugging('Incorrect search result from '.$child->name);
856 continue;
858 $result = array_merge($result, $subsearch);
860 return $result;
864 * Removes part_of_admin_tree object with internal name $name.
866 * @param string $name The internal name of the object we want to remove.
867 * @return bool success
869 public function prune($name) {
871 if ($this->name == $name) {
872 return false; //can not remove itself
875 foreach($this->children as $precedence => $child) {
876 if ($child->name == $name) {
877 // clear cache and delete self
878 while($this->category_cache) {
879 // delete the cache, but keep the original array address
880 array_pop($this->category_cache);
882 unset($this->children[$precedence]);
883 return true;
884 } else if ($this->children[$precedence]->prune($name)) {
885 return true;
888 return false;
892 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
894 * By default the new part of the tree is appended as the last child of the parent. You
895 * can specify a sibling node that the new part should be prepended to. If the given
896 * sibling is not found, the part is appended to the end (as it would be by default) and
897 * a developer debugging message is displayed.
899 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
900 * @param string $destinationame The internal name of the immediate parent that we want for $something.
901 * @param mixed $something A part_of_admin_tree or setting instance to be added.
902 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
903 * @return bool True if successfully added, false if $something can not be added.
905 public function add($parentname, $something, $beforesibling = null) {
906 global $CFG;
908 $parent = $this->locate($parentname);
909 if (is_null($parent)) {
910 debugging('parent does not exist!');
911 return false;
914 if ($something instanceof part_of_admin_tree) {
915 if (!($parent instanceof parentable_part_of_admin_tree)) {
916 debugging('error - parts of tree can be inserted only into parentable parts');
917 return false;
919 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
920 // The name of the node is already used, simply warn the developer that this should not happen.
921 // It is intentional to check for the debug level before performing the check.
922 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
924 if (is_null($beforesibling)) {
925 // Append $something as the parent's last child.
926 $parent->children[] = $something;
927 } else {
928 if (!is_string($beforesibling) or trim($beforesibling) === '') {
929 throw new coding_exception('Unexpected value of the beforesibling parameter');
931 // Try to find the position of the sibling.
932 $siblingposition = null;
933 foreach ($parent->children as $childposition => $child) {
934 if ($child->name === $beforesibling) {
935 $siblingposition = $childposition;
936 break;
939 if (is_null($siblingposition)) {
940 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
941 $parent->children[] = $something;
942 } else {
943 $parent->children = array_merge(
944 array_slice($parent->children, 0, $siblingposition),
945 array($something),
946 array_slice($parent->children, $siblingposition)
950 if ($something instanceof admin_category) {
951 if (isset($this->category_cache[$something->name])) {
952 debugging('Duplicate admin category name: '.$something->name);
953 } else {
954 $this->category_cache[$something->name] = $something;
955 $something->category_cache =& $this->category_cache;
956 foreach ($something->children as $child) {
957 // just in case somebody already added subcategories
958 if ($child instanceof admin_category) {
959 if (isset($this->category_cache[$child->name])) {
960 debugging('Duplicate admin category name: '.$child->name);
961 } else {
962 $this->category_cache[$child->name] = $child;
963 $child->category_cache =& $this->category_cache;
969 return true;
971 } else {
972 debugging('error - can not add this element');
973 return false;
979 * Checks if the user has access to anything in this category.
981 * @return bool True if the user has access to at least one child in this category, false otherwise.
983 public function check_access() {
984 foreach ($this->children as $child) {
985 if ($child->check_access()) {
986 return true;
989 return false;
993 * Is this category hidden in admin tree block?
995 * @return bool True if hidden
997 public function is_hidden() {
998 return $this->hidden;
1002 * Show we display Save button at the page bottom?
1003 * @return bool
1005 public function show_save() {
1006 foreach ($this->children as $child) {
1007 if ($child->show_save()) {
1008 return true;
1011 return false;
1015 * Sets sorting on this category.
1017 * Please note this function doesn't actually do the sorting.
1018 * It can be called anytime.
1019 * Sorting occurs when the user calls get_children.
1020 * Code using the children array directly won't see the sorted results.
1022 * @param bool $sort If set to true children will be sorted, if false they won't be.
1023 * @param bool $asc If true sorting will be ascending, otherwise descending.
1024 * @param bool $split If true we sort pages and sub categories separately.
1026 public function set_sorting($sort, $asc = true, $split = true) {
1027 $this->sort = (bool)$sort;
1028 $this->sortasc = (bool)$asc;
1029 $this->sortsplit = (bool)$split;
1033 * Returns the children associated with this category.
1035 * @return part_of_admin_tree[]
1037 public function get_children() {
1038 // If we should sort and it hasn't already been sorted.
1039 if ($this->sort && !$this->sorted) {
1040 if ($this->sortsplit) {
1041 $categories = array();
1042 $pages = array();
1043 foreach ($this->children as $child) {
1044 if ($child instanceof admin_category) {
1045 $categories[] = $child;
1046 } else {
1047 $pages[] = $child;
1050 core_collator::asort_objects_by_property($categories, 'visiblename');
1051 core_collator::asort_objects_by_property($pages, 'visiblename');
1052 if (!$this->sortasc) {
1053 $categories = array_reverse($categories);
1054 $pages = array_reverse($pages);
1056 $this->children = array_merge($pages, $categories);
1057 } else {
1058 core_collator::asort_objects_by_property($this->children, 'visiblename');
1059 if (!$this->sortasc) {
1060 $this->children = array_reverse($this->children);
1063 $this->sorted = true;
1065 return $this->children;
1069 * Magically gets a property from this object.
1071 * @param $property
1072 * @return part_of_admin_tree[]
1073 * @throws coding_exception
1075 public function __get($property) {
1076 if ($property === 'children') {
1077 return $this->get_children();
1079 throw new coding_exception('Invalid property requested.');
1083 * Magically sets a property against this object.
1085 * @param string $property
1086 * @param mixed $value
1087 * @throws coding_exception
1089 public function __set($property, $value) {
1090 if ($property === 'children') {
1091 $this->sorted = false;
1092 $this->children = $value;
1093 } else {
1094 throw new coding_exception('Invalid property requested.');
1099 * Checks if an inaccessible property is set.
1101 * @param string $property
1102 * @return bool
1103 * @throws coding_exception
1105 public function __isset($property) {
1106 if ($property === 'children') {
1107 return isset($this->children);
1109 throw new coding_exception('Invalid property requested.');
1115 * Root of admin settings tree, does not have any parent.
1117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1119 class admin_root extends admin_category {
1120 /** @var array List of errors */
1121 public $errors;
1122 /** @var string search query */
1123 public $search;
1124 /** @var bool full tree flag - true means all settings required, false only pages required */
1125 public $fulltree;
1126 /** @var bool flag indicating loaded tree */
1127 public $loaded;
1128 /** @var mixed site custom defaults overriding defaults in settings files*/
1129 public $custom_defaults;
1132 * @param bool $fulltree true means all settings required,
1133 * false only pages required
1135 public function __construct($fulltree) {
1136 global $CFG;
1138 parent::__construct('root', get_string('administration'), false);
1139 $this->errors = array();
1140 $this->search = '';
1141 $this->fulltree = $fulltree;
1142 $this->loaded = false;
1144 $this->category_cache = array();
1146 // load custom defaults if found
1147 $this->custom_defaults = null;
1148 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1149 if (is_readable($defaultsfile)) {
1150 $defaults = array();
1151 include($defaultsfile);
1152 if (is_array($defaults) and count($defaults)) {
1153 $this->custom_defaults = $defaults;
1159 * Empties children array, and sets loaded to false
1161 * @param bool $requirefulltree
1163 public function purge_children($requirefulltree) {
1164 $this->children = array();
1165 $this->fulltree = ($requirefulltree || $this->fulltree);
1166 $this->loaded = false;
1167 //break circular dependencies - this helps PHP 5.2
1168 while($this->category_cache) {
1169 array_pop($this->category_cache);
1171 $this->category_cache = array();
1177 * Links external PHP pages into the admin tree.
1179 * See detailed usage example at the top of this document (adminlib.php)
1181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1183 class admin_externalpage implements part_of_admin_tree {
1185 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1186 public $name;
1188 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1189 public $visiblename;
1191 /** @var string The external URL that we should link to when someone requests this external page. */
1192 public $url;
1194 /** @var string The role capability/permission a user must have to access this external page. */
1195 public $req_capability;
1197 /** @var object The context in which capability/permission should be checked, default is site context. */
1198 public $context;
1200 /** @var bool hidden in admin tree block. */
1201 public $hidden;
1203 /** @var mixed either string or array of string */
1204 public $path;
1206 /** @var array list of visible names of page parents */
1207 public $visiblepath;
1210 * Constructor for adding an external page into the admin tree.
1212 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1213 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1214 * @param string $url The external URL that we should link to when someone requests this external page.
1215 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1216 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1217 * @param stdClass $context The context the page relates to. Not sure what happens
1218 * if you specify something other than system or front page. Defaults to system.
1220 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1221 $this->name = $name;
1222 $this->visiblename = $visiblename;
1223 $this->url = $url;
1224 if (is_array($req_capability)) {
1225 $this->req_capability = $req_capability;
1226 } else {
1227 $this->req_capability = array($req_capability);
1229 $this->hidden = $hidden;
1230 $this->context = $context;
1234 * Returns a reference to the part_of_admin_tree object with internal name $name.
1236 * @param string $name The internal name of the object we want.
1237 * @param bool $findpath defaults to false
1238 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1240 public function locate($name, $findpath=false) {
1241 if ($this->name == $name) {
1242 if ($findpath) {
1243 $this->visiblepath = array($this->visiblename);
1244 $this->path = array($this->name);
1246 return $this;
1247 } else {
1248 $return = NULL;
1249 return $return;
1254 * This function always returns false, required function by interface
1256 * @param string $name
1257 * @return false
1259 public function prune($name) {
1260 return false;
1264 * Search using query
1266 * @param string $query
1267 * @return mixed array-object structure of found settings and pages
1269 public function search($query) {
1270 $found = false;
1271 if (strpos(strtolower($this->name), $query) !== false) {
1272 $found = true;
1273 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1274 $found = true;
1276 if ($found) {
1277 $result = new stdClass();
1278 $result->page = $this;
1279 $result->settings = array();
1280 return array($this->name => $result);
1281 } else {
1282 return array();
1287 * Determines if the current user has access to this external page based on $this->req_capability.
1289 * @return bool True if user has access, false otherwise.
1291 public function check_access() {
1292 global $CFG;
1293 $context = empty($this->context) ? context_system::instance() : $this->context;
1294 foreach($this->req_capability as $cap) {
1295 if (has_capability($cap, $context)) {
1296 return true;
1299 return false;
1303 * Is this external page hidden in admin tree block?
1305 * @return bool True if hidden
1307 public function is_hidden() {
1308 return $this->hidden;
1312 * Show we display Save button at the page bottom?
1313 * @return bool
1315 public function show_save() {
1316 return false;
1322 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1324 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1326 class admin_settingpage implements part_of_admin_tree {
1328 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1329 public $name;
1331 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1332 public $visiblename;
1334 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1335 public $settings;
1337 /** @var string The role capability/permission a user must have to access this external page. */
1338 public $req_capability;
1340 /** @var object The context in which capability/permission should be checked, default is site context. */
1341 public $context;
1343 /** @var bool hidden in admin tree block. */
1344 public $hidden;
1346 /** @var mixed string of paths or array of strings of paths */
1347 public $path;
1349 /** @var array list of visible names of page parents */
1350 public $visiblepath;
1353 * see admin_settingpage for details of this function
1355 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1356 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1357 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1358 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1359 * @param stdClass $context The context the page relates to. Not sure what happens
1360 * if you specify something other than system or front page. Defaults to system.
1362 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1363 $this->settings = new stdClass();
1364 $this->name = $name;
1365 $this->visiblename = $visiblename;
1366 if (is_array($req_capability)) {
1367 $this->req_capability = $req_capability;
1368 } else {
1369 $this->req_capability = array($req_capability);
1371 $this->hidden = $hidden;
1372 $this->context = $context;
1376 * see admin_category
1378 * @param string $name
1379 * @param bool $findpath
1380 * @return mixed Object (this) if name == this->name, else returns null
1382 public function locate($name, $findpath=false) {
1383 if ($this->name == $name) {
1384 if ($findpath) {
1385 $this->visiblepath = array($this->visiblename);
1386 $this->path = array($this->name);
1388 return $this;
1389 } else {
1390 $return = NULL;
1391 return $return;
1396 * Search string in settings page.
1398 * @param string $query
1399 * @return array
1401 public function search($query) {
1402 $found = array();
1404 foreach ($this->settings as $setting) {
1405 if ($setting->is_related($query)) {
1406 $found[] = $setting;
1410 if ($found) {
1411 $result = new stdClass();
1412 $result->page = $this;
1413 $result->settings = $found;
1414 return array($this->name => $result);
1417 $found = false;
1418 if (strpos(strtolower($this->name), $query) !== false) {
1419 $found = true;
1420 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1421 $found = true;
1423 if ($found) {
1424 $result = new stdClass();
1425 $result->page = $this;
1426 $result->settings = array();
1427 return array($this->name => $result);
1428 } else {
1429 return array();
1434 * This function always returns false, required by interface
1436 * @param string $name
1437 * @return bool Always false
1439 public function prune($name) {
1440 return false;
1444 * adds an admin_setting to this admin_settingpage
1446 * 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
1447 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1449 * @param object $setting is the admin_setting object you want to add
1450 * @return bool true if successful, false if not
1452 public function add($setting) {
1453 if (!($setting instanceof admin_setting)) {
1454 debugging('error - not a setting instance');
1455 return false;
1458 $name = $setting->name;
1459 if ($setting->plugin) {
1460 $name = $setting->plugin . $name;
1462 $this->settings->{$name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1552 /** @var bool Whether this field must be forced LTR. */
1553 private $forceltr = null;
1556 * Constructor
1557 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1558 * or 'myplugin/mysetting' for ones in config_plugins.
1559 * @param string $visiblename localised name
1560 * @param string $description localised long description
1561 * @param mixed $defaultsetting string or array depending on implementation
1563 public function __construct($name, $visiblename, $description, $defaultsetting) {
1564 $this->parse_setting_name($name);
1565 $this->visiblename = $visiblename;
1566 $this->description = $description;
1567 $this->defaultsetting = $defaultsetting;
1571 * Generic function to add a flag to this admin setting.
1573 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1574 * @param bool $default - The default for the flag
1575 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1576 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1578 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1579 if (empty($this->flags[$shortname])) {
1580 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1581 } else {
1582 $this->flags[$shortname]->set_options($enabled, $default);
1587 * Set the enabled options flag on this admin setting.
1589 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1590 * @param bool $default - The default for the flag
1592 public function set_enabled_flag_options($enabled, $default) {
1593 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1597 * Set the advanced options flag on this admin setting.
1599 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1600 * @param bool $default - The default for the flag
1602 public function set_advanced_flag_options($enabled, $default) {
1603 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1608 * Set the locked options flag on this admin setting.
1610 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1611 * @param bool $default - The default for the flag
1613 public function set_locked_flag_options($enabled, $default) {
1614 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1618 * Get the currently saved value for a setting flag
1620 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1621 * @return bool
1623 public function get_setting_flag_value(admin_setting_flag $flag) {
1624 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1625 if (!isset($value)) {
1626 $value = $flag->get_default();
1629 return !empty($value);
1633 * Get the list of defaults for the flags on this setting.
1635 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1637 public function get_setting_flag_defaults(& $defaults) {
1638 foreach ($this->flags as $flag) {
1639 if ($flag->is_enabled() && $flag->get_default()) {
1640 $defaults[] = $flag->get_displayname();
1646 * Output the input fields for the advanced and locked flags on this setting.
1648 * @param bool $adv - The current value of the advanced flag.
1649 * @param bool $locked - The current value of the locked flag.
1650 * @return string $output - The html for the flags.
1652 public function output_setting_flags() {
1653 $output = '';
1655 foreach ($this->flags as $flag) {
1656 if ($flag->is_enabled()) {
1657 $output .= $flag->output_setting_flag($this);
1661 if (!empty($output)) {
1662 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1664 return $output;
1668 * Write the values of the flags for this admin setting.
1670 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1671 * @return bool - true if successful.
1673 public function write_setting_flags($data) {
1674 $result = true;
1675 foreach ($this->flags as $flag) {
1676 $result = $result && $flag->write_setting_flag($this, $data);
1678 return $result;
1682 * Set up $this->name and potentially $this->plugin
1684 * Set up $this->name and possibly $this->plugin based on whether $name looks
1685 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1686 * on the names, that is, output a developer debug warning if the name
1687 * contains anything other than [a-zA-Z0-9_]+.
1689 * @param string $name the setting name passed in to the constructor.
1691 private function parse_setting_name($name) {
1692 $bits = explode('/', $name);
1693 if (count($bits) > 2) {
1694 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1696 $this->name = array_pop($bits);
1697 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1698 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1700 if (!empty($bits)) {
1701 $this->plugin = array_pop($bits);
1702 if ($this->plugin === 'moodle') {
1703 $this->plugin = null;
1704 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1705 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1711 * Returns the fullname prefixed by the plugin
1712 * @return string
1714 public function get_full_name() {
1715 return 's_'.$this->plugin.'_'.$this->name;
1719 * Returns the ID string based on plugin and name
1720 * @return string
1722 public function get_id() {
1723 return 'id_s_'.$this->plugin.'_'.$this->name;
1727 * @param bool $affectsmodinfo If true, changes to this setting will
1728 * cause the course cache to be rebuilt
1730 public function set_affects_modinfo($affectsmodinfo) {
1731 $this->affectsmodinfo = $affectsmodinfo;
1735 * Returns the config if possible
1737 * @return mixed returns config if successful else null
1739 public function config_read($name) {
1740 global $CFG;
1741 if (!empty($this->plugin)) {
1742 $value = get_config($this->plugin, $name);
1743 return $value === false ? NULL : $value;
1745 } else {
1746 if (isset($CFG->$name)) {
1747 return $CFG->$name;
1748 } else {
1749 return NULL;
1755 * Used to set a config pair and log change
1757 * @param string $name
1758 * @param mixed $value Gets converted to string if not null
1759 * @return bool Write setting to config table
1761 public function config_write($name, $value) {
1762 global $DB, $USER, $CFG;
1764 if ($this->nosave) {
1765 return true;
1768 // make sure it is a real change
1769 $oldvalue = get_config($this->plugin, $name);
1770 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1771 $value = is_null($value) ? null : (string)$value;
1773 if ($oldvalue === $value) {
1774 return true;
1777 // store change
1778 set_config($name, $value, $this->plugin);
1780 // Some admin settings affect course modinfo
1781 if ($this->affectsmodinfo) {
1782 // Clear course cache for all courses
1783 rebuild_course_cache(0, true);
1786 $this->add_to_config_log($name, $oldvalue, $value);
1788 return true; // BC only
1792 * Log config changes if necessary.
1793 * @param string $name
1794 * @param string $oldvalue
1795 * @param string $value
1797 protected function add_to_config_log($name, $oldvalue, $value) {
1798 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1802 * Returns current value of this setting
1803 * @return mixed array or string depending on instance, NULL means not set yet
1805 public abstract function get_setting();
1808 * Returns default setting if exists
1809 * @return mixed array or string depending on instance; NULL means no default, user must supply
1811 public function get_defaultsetting() {
1812 $adminroot = admin_get_root(false, false);
1813 if (!empty($adminroot->custom_defaults)) {
1814 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1815 if (isset($adminroot->custom_defaults[$plugin])) {
1816 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1817 return $adminroot->custom_defaults[$plugin][$this->name];
1821 return $this->defaultsetting;
1825 * Store new setting
1827 * @param mixed $data string or array, must not be NULL
1828 * @return string empty string if ok, string error message otherwise
1830 public abstract function write_setting($data);
1833 * Return part of form with setting
1834 * This function should always be overwritten
1836 * @param mixed $data array or string depending on setting
1837 * @param string $query
1838 * @return string
1840 public function output_html($data, $query='') {
1841 // should be overridden
1842 return;
1846 * Function called if setting updated - cleanup, cache reset, etc.
1847 * @param string $functionname Sets the function name
1848 * @return void
1850 public function set_updatedcallback($functionname) {
1851 $this->updatedcallback = $functionname;
1855 * Execute postupdatecallback if necessary.
1856 * @param mixed $original original value before write_setting()
1857 * @return bool true if changed, false if not.
1859 public function post_write_settings($original) {
1860 // Comparison must work for arrays too.
1861 if (serialize($original) === serialize($this->get_setting())) {
1862 return false;
1865 $callbackfunction = $this->updatedcallback;
1866 if (!empty($callbackfunction) and is_callable($callbackfunction)) {
1867 $callbackfunction($this->get_full_name());
1869 return true;
1873 * Is setting related to query text - used when searching
1874 * @param string $query
1875 * @return bool
1877 public function is_related($query) {
1878 if (strpos(strtolower($this->name), $query) !== false) {
1879 return true;
1881 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1882 return true;
1884 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1885 return true;
1887 $current = $this->get_setting();
1888 if (!is_null($current)) {
1889 if (is_string($current)) {
1890 if (strpos(core_text::strtolower($current), $query) !== false) {
1891 return true;
1895 $default = $this->get_defaultsetting();
1896 if (!is_null($default)) {
1897 if (is_string($default)) {
1898 if (strpos(core_text::strtolower($default), $query) !== false) {
1899 return true;
1903 return false;
1907 * Get whether this should be displayed in LTR mode.
1909 * @return bool|null
1911 public function get_force_ltr() {
1912 return $this->forceltr;
1916 * Set whether to force LTR or not.
1918 * @param bool $value True when forced, false when not force, null when unknown.
1920 public function set_force_ltr($value) {
1921 $this->forceltr = $value;
1926 * An additional option that can be applied to an admin setting.
1927 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1931 class admin_setting_flag {
1932 /** @var bool Flag to indicate if this option can be toggled for this setting */
1933 private $enabled = false;
1934 /** @var bool Flag to indicate if this option defaults to true or false */
1935 private $default = false;
1936 /** @var string Short string used to create setting name - e.g. 'adv' */
1937 private $shortname = '';
1938 /** @var string String used as the label for this flag */
1939 private $displayname = '';
1940 /** @const Checkbox for this flag is displayed in admin page */
1941 const ENABLED = true;
1942 /** @const Checkbox for this flag is not displayed in admin page */
1943 const DISABLED = false;
1946 * Constructor
1948 * @param bool $enabled Can this option can be toggled.
1949 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1950 * @param bool $default The default checked state for this setting option.
1951 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1952 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1954 public function __construct($enabled, $default, $shortname, $displayname) {
1955 $this->shortname = $shortname;
1956 $this->displayname = $displayname;
1957 $this->set_options($enabled, $default);
1961 * Update the values of this setting options class
1963 * @param bool $enabled Can this option can be toggled.
1964 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1965 * @param bool $default The default checked state for this setting option.
1967 public function set_options($enabled, $default) {
1968 $this->enabled = $enabled;
1969 $this->default = $default;
1973 * Should this option appear in the interface and be toggleable?
1975 * @return bool Is it enabled?
1977 public function is_enabled() {
1978 return $this->enabled;
1982 * Should this option be checked by default?
1984 * @return bool Is it on by default?
1986 public function get_default() {
1987 return $this->default;
1991 * Return the short name for this flag. e.g. 'adv' or 'locked'
1993 * @return string
1995 public function get_shortname() {
1996 return $this->shortname;
2000 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
2002 * @return string
2004 public function get_displayname() {
2005 return $this->displayname;
2009 * Save the submitted data for this flag - or set it to the default if $data is null.
2011 * @param admin_setting $setting - The admin setting for this flag
2012 * @param array $data - The data submitted from the form or null to set the default value for new installs.
2013 * @return bool
2015 public function write_setting_flag(admin_setting $setting, $data) {
2016 $result = true;
2017 if ($this->is_enabled()) {
2018 if (!isset($data)) {
2019 $value = $this->get_default();
2020 } else {
2021 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2023 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2026 return $result;
2031 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2033 * @param admin_setting $setting - The admin setting for this flag
2034 * @return string - The html for the checkbox.
2036 public function output_setting_flag(admin_setting $setting) {
2037 global $OUTPUT;
2039 $value = $setting->get_setting_flag_value($this);
2041 $context = new stdClass();
2042 $context->id = $setting->get_id() . '_' . $this->get_shortname();
2043 $context->name = $setting->get_full_name() . '_' . $this->get_shortname();
2044 $context->value = 1;
2045 $context->checked = $value ? true : false;
2046 $context->label = $this->get_displayname();
2048 return $OUTPUT->render_from_template('core_admin/setting_flag', $context);
2054 * No setting - just heading and text.
2056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2058 class admin_setting_heading extends admin_setting {
2061 * not a setting, just text
2062 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2063 * @param string $heading heading
2064 * @param string $information text in box
2066 public function __construct($name, $heading, $information) {
2067 $this->nosave = true;
2068 parent::__construct($name, $heading, $information, '');
2072 * Always returns true
2073 * @return bool Always returns true
2075 public function get_setting() {
2076 return true;
2080 * Always returns true
2081 * @return bool Always returns true
2083 public function get_defaultsetting() {
2084 return true;
2088 * Never write settings
2089 * @return string Always returns an empty string
2091 public function write_setting($data) {
2092 // do not write any setting
2093 return '';
2097 * Returns an HTML string
2098 * @return string Returns an HTML string
2100 public function output_html($data, $query='') {
2101 global $OUTPUT;
2102 $context = new stdClass();
2103 $context->title = $this->visiblename;
2104 $context->description = $this->description;
2105 $context->descriptionformatted = highlight($query, markdown_to_html($this->description));
2106 return $OUTPUT->render_from_template('core_admin/setting_heading', $context);
2112 * The most flexible setting, the user enters text.
2114 * This type of field should be used for config settings which are using
2115 * English words and are not localised (passwords, database name, list of values, ...).
2117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2119 class admin_setting_configtext extends admin_setting {
2121 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2122 public $paramtype;
2123 /** @var int default field size */
2124 public $size;
2127 * Config text constructor
2129 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2130 * @param string $visiblename localised
2131 * @param string $description long localised info
2132 * @param string $defaultsetting
2133 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2134 * @param int $size default field size
2136 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2137 $this->paramtype = $paramtype;
2138 if (!is_null($size)) {
2139 $this->size = $size;
2140 } else {
2141 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2143 parent::__construct($name, $visiblename, $description, $defaultsetting);
2147 * Get whether this should be displayed in LTR mode.
2149 * Try to guess from the PARAM type unless specifically set.
2151 public function get_force_ltr() {
2152 $forceltr = parent::get_force_ltr();
2153 if ($forceltr === null) {
2154 return !is_rtl_compatible($this->paramtype);
2156 return $forceltr;
2160 * Return the setting
2162 * @return mixed returns config if successful else null
2164 public function get_setting() {
2165 return $this->config_read($this->name);
2168 public function write_setting($data) {
2169 if ($this->paramtype === PARAM_INT and $data === '') {
2170 // do not complain if '' used instead of 0
2171 $data = 0;
2173 // $data is a string
2174 $validated = $this->validate($data);
2175 if ($validated !== true) {
2176 return $validated;
2178 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2182 * Validate data before storage
2183 * @param string data
2184 * @return mixed true if ok string if error found
2186 public function validate($data) {
2187 // allow paramtype to be a custom regex if it is the form of /pattern/
2188 if (preg_match('#^/.*/$#', $this->paramtype)) {
2189 if (preg_match($this->paramtype, $data)) {
2190 return true;
2191 } else {
2192 return get_string('validateerror', 'admin');
2195 } else if ($this->paramtype === PARAM_RAW) {
2196 return true;
2198 } else {
2199 $cleaned = clean_param($data, $this->paramtype);
2200 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2201 return true;
2202 } else {
2203 return get_string('validateerror', 'admin');
2209 * Return an XHTML string for the setting
2210 * @return string Returns an XHTML string
2212 public function output_html($data, $query='') {
2213 global $OUTPUT;
2215 $default = $this->get_defaultsetting();
2216 $context = (object) [
2217 'size' => $this->size,
2218 'id' => $this->get_id(),
2219 'name' => $this->get_full_name(),
2220 'value' => $data,
2221 'forceltr' => $this->get_force_ltr(),
2223 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
2225 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2230 * Text input with a maximum length constraint.
2232 * @copyright 2015 onwards Ankit Agarwal
2233 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2235 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2237 /** @var int maximum number of chars allowed. */
2238 protected $maxlength;
2241 * Config text constructor
2243 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2244 * or 'myplugin/mysetting' for ones in config_plugins.
2245 * @param string $visiblename localised
2246 * @param string $description long localised info
2247 * @param string $defaultsetting
2248 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2249 * @param int $size default field size
2250 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2252 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2253 $size=null, $maxlength = 0) {
2254 $this->maxlength = $maxlength;
2255 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2259 * Validate data before storage
2261 * @param string $data data
2262 * @return mixed true if ok string if error found
2264 public function validate($data) {
2265 $parentvalidation = parent::validate($data);
2266 if ($parentvalidation === true) {
2267 if ($this->maxlength > 0) {
2268 // Max length check.
2269 $length = core_text::strlen($data);
2270 if ($length > $this->maxlength) {
2271 return get_string('maximumchars', 'moodle', $this->maxlength);
2273 return true;
2274 } else {
2275 return true; // No max length check needed.
2277 } else {
2278 return $parentvalidation;
2284 * General text area without html editor.
2286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2288 class admin_setting_configtextarea extends admin_setting_configtext {
2289 private $rows;
2290 private $cols;
2293 * @param string $name
2294 * @param string $visiblename
2295 * @param string $description
2296 * @param mixed $defaultsetting string or array
2297 * @param mixed $paramtype
2298 * @param string $cols The number of columns to make the editor
2299 * @param string $rows The number of rows to make the editor
2301 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2302 $this->rows = $rows;
2303 $this->cols = $cols;
2304 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2308 * Returns an XHTML string for the editor
2310 * @param string $data
2311 * @param string $query
2312 * @return string XHTML string for the editor
2314 public function output_html($data, $query='') {
2315 global $OUTPUT;
2317 $default = $this->get_defaultsetting();
2318 $defaultinfo = $default;
2319 if (!is_null($default) and $default !== '') {
2320 $defaultinfo = "\n".$default;
2323 $context = (object) [
2324 'cols' => $this->cols,
2325 'rows' => $this->rows,
2326 'id' => $this->get_id(),
2327 'name' => $this->get_full_name(),
2328 'value' => $data,
2329 'forceltr' => $this->get_force_ltr(),
2331 $element = $OUTPUT->render_from_template('core_admin/setting_configtextarea', $context);
2333 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2338 * General text area with html editor.
2340 class admin_setting_confightmleditor extends admin_setting_configtextarea {
2343 * @param string $name
2344 * @param string $visiblename
2345 * @param string $description
2346 * @param mixed $defaultsetting string or array
2347 * @param mixed $paramtype
2349 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2350 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
2351 $this->set_force_ltr(false);
2352 editors_head_setup();
2356 * Returns an XHTML string for the editor
2358 * @param string $data
2359 * @param string $query
2360 * @return string XHTML string for the editor
2362 public function output_html($data, $query='') {
2363 $editor = editors_get_preferred_editor(FORMAT_HTML);
2364 $editor->set_text($data);
2365 $editor->use_editor($this->get_id(), array('noclean'=>true));
2366 return parent::output_html($data, $query);
2372 * Password field, allows unmasking of password
2374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2376 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2379 * Constructor
2380 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2381 * @param string $visiblename localised
2382 * @param string $description long localised info
2383 * @param string $defaultsetting default password
2385 public function __construct($name, $visiblename, $description, $defaultsetting) {
2386 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2390 * Log config changes if necessary.
2391 * @param string $name
2392 * @param string $oldvalue
2393 * @param string $value
2395 protected function add_to_config_log($name, $oldvalue, $value) {
2396 if ($value !== '') {
2397 $value = '********';
2399 if ($oldvalue !== '' and $oldvalue !== null) {
2400 $oldvalue = '********';
2402 parent::add_to_config_log($name, $oldvalue, $value);
2406 * Returns HTML for the field.
2408 * @param string $data Value for the field
2409 * @param string $query Passed as final argument for format_admin_setting
2410 * @return string Rendered HTML
2412 public function output_html($data, $query='') {
2413 global $OUTPUT;
2414 $context = (object) [
2415 'id' => $this->get_id(),
2416 'name' => $this->get_full_name(),
2417 'size' => $this->size,
2418 'value' => $data,
2419 'forceltr' => $this->get_force_ltr(),
2421 $element = $OUTPUT->render_from_template('core_admin/setting_configpasswordunmask', $context);
2422 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', null, $query);
2428 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2429 * Note: Only advanced makes sense right now - locked does not.
2431 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2433 class admin_setting_configempty extends admin_setting_configtext {
2436 * @param string $name
2437 * @param string $visiblename
2438 * @param string $description
2440 public function __construct($name, $visiblename, $description) {
2441 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2445 * Returns an XHTML string for the hidden field
2447 * @param string $data
2448 * @param string $query
2449 * @return string XHTML string for the editor
2451 public function output_html($data, $query='') {
2452 global $OUTPUT;
2454 $context = (object) [
2455 'id' => $this->get_id(),
2456 'name' => $this->get_full_name()
2458 $element = $OUTPUT->render_from_template('core_admin/setting_configempty', $context);
2460 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', get_string('none'), $query);
2466 * Path to directory
2468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2470 class admin_setting_configfile extends admin_setting_configtext {
2472 * Constructor
2473 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2474 * @param string $visiblename localised
2475 * @param string $description long localised info
2476 * @param string $defaultdirectory default directory location
2478 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2479 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2483 * Returns XHTML for the field
2485 * Returns XHTML for the field and also checks whether the file
2486 * specified in $data exists using file_exists()
2488 * @param string $data File name and path to use in value attr
2489 * @param string $query
2490 * @return string XHTML field
2492 public function output_html($data, $query='') {
2493 global $CFG, $OUTPUT;
2495 $default = $this->get_defaultsetting();
2496 $context = (object) [
2497 'id' => $this->get_id(),
2498 'name' => $this->get_full_name(),
2499 'size' => $this->size,
2500 'value' => $data,
2501 'showvalidity' => !empty($data),
2502 'valid' => $data && file_exists($data),
2503 'readonly' => !empty($CFG->preventexecpath),
2504 'forceltr' => $this->get_force_ltr(),
2507 if ($context->readonly) {
2508 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2511 $element = $OUTPUT->render_from_template('core_admin/setting_configfile', $context);
2513 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2517 * Checks if execpatch has been disabled in config.php
2519 public function write_setting($data) {
2520 global $CFG;
2521 if (!empty($CFG->preventexecpath)) {
2522 if ($this->get_setting() === null) {
2523 // Use default during installation.
2524 $data = $this->get_defaultsetting();
2525 if ($data === null) {
2526 $data = '';
2528 } else {
2529 return '';
2532 return parent::write_setting($data);
2539 * Path to executable file
2541 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2543 class admin_setting_configexecutable extends admin_setting_configfile {
2546 * Returns an XHTML field
2548 * @param string $data This is the value for the field
2549 * @param string $query
2550 * @return string XHTML field
2552 public function output_html($data, $query='') {
2553 global $CFG, $OUTPUT;
2554 $default = $this->get_defaultsetting();
2555 require_once("$CFG->libdir/filelib.php");
2557 $context = (object) [
2558 'id' => $this->get_id(),
2559 'name' => $this->get_full_name(),
2560 'size' => $this->size,
2561 'value' => $data,
2562 'showvalidity' => !empty($data),
2563 'valid' => $data && file_exists($data) && !is_dir($data) && file_is_executable($data),
2564 'readonly' => !empty($CFG->preventexecpath),
2565 'forceltr' => $this->get_force_ltr()
2568 if (!empty($CFG->preventexecpath)) {
2569 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2572 $element = $OUTPUT->render_from_template('core_admin/setting_configexecutable', $context);
2574 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2580 * Path to directory
2582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2584 class admin_setting_configdirectory extends admin_setting_configfile {
2587 * Returns an XHTML field
2589 * @param string $data This is the value for the field
2590 * @param string $query
2591 * @return string XHTML
2593 public function output_html($data, $query='') {
2594 global $CFG, $OUTPUT;
2595 $default = $this->get_defaultsetting();
2597 $context = (object) [
2598 'id' => $this->get_id(),
2599 'name' => $this->get_full_name(),
2600 'size' => $this->size,
2601 'value' => $data,
2602 'showvalidity' => !empty($data),
2603 'valid' => $data && file_exists($data) && is_dir($data),
2604 'readonly' => !empty($CFG->preventexecpath),
2605 'forceltr' => $this->get_force_ltr()
2608 if (!empty($CFG->preventexecpath)) {
2609 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2612 $element = $OUTPUT->render_from_template('core_admin/setting_configdirectory', $context);
2614 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
2620 * Checkbox
2622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2624 class admin_setting_configcheckbox extends admin_setting {
2625 /** @var string Value used when checked */
2626 public $yes;
2627 /** @var string Value used when not checked */
2628 public $no;
2631 * Constructor
2632 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2633 * @param string $visiblename localised
2634 * @param string $description long localised info
2635 * @param string $defaultsetting
2636 * @param string $yes value used when checked
2637 * @param string $no value used when not checked
2639 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2640 parent::__construct($name, $visiblename, $description, $defaultsetting);
2641 $this->yes = (string)$yes;
2642 $this->no = (string)$no;
2646 * Retrieves the current setting using the objects name
2648 * @return string
2650 public function get_setting() {
2651 return $this->config_read($this->name);
2655 * Sets the value for the setting
2657 * Sets the value for the setting to either the yes or no values
2658 * of the object by comparing $data to yes
2660 * @param mixed $data Gets converted to str for comparison against yes value
2661 * @return string empty string or error
2663 public function write_setting($data) {
2664 if ((string)$data === $this->yes) { // convert to strings before comparison
2665 $data = $this->yes;
2666 } else {
2667 $data = $this->no;
2669 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2673 * Returns an XHTML checkbox field
2675 * @param string $data If $data matches yes then checkbox is checked
2676 * @param string $query
2677 * @return string XHTML field
2679 public function output_html($data, $query='') {
2680 global $OUTPUT;
2682 $context = (object) [
2683 'id' => $this->get_id(),
2684 'name' => $this->get_full_name(),
2685 'no' => $this->no,
2686 'value' => $this->yes,
2687 'checked' => (string) $data === $this->yes,
2690 $default = $this->get_defaultsetting();
2691 if (!is_null($default)) {
2692 if ((string)$default === $this->yes) {
2693 $defaultinfo = get_string('checkboxyes', 'admin');
2694 } else {
2695 $defaultinfo = get_string('checkboxno', 'admin');
2697 } else {
2698 $defaultinfo = NULL;
2701 $element = $OUTPUT->render_from_template('core_admin/setting_configcheckbox', $context);
2703 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
2709 * Multiple checkboxes, each represents different value, stored in csv format
2711 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2713 class admin_setting_configmulticheckbox extends admin_setting {
2714 /** @var array Array of choices value=>label */
2715 public $choices;
2718 * Constructor: uses parent::__construct
2720 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2721 * @param string $visiblename localised
2722 * @param string $description long localised info
2723 * @param array $defaultsetting array of selected
2724 * @param array $choices array of $value=>$label for each checkbox
2726 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2727 $this->choices = $choices;
2728 parent::__construct($name, $visiblename, $description, $defaultsetting);
2732 * This public function may be used in ancestors for lazy loading of choices
2734 * @todo Check if this function is still required content commented out only returns true
2735 * @return bool true if loaded, false if error
2737 public function load_choices() {
2739 if (is_array($this->choices)) {
2740 return true;
2742 .... load choices here
2744 return true;
2748 * Is setting related to query text - used when searching
2750 * @param string $query
2751 * @return bool true on related, false on not or failure
2753 public function is_related($query) {
2754 if (!$this->load_choices() or empty($this->choices)) {
2755 return false;
2757 if (parent::is_related($query)) {
2758 return true;
2761 foreach ($this->choices as $desc) {
2762 if (strpos(core_text::strtolower($desc), $query) !== false) {
2763 return true;
2766 return false;
2770 * Returns the current setting if it is set
2772 * @return mixed null if null, else an array
2774 public function get_setting() {
2775 $result = $this->config_read($this->name);
2777 if (is_null($result)) {
2778 return NULL;
2780 if ($result === '') {
2781 return array();
2783 $enabled = explode(',', $result);
2784 $setting = array();
2785 foreach ($enabled as $option) {
2786 $setting[$option] = 1;
2788 return $setting;
2792 * Saves the setting(s) provided in $data
2794 * @param array $data An array of data, if not array returns empty str
2795 * @return mixed empty string on useless data or bool true=success, false=failed
2797 public function write_setting($data) {
2798 if (!is_array($data)) {
2799 return ''; // ignore it
2801 if (!$this->load_choices() or empty($this->choices)) {
2802 return '';
2804 unset($data['xxxxx']);
2805 $result = array();
2806 foreach ($data as $key => $value) {
2807 if ($value and array_key_exists($key, $this->choices)) {
2808 $result[] = $key;
2811 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2815 * Returns XHTML field(s) as required by choices
2817 * Relies on data being an array should data ever be another valid vartype with
2818 * acceptable value this may cause a warning/error
2819 * if (!is_array($data)) would fix the problem
2821 * @todo Add vartype handling to ensure $data is an array
2823 * @param array $data An array of checked values
2824 * @param string $query
2825 * @return string XHTML field
2827 public function output_html($data, $query='') {
2828 global $OUTPUT;
2830 if (!$this->load_choices() or empty($this->choices)) {
2831 return '';
2834 $default = $this->get_defaultsetting();
2835 if (is_null($default)) {
2836 $default = array();
2838 if (is_null($data)) {
2839 $data = array();
2842 $context = (object) [
2843 'id' => $this->get_id(),
2844 'name' => $this->get_full_name(),
2847 $options = array();
2848 $defaults = array();
2849 foreach ($this->choices as $key => $description) {
2850 if (!empty($default[$key])) {
2851 $defaults[] = $description;
2854 $options[] = [
2855 'key' => $key,
2856 'checked' => !empty($data[$key]),
2857 'label' => highlightfast($query, $description)
2861 if (is_null($default)) {
2862 $defaultinfo = null;
2863 } else if (!empty($defaults)) {
2864 $defaultinfo = implode(', ', $defaults);
2865 } else {
2866 $defaultinfo = get_string('none');
2869 $context->options = $options;
2870 $context->hasoptions = !empty($options);
2872 $element = $OUTPUT->render_from_template('core_admin/setting_configmulticheckbox', $context);
2874 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', $defaultinfo, $query);
2881 * Multiple checkboxes 2, value stored as string 00101011
2883 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2885 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2888 * Returns the setting if set
2890 * @return mixed null if not set, else an array of set settings
2892 public function get_setting() {
2893 $result = $this->config_read($this->name);
2894 if (is_null($result)) {
2895 return NULL;
2897 if (!$this->load_choices()) {
2898 return NULL;
2900 $result = str_pad($result, count($this->choices), '0');
2901 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2902 $setting = array();
2903 foreach ($this->choices as $key=>$unused) {
2904 $value = array_shift($result);
2905 if ($value) {
2906 $setting[$key] = 1;
2909 return $setting;
2913 * Save setting(s) provided in $data param
2915 * @param array $data An array of settings to save
2916 * @return mixed empty string for bad data or bool true=>success, false=>error
2918 public function write_setting($data) {
2919 if (!is_array($data)) {
2920 return ''; // ignore it
2922 if (!$this->load_choices() or empty($this->choices)) {
2923 return '';
2925 $result = '';
2926 foreach ($this->choices as $key=>$unused) {
2927 if (!empty($data[$key])) {
2928 $result .= '1';
2929 } else {
2930 $result .= '0';
2933 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2939 * Select one value from list
2941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2943 class admin_setting_configselect extends admin_setting {
2944 /** @var array Array of choices value=>label */
2945 public $choices;
2946 /** @var array Array of choices grouped using optgroups */
2947 public $optgroups;
2950 * Constructor
2951 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2952 * @param string $visiblename localised
2953 * @param string $description long localised info
2954 * @param string|int $defaultsetting
2955 * @param array $choices array of $value=>$label for each selection
2957 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2958 // Look for optgroup and single options.
2959 if (is_array($choices)) {
2960 $this->choices = [];
2961 foreach ($choices as $key => $val) {
2962 if (is_array($val)) {
2963 $this->optgroups[$key] = $val;
2964 $this->choices = array_merge($this->choices, $val);
2965 } else {
2966 $this->choices[$key] = $val;
2971 parent::__construct($name, $visiblename, $description, $defaultsetting);
2975 * This function may be used in ancestors for lazy loading of choices
2977 * Override this method if loading of choices is expensive, such
2978 * as when it requires multiple db requests.
2980 * @return bool true if loaded, false if error
2982 public function load_choices() {
2984 if (is_array($this->choices)) {
2985 return true;
2987 .... load choices here
2989 return true;
2993 * Check if this is $query is related to a choice
2995 * @param string $query
2996 * @return bool true if related, false if not
2998 public function is_related($query) {
2999 if (parent::is_related($query)) {
3000 return true;
3002 if (!$this->load_choices()) {
3003 return false;
3005 foreach ($this->choices as $key=>$value) {
3006 if (strpos(core_text::strtolower($key), $query) !== false) {
3007 return true;
3009 if (strpos(core_text::strtolower($value), $query) !== false) {
3010 return true;
3013 return false;
3017 * Return the setting
3019 * @return mixed returns config if successful else null
3021 public function get_setting() {
3022 return $this->config_read($this->name);
3026 * Save a setting
3028 * @param string $data
3029 * @return string empty of error string
3031 public function write_setting($data) {
3032 if (!$this->load_choices() or empty($this->choices)) {
3033 return '';
3035 if (!array_key_exists($data, $this->choices)) {
3036 return ''; // ignore it
3039 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3043 * Returns XHTML select field
3045 * Ensure the options are loaded, and generate the XHTML for the select
3046 * element and any warning message. Separating this out from output_html
3047 * makes it easier to subclass this class.
3049 * @param string $data the option to show as selected.
3050 * @param string $current the currently selected option in the database, null if none.
3051 * @param string $default the default selected option.
3052 * @return array the HTML for the select element, and a warning message.
3053 * @deprecated since Moodle 3.2
3055 public function output_select_html($data, $current, $default, $extraname = '') {
3056 debugging('The method admin_setting_configselect::output_select_html is depreacted, do not use any more.', DEBUG_DEVELOPER);
3060 * Returns XHTML select field and wrapping div(s)
3062 * @see output_select_html()
3064 * @param string $data the option to show as selected
3065 * @param string $query
3066 * @return string XHTML field and wrapping div
3068 public function output_html($data, $query='') {
3069 global $OUTPUT;
3071 $default = $this->get_defaultsetting();
3072 $current = $this->get_setting();
3074 if (!$this->load_choices() || empty($this->choices)) {
3075 return '';
3078 $context = (object) [
3079 'id' => $this->get_id(),
3080 'name' => $this->get_full_name(),
3083 if (!is_null($default) && array_key_exists($default, $this->choices)) {
3084 $defaultinfo = $this->choices[$default];
3085 } else {
3086 $defaultinfo = NULL;
3089 // Warnings.
3090 $warning = '';
3091 if ($current === null) {
3092 // First run.
3093 } else if (empty($current) && (array_key_exists('', $this->choices) || array_key_exists(0, $this->choices))) {
3094 // No warning.
3095 } else if (!array_key_exists($current, $this->choices)) {
3096 $warning = get_string('warningcurrentsetting', 'admin', $current);
3097 if (!is_null($default) && $data == $current) {
3098 $data = $default; // Use default instead of first value when showing the form.
3102 $options = [];
3103 $template = 'core_admin/setting_configselect';
3105 if (!empty($this->optgroups)) {
3106 $optgroups = [];
3107 foreach ($this->optgroups as $label => $choices) {
3108 $optgroup = array('label' => $label, 'options' => []);
3109 foreach ($choices as $value => $name) {
3110 $optgroup['options'][] = [
3111 'value' => $value,
3112 'name' => $name,
3113 'selected' => (string) $value == $data
3115 unset($this->choices[$value]);
3117 $optgroups[] = $optgroup;
3119 $context->options = $options;
3120 $context->optgroups = $optgroups;
3121 $template = 'core_admin/setting_configselect_optgroup';
3124 foreach ($this->choices as $value => $name) {
3125 $options[] = [
3126 'value' => $value,
3127 'name' => $name,
3128 'selected' => (string) $value == $data
3131 $context->options = $options;
3133 $element = $OUTPUT->render_from_template($template, $context);
3135 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, $warning, $defaultinfo, $query);
3141 * Select multiple items from list
3143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3145 class admin_setting_configmultiselect extends admin_setting_configselect {
3147 * Constructor
3148 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3149 * @param string $visiblename localised
3150 * @param string $description long localised info
3151 * @param array $defaultsetting array of selected items
3152 * @param array $choices array of $value=>$label for each list item
3154 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3155 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3159 * Returns the select setting(s)
3161 * @return mixed null or array. Null if no settings else array of setting(s)
3163 public function get_setting() {
3164 $result = $this->config_read($this->name);
3165 if (is_null($result)) {
3166 return NULL;
3168 if ($result === '') {
3169 return array();
3171 return explode(',', $result);
3175 * Saves setting(s) provided through $data
3177 * Potential bug in the works should anyone call with this function
3178 * using a vartype that is not an array
3180 * @param array $data
3182 public function write_setting($data) {
3183 if (!is_array($data)) {
3184 return ''; //ignore it
3186 if (!$this->load_choices() or empty($this->choices)) {
3187 return '';
3190 unset($data['xxxxx']);
3192 $save = array();
3193 foreach ($data as $value) {
3194 if (!array_key_exists($value, $this->choices)) {
3195 continue; // ignore it
3197 $save[] = $value;
3200 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3204 * Is setting related to query text - used when searching
3206 * @param string $query
3207 * @return bool true if related, false if not
3209 public function is_related($query) {
3210 if (!$this->load_choices() or empty($this->choices)) {
3211 return false;
3213 if (parent::is_related($query)) {
3214 return true;
3217 foreach ($this->choices as $desc) {
3218 if (strpos(core_text::strtolower($desc), $query) !== false) {
3219 return true;
3222 return false;
3226 * Returns XHTML multi-select field
3228 * @todo Add vartype handling to ensure $data is an array
3229 * @param array $data Array of values to select by default
3230 * @param string $query
3231 * @return string XHTML multi-select field
3233 public function output_html($data, $query='') {
3234 global $OUTPUT;
3236 if (!$this->load_choices() or empty($this->choices)) {
3237 return '';
3240 $default = $this->get_defaultsetting();
3241 if (is_null($default)) {
3242 $default = array();
3244 if (is_null($data)) {
3245 $data = array();
3248 $context = (object) [
3249 'id' => $this->get_id(),
3250 'name' => $this->get_full_name(),
3251 'size' => min(10, count($this->choices))
3254 $defaults = [];
3255 $options = [];
3256 $template = 'core_admin/setting_configmultiselect';
3258 if (!empty($this->optgroups)) {
3259 $optgroups = [];
3260 foreach ($this->optgroups as $label => $choices) {
3261 $optgroup = array('label' => $label, 'options' => []);
3262 foreach ($choices as $value => $name) {
3263 if (in_array($value, $default)) {
3264 $defaults[] = $name;
3266 $optgroup['options'][] = [
3267 'value' => $value,
3268 'name' => $name,
3269 'selected' => in_array($value, $data)
3271 unset($this->choices[$value]);
3273 $optgroups[] = $optgroup;
3275 $context->optgroups = $optgroups;
3276 $template = 'core_admin/setting_configmultiselect_optgroup';
3279 foreach ($this->choices as $value => $name) {
3280 if (in_array($value, $default)) {
3281 $defaults[] = $name;
3283 $options[] = [
3284 'value' => $value,
3285 'name' => $name,
3286 'selected' => in_array($value, $data)
3289 $context->options = $options;
3291 if (is_null($default)) {
3292 $defaultinfo = NULL;
3293 } if (!empty($defaults)) {
3294 $defaultinfo = implode(', ', $defaults);
3295 } else {
3296 $defaultinfo = get_string('none');
3299 $element = $OUTPUT->render_from_template($template, $context);
3301 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
3306 * Time selector
3308 * This is a liiitle bit messy. we're using two selects, but we're returning
3309 * them as an array named after $name (so we only use $name2 internally for the setting)
3311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3313 class admin_setting_configtime extends admin_setting {
3314 /** @var string Used for setting second select (minutes) */
3315 public $name2;
3318 * Constructor
3319 * @param string $hoursname setting for hours
3320 * @param string $minutesname setting for hours
3321 * @param string $visiblename localised
3322 * @param string $description long localised info
3323 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3325 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3326 $this->name2 = $minutesname;
3327 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3331 * Get the selected time
3333 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3335 public function get_setting() {
3336 $result1 = $this->config_read($this->name);
3337 $result2 = $this->config_read($this->name2);
3338 if (is_null($result1) or is_null($result2)) {
3339 return NULL;
3342 return array('h' => $result1, 'm' => $result2);
3346 * Store the time (hours and minutes)
3348 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3349 * @return bool true if success, false if not
3351 public function write_setting($data) {
3352 if (!is_array($data)) {
3353 return '';
3356 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3357 return ($result ? '' : get_string('errorsetting', 'admin'));
3361 * Returns XHTML time select fields
3363 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3364 * @param string $query
3365 * @return string XHTML time select fields and wrapping div(s)
3367 public function output_html($data, $query='') {
3368 global $OUTPUT;
3370 $default = $this->get_defaultsetting();
3371 if (is_array($default)) {
3372 $defaultinfo = $default['h'].':'.$default['m'];
3373 } else {
3374 $defaultinfo = NULL;
3377 $context = (object) [
3378 'id' => $this->get_id(),
3379 'name' => $this->get_full_name(),
3380 'hours' => array_map(function($i) use ($data) {
3381 return [
3382 'value' => $i,
3383 'name' => $i,
3384 'selected' => $i == $data['h']
3386 }, range(0, 23)),
3387 'minutes' => array_map(function($i) use ($data) {
3388 return [
3389 'value' => $i,
3390 'name' => $i,
3391 'selected' => $i == $data['m']
3393 }, range(0, 59, 5))
3396 $element = $OUTPUT->render_from_template('core_admin/setting_configtime', $context);
3398 return format_admin_setting($this, $this->visiblename, $element, $this->description,
3399 $this->get_id() . 'h', '', $defaultinfo, $query);
3406 * Seconds duration setting.
3408 * @copyright 2012 Petr Skoda (http://skodak.org)
3409 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3411 class admin_setting_configduration extends admin_setting {
3413 /** @var int default duration unit */
3414 protected $defaultunit;
3417 * Constructor
3418 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3419 * or 'myplugin/mysetting' for ones in config_plugins.
3420 * @param string $visiblename localised name
3421 * @param string $description localised long description
3422 * @param mixed $defaultsetting string or array depending on implementation
3423 * @param int $defaultunit - day, week, etc. (in seconds)
3425 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3426 if (is_number($defaultsetting)) {
3427 $defaultsetting = self::parse_seconds($defaultsetting);
3429 $units = self::get_units();
3430 if (isset($units[$defaultunit])) {
3431 $this->defaultunit = $defaultunit;
3432 } else {
3433 $this->defaultunit = 86400;
3435 parent::__construct($name, $visiblename, $description, $defaultsetting);
3439 * Returns selectable units.
3440 * @static
3441 * @return array
3443 protected static function get_units() {
3444 return array(
3445 604800 => get_string('weeks'),
3446 86400 => get_string('days'),
3447 3600 => get_string('hours'),
3448 60 => get_string('minutes'),
3449 1 => get_string('seconds'),
3454 * Converts seconds to some more user friendly string.
3455 * @static
3456 * @param int $seconds
3457 * @return string
3459 protected static function get_duration_text($seconds) {
3460 if (empty($seconds)) {
3461 return get_string('none');
3463 $data = self::parse_seconds($seconds);
3464 switch ($data['u']) {
3465 case (60*60*24*7):
3466 return get_string('numweeks', '', $data['v']);
3467 case (60*60*24):
3468 return get_string('numdays', '', $data['v']);
3469 case (60*60):
3470 return get_string('numhours', '', $data['v']);
3471 case (60):
3472 return get_string('numminutes', '', $data['v']);
3473 default:
3474 return get_string('numseconds', '', $data['v']*$data['u']);
3479 * Finds suitable units for given duration.
3480 * @static
3481 * @param int $seconds
3482 * @return array
3484 protected static function parse_seconds($seconds) {
3485 foreach (self::get_units() as $unit => $unused) {
3486 if ($seconds % $unit === 0) {
3487 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3490 return array('v'=>(int)$seconds, 'u'=>1);
3494 * Get the selected duration as array.
3496 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3498 public function get_setting() {
3499 $seconds = $this->config_read($this->name);
3500 if (is_null($seconds)) {
3501 return null;
3504 return self::parse_seconds($seconds);
3508 * Store the duration as seconds.
3510 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3511 * @return bool true if success, false if not
3513 public function write_setting($data) {
3514 if (!is_array($data)) {
3515 return '';
3518 $seconds = (int)($data['v']*$data['u']);
3519 if ($seconds < 0) {
3520 return get_string('errorsetting', 'admin');
3523 $result = $this->config_write($this->name, $seconds);
3524 return ($result ? '' : get_string('errorsetting', 'admin'));
3528 * Returns duration text+select fields.
3530 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3531 * @param string $query
3532 * @return string duration text+select fields and wrapping div(s)
3534 public function output_html($data, $query='') {
3535 global $OUTPUT;
3537 $default = $this->get_defaultsetting();
3538 if (is_number($default)) {
3539 $defaultinfo = self::get_duration_text($default);
3540 } else if (is_array($default)) {
3541 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3542 } else {
3543 $defaultinfo = null;
3546 $inputid = $this->get_id() . 'v';
3547 $units = self::get_units();
3548 $defaultunit = $this->defaultunit;
3550 $context = (object) [
3551 'id' => $this->get_id(),
3552 'name' => $this->get_full_name(),
3553 'value' => $data['v'],
3554 'options' => array_map(function($unit) use ($units, $data, $defaultunit) {
3555 return [
3556 'value' => $unit,
3557 'name' => $units[$unit],
3558 'selected' => ($data['v'] == 0 && $unit == $defaultunit) || $unit == $data['u']
3560 }, array_keys($units))
3563 $element = $OUTPUT->render_from_template('core_admin/setting_configduration', $context);
3565 return format_admin_setting($this, $this->visiblename, $element, $this->description, $inputid, '', $defaultinfo, $query);
3571 * Seconds duration setting with an advanced checkbox, that controls a additional
3572 * $name.'_adv' setting.
3574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3575 * @copyright 2014 The Open University
3577 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3579 * Constructor
3580 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3581 * or 'myplugin/mysetting' for ones in config_plugins.
3582 * @param string $visiblename localised name
3583 * @param string $description localised long description
3584 * @param array $defaultsetting array of int value, and bool whether it is
3585 * is advanced by default.
3586 * @param int $defaultunit - day, week, etc. (in seconds)
3588 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3589 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3590 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3596 * Used to validate a textarea used for ip addresses
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3599 * @copyright 2011 Petr Skoda (http://skodak.org)
3601 class admin_setting_configiplist extends admin_setting_configtextarea {
3604 * Validate the contents of the textarea as IP addresses
3606 * Used to validate a new line separated list of IP addresses collected from
3607 * a textarea control
3609 * @param string $data A list of IP Addresses separated by new lines
3610 * @return mixed bool true for success or string:error on failure
3612 public function validate($data) {
3613 if(!empty($data)) {
3614 $lines = explode("\n", $data);
3615 } else {
3616 return true;
3618 $result = true;
3619 $badips = array();
3620 foreach ($lines as $line) {
3621 $tokens = explode('#', $line);
3622 $ip = trim($tokens[0]);
3623 if (empty($ip)) {
3624 continue;
3626 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3627 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3628 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3629 } else {
3630 $result = false;
3631 $badips[] = $ip;
3634 if($result) {
3635 return true;
3636 } else {
3637 return get_string('validateiperror', 'admin', join(', ', $badips));
3643 * Used to validate a textarea used for domain names, wildcard domain names and IP addresses/ranges (both IPv4 and IPv6 format).
3645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3646 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3648 class admin_setting_configmixedhostiplist extends admin_setting_configtextarea {
3651 * Validate the contents of the textarea as either IP addresses, domain name or wildcard domain name (RFC 4592).
3652 * Used to validate a new line separated list of entries collected from a textarea control.
3654 * This setting provides support for internationalised domain names (IDNs), however, such UTF-8 names will be converted to
3655 * their ascii-compatible encoding (punycode) on save, and converted back to their UTF-8 representation when fetched
3656 * via the get_setting() method, which has been overriden.
3658 * @param string $data A list of FQDNs, DNS wildcard format domains, and IP addresses, separated by new lines.
3659 * @return mixed bool true for success or string:error on failure
3661 public function validate($data) {
3662 if (empty($data)) {
3663 return true;
3665 $entries = explode("\n", $data);
3666 $badentries = [];
3668 foreach ($entries as $key => $entry) {
3669 $entry = trim($entry);
3670 if (empty($entry)) {
3671 return get_string('validateemptylineerror', 'admin');
3674 // Validate each string entry against the supported formats.
3675 if (\core\ip_utils::is_ip_address($entry) || \core\ip_utils::is_ipv6_range($entry)
3676 || \core\ip_utils::is_ipv4_range($entry) || \core\ip_utils::is_domain_name($entry)
3677 || \core\ip_utils::is_domain_matching_pattern($entry)) {
3678 continue;
3681 // Otherwise, the entry is invalid.
3682 $badentries[] = $entry;
3685 if ($badentries) {
3686 return get_string('validateerrorlist', 'admin', join(', ', $badentries));
3688 return true;
3692 * Convert any lines containing international domain names (IDNs) to their ascii-compatible encoding (ACE).
3694 * @param string $data the setting data, as sent from the web form.
3695 * @return string $data the setting data, with all IDNs converted (using punycode) to their ascii encoded version.
3697 protected function ace_encode($data) {
3698 if (empty($data)) {
3699 return $data;
3701 $entries = explode("\n", $data);
3702 foreach ($entries as $key => $entry) {
3703 $entry = trim($entry);
3704 // This regex matches any string that has non-ascii character.
3705 if (preg_match('/[^\x00-\x7f]/', $entry)) {
3706 // If we can convert the unicode string to an idn, do so.
3707 // Otherwise, leave the original unicode string alone and let the validation function handle it (it will fail).
3708 $val = idn_to_ascii($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3709 $entries[$key] = $val ? $val : $entry;
3712 return implode("\n", $entries);
3716 * Decode any ascii-encoded domain names back to their utf-8 representation for display.
3718 * @param string $data the setting data, as found in the database.
3719 * @return string $data the setting data, with all ascii-encoded IDNs decoded back to their utf-8 representation.
3721 protected function ace_decode($data) {
3722 $entries = explode("\n", $data);
3723 foreach ($entries as $key => $entry) {
3724 $entry = trim($entry);
3725 if (strpos($entry, 'xn--') !== false) {
3726 $entries[$key] = idn_to_utf8($entry, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
3729 return implode("\n", $entries);
3733 * Override, providing utf8-decoding for ascii-encoded IDN strings.
3735 * @return mixed returns punycode-converted setting string if successful, else null.
3737 public function get_setting() {
3738 // Here, we need to decode any ascii-encoded IDNs back to their native, utf-8 representation.
3739 $data = $this->config_read($this->name);
3740 if (function_exists('idn_to_utf8') && !is_null($data)) {
3741 $data = $this->ace_decode($data);
3743 return $data;
3747 * Override, providing ascii-encoding for utf8 (native) IDN strings.
3749 * @param string $data
3750 * @return string
3752 public function write_setting($data) {
3753 if ($this->paramtype === PARAM_INT and $data === '') {
3754 // Do not complain if '' used instead of 0.
3755 $data = 0;
3758 // Try to convert any non-ascii domains to ACE prior to validation - we can't modify anything in validate!
3759 if (function_exists('idn_to_ascii')) {
3760 $data = $this->ace_encode($data);
3763 $validated = $this->validate($data);
3764 if ($validated !== true) {
3765 return $validated;
3767 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3772 * Used to validate a textarea used for port numbers.
3774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3775 * @copyright 2016 Jake Dallimore (jrhdallimore@gmail.com)
3777 class admin_setting_configportlist extends admin_setting_configtextarea {
3780 * Validate the contents of the textarea as port numbers.
3781 * Used to validate a new line separated list of ports collected from a textarea control.
3783 * @param string $data A list of ports separated by new lines
3784 * @return mixed bool true for success or string:error on failure
3786 public function validate($data) {
3787 if (empty($data)) {
3788 return true;
3790 $ports = explode("\n", $data);
3791 $badentries = [];
3792 foreach ($ports as $port) {
3793 $port = trim($port);
3794 if (empty($port)) {
3795 return get_string('validateemptylineerror', 'admin');
3798 // Is the string a valid integer number?
3799 if (strval(intval($port)) !== $port || intval($port) <= 0) {
3800 $badentries[] = $port;
3803 if ($badentries) {
3804 return get_string('validateerrorlist', 'admin', $badentries);
3806 return true;
3812 * An admin setting for selecting one or more users who have a capability
3813 * in the system context
3815 * An admin setting for selecting one or more users, who have a particular capability
3816 * in the system context. Warning, make sure the list will never be too long. There is
3817 * no paging or searching of this list.
3819 * To correctly get a list of users from this config setting, you need to call the
3820 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3824 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3825 /** @var string The capabilities name */
3826 protected $capability;
3827 /** @var int include admin users too */
3828 protected $includeadmins;
3831 * Constructor.
3833 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3834 * @param string $visiblename localised name
3835 * @param string $description localised long description
3836 * @param array $defaultsetting array of usernames
3837 * @param string $capability string capability name.
3838 * @param bool $includeadmins include administrators
3840 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3841 $this->capability = $capability;
3842 $this->includeadmins = $includeadmins;
3843 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3847 * Load all of the uses who have the capability into choice array
3849 * @return bool Always returns true
3851 function load_choices() {
3852 if (is_array($this->choices)) {
3853 return true;
3855 list($sort, $sortparams) = users_order_by_sql('u');
3856 if (!empty($sortparams)) {
3857 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3858 'This is unexpected, and a problem because there is no way to pass these ' .
3859 'parameters to get_users_by_capability. See MDL-34657.');
3861 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3862 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3863 $this->choices = array(
3864 '$@NONE@$' => get_string('nobody'),
3865 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3867 if ($this->includeadmins) {
3868 $admins = get_admins();
3869 foreach ($admins as $user) {
3870 $this->choices[$user->id] = fullname($user);
3873 if (is_array($users)) {
3874 foreach ($users as $user) {
3875 $this->choices[$user->id] = fullname($user);
3878 return true;
3882 * Returns the default setting for class
3884 * @return mixed Array, or string. Empty string if no default
3886 public function get_defaultsetting() {
3887 $this->load_choices();
3888 $defaultsetting = parent::get_defaultsetting();
3889 if (empty($defaultsetting)) {
3890 return array('$@NONE@$');
3891 } else if (array_key_exists($defaultsetting, $this->choices)) {
3892 return $defaultsetting;
3893 } else {
3894 return '';
3899 * Returns the current setting
3901 * @return mixed array or string
3903 public function get_setting() {
3904 $result = parent::get_setting();
3905 if ($result === null) {
3906 // this is necessary for settings upgrade
3907 return null;
3909 if (empty($result)) {
3910 $result = array('$@NONE@$');
3912 return $result;
3916 * Save the chosen setting provided as $data
3918 * @param array $data
3919 * @return mixed string or array
3921 public function write_setting($data) {
3922 // If all is selected, remove any explicit options.
3923 if (in_array('$@ALL@$', $data)) {
3924 $data = array('$@ALL@$');
3926 // None never needs to be written to the DB.
3927 if (in_array('$@NONE@$', $data)) {
3928 unset($data[array_search('$@NONE@$', $data)]);
3930 return parent::write_setting($data);
3936 * Special checkbox for calendar - resets SESSION vars.
3938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3940 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3942 * Calls the parent::__construct with default values
3944 * name => calendar_adminseesall
3945 * visiblename => get_string('adminseesall', 'admin')
3946 * description => get_string('helpadminseesall', 'admin')
3947 * defaultsetting => 0
3949 public function __construct() {
3950 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3951 get_string('helpadminseesall', 'admin'), '0');
3955 * Stores the setting passed in $data
3957 * @param mixed gets converted to string for comparison
3958 * @return string empty string or error message
3960 public function write_setting($data) {
3961 global $SESSION;
3962 return parent::write_setting($data);
3967 * Special select for settings that are altered in setup.php and can not be altered on the fly
3969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3971 class admin_setting_special_selectsetup extends admin_setting_configselect {
3973 * Reads the setting directly from the database
3975 * @return mixed
3977 public function get_setting() {
3978 // read directly from db!
3979 return get_config(NULL, $this->name);
3983 * Save the setting passed in $data
3985 * @param string $data The setting to save
3986 * @return string empty or error message
3988 public function write_setting($data) {
3989 global $CFG;
3990 // do not change active CFG setting!
3991 $current = $CFG->{$this->name};
3992 $result = parent::write_setting($data);
3993 $CFG->{$this->name} = $current;
3994 return $result;
4000 * Special select for frontpage - stores data in course table
4002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4004 class admin_setting_sitesetselect extends admin_setting_configselect {
4006 * Returns the site name for the selected site
4008 * @see get_site()
4009 * @return string The site name of the selected site
4011 public function get_setting() {
4012 $site = course_get_format(get_site())->get_course();
4013 return $site->{$this->name};
4017 * Updates the database and save the setting
4019 * @param string data
4020 * @return string empty or error message
4022 public function write_setting($data) {
4023 global $DB, $SITE, $COURSE;
4024 if (!in_array($data, array_keys($this->choices))) {
4025 return get_string('errorsetting', 'admin');
4027 $record = new stdClass();
4028 $record->id = SITEID;
4029 $temp = $this->name;
4030 $record->$temp = $data;
4031 $record->timemodified = time();
4033 course_get_format($SITE)->update_course_format_options($record);
4034 $DB->update_record('course', $record);
4036 // Reset caches.
4037 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4038 if ($SITE->id == $COURSE->id) {
4039 $COURSE = $SITE;
4041 format_base::reset_course_cache($SITE->id);
4043 return '';
4050 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
4051 * block to hidden.
4053 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4055 class admin_setting_bloglevel extends admin_setting_configselect {
4057 * Updates the database and save the setting
4059 * @param string data
4060 * @return string empty or error message
4062 public function write_setting($data) {
4063 global $DB, $CFG;
4064 if ($data == 0) {
4065 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
4066 foreach ($blogblocks as $block) {
4067 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
4069 } else {
4070 // reenable all blocks only when switching from disabled blogs
4071 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
4072 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
4073 foreach ($blogblocks as $block) {
4074 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
4078 return parent::write_setting($data);
4084 * Special select - lists on the frontpage - hacky
4086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4088 class admin_setting_courselist_frontpage extends admin_setting {
4089 /** @var array Array of choices value=>label */
4090 public $choices;
4093 * Construct override, requires one param
4095 * @param bool $loggedin Is the user logged in
4097 public function __construct($loggedin) {
4098 global $CFG;
4099 require_once($CFG->dirroot.'/course/lib.php');
4100 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
4101 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
4102 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
4103 $defaults = array(FRONTPAGEALLCOURSELIST);
4104 parent::__construct($name, $visiblename, $description, $defaults);
4108 * Loads the choices available
4110 * @return bool always returns true
4112 public function load_choices() {
4113 if (is_array($this->choices)) {
4114 return true;
4116 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
4117 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
4118 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
4119 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
4120 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
4121 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
4122 'none' => get_string('none'));
4123 if ($this->name === 'frontpage') {
4124 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
4126 return true;
4130 * Returns the selected settings
4132 * @param mixed array or setting or null
4134 public function get_setting() {
4135 $result = $this->config_read($this->name);
4136 if (is_null($result)) {
4137 return NULL;
4139 if ($result === '') {
4140 return array();
4142 return explode(',', $result);
4146 * Save the selected options
4148 * @param array $data
4149 * @return mixed empty string (data is not an array) or bool true=success false=failure
4151 public function write_setting($data) {
4152 if (!is_array($data)) {
4153 return '';
4155 $this->load_choices();
4156 $save = array();
4157 foreach($data as $datum) {
4158 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
4159 continue;
4161 $save[$datum] = $datum; // no duplicates
4163 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
4167 * Return XHTML select field and wrapping div
4169 * @todo Add vartype handling to make sure $data is an array
4170 * @param array $data Array of elements to select by default
4171 * @return string XHTML select field and wrapping div
4173 public function output_html($data, $query='') {
4174 global $OUTPUT;
4176 $this->load_choices();
4177 $currentsetting = array();
4178 foreach ($data as $key) {
4179 if ($key != 'none' and array_key_exists($key, $this->choices)) {
4180 $currentsetting[] = $key; // already selected first
4184 $context = (object) [
4185 'id' => $this->get_id(),
4186 'name' => $this->get_full_name(),
4189 $options = $this->choices;
4190 $selects = [];
4191 for ($i = 0; $i < count($this->choices) - 1; $i++) {
4192 if (!array_key_exists($i, $currentsetting)) {
4193 $currentsetting[$i] = 'none';
4195 $selects[] = [
4196 'key' => $i,
4197 'options' => array_map(function($option) use ($options, $currentsetting, $i) {
4198 return [
4199 'name' => $options[$option],
4200 'value' => $option,
4201 'selected' => $currentsetting[$i] == $option
4203 }, array_keys($options))
4206 $context->selects = $selects;
4208 $element = $OUTPUT->render_from_template('core_admin/setting_courselist_frontpage', $context);
4210 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
4216 * Special checkbox for frontpage - stores data in course table
4218 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4220 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
4222 * Returns the current sites name
4224 * @return string
4226 public function get_setting() {
4227 $site = course_get_format(get_site())->get_course();
4228 return $site->{$this->name};
4232 * Save the selected setting
4234 * @param string $data The selected site
4235 * @return string empty string or error message
4237 public function write_setting($data) {
4238 global $DB, $SITE, $COURSE;
4239 $record = new stdClass();
4240 $record->id = $SITE->id;
4241 $record->{$this->name} = ($data == '1' ? 1 : 0);
4242 $record->timemodified = time();
4244 course_get_format($SITE)->update_course_format_options($record);
4245 $DB->update_record('course', $record);
4247 // Reset caches.
4248 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4249 if ($SITE->id == $COURSE->id) {
4250 $COURSE = $SITE;
4252 format_base::reset_course_cache($SITE->id);
4254 return '';
4259 * Special text for frontpage - stores data in course table.
4260 * Empty string means not set here. Manual setting is required.
4262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4264 class admin_setting_sitesettext extends admin_setting_configtext {
4267 * Constructor.
4269 public function __construct() {
4270 call_user_func_array(['parent', '__construct'], func_get_args());
4271 $this->set_force_ltr(false);
4275 * Return the current setting
4277 * @return mixed string or null
4279 public function get_setting() {
4280 $site = course_get_format(get_site())->get_course();
4281 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4285 * Validate the selected data
4287 * @param string $data The selected value to validate
4288 * @return mixed true or message string
4290 public function validate($data) {
4291 global $DB, $SITE;
4292 $cleaned = clean_param($data, PARAM_TEXT);
4293 if ($cleaned === '') {
4294 return get_string('required');
4296 if ($this->name ==='shortname' &&
4297 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4298 return get_string('shortnametaken', 'error', $data);
4300 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4301 return true;
4302 } else {
4303 return get_string('validateerror', 'admin');
4308 * Save the selected setting
4310 * @param string $data The selected value
4311 * @return string empty or error message
4313 public function write_setting($data) {
4314 global $DB, $SITE, $COURSE;
4315 $data = trim($data);
4316 $validated = $this->validate($data);
4317 if ($validated !== true) {
4318 return $validated;
4321 $record = new stdClass();
4322 $record->id = $SITE->id;
4323 $record->{$this->name} = $data;
4324 $record->timemodified = time();
4326 course_get_format($SITE)->update_course_format_options($record);
4327 $DB->update_record('course', $record);
4329 // Reset caches.
4330 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4331 if ($SITE->id == $COURSE->id) {
4332 $COURSE = $SITE;
4334 format_base::reset_course_cache($SITE->id);
4336 return '';
4342 * Special text editor for site description.
4344 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4346 class admin_setting_special_frontpagedesc extends admin_setting_confightmleditor {
4349 * Calls parent::__construct with specific arguments
4351 public function __construct() {
4352 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), null,
4353 PARAM_RAW, 60, 15);
4357 * Return the current setting
4358 * @return string The current setting
4360 public function get_setting() {
4361 $site = course_get_format(get_site())->get_course();
4362 return $site->{$this->name};
4366 * Save the new setting
4368 * @param string $data The new value to save
4369 * @return string empty or error message
4371 public function write_setting($data) {
4372 global $DB, $SITE, $COURSE;
4373 $record = new stdClass();
4374 $record->id = $SITE->id;
4375 $record->{$this->name} = $data;
4376 $record->timemodified = time();
4378 course_get_format($SITE)->update_course_format_options($record);
4379 $DB->update_record('course', $record);
4381 // Reset caches.
4382 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4383 if ($SITE->id == $COURSE->id) {
4384 $COURSE = $SITE;
4386 format_base::reset_course_cache($SITE->id);
4388 return '';
4394 * Administration interface for emoticon_manager settings.
4396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4398 class admin_setting_emoticons extends admin_setting {
4401 * Calls parent::__construct with specific args
4403 public function __construct() {
4404 global $CFG;
4406 $manager = get_emoticon_manager();
4407 $defaults = $this->prepare_form_data($manager->default_emoticons());
4408 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4412 * Return the current setting(s)
4414 * @return array Current settings array
4416 public function get_setting() {
4417 global $CFG;
4419 $manager = get_emoticon_manager();
4421 $config = $this->config_read($this->name);
4422 if (is_null($config)) {
4423 return null;
4426 $config = $manager->decode_stored_config($config);
4427 if (is_null($config)) {
4428 return null;
4431 return $this->prepare_form_data($config);
4435 * Save selected settings
4437 * @param array $data Array of settings to save
4438 * @return bool
4440 public function write_setting($data) {
4442 $manager = get_emoticon_manager();
4443 $emoticons = $this->process_form_data($data);
4445 if ($emoticons === false) {
4446 return false;
4449 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4450 return ''; // success
4451 } else {
4452 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4457 * Return XHTML field(s) for options
4459 * @param array $data Array of options to set in HTML
4460 * @return string XHTML string for the fields and wrapping div(s)
4462 public function output_html($data, $query='') {
4463 global $OUTPUT;
4465 $context = (object) [
4466 'name' => $this->get_full_name(),
4467 'emoticons' => [],
4468 'forceltr' => true,
4471 $i = 0;
4472 foreach ($data as $field => $value) {
4474 // When $i == 0: text.
4475 // When $i == 1: imagename.
4476 // When $i == 2: imagecomponent.
4477 // When $i == 3: altidentifier.
4478 // When $i == 4: altcomponent.
4479 $fields[$i] = (object) [
4480 'field' => $field,
4481 'value' => $value,
4482 'index' => $i
4484 $i++;
4486 if ($i > 4) {
4487 $icon = null;
4488 if (!empty($fields[1]->value)) {
4489 if (get_string_manager()->string_exists($fields[3]->value, $fields[4]->value)) {
4490 $alt = get_string($fields[3]->value, $fields[4]->value);
4491 } else {
4492 $alt = $fields[0]->value;
4494 $icon = new pix_emoticon($fields[1]->value, $alt, $fields[2]->value);
4496 $context->emoticons[] = [
4497 'fields' => $fields,
4498 'icon' => $icon ? $icon->export_for_template($OUTPUT) : null
4500 $fields = [];
4501 $i = 0;
4505 $context->reseturl = new moodle_url('/admin/resetemoticons.php');
4506 $element = $OUTPUT->render_from_template('core_admin/setting_emoticons', $context);
4507 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4511 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4513 * @see self::process_form_data()
4514 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4515 * @return array of form fields and their values
4517 protected function prepare_form_data(array $emoticons) {
4519 $form = array();
4520 $i = 0;
4521 foreach ($emoticons as $emoticon) {
4522 $form['text'.$i] = $emoticon->text;
4523 $form['imagename'.$i] = $emoticon->imagename;
4524 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4525 $form['altidentifier'.$i] = $emoticon->altidentifier;
4526 $form['altcomponent'.$i] = $emoticon->altcomponent;
4527 $i++;
4529 // add one more blank field set for new object
4530 $form['text'.$i] = '';
4531 $form['imagename'.$i] = '';
4532 $form['imagecomponent'.$i] = '';
4533 $form['altidentifier'.$i] = '';
4534 $form['altcomponent'.$i] = '';
4536 return $form;
4540 * Converts the data from admin settings form into an array of emoticon objects
4542 * @see self::prepare_form_data()
4543 * @param array $data array of admin form fields and values
4544 * @return false|array of emoticon objects
4546 protected function process_form_data(array $form) {
4548 $count = count($form); // number of form field values
4550 if ($count % 5) {
4551 // we must get five fields per emoticon object
4552 return false;
4555 $emoticons = array();
4556 for ($i = 0; $i < $count / 5; $i++) {
4557 $emoticon = new stdClass();
4558 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4559 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4560 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4561 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4562 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4564 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4565 // prevent from breaking http://url.addresses by accident
4566 $emoticon->text = '';
4569 if (strlen($emoticon->text) < 2) {
4570 // do not allow single character emoticons
4571 $emoticon->text = '';
4574 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4575 // emoticon text must contain some non-alphanumeric character to prevent
4576 // breaking HTML tags
4577 $emoticon->text = '';
4580 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4581 $emoticons[] = $emoticon;
4584 return $emoticons;
4591 * Special setting for limiting of the list of available languages.
4593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4595 class admin_setting_langlist extends admin_setting_configtext {
4597 * Calls parent::__construct with specific arguments
4599 public function __construct() {
4600 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4604 * Save the new setting
4606 * @param string $data The new setting
4607 * @return bool
4609 public function write_setting($data) {
4610 $return = parent::write_setting($data);
4611 get_string_manager()->reset_caches();
4612 return $return;
4618 * Selection of one of the recognised countries using the list
4619 * returned by {@link get_list_of_countries()}.
4621 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4623 class admin_settings_country_select extends admin_setting_configselect {
4624 protected $includeall;
4625 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4626 $this->includeall = $includeall;
4627 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
4631 * Lazy-load the available choices for the select box
4633 public function load_choices() {
4634 global $CFG;
4635 if (is_array($this->choices)) {
4636 return true;
4638 $this->choices = array_merge(
4639 array('0' => get_string('choosedots')),
4640 get_string_manager()->get_list_of_countries($this->includeall));
4641 return true;
4647 * admin_setting_configselect for the default number of sections in a course,
4648 * simply so we can lazy-load the choices.
4650 * @copyright 2011 The Open University
4651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4653 class admin_settings_num_course_sections extends admin_setting_configselect {
4654 public function __construct($name, $visiblename, $description, $defaultsetting) {
4655 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4658 /** Lazy-load the available choices for the select box */
4659 public function load_choices() {
4660 $max = get_config('moodlecourse', 'maxsections');
4661 if (!isset($max) || !is_numeric($max)) {
4662 $max = 52;
4664 for ($i = 0; $i <= $max; $i++) {
4665 $this->choices[$i] = "$i";
4667 return true;
4673 * Course category selection
4675 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4677 class admin_settings_coursecat_select extends admin_setting_configselect {
4679 * Calls parent::__construct with specific arguments
4681 public function __construct($name, $visiblename, $description, $defaultsetting) {
4682 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4686 * Load the available choices for the select box
4688 * @return bool
4690 public function load_choices() {
4691 global $CFG;
4692 require_once($CFG->dirroot.'/course/lib.php');
4693 if (is_array($this->choices)) {
4694 return true;
4696 $this->choices = make_categories_options();
4697 return true;
4703 * Special control for selecting days to backup
4705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4707 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4709 * Calls parent::__construct with specific arguments
4711 public function __construct() {
4712 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4713 $this->plugin = 'backup';
4717 * Load the available choices for the select box
4719 * @return bool Always returns true
4721 public function load_choices() {
4722 if (is_array($this->choices)) {
4723 return true;
4725 $this->choices = array();
4726 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4727 foreach ($days as $day) {
4728 $this->choices[$day] = get_string($day, 'calendar');
4730 return true;
4735 * Special setting for backup auto destination.
4737 * @package core
4738 * @subpackage admin
4739 * @copyright 2014 Frédéric Massart - FMCorz.net
4740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4742 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4745 * Calls parent::__construct with specific arguments.
4747 public function __construct() {
4748 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4752 * Check if the directory must be set, depending on backup/backup_auto_storage.
4754 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4755 * there will be conflicts if this validation happens before the other one.
4757 * @param string $data Form data.
4758 * @return string Empty when no errors.
4760 public function write_setting($data) {
4761 $storage = (int) get_config('backup', 'backup_auto_storage');
4762 if ($storage !== 0) {
4763 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4764 // The directory must exist and be writable.
4765 return get_string('backuperrorinvaliddestination');
4768 return parent::write_setting($data);
4774 * Special debug setting
4776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4778 class admin_setting_special_debug extends admin_setting_configselect {
4780 * Calls parent::__construct with specific arguments
4782 public function __construct() {
4783 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4787 * Load the available choices for the select box
4789 * @return bool
4791 public function load_choices() {
4792 if (is_array($this->choices)) {
4793 return true;
4795 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4796 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4797 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4798 DEBUG_ALL => get_string('debugall', 'admin'),
4799 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4800 return true;
4806 * Special admin control
4808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4810 class admin_setting_special_calendar_weekend extends admin_setting {
4812 * Calls parent::__construct with specific arguments
4814 public function __construct() {
4815 $name = 'calendar_weekend';
4816 $visiblename = get_string('calendar_weekend', 'admin');
4817 $description = get_string('helpweekenddays', 'admin');
4818 $default = array ('0', '6'); // Saturdays and Sundays
4819 parent::__construct($name, $visiblename, $description, $default);
4823 * Gets the current settings as an array
4825 * @return mixed Null if none, else array of settings
4827 public function get_setting() {
4828 $result = $this->config_read($this->name);
4829 if (is_null($result)) {
4830 return NULL;
4832 if ($result === '') {
4833 return array();
4835 $settings = array();
4836 for ($i=0; $i<7; $i++) {
4837 if ($result & (1 << $i)) {
4838 $settings[] = $i;
4841 return $settings;
4845 * Save the new settings
4847 * @param array $data Array of new settings
4848 * @return bool
4850 public function write_setting($data) {
4851 if (!is_array($data)) {
4852 return '';
4854 unset($data['xxxxx']);
4855 $result = 0;
4856 foreach($data as $index) {
4857 $result |= 1 << $index;
4859 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4863 * Return XHTML to display the control
4865 * @param array $data array of selected days
4866 * @param string $query
4867 * @return string XHTML for display (field + wrapping div(s)
4869 public function output_html($data, $query='') {
4870 global $OUTPUT;
4872 // The order matters very much because of the implied numeric keys.
4873 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4874 $context = (object) [
4875 'name' => $this->get_full_name(),
4876 'id' => $this->get_id(),
4877 'days' => array_map(function($index) use ($days, $data) {
4878 return [
4879 'index' => $index,
4880 'label' => get_string($days[$index], 'calendar'),
4881 'checked' => in_array($index, $data)
4883 }, array_keys($days))
4886 $element = $OUTPUT->render_from_template('core_admin/setting_special_calendar_weekend', $context);
4888 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', NULL, $query);
4895 * Admin setting that allows a user to pick a behaviour.
4897 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4899 class admin_setting_question_behaviour extends admin_setting_configselect {
4901 * @param string $name name of config variable
4902 * @param string $visiblename display name
4903 * @param string $description description
4904 * @param string $default default.
4906 public function __construct($name, $visiblename, $description, $default) {
4907 parent::__construct($name, $visiblename, $description, $default, null);
4911 * Load list of behaviours as choices
4912 * @return bool true => success, false => error.
4914 public function load_choices() {
4915 global $CFG;
4916 require_once($CFG->dirroot . '/question/engine/lib.php');
4917 $this->choices = question_engine::get_behaviour_options('');
4918 return true;
4924 * Admin setting that allows a user to pick appropriate roles for something.
4926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4928 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4929 /** @var array Array of capabilities which identify roles */
4930 private $types;
4933 * @param string $name Name of config variable
4934 * @param string $visiblename Display name
4935 * @param string $description Description
4936 * @param array $types Array of archetypes which identify
4937 * roles that will be enabled by default.
4939 public function __construct($name, $visiblename, $description, $types) {
4940 parent::__construct($name, $visiblename, $description, NULL, NULL);
4941 $this->types = $types;
4945 * Load roles as choices
4947 * @return bool true=>success, false=>error
4949 public function load_choices() {
4950 global $CFG, $DB;
4951 if (during_initial_install()) {
4952 return false;
4954 if (is_array($this->choices)) {
4955 return true;
4957 if ($roles = get_all_roles()) {
4958 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4959 return true;
4960 } else {
4961 return false;
4966 * Return the default setting for this control
4968 * @return array Array of default settings
4970 public function get_defaultsetting() {
4971 global $CFG;
4973 if (during_initial_install()) {
4974 return null;
4976 $result = array();
4977 foreach($this->types as $archetype) {
4978 if ($caproles = get_archetype_roles($archetype)) {
4979 foreach ($caproles as $caprole) {
4980 $result[$caprole->id] = 1;
4984 return $result;
4990 * Admin setting that is a list of installed filter plugins.
4992 * @copyright 2015 The Open University
4993 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4995 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
4998 * Constructor
5000 * @param string $name unique ascii name, either 'mysetting' for settings
5001 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
5002 * @param string $visiblename localised name
5003 * @param string $description localised long description
5004 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
5006 public function __construct($name, $visiblename, $description, $default) {
5007 if (empty($default)) {
5008 $default = array();
5010 $this->load_choices();
5011 foreach ($default as $plugin) {
5012 if (!isset($this->choices[$plugin])) {
5013 unset($default[$plugin]);
5016 parent::__construct($name, $visiblename, $description, $default, null);
5019 public function load_choices() {
5020 if (is_array($this->choices)) {
5021 return true;
5023 $this->choices = array();
5025 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
5026 $this->choices[$plugin] = filter_get_name($plugin);
5028 return true;
5034 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
5036 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5038 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
5040 * Constructor
5041 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5042 * @param string $visiblename localised
5043 * @param string $description long localised info
5044 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
5045 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
5046 * @param int $size default field size
5048 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
5049 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
5050 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5056 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
5058 * @copyright 2009 Petr Skoda (http://skodak.org)
5059 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5061 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
5064 * Constructor
5065 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5066 * @param string $visiblename localised
5067 * @param string $description long localised info
5068 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
5069 * @param string $yes value used when checked
5070 * @param string $no value used when not checked
5072 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5073 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5074 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5081 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
5083 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
5085 * @copyright 2010 Sam Hemelryk
5086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5088 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
5090 * Constructor
5091 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
5092 * @param string $visiblename localised
5093 * @param string $description long localised info
5094 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5095 * @param string $yes value used when checked
5096 * @param string $no value used when not checked
5098 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
5099 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
5100 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5107 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
5109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5111 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
5113 * Calls parent::__construct with specific arguments
5115 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5116 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5117 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
5123 * Select with an advanced checkbox that controls an additional $name.'_locked' config setting.
5125 * @copyright 2017 Marina Glancy
5126 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5128 class admin_setting_configselect_with_lock extends admin_setting_configselect {
5130 * Constructor
5131 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
5132 * or 'myplugin/mysetting' for ones in config_plugins.
5133 * @param string $visiblename localised
5134 * @param string $description long localised info
5135 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
5136 * @param array $choices array of $value=>$label for each selection
5138 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5139 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
5140 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
5146 * Graded roles in gradebook
5148 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5150 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
5152 * Calls parent::__construct with specific arguments
5154 public function __construct() {
5155 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
5156 get_string('configgradebookroles', 'admin'),
5157 array('student'));
5164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5166 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
5168 * Saves the new settings passed in $data
5170 * @param string $data
5171 * @return mixed string or Array
5173 public function write_setting($data) {
5174 global $CFG, $DB;
5176 $oldvalue = $this->config_read($this->name);
5177 $return = parent::write_setting($data);
5178 $newvalue = $this->config_read($this->name);
5180 if ($oldvalue !== $newvalue) {
5181 // force full regrading
5182 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
5185 return $return;
5191 * Which roles to show on course description page
5193 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5195 class admin_setting_special_coursecontact extends admin_setting_pickroles {
5197 * Calls parent::__construct with specific arguments
5199 public function __construct() {
5200 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
5201 get_string('coursecontact_desc', 'admin'),
5202 array('editingteacher'));
5203 $this->set_updatedcallback(function (){
5204 cache::make('core', 'coursecontacts')->purge();
5212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5214 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
5216 * Calls parent::__construct with specific arguments
5218 public function __construct() {
5219 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
5220 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
5224 * Old syntax of class constructor. Deprecated in PHP7.
5226 * @deprecated since Moodle 3.1
5228 public function admin_setting_special_gradelimiting() {
5229 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
5230 self::__construct();
5234 * Force site regrading
5236 function regrade_all() {
5237 global $CFG;
5238 require_once("$CFG->libdir/gradelib.php");
5239 grade_force_site_regrading();
5243 * Saves the new settings
5245 * @param mixed $data
5246 * @return string empty string or error message
5248 function write_setting($data) {
5249 $previous = $this->get_setting();
5251 if ($previous === null) {
5252 if ($data) {
5253 $this->regrade_all();
5255 } else {
5256 if ($data != $previous) {
5257 $this->regrade_all();
5260 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
5266 * Special setting for $CFG->grade_minmaxtouse.
5268 * @package core
5269 * @copyright 2015 Frédéric Massart - FMCorz.net
5270 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5272 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5275 * Constructor.
5277 public function __construct() {
5278 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5279 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5280 array(
5281 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5282 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5288 * Saves the new setting.
5290 * @param mixed $data
5291 * @return string empty string or error message
5293 function write_setting($data) {
5294 global $CFG;
5296 $previous = $this->get_setting();
5297 $result = parent::write_setting($data);
5299 // If saved and the value has changed.
5300 if (empty($result) && $previous != $data) {
5301 require_once($CFG->libdir . '/gradelib.php');
5302 grade_force_site_regrading();
5305 return $result;
5312 * Primary grade export plugin - has state tracking.
5314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5316 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5318 * Calls parent::__construct with specific arguments
5320 public function __construct() {
5321 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5322 get_string('configgradeexport', 'admin'), array(), NULL);
5326 * Load the available choices for the multicheckbox
5328 * @return bool always returns true
5330 public function load_choices() {
5331 if (is_array($this->choices)) {
5332 return true;
5334 $this->choices = array();
5336 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5337 foreach($plugins as $plugin => $unused) {
5338 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5341 return true;
5347 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5349 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5351 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5353 * Config gradepointmax constructor
5355 * @param string $name Overidden by "gradepointmax"
5356 * @param string $visiblename Overridden by "gradepointmax" language string.
5357 * @param string $description Overridden by "gradepointmax_help" language string.
5358 * @param string $defaultsetting Not used, overridden by 100.
5359 * @param mixed $paramtype Overridden by PARAM_INT.
5360 * @param int $size Overridden by 5.
5362 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5363 $name = 'gradepointdefault';
5364 $visiblename = get_string('gradepointdefault', 'grades');
5365 $description = get_string('gradepointdefault_help', 'grades');
5366 $defaultsetting = 100;
5367 $paramtype = PARAM_INT;
5368 $size = 5;
5369 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5373 * Validate data before storage
5374 * @param string $data The submitted data
5375 * @return bool|string true if ok, string if error found
5377 public function validate($data) {
5378 global $CFG;
5379 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5380 return true;
5381 } else {
5382 return get_string('gradepointdefault_validateerror', 'grades');
5389 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5391 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5393 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5396 * Config gradepointmax constructor
5398 * @param string $name Overidden by "gradepointmax"
5399 * @param string $visiblename Overridden by "gradepointmax" language string.
5400 * @param string $description Overridden by "gradepointmax_help" language string.
5401 * @param string $defaultsetting Not used, overridden by 100.
5402 * @param mixed $paramtype Overridden by PARAM_INT.
5403 * @param int $size Overridden by 5.
5405 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5406 $name = 'gradepointmax';
5407 $visiblename = get_string('gradepointmax', 'grades');
5408 $description = get_string('gradepointmax_help', 'grades');
5409 $defaultsetting = 100;
5410 $paramtype = PARAM_INT;
5411 $size = 5;
5412 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5416 * Save the selected setting
5418 * @param string $data The selected site
5419 * @return string empty string or error message
5421 public function write_setting($data) {
5422 if ($data === '') {
5423 $data = (int)$this->defaultsetting;
5424 } else {
5425 $data = $data;
5427 return parent::write_setting($data);
5431 * Validate data before storage
5432 * @param string $data The submitted data
5433 * @return bool|string true if ok, string if error found
5435 public function validate($data) {
5436 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5437 return true;
5438 } else {
5439 return get_string('gradepointmax_validateerror', 'grades');
5444 * Return an XHTML string for the setting
5445 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5446 * @param string $query search query to be highlighted
5447 * @return string XHTML to display control
5449 public function output_html($data, $query = '') {
5450 global $OUTPUT;
5452 $default = $this->get_defaultsetting();
5453 $context = (object) [
5454 'size' => $this->size,
5455 'id' => $this->get_id(),
5456 'name' => $this->get_full_name(),
5457 'value' => $data,
5458 'attributes' => [
5459 'maxlength' => 5
5461 'forceltr' => $this->get_force_ltr()
5463 $element = $OUTPUT->render_from_template('core_admin/setting_configtext', $context);
5465 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
5471 * Grade category settings
5473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5475 class admin_setting_gradecat_combo extends admin_setting {
5476 /** @var array Array of choices */
5477 public $choices;
5480 * Sets choices and calls parent::__construct with passed arguments
5481 * @param string $name
5482 * @param string $visiblename
5483 * @param string $description
5484 * @param mixed $defaultsetting string or array depending on implementation
5485 * @param array $choices An array of choices for the control
5487 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5488 $this->choices = $choices;
5489 parent::__construct($name, $visiblename, $description, $defaultsetting);
5493 * Return the current setting(s) array
5495 * @return array Array of value=>xx, forced=>xx, adv=>xx
5497 public function get_setting() {
5498 global $CFG;
5500 $value = $this->config_read($this->name);
5501 $flag = $this->config_read($this->name.'_flag');
5503 if (is_null($value) or is_null($flag)) {
5504 return NULL;
5507 $flag = (int)$flag;
5508 $forced = (boolean)(1 & $flag); // first bit
5509 $adv = (boolean)(2 & $flag); // second bit
5511 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5515 * Save the new settings passed in $data
5517 * @todo Add vartype handling to ensure $data is array
5518 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5519 * @return string empty or error message
5521 public function write_setting($data) {
5522 global $CFG;
5524 $value = $data['value'];
5525 $forced = empty($data['forced']) ? 0 : 1;
5526 $adv = empty($data['adv']) ? 0 : 2;
5527 $flag = ($forced | $adv); //bitwise or
5529 if (!in_array($value, array_keys($this->choices))) {
5530 return 'Error setting ';
5533 $oldvalue = $this->config_read($this->name);
5534 $oldflag = (int)$this->config_read($this->name.'_flag');
5535 $oldforced = (1 & $oldflag); // first bit
5537 $result1 = $this->config_write($this->name, $value);
5538 $result2 = $this->config_write($this->name.'_flag', $flag);
5540 // force regrade if needed
5541 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5542 require_once($CFG->libdir.'/gradelib.php');
5543 grade_category::updated_forced_settings();
5546 if ($result1 and $result2) {
5547 return '';
5548 } else {
5549 return get_string('errorsetting', 'admin');
5554 * Return XHTML to display the field and wrapping div
5556 * @todo Add vartype handling to ensure $data is array
5557 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5558 * @param string $query
5559 * @return string XHTML to display control
5561 public function output_html($data, $query='') {
5562 global $OUTPUT;
5564 $value = $data['value'];
5566 $default = $this->get_defaultsetting();
5567 if (!is_null($default)) {
5568 $defaultinfo = array();
5569 if (isset($this->choices[$default['value']])) {
5570 $defaultinfo[] = $this->choices[$default['value']];
5572 if (!empty($default['forced'])) {
5573 $defaultinfo[] = get_string('force');
5575 if (!empty($default['adv'])) {
5576 $defaultinfo[] = get_string('advanced');
5578 $defaultinfo = implode(', ', $defaultinfo);
5580 } else {
5581 $defaultinfo = NULL;
5584 $options = $this->choices;
5585 $context = (object) [
5586 'id' => $this->get_id(),
5587 'name' => $this->get_full_name(),
5588 'forced' => !empty($data['forced']),
5589 'advanced' => !empty($data['adv']),
5590 'options' => array_map(function($option) use ($options, $value) {
5591 return [
5592 'value' => $option,
5593 'name' => $options[$option],
5594 'selected' => $option == $value
5596 }, array_keys($options)),
5599 $element = $OUTPUT->render_from_template('core_admin/setting_gradecat_combo', $context);
5601 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $defaultinfo, $query);
5607 * Selection of grade report in user profiles
5609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5611 class admin_setting_grade_profilereport extends admin_setting_configselect {
5613 * Calls parent::__construct with specific arguments
5615 public function __construct() {
5616 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5620 * Loads an array of choices for the configselect control
5622 * @return bool always return true
5624 public function load_choices() {
5625 if (is_array($this->choices)) {
5626 return true;
5628 $this->choices = array();
5630 global $CFG;
5631 require_once($CFG->libdir.'/gradelib.php');
5633 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5634 if (file_exists($plugindir.'/lib.php')) {
5635 require_once($plugindir.'/lib.php');
5636 $functionname = 'grade_report_'.$plugin.'_profilereport';
5637 if (function_exists($functionname)) {
5638 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5642 return true;
5647 * Provides a selection of grade reports to be used for "grades".
5649 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5652 class admin_setting_my_grades_report extends admin_setting_configselect {
5655 * Calls parent::__construct with specific arguments.
5657 public function __construct() {
5658 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5659 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5663 * Loads an array of choices for the configselect control.
5665 * @return bool always returns true.
5667 public function load_choices() {
5668 global $CFG; // Remove this line and behold the horror of behat test failures!
5669 $this->choices = array();
5670 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5671 if (file_exists($plugindir . '/lib.php')) {
5672 require_once($plugindir . '/lib.php');
5673 // Check to see if the class exists. Check the correct plugin convention first.
5674 if (class_exists('gradereport_' . $plugin)) {
5675 $classname = 'gradereport_' . $plugin;
5676 } else if (class_exists('grade_report_' . $plugin)) {
5677 // We are using the old plugin naming convention.
5678 $classname = 'grade_report_' . $plugin;
5679 } else {
5680 continue;
5682 if ($classname::supports_mygrades()) {
5683 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5687 // Add an option to specify an external url.
5688 $this->choices['external'] = get_string('externalurl', 'grades');
5689 return true;
5694 * Special class for register auth selection
5696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5698 class admin_setting_special_registerauth extends admin_setting_configselect {
5700 * Calls parent::__construct with specific arguments
5702 public function __construct() {
5703 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5707 * Returns the default option
5709 * @return string empty or default option
5711 public function get_defaultsetting() {
5712 $this->load_choices();
5713 $defaultsetting = parent::get_defaultsetting();
5714 if (array_key_exists($defaultsetting, $this->choices)) {
5715 return $defaultsetting;
5716 } else {
5717 return '';
5722 * Loads the possible choices for the array
5724 * @return bool always returns true
5726 public function load_choices() {
5727 global $CFG;
5729 if (is_array($this->choices)) {
5730 return true;
5732 $this->choices = array();
5733 $this->choices[''] = get_string('disable');
5735 $authsenabled = get_enabled_auth_plugins(true);
5737 foreach ($authsenabled as $auth) {
5738 $authplugin = get_auth_plugin($auth);
5739 if (!$authplugin->can_signup()) {
5740 continue;
5742 // Get the auth title (from core or own auth lang files)
5743 $authtitle = $authplugin->get_title();
5744 $this->choices[$auth] = $authtitle;
5746 return true;
5752 * General plugins manager
5754 class admin_page_pluginsoverview extends admin_externalpage {
5757 * Sets basic information about the external page
5759 public function __construct() {
5760 global $CFG;
5761 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5762 "$CFG->wwwroot/$CFG->admin/plugins.php");
5767 * Module manage page
5769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5771 class admin_page_managemods extends admin_externalpage {
5773 * Calls parent::__construct with specific arguments
5775 public function __construct() {
5776 global $CFG;
5777 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5781 * Try to find the specified module
5783 * @param string $query The module to search for
5784 * @return array
5786 public function search($query) {
5787 global $CFG, $DB;
5788 if ($result = parent::search($query)) {
5789 return $result;
5792 $found = false;
5793 if ($modules = $DB->get_records('modules')) {
5794 foreach ($modules as $module) {
5795 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5796 continue;
5798 if (strpos($module->name, $query) !== false) {
5799 $found = true;
5800 break;
5802 $strmodulename = get_string('modulename', $module->name);
5803 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5804 $found = true;
5805 break;
5809 if ($found) {
5810 $result = new stdClass();
5811 $result->page = $this;
5812 $result->settings = array();
5813 return array($this->name => $result);
5814 } else {
5815 return array();
5822 * Special class for enrol plugins management.
5824 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5827 class admin_setting_manageenrols extends admin_setting {
5829 * Calls parent::__construct with specific arguments
5831 public function __construct() {
5832 $this->nosave = true;
5833 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5837 * Always returns true, does nothing
5839 * @return true
5841 public function get_setting() {
5842 return true;
5846 * Always returns true, does nothing
5848 * @return true
5850 public function get_defaultsetting() {
5851 return true;
5855 * Always returns '', does not write anything
5857 * @return string Always returns ''
5859 public function write_setting($data) {
5860 // do not write any setting
5861 return '';
5865 * Checks if $query is one of the available enrol plugins
5867 * @param string $query The string to search for
5868 * @return bool Returns true if found, false if not
5870 public function is_related($query) {
5871 if (parent::is_related($query)) {
5872 return true;
5875 $query = core_text::strtolower($query);
5876 $enrols = enrol_get_plugins(false);
5877 foreach ($enrols as $name=>$enrol) {
5878 $localised = get_string('pluginname', 'enrol_'.$name);
5879 if (strpos(core_text::strtolower($name), $query) !== false) {
5880 return true;
5882 if (strpos(core_text::strtolower($localised), $query) !== false) {
5883 return true;
5886 return false;
5890 * Builds the XHTML to display the control
5892 * @param string $data Unused
5893 * @param string $query
5894 * @return string
5896 public function output_html($data, $query='') {
5897 global $CFG, $OUTPUT, $DB, $PAGE;
5899 // Display strings.
5900 $strup = get_string('up');
5901 $strdown = get_string('down');
5902 $strsettings = get_string('settings');
5903 $strenable = get_string('enable');
5904 $strdisable = get_string('disable');
5905 $struninstall = get_string('uninstallplugin', 'core_admin');
5906 $strusage = get_string('enrolusage', 'enrol');
5907 $strversion = get_string('version');
5908 $strtest = get_string('testsettings', 'core_enrol');
5910 $pluginmanager = core_plugin_manager::instance();
5912 $enrols_available = enrol_get_plugins(false);
5913 $active_enrols = enrol_get_plugins(true);
5915 $allenrols = array();
5916 foreach ($active_enrols as $key=>$enrol) {
5917 $allenrols[$key] = true;
5919 foreach ($enrols_available as $key=>$enrol) {
5920 $allenrols[$key] = true;
5922 // Now find all borked plugins and at least allow then to uninstall.
5923 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5924 foreach ($condidates as $candidate) {
5925 if (empty($allenrols[$candidate])) {
5926 $allenrols[$candidate] = true;
5930 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5931 $return .= $OUTPUT->box_start('generalbox enrolsui');
5933 $table = new html_table();
5934 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5935 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5936 $table->id = 'courseenrolmentplugins';
5937 $table->attributes['class'] = 'admintable generaltable';
5938 $table->data = array();
5940 // Iterate through enrol plugins and add to the display table.
5941 $updowncount = 1;
5942 $enrolcount = count($active_enrols);
5943 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5944 $printed = array();
5945 foreach($allenrols as $enrol => $unused) {
5946 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5947 $version = get_config('enrol_'.$enrol, 'version');
5948 if ($version === false) {
5949 $version = '';
5952 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5953 $name = get_string('pluginname', 'enrol_'.$enrol);
5954 } else {
5955 $name = $enrol;
5957 // Usage.
5958 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5959 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5960 $usage = "$ci / $cp";
5962 // Hide/show links.
5963 $class = '';
5964 if (isset($active_enrols[$enrol])) {
5965 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5966 $hideshow = "<a href=\"$aurl\">";
5967 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
5968 $enabled = true;
5969 $displayname = $name;
5970 } else if (isset($enrols_available[$enrol])) {
5971 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5972 $hideshow = "<a href=\"$aurl\">";
5973 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
5974 $enabled = false;
5975 $displayname = $name;
5976 $class = 'dimmed_text';
5977 } else {
5978 $hideshow = '';
5979 $enabled = false;
5980 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5982 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5983 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5984 } else {
5985 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5988 // Up/down link (only if enrol is enabled).
5989 $updown = '';
5990 if ($enabled) {
5991 if ($updowncount > 1) {
5992 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5993 $updown .= "<a href=\"$aurl\">";
5994 $updown .= $OUTPUT->pix_icon('t/up', $strup) . '</a>&nbsp;';
5995 } else {
5996 $updown .= $OUTPUT->spacer() . '&nbsp;';
5998 if ($updowncount < $enrolcount) {
5999 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
6000 $updown .= "<a href=\"$aurl\">";
6001 $updown .= $OUTPUT->pix_icon('t/down', $strdown) . '</a>&nbsp;';
6002 } else {
6003 $updown .= $OUTPUT->spacer() . '&nbsp;';
6005 ++$updowncount;
6008 // Add settings link.
6009 if (!$version) {
6010 $settings = '';
6011 } else if ($surl = $plugininfo->get_settings_url()) {
6012 $settings = html_writer::link($surl, $strsettings);
6013 } else {
6014 $settings = '';
6017 // Add uninstall info.
6018 $uninstall = '';
6019 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
6020 $uninstall = html_writer::link($uninstallurl, $struninstall);
6023 $test = '';
6024 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
6025 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
6026 $test = html_writer::link($testsettingsurl, $strtest);
6029 // Add a row to the table.
6030 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
6031 if ($class) {
6032 $row->attributes['class'] = $class;
6034 $table->data[] = $row;
6036 $printed[$enrol] = true;
6039 $return .= html_writer::table($table);
6040 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
6041 $return .= $OUTPUT->box_end();
6042 return highlight($query, $return);
6048 * Blocks manage page
6050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6052 class admin_page_manageblocks extends admin_externalpage {
6054 * Calls parent::__construct with specific arguments
6056 public function __construct() {
6057 global $CFG;
6058 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
6062 * Search for a specific block
6064 * @param string $query The string to search for
6065 * @return array
6067 public function search($query) {
6068 global $CFG, $DB;
6069 if ($result = parent::search($query)) {
6070 return $result;
6073 $found = false;
6074 if ($blocks = $DB->get_records('block')) {
6075 foreach ($blocks as $block) {
6076 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
6077 continue;
6079 if (strpos($block->name, $query) !== false) {
6080 $found = true;
6081 break;
6083 $strblockname = get_string('pluginname', 'block_'.$block->name);
6084 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
6085 $found = true;
6086 break;
6090 if ($found) {
6091 $result = new stdClass();
6092 $result->page = $this;
6093 $result->settings = array();
6094 return array($this->name => $result);
6095 } else {
6096 return array();
6102 * Message outputs configuration
6104 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6106 class admin_page_managemessageoutputs extends admin_externalpage {
6108 * Calls parent::__construct with specific arguments
6110 public function __construct() {
6111 global $CFG;
6112 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
6116 * Search for a specific message processor
6118 * @param string $query The string to search for
6119 * @return array
6121 public function search($query) {
6122 global $CFG, $DB;
6123 if ($result = parent::search($query)) {
6124 return $result;
6127 $found = false;
6128 if ($processors = get_message_processors()) {
6129 foreach ($processors as $processor) {
6130 if (!$processor->available) {
6131 continue;
6133 if (strpos($processor->name, $query) !== false) {
6134 $found = true;
6135 break;
6137 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
6138 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
6139 $found = true;
6140 break;
6144 if ($found) {
6145 $result = new stdClass();
6146 $result->page = $this;
6147 $result->settings = array();
6148 return array($this->name => $result);
6149 } else {
6150 return array();
6156 * Default message outputs configuration
6158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6160 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
6162 * Calls parent::__construct with specific arguments
6164 public function __construct() {
6165 global $CFG;
6166 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
6172 * Manage question behaviours page
6174 * @copyright 2011 The Open University
6175 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6177 class admin_page_manageqbehaviours extends admin_externalpage {
6179 * Constructor
6181 public function __construct() {
6182 global $CFG;
6183 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
6184 new moodle_url('/admin/qbehaviours.php'));
6188 * Search question behaviours for the specified string
6190 * @param string $query The string to search for in question behaviours
6191 * @return array
6193 public function search($query) {
6194 global $CFG;
6195 if ($result = parent::search($query)) {
6196 return $result;
6199 $found = false;
6200 require_once($CFG->dirroot . '/question/engine/lib.php');
6201 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
6202 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
6203 $query) !== false) {
6204 $found = true;
6205 break;
6208 if ($found) {
6209 $result = new stdClass();
6210 $result->page = $this;
6211 $result->settings = array();
6212 return array($this->name => $result);
6213 } else {
6214 return array();
6221 * Question type manage page
6223 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6225 class admin_page_manageqtypes extends admin_externalpage {
6227 * Calls parent::__construct with specific arguments
6229 public function __construct() {
6230 global $CFG;
6231 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
6232 new moodle_url('/admin/qtypes.php'));
6236 * Search question types for the specified string
6238 * @param string $query The string to search for in question types
6239 * @return array
6241 public function search($query) {
6242 global $CFG;
6243 if ($result = parent::search($query)) {
6244 return $result;
6247 $found = false;
6248 require_once($CFG->dirroot . '/question/engine/bank.php');
6249 foreach (question_bank::get_all_qtypes() as $qtype) {
6250 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
6251 $found = true;
6252 break;
6255 if ($found) {
6256 $result = new stdClass();
6257 $result->page = $this;
6258 $result->settings = array();
6259 return array($this->name => $result);
6260 } else {
6261 return array();
6267 class admin_page_manageportfolios extends admin_externalpage {
6269 * Calls parent::__construct with specific arguments
6271 public function __construct() {
6272 global $CFG;
6273 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
6274 "$CFG->wwwroot/$CFG->admin/portfolio.php");
6278 * Searches page for the specified string.
6279 * @param string $query The string to search for
6280 * @return bool True if it is found on this page
6282 public function search($query) {
6283 global $CFG;
6284 if ($result = parent::search($query)) {
6285 return $result;
6288 $found = false;
6289 $portfolios = core_component::get_plugin_list('portfolio');
6290 foreach ($portfolios as $p => $dir) {
6291 if (strpos($p, $query) !== false) {
6292 $found = true;
6293 break;
6296 if (!$found) {
6297 foreach (portfolio_instances(false, false) as $instance) {
6298 $title = $instance->get('name');
6299 if (strpos(core_text::strtolower($title), $query) !== false) {
6300 $found = true;
6301 break;
6306 if ($found) {
6307 $result = new stdClass();
6308 $result->page = $this;
6309 $result->settings = array();
6310 return array($this->name => $result);
6311 } else {
6312 return array();
6318 class admin_page_managerepositories extends admin_externalpage {
6320 * Calls parent::__construct with specific arguments
6322 public function __construct() {
6323 global $CFG;
6324 parent::__construct('managerepositories', get_string('manage',
6325 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6329 * Searches page for the specified string.
6330 * @param string $query The string to search for
6331 * @return bool True if it is found on this page
6333 public function search($query) {
6334 global $CFG;
6335 if ($result = parent::search($query)) {
6336 return $result;
6339 $found = false;
6340 $repositories= core_component::get_plugin_list('repository');
6341 foreach ($repositories as $p => $dir) {
6342 if (strpos($p, $query) !== false) {
6343 $found = true;
6344 break;
6347 if (!$found) {
6348 foreach (repository::get_types() as $instance) {
6349 $title = $instance->get_typename();
6350 if (strpos(core_text::strtolower($title), $query) !== false) {
6351 $found = true;
6352 break;
6357 if ($found) {
6358 $result = new stdClass();
6359 $result->page = $this;
6360 $result->settings = array();
6361 return array($this->name => $result);
6362 } else {
6363 return array();
6370 * Special class for authentication administration.
6372 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6374 class admin_setting_manageauths extends admin_setting {
6376 * Calls parent::__construct with specific arguments
6378 public function __construct() {
6379 $this->nosave = true;
6380 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6384 * Always returns true
6386 * @return true
6388 public function get_setting() {
6389 return true;
6393 * Always returns true
6395 * @return true
6397 public function get_defaultsetting() {
6398 return true;
6402 * Always returns '' and doesn't write anything
6404 * @return string Always returns ''
6406 public function write_setting($data) {
6407 // do not write any setting
6408 return '';
6412 * Search to find if Query is related to auth plugin
6414 * @param string $query The string to search for
6415 * @return bool true for related false for not
6417 public function is_related($query) {
6418 if (parent::is_related($query)) {
6419 return true;
6422 $authsavailable = core_component::get_plugin_list('auth');
6423 foreach ($authsavailable as $auth => $dir) {
6424 if (strpos($auth, $query) !== false) {
6425 return true;
6427 $authplugin = get_auth_plugin($auth);
6428 $authtitle = $authplugin->get_title();
6429 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6430 return true;
6433 return false;
6437 * Return XHTML to display control
6439 * @param mixed $data Unused
6440 * @param string $query
6441 * @return string highlight
6443 public function output_html($data, $query='') {
6444 global $CFG, $OUTPUT, $DB;
6446 // display strings
6447 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6448 'settings', 'edit', 'name', 'enable', 'disable',
6449 'up', 'down', 'none', 'users'));
6450 $txt->updown = "$txt->up/$txt->down";
6451 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6452 $txt->testsettings = get_string('testsettings', 'core_auth');
6454 $authsavailable = core_component::get_plugin_list('auth');
6455 get_enabled_auth_plugins(true); // fix the list of enabled auths
6456 if (empty($CFG->auth)) {
6457 $authsenabled = array();
6458 } else {
6459 $authsenabled = explode(',', $CFG->auth);
6462 // construct the display array, with enabled auth plugins at the top, in order
6463 $displayauths = array();
6464 $registrationauths = array();
6465 $registrationauths[''] = $txt->disable;
6466 $authplugins = array();
6467 foreach ($authsenabled as $auth) {
6468 $authplugin = get_auth_plugin($auth);
6469 $authplugins[$auth] = $authplugin;
6470 /// Get the auth title (from core or own auth lang files)
6471 $authtitle = $authplugin->get_title();
6472 /// Apply titles
6473 $displayauths[$auth] = $authtitle;
6474 if ($authplugin->can_signup()) {
6475 $registrationauths[$auth] = $authtitle;
6479 foreach ($authsavailable as $auth => $dir) {
6480 if (array_key_exists($auth, $displayauths)) {
6481 continue; //already in the list
6483 $authplugin = get_auth_plugin($auth);
6484 $authplugins[$auth] = $authplugin;
6485 /// Get the auth title (from core or own auth lang files)
6486 $authtitle = $authplugin->get_title();
6487 /// Apply titles
6488 $displayauths[$auth] = $authtitle;
6489 if ($authplugin->can_signup()) {
6490 $registrationauths[$auth] = $authtitle;
6494 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6495 $return .= $OUTPUT->box_start('generalbox authsui');
6497 $table = new html_table();
6498 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6499 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6500 $table->data = array();
6501 $table->attributes['class'] = 'admintable generaltable';
6502 $table->id = 'manageauthtable';
6504 //add always enabled plugins first
6505 $displayname = $displayauths['manual'];
6506 $settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6507 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6508 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6509 $displayname = $displayauths['nologin'];
6510 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6511 $table->data[] = array($displayname, $usercount, '', '', '', '', '');
6514 // iterate through auth plugins and add to the display table
6515 $updowncount = 1;
6516 $authcount = count($authsenabled);
6517 $url = "auth.php?sesskey=" . sesskey();
6518 foreach ($displayauths as $auth => $name) {
6519 if ($auth == 'manual' or $auth == 'nologin') {
6520 continue;
6522 $class = '';
6523 // hide/show link
6524 if (in_array($auth, $authsenabled)) {
6525 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6526 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6527 $enabled = true;
6528 $displayname = $name;
6530 else {
6531 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6532 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6533 $enabled = false;
6534 $displayname = $name;
6535 $class = 'dimmed_text';
6538 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6540 // up/down link (only if auth is enabled)
6541 $updown = '';
6542 if ($enabled) {
6543 if ($updowncount > 1) {
6544 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6545 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6547 else {
6548 $updown .= $OUTPUT->spacer() . '&nbsp;';
6550 if ($updowncount < $authcount) {
6551 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6552 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6554 else {
6555 $updown .= $OUTPUT->spacer() . '&nbsp;';
6557 ++ $updowncount;
6560 // settings link
6561 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6562 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6563 } else if (file_exists($CFG->dirroot.'/auth/'.$auth.'/config.html')) {
6564 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6565 } else {
6566 $settings = '';
6569 // Uninstall link.
6570 $uninstall = '';
6571 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6572 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6575 $test = '';
6576 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6577 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6578 $test = html_writer::link($testurl, $txt->testsettings);
6581 // Add a row to the table.
6582 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6583 if ($class) {
6584 $row->attributes['class'] = $class;
6586 $table->data[] = $row;
6588 $return .= html_writer::table($table);
6589 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6590 $return .= $OUTPUT->box_end();
6591 return highlight($query, $return);
6597 * Special class for authentication administration.
6599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6601 class admin_setting_manageeditors extends admin_setting {
6603 * Calls parent::__construct with specific arguments
6605 public function __construct() {
6606 $this->nosave = true;
6607 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6611 * Always returns true, does nothing
6613 * @return true
6615 public function get_setting() {
6616 return true;
6620 * Always returns true, does nothing
6622 * @return true
6624 public function get_defaultsetting() {
6625 return true;
6629 * Always returns '', does not write anything
6631 * @return string Always returns ''
6633 public function write_setting($data) {
6634 // do not write any setting
6635 return '';
6639 * Checks if $query is one of the available editors
6641 * @param string $query The string to search for
6642 * @return bool Returns true if found, false if not
6644 public function is_related($query) {
6645 if (parent::is_related($query)) {
6646 return true;
6649 $editors_available = editors_get_available();
6650 foreach ($editors_available as $editor=>$editorstr) {
6651 if (strpos($editor, $query) !== false) {
6652 return true;
6654 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6655 return true;
6658 return false;
6662 * Builds the XHTML to display the control
6664 * @param string $data Unused
6665 * @param string $query
6666 * @return string
6668 public function output_html($data, $query='') {
6669 global $CFG, $OUTPUT;
6671 // display strings
6672 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6673 'up', 'down', 'none'));
6674 $struninstall = get_string('uninstallplugin', 'core_admin');
6676 $txt->updown = "$txt->up/$txt->down";
6678 $editors_available = editors_get_available();
6679 $active_editors = explode(',', $CFG->texteditors);
6681 $active_editors = array_reverse($active_editors);
6682 foreach ($active_editors as $key=>$editor) {
6683 if (empty($editors_available[$editor])) {
6684 unset($active_editors[$key]);
6685 } else {
6686 $name = $editors_available[$editor];
6687 unset($editors_available[$editor]);
6688 $editors_available[$editor] = $name;
6691 if (empty($active_editors)) {
6692 //$active_editors = array('textarea');
6694 $editors_available = array_reverse($editors_available, true);
6695 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6696 $return .= $OUTPUT->box_start('generalbox editorsui');
6698 $table = new html_table();
6699 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6700 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6701 $table->id = 'editormanagement';
6702 $table->attributes['class'] = 'admintable generaltable';
6703 $table->data = array();
6705 // iterate through auth plugins and add to the display table
6706 $updowncount = 1;
6707 $editorcount = count($active_editors);
6708 $url = "editors.php?sesskey=" . sesskey();
6709 foreach ($editors_available as $editor => $name) {
6710 // hide/show link
6711 $class = '';
6712 if (in_array($editor, $active_editors)) {
6713 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6714 $hideshow .= $OUTPUT->pix_icon('t/hide', get_string('disable')) . '</a>';
6715 $enabled = true;
6716 $displayname = $name;
6718 else {
6719 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6720 $hideshow .= $OUTPUT->pix_icon('t/show', get_string('enable')) . '</a>';
6721 $enabled = false;
6722 $displayname = $name;
6723 $class = 'dimmed_text';
6726 // up/down link (only if auth is enabled)
6727 $updown = '';
6728 if ($enabled) {
6729 if ($updowncount > 1) {
6730 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6731 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
6733 else {
6734 $updown .= $OUTPUT->spacer() . '&nbsp;';
6736 if ($updowncount < $editorcount) {
6737 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6738 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
6740 else {
6741 $updown .= $OUTPUT->spacer() . '&nbsp;';
6743 ++ $updowncount;
6746 // settings link
6747 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6748 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6749 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6750 } else {
6751 $settings = '';
6754 $uninstall = '';
6755 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6756 $uninstall = html_writer::link($uninstallurl, $struninstall);
6759 // Add a row to the table.
6760 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6761 if ($class) {
6762 $row->attributes['class'] = $class;
6764 $table->data[] = $row;
6766 $return .= html_writer::table($table);
6767 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6768 $return .= $OUTPUT->box_end();
6769 return highlight($query, $return);
6774 * Special class for antiviruses administration.
6776 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6779 class admin_setting_manageantiviruses extends admin_setting {
6781 * Calls parent::__construct with specific arguments
6783 public function __construct() {
6784 $this->nosave = true;
6785 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6789 * Always returns true, does nothing
6791 * @return true
6793 public function get_setting() {
6794 return true;
6798 * Always returns true, does nothing
6800 * @return true
6802 public function get_defaultsetting() {
6803 return true;
6807 * Always returns '', does not write anything
6809 * @param string $data Unused
6810 * @return string Always returns ''
6812 public function write_setting($data) {
6813 // Do not write any setting.
6814 return '';
6818 * Checks if $query is one of the available editors
6820 * @param string $query The string to search for
6821 * @return bool Returns true if found, false if not
6823 public function is_related($query) {
6824 if (parent::is_related($query)) {
6825 return true;
6828 $antivirusesavailable = \core\antivirus\manager::get_available();
6829 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6830 if (strpos($antivirus, $query) !== false) {
6831 return true;
6833 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6834 return true;
6837 return false;
6841 * Builds the XHTML to display the control
6843 * @param string $data Unused
6844 * @param string $query
6845 * @return string
6847 public function output_html($data, $query='') {
6848 global $CFG, $OUTPUT;
6850 // Display strings.
6851 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6852 'up', 'down', 'none'));
6853 $struninstall = get_string('uninstallplugin', 'core_admin');
6855 $txt->updown = "$txt->up/$txt->down";
6857 $antivirusesavailable = \core\antivirus\manager::get_available();
6858 $activeantiviruses = explode(',', $CFG->antiviruses);
6860 $activeantiviruses = array_reverse($activeantiviruses);
6861 foreach ($activeantiviruses as $key => $antivirus) {
6862 if (empty($antivirusesavailable[$antivirus])) {
6863 unset($activeantiviruses[$key]);
6864 } else {
6865 $name = $antivirusesavailable[$antivirus];
6866 unset($antivirusesavailable[$antivirus]);
6867 $antivirusesavailable[$antivirus] = $name;
6870 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6871 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6872 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6874 $table = new html_table();
6875 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6876 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6877 $table->id = 'antivirusmanagement';
6878 $table->attributes['class'] = 'admintable generaltable';
6879 $table->data = array();
6881 // Iterate through auth plugins and add to the display table.
6882 $updowncount = 1;
6883 $antiviruscount = count($activeantiviruses);
6884 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6885 foreach ($antivirusesavailable as $antivirus => $name) {
6886 // Hide/show link.
6887 $class = '';
6888 if (in_array($antivirus, $activeantiviruses)) {
6889 $hideshowurl = $baseurl;
6890 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6891 $hideshowimg = $OUTPUT->pix_icon('t/hide', get_string('disable'));
6892 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6893 $enabled = true;
6894 $displayname = $name;
6895 } else {
6896 $hideshowurl = $baseurl;
6897 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6898 $hideshowimg = $OUTPUT->pix_icon('t/show', get_string('enable'));
6899 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6900 $enabled = false;
6901 $displayname = $name;
6902 $class = 'dimmed_text';
6905 // Up/down link.
6906 $updown = '';
6907 if ($enabled) {
6908 if ($updowncount > 1) {
6909 $updownurl = $baseurl;
6910 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6911 $updownimg = $OUTPUT->pix_icon('t/up', get_string('moveup'));
6912 $updown = html_writer::link($updownurl, $updownimg);
6913 } else {
6914 $updownimg = $OUTPUT->spacer();
6916 if ($updowncount < $antiviruscount) {
6917 $updownurl = $baseurl;
6918 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6919 $updownimg = $OUTPUT->pix_icon('t/down', get_string('movedown'));
6920 $updown = html_writer::link($updownurl, $updownimg);
6921 } else {
6922 $updownimg = $OUTPUT->spacer();
6924 ++ $updowncount;
6927 // Settings link.
6928 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6929 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6930 $settings = html_writer::link($eurl, $txt->settings);
6931 } else {
6932 $settings = '';
6935 $uninstall = '';
6936 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6937 $uninstall = html_writer::link($uninstallurl, $struninstall);
6940 // Add a row to the table.
6941 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6942 if ($class) {
6943 $row->attributes['class'] = $class;
6945 $table->data[] = $row;
6947 $return .= html_writer::table($table);
6948 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6949 $return .= $OUTPUT->box_end();
6950 return highlight($query, $return);
6955 * Special class for license administration.
6957 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6959 class admin_setting_managelicenses extends admin_setting {
6961 * Calls parent::__construct with specific arguments
6963 public function __construct() {
6964 $this->nosave = true;
6965 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6969 * Always returns true, does nothing
6971 * @return true
6973 public function get_setting() {
6974 return true;
6978 * Always returns true, does nothing
6980 * @return true
6982 public function get_defaultsetting() {
6983 return true;
6987 * Always returns '', does not write anything
6989 * @return string Always returns ''
6991 public function write_setting($data) {
6992 // do not write any setting
6993 return '';
6997 * Builds the XHTML to display the control
6999 * @param string $data Unused
7000 * @param string $query
7001 * @return string
7003 public function output_html($data, $query='') {
7004 global $CFG, $OUTPUT;
7005 require_once($CFG->libdir . '/licenselib.php');
7006 $url = "licenses.php?sesskey=" . sesskey();
7008 // display strings
7009 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
7010 $licenses = license_manager::get_licenses();
7012 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
7014 $return .= $OUTPUT->box_start('generalbox editorsui');
7016 $table = new html_table();
7017 $table->head = array($txt->name, $txt->enable);
7018 $table->colclasses = array('leftalign', 'centeralign');
7019 $table->id = 'availablelicenses';
7020 $table->attributes['class'] = 'admintable generaltable';
7021 $table->data = array();
7023 foreach ($licenses as $value) {
7024 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
7026 if ($value->enabled == 1) {
7027 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
7028 $OUTPUT->pix_icon('t/hide', get_string('disable')));
7029 } else {
7030 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
7031 $OUTPUT->pix_icon('t/show', get_string('enable')));
7034 if ($value->shortname == $CFG->sitedefaultlicense) {
7035 $displayname .= ' '.$OUTPUT->pix_icon('t/locked', get_string('default'));
7036 $hideshow = '';
7039 $enabled = true;
7041 $table->data[] =array($displayname, $hideshow);
7043 $return .= html_writer::table($table);
7044 $return .= $OUTPUT->box_end();
7045 return highlight($query, $return);
7050 * Course formats manager. Allows to enable/disable formats and jump to settings
7052 class admin_setting_manageformats extends admin_setting {
7055 * Calls parent::__construct with specific arguments
7057 public function __construct() {
7058 $this->nosave = true;
7059 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
7063 * Always returns true
7065 * @return true
7067 public function get_setting() {
7068 return true;
7072 * Always returns true
7074 * @return true
7076 public function get_defaultsetting() {
7077 return true;
7081 * Always returns '' and doesn't write anything
7083 * @param mixed $data string or array, must not be NULL
7084 * @return string Always returns ''
7086 public function write_setting($data) {
7087 // do not write any setting
7088 return '';
7092 * Search to find if Query is related to format plugin
7094 * @param string $query The string to search for
7095 * @return bool true for related false for not
7097 public function is_related($query) {
7098 if (parent::is_related($query)) {
7099 return true;
7101 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7102 foreach ($formats as $format) {
7103 if (strpos($format->component, $query) !== false ||
7104 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7105 return true;
7108 return false;
7112 * Return XHTML to display control
7114 * @param mixed $data Unused
7115 * @param string $query
7116 * @return string highlight
7118 public function output_html($data, $query='') {
7119 global $CFG, $OUTPUT;
7120 $return = '';
7121 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
7122 $return .= $OUTPUT->box_start('generalbox formatsui');
7124 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
7126 // display strings
7127 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7128 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7129 $txt->updown = "$txt->up/$txt->down";
7131 $table = new html_table();
7132 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7133 $table->align = array('left', 'center', 'center', 'center', 'center');
7134 $table->attributes['class'] = 'manageformattable generaltable admintable';
7135 $table->data = array();
7137 $cnt = 0;
7138 $defaultformat = get_config('moodlecourse', 'format');
7139 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7140 foreach ($formats as $format) {
7141 $url = new moodle_url('/admin/courseformats.php',
7142 array('sesskey' => sesskey(), 'format' => $format->name));
7143 $isdefault = '';
7144 $class = '';
7145 if ($format->is_enabled()) {
7146 $strformatname = $format->displayname;
7147 if ($defaultformat === $format->name) {
7148 $hideshow = $txt->default;
7149 } else {
7150 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7151 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7153 } else {
7154 $strformatname = $format->displayname;
7155 $class = 'dimmed_text';
7156 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7157 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7159 $updown = '';
7160 if ($cnt) {
7161 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7162 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7163 } else {
7164 $updown .= $spacer;
7166 if ($cnt < count($formats) - 1) {
7167 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7168 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7169 } else {
7170 $updown .= $spacer;
7172 $cnt++;
7173 $settings = '';
7174 if ($format->get_settings_url()) {
7175 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7177 $uninstall = '';
7178 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
7179 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7181 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7182 if ($class) {
7183 $row->attributes['class'] = $class;
7185 $table->data[] = $row;
7187 $return .= html_writer::table($table);
7188 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
7189 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
7190 $return .= $OUTPUT->box_end();
7191 return highlight($query, $return);
7196 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
7198 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
7199 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7201 class admin_setting_managedataformats extends admin_setting {
7204 * Calls parent::__construct with specific arguments
7206 public function __construct() {
7207 $this->nosave = true;
7208 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
7212 * Always returns true
7214 * @return true
7216 public function get_setting() {
7217 return true;
7221 * Always returns true
7223 * @return true
7225 public function get_defaultsetting() {
7226 return true;
7230 * Always returns '' and doesn't write anything
7232 * @param mixed $data string or array, must not be NULL
7233 * @return string Always returns ''
7235 public function write_setting($data) {
7236 // Do not write any setting.
7237 return '';
7241 * Search to find if Query is related to format plugin
7243 * @param string $query The string to search for
7244 * @return bool true for related false for not
7246 public function is_related($query) {
7247 if (parent::is_related($query)) {
7248 return true;
7250 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7251 foreach ($formats as $format) {
7252 if (strpos($format->component, $query) !== false ||
7253 strpos(core_text::strtolower($format->displayname), $query) !== false) {
7254 return true;
7257 return false;
7261 * Return XHTML to display control
7263 * @param mixed $data Unused
7264 * @param string $query
7265 * @return string highlight
7267 public function output_html($data, $query='') {
7268 global $CFG, $OUTPUT;
7269 $return = '';
7271 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
7273 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
7274 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7275 $txt->updown = "$txt->up/$txt->down";
7277 $table = new html_table();
7278 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7279 $table->align = array('left', 'center', 'center', 'center', 'center');
7280 $table->attributes['class'] = 'manageformattable generaltable admintable';
7281 $table->data = array();
7283 $cnt = 0;
7284 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7285 $totalenabled = 0;
7286 foreach ($formats as $format) {
7287 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7288 $totalenabled++;
7291 foreach ($formats as $format) {
7292 $status = $format->get_status();
7293 $url = new moodle_url('/admin/dataformats.php',
7294 array('sesskey' => sesskey(), 'name' => $format->name));
7296 $class = '';
7297 if ($format->is_enabled()) {
7298 $strformatname = $format->displayname;
7299 if ($totalenabled == 1&& $format->is_enabled()) {
7300 $hideshow = '';
7301 } else {
7302 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7303 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7305 } else {
7306 $class = 'dimmed_text';
7307 $strformatname = $format->displayname;
7308 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7309 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7312 $updown = '';
7313 if ($cnt) {
7314 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7315 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7316 } else {
7317 $updown .= $spacer;
7319 if ($cnt < count($formats) - 1) {
7320 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7321 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7322 } else {
7323 $updown .= $spacer;
7326 $uninstall = '';
7327 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7328 $uninstall = get_string('status_missing', 'core_plugin');
7329 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7330 $uninstall = get_string('status_new', 'core_plugin');
7331 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7332 if ($totalenabled != 1 || !$format->is_enabled()) {
7333 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7337 $settings = '';
7338 if ($format->get_settings_url()) {
7339 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7342 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7343 if ($class) {
7344 $row->attributes['class'] = $class;
7346 $table->data[] = $row;
7347 $cnt++;
7349 $return .= html_writer::table($table);
7350 return highlight($query, $return);
7355 * Special class for filter administration.
7357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7359 class admin_page_managefilters extends admin_externalpage {
7361 * Calls parent::__construct with specific arguments
7363 public function __construct() {
7364 global $CFG;
7365 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7369 * Searches all installed filters for specified filter
7371 * @param string $query The filter(string) to search for
7372 * @param string $query
7374 public function search($query) {
7375 global $CFG;
7376 if ($result = parent::search($query)) {
7377 return $result;
7380 $found = false;
7381 $filternames = filter_get_all_installed();
7382 foreach ($filternames as $path => $strfiltername) {
7383 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7384 $found = true;
7385 break;
7387 if (strpos($path, $query) !== false) {
7388 $found = true;
7389 break;
7393 if ($found) {
7394 $result = new stdClass;
7395 $result->page = $this;
7396 $result->settings = array();
7397 return array($this->name => $result);
7398 } else {
7399 return array();
7405 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7406 * Requires a get_rank method on the plugininfo class for sorting.
7408 * @copyright 2017 Damyon Wiese
7409 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7411 abstract class admin_setting_manage_plugins extends admin_setting {
7414 * Get the admin settings section name (just a unique string)
7416 * @return string
7418 public function get_section_name() {
7419 return 'manage' . $this->get_plugin_type() . 'plugins';
7423 * Get the admin settings section title (use get_string).
7425 * @return string
7427 abstract public function get_section_title();
7430 * Get the type of plugin to manage.
7432 * @return string
7434 abstract public function get_plugin_type();
7437 * Get the name of the second column.
7439 * @return string
7441 public function get_info_column_name() {
7442 return '';
7446 * Get the type of plugin to manage.
7448 * @param plugininfo The plugin info class.
7449 * @return string
7451 abstract public function get_info_column($plugininfo);
7454 * Calls parent::__construct with specific arguments
7456 public function __construct() {
7457 $this->nosave = true;
7458 parent::__construct($this->get_section_name(), $this->get_section_title(), '', '');
7462 * Always returns true, does nothing
7464 * @return true
7466 public function get_setting() {
7467 return true;
7471 * Always returns true, does nothing
7473 * @return true
7475 public function get_defaultsetting() {
7476 return true;
7480 * Always returns '', does not write anything
7482 * @param mixed $data
7483 * @return string Always returns ''
7485 public function write_setting($data) {
7486 // Do not write any setting.
7487 return '';
7491 * Checks if $query is one of the available plugins of this type
7493 * @param string $query The string to search for
7494 * @return bool Returns true if found, false if not
7496 public function is_related($query) {
7497 if (parent::is_related($query)) {
7498 return true;
7501 $query = core_text::strtolower($query);
7502 $plugins = core_plugin_manager::instance()->get_plugins_of_type($this->get_plugin_type());
7503 foreach ($plugins as $name => $plugin) {
7504 $localised = $plugin->displayname;
7505 if (strpos(core_text::strtolower($name), $query) !== false) {
7506 return true;
7508 if (strpos(core_text::strtolower($localised), $query) !== false) {
7509 return true;
7512 return false;
7516 * The URL for the management page for this plugintype.
7518 * @return moodle_url
7520 protected function get_manage_url() {
7521 return new moodle_url('/admin/updatesetting.php');
7525 * Builds the HTML to display the control.
7527 * @param string $data Unused
7528 * @param string $query
7529 * @return string
7531 public function output_html($data, $query = '') {
7532 global $CFG, $OUTPUT, $DB, $PAGE;
7534 $context = (object) [
7535 'manageurl' => new moodle_url($this->get_manage_url(), [
7536 'type' => $this->get_plugin_type(),
7537 'sesskey' => sesskey(),
7539 'infocolumnname' => $this->get_info_column_name(),
7540 'plugins' => [],
7543 $pluginmanager = core_plugin_manager::instance();
7544 $allplugins = $pluginmanager->get_plugins_of_type($this->get_plugin_type());
7545 $enabled = $pluginmanager->get_enabled_plugins($this->get_plugin_type());
7546 $plugins = array_merge($enabled, $allplugins);
7547 foreach ($plugins as $key => $plugin) {
7548 $pluginlink = new moodle_url($context->manageurl, ['plugin' => $key]);
7550 $pluginkey = (object) [
7551 'plugin' => $plugin->displayname,
7552 'enabled' => $plugin->is_enabled(),
7553 'togglelink' => '',
7554 'moveuplink' => '',
7555 'movedownlink' => '',
7556 'settingslink' => $plugin->get_settings_url(),
7557 'uninstalllink' => '',
7558 'info' => '',
7561 // Enable/Disable link.
7562 $togglelink = new moodle_url($pluginlink);
7563 if ($plugin->is_enabled()) {
7564 $toggletarget = false;
7565 $togglelink->param('action', 'disable');
7567 if (count($context->plugins)) {
7568 // This is not the first plugin.
7569 $pluginkey->moveuplink = new moodle_url($pluginlink, ['action' => 'up']);
7572 if (count($enabled) > count($context->plugins) + 1) {
7573 // This is not the last plugin.
7574 $pluginkey->movedownlink = new moodle_url($pluginlink, ['action' => 'down']);
7577 $pluginkey->info = $this->get_info_column($plugin);
7578 } else {
7579 $toggletarget = true;
7580 $togglelink->param('action', 'enable');
7583 $pluginkey->toggletarget = $toggletarget;
7584 $pluginkey->togglelink = $togglelink;
7586 $frankenstyle = $plugin->type . '_' . $plugin->name;
7587 if ($uninstalllink = core_plugin_manager::instance()->get_uninstall_url($frankenstyle, 'manage')) {
7588 // This plugin supports uninstallation.
7589 $pluginkey->uninstalllink = $uninstalllink;
7592 if (!empty($this->get_info_column_name())) {
7593 // This plugintype has an info column.
7594 $pluginkey->info = $this->get_info_column($plugin);
7597 $context->plugins[] = $pluginkey;
7600 $str = $OUTPUT->render_from_template('core_admin/setting_manage_plugins', $context);
7601 return highlight($query, $str);
7606 * Generic class for managing plugins in a table that allows re-ordering and enable/disable of each plugin.
7607 * Requires a get_rank method on the plugininfo class for sorting.
7609 * @copyright 2017 Andrew Nicols <andrew@nicols.co.uk>
7610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7612 class admin_setting_manage_fileconverter_plugins extends admin_setting_manage_plugins {
7613 public function get_section_title() {
7614 return get_string('type_fileconverter_plural', 'plugin');
7617 public function get_plugin_type() {
7618 return 'fileconverter';
7621 public function get_info_column_name() {
7622 return get_string('supportedconversions', 'plugin');
7625 public function get_info_column($plugininfo) {
7626 return $plugininfo->get_supported_conversions();
7631 * Special class for media player plugins management.
7633 * @copyright 2016 Marina Glancy
7634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7636 class admin_setting_managemediaplayers extends admin_setting {
7638 * Calls parent::__construct with specific arguments
7640 public function __construct() {
7641 $this->nosave = true;
7642 parent::__construct('managemediaplayers', get_string('managemediaplayers', 'media'), '', '');
7646 * Always returns true, does nothing
7648 * @return true
7650 public function get_setting() {
7651 return true;
7655 * Always returns true, does nothing
7657 * @return true
7659 public function get_defaultsetting() {
7660 return true;
7664 * Always returns '', does not write anything
7666 * @param mixed $data
7667 * @return string Always returns ''
7669 public function write_setting($data) {
7670 // Do not write any setting.
7671 return '';
7675 * Checks if $query is one of the available enrol plugins
7677 * @param string $query The string to search for
7678 * @return bool Returns true if found, false if not
7680 public function is_related($query) {
7681 if (parent::is_related($query)) {
7682 return true;
7685 $query = core_text::strtolower($query);
7686 $plugins = core_plugin_manager::instance()->get_plugins_of_type('media');
7687 foreach ($plugins as $name => $plugin) {
7688 $localised = $plugin->displayname;
7689 if (strpos(core_text::strtolower($name), $query) !== false) {
7690 return true;
7692 if (strpos(core_text::strtolower($localised), $query) !== false) {
7693 return true;
7696 return false;
7700 * Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7701 * @return \core\plugininfo\media[]
7703 protected function get_sorted_plugins() {
7704 $pluginmanager = core_plugin_manager::instance();
7706 $plugins = $pluginmanager->get_plugins_of_type('media');
7707 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7709 // Sort plugins so enabled plugins are displayed first and all others are displayed in the end sorted by rank.
7710 \core_collator::asort_objects_by_method($plugins, 'get_rank', \core_collator::SORT_NUMERIC);
7712 $order = array_values($enabledplugins);
7713 $order = array_merge($order, array_diff(array_reverse(array_keys($plugins)), $order));
7715 $sortedplugins = array();
7716 foreach ($order as $name) {
7717 $sortedplugins[$name] = $plugins[$name];
7720 return $sortedplugins;
7724 * Builds the XHTML to display the control
7726 * @param string $data Unused
7727 * @param string $query
7728 * @return string
7730 public function output_html($data, $query='') {
7731 global $CFG, $OUTPUT, $DB, $PAGE;
7733 // Display strings.
7734 $strup = get_string('up');
7735 $strdown = get_string('down');
7736 $strsettings = get_string('settings');
7737 $strenable = get_string('enable');
7738 $strdisable = get_string('disable');
7739 $struninstall = get_string('uninstallplugin', 'core_admin');
7740 $strversion = get_string('version');
7741 $strname = get_string('name');
7742 $strsupports = get_string('supports', 'core_media');
7744 $pluginmanager = core_plugin_manager::instance();
7746 $plugins = $this->get_sorted_plugins();
7747 $enabledplugins = $pluginmanager->get_enabled_plugins('media');
7749 $return = $OUTPUT->box_start('generalbox mediaplayersui');
7751 $table = new html_table();
7752 $table->head = array($strname, $strsupports, $strversion,
7753 $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
7754 $table->colclasses = array('leftalign', 'leftalign', 'centeralign',
7755 'centeralign', 'centeralign', 'centeralign', 'centeralign');
7756 $table->id = 'mediaplayerplugins';
7757 $table->attributes['class'] = 'admintable generaltable';
7758 $table->data = array();
7760 // Iterate through media plugins and add to the display table.
7761 $updowncount = 1;
7762 $url = new moodle_url('/admin/media.php', array('sesskey' => sesskey()));
7763 $printed = array();
7764 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7766 $usedextensions = [];
7767 foreach ($plugins as $name => $plugin) {
7768 $url->param('media', $name);
7769 $plugininfo = $pluginmanager->get_plugin_info('media_'.$name);
7770 $version = $plugininfo->versiondb;
7771 $supports = $plugininfo->supports($usedextensions);
7773 // Hide/show links.
7774 $class = '';
7775 if (!$plugininfo->is_installed_and_upgraded()) {
7776 $hideshow = '';
7777 $enabled = false;
7778 $displayname = '<span class="notifyproblem">'.$name.'</span>';
7779 } else {
7780 $enabled = $plugininfo->is_enabled();
7781 if ($enabled) {
7782 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'disable')),
7783 $OUTPUT->pix_icon('t/hide', $strdisable, 'moodle', array('class' => 'iconsmall')));
7784 } else {
7785 $hideshow = html_writer::link(new moodle_url($url, array('action' => 'enable')),
7786 $OUTPUT->pix_icon('t/show', $strenable, 'moodle', array('class' => 'iconsmall')));
7787 $class = 'dimmed_text';
7789 $displayname = $plugin->displayname;
7790 if (get_string_manager()->string_exists('pluginname_help', 'media_' . $name)) {
7791 $displayname .= '&nbsp;' . $OUTPUT->help_icon('pluginname', 'media_' . $name);
7794 if ($PAGE->theme->resolve_image_location('icon', 'media_' . $name, false)) {
7795 $icon = $OUTPUT->pix_icon('icon', '', 'media_' . $name, array('class' => 'icon pluginicon'));
7796 } else {
7797 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
7800 // Up/down link (only if enrol is enabled).
7801 $updown = '';
7802 if ($enabled) {
7803 if ($updowncount > 1) {
7804 $updown = html_writer::link(new moodle_url($url, array('action' => 'up')),
7805 $OUTPUT->pix_icon('t/up', $strup, 'moodle', array('class' => 'iconsmall')));
7806 } else {
7807 $updown = $spacer;
7809 if ($updowncount < count($enabledplugins)) {
7810 $updown .= html_writer::link(new moodle_url($url, array('action' => 'down')),
7811 $OUTPUT->pix_icon('t/down', $strdown, 'moodle', array('class' => 'iconsmall')));
7812 } else {
7813 $updown .= $spacer;
7815 ++$updowncount;
7818 $uninstall = '';
7819 $status = $plugininfo->get_status();
7820 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7821 $uninstall = get_string('status_missing', 'core_plugin') . '<br/>';
7823 if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7824 $uninstall = get_string('status_new', 'core_plugin');
7825 } else if ($uninstallurl = $pluginmanager->get_uninstall_url('media_'.$name, 'manage')) {
7826 $uninstall .= html_writer::link($uninstallurl, $struninstall);
7829 $settings = '';
7830 if ($plugininfo->get_settings_url()) {
7831 $settings = html_writer::link($plugininfo->get_settings_url(), $strsettings);
7834 // Add a row to the table.
7835 $row = new html_table_row(array($icon.$displayname, $supports, $version, $hideshow, $updown, $settings, $uninstall));
7836 if ($class) {
7837 $row->attributes['class'] = $class;
7839 $table->data[] = $row;
7841 $printed[$name] = true;
7844 $return .= html_writer::table($table);
7845 $return .= $OUTPUT->box_end();
7846 return highlight($query, $return);
7851 * Initialise admin page - this function does require login and permission
7852 * checks specified in page definition.
7854 * This function must be called on each admin page before other code.
7856 * @global moodle_page $PAGE
7858 * @param string $section name of page
7859 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7860 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7861 * added to the turn blocks editing on/off form, so this page reloads correctly.
7862 * @param string $actualurl if the actual page being viewed is not the normal one for this
7863 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7864 * @param array $options Additional options that can be specified for page setup.
7865 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7867 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7868 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7870 $PAGE->set_context(null); // hack - set context to something, by default to system context
7872 $site = get_site();
7873 require_login();
7875 if (!empty($options['pagelayout'])) {
7876 // A specific page layout has been requested.
7877 $PAGE->set_pagelayout($options['pagelayout']);
7878 } else if ($section === 'upgradesettings') {
7879 $PAGE->set_pagelayout('maintenance');
7880 } else {
7881 $PAGE->set_pagelayout('admin');
7884 $adminroot = admin_get_root(false, false); // settings not required for external pages
7885 $extpage = $adminroot->locate($section, true);
7887 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7888 // The requested section isn't in the admin tree
7889 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7890 if (!has_capability('moodle/site:config', context_system::instance())) {
7891 // The requested section could depend on a different capability
7892 // but most likely the user has inadequate capabilities
7893 print_error('accessdenied', 'admin');
7894 } else {
7895 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7899 // this eliminates our need to authenticate on the actual pages
7900 if (!$extpage->check_access()) {
7901 print_error('accessdenied', 'admin');
7902 die;
7905 navigation_node::require_admin_tree();
7907 // $PAGE->set_extra_button($extrabutton); TODO
7909 if (!$actualurl) {
7910 $actualurl = $extpage->url;
7913 $PAGE->set_url($actualurl, $extraurlparams);
7914 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7915 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7918 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7919 // During initial install.
7920 $strinstallation = get_string('installation', 'install');
7921 $strsettings = get_string('settings');
7922 $PAGE->navbar->add($strsettings);
7923 $PAGE->set_title($strinstallation);
7924 $PAGE->set_heading($strinstallation);
7925 $PAGE->set_cacheable(false);
7926 return;
7929 // Locate the current item on the navigation and make it active when found.
7930 $path = $extpage->path;
7931 $node = $PAGE->settingsnav;
7932 while ($node && count($path) > 0) {
7933 $node = $node->get(array_pop($path));
7935 if ($node) {
7936 $node->make_active();
7939 // Normal case.
7940 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7941 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7942 $USER->editing = $adminediting;
7945 $visiblepathtosection = array_reverse($extpage->visiblepath);
7947 if ($PAGE->user_allowed_editing()) {
7948 if ($PAGE->user_is_editing()) {
7949 $caption = get_string('blockseditoff');
7950 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7951 } else {
7952 $caption = get_string('blocksediton');
7953 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7955 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7958 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7959 $PAGE->set_heading($SITE->fullname);
7961 // prevent caching in nav block
7962 $PAGE->navigation->clear_cache();
7966 * Returns the reference to admin tree root
7968 * @return object admin_root object
7970 function admin_get_root($reload=false, $requirefulltree=true) {
7971 global $CFG, $DB, $OUTPUT;
7973 static $ADMIN = NULL;
7975 if (is_null($ADMIN)) {
7976 // create the admin tree!
7977 $ADMIN = new admin_root($requirefulltree);
7980 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7981 $ADMIN->purge_children($requirefulltree);
7984 if (!$ADMIN->loaded) {
7985 // we process this file first to create categories first and in correct order
7986 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7988 // now we process all other files in admin/settings to build the admin tree
7989 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7990 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7991 continue;
7993 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7994 // plugins are loaded last - they may insert pages anywhere
7995 continue;
7997 require($file);
7999 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
8001 $ADMIN->loaded = true;
8004 return $ADMIN;
8007 /// settings utility functions
8010 * This function applies default settings.
8012 * @param object $node, NULL means complete tree, null by default
8013 * @param bool $unconditional if true overrides all values with defaults, null buy default
8015 function admin_apply_default_settings($node=NULL, $unconditional=true) {
8016 global $CFG;
8018 if (is_null($node)) {
8019 core_plugin_manager::reset_caches();
8020 $node = admin_get_root(true, true);
8023 if ($node instanceof admin_category) {
8024 $entries = array_keys($node->children);
8025 foreach ($entries as $entry) {
8026 admin_apply_default_settings($node->children[$entry], $unconditional);
8029 } else if ($node instanceof admin_settingpage) {
8030 foreach ($node->settings as $setting) {
8031 if (!$unconditional and !is_null($setting->get_setting())) {
8032 //do not override existing defaults
8033 continue;
8035 $defaultsetting = $setting->get_defaultsetting();
8036 if (is_null($defaultsetting)) {
8037 // no value yet - default maybe applied after admin user creation or in upgradesettings
8038 continue;
8040 $setting->write_setting($defaultsetting);
8041 $setting->write_setting_flags(null);
8044 // Just in case somebody modifies the list of active plugins directly.
8045 core_plugin_manager::reset_caches();
8049 * Store changed settings, this function updates the errors variable in $ADMIN
8051 * @param object $formdata from form
8052 * @return int number of changed settings
8054 function admin_write_settings($formdata) {
8055 global $CFG, $SITE, $DB;
8057 $olddbsessions = !empty($CFG->dbsessions);
8058 $formdata = (array)$formdata;
8060 $data = array();
8061 foreach ($formdata as $fullname=>$value) {
8062 if (strpos($fullname, 's_') !== 0) {
8063 continue; // not a config value
8065 $data[$fullname] = $value;
8068 $adminroot = admin_get_root();
8069 $settings = admin_find_write_settings($adminroot, $data);
8071 $count = 0;
8072 foreach ($settings as $fullname=>$setting) {
8073 /** @var $setting admin_setting */
8074 $original = $setting->get_setting();
8075 $error = $setting->write_setting($data[$fullname]);
8076 if ($error !== '') {
8077 $adminroot->errors[$fullname] = new stdClass();
8078 $adminroot->errors[$fullname]->data = $data[$fullname];
8079 $adminroot->errors[$fullname]->id = $setting->get_id();
8080 $adminroot->errors[$fullname]->error = $error;
8081 } else {
8082 $setting->write_setting_flags($data);
8084 if ($setting->post_write_settings($original)) {
8085 $count++;
8089 if ($olddbsessions != !empty($CFG->dbsessions)) {
8090 require_logout();
8093 // Now update $SITE - just update the fields, in case other people have a
8094 // a reference to it (e.g. $PAGE, $COURSE).
8095 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
8096 foreach (get_object_vars($newsite) as $field => $value) {
8097 $SITE->$field = $value;
8100 // now reload all settings - some of them might depend on the changed
8101 admin_get_root(true);
8102 return $count;
8106 * Internal recursive function - finds all settings from submitted form
8108 * @param object $node Instance of admin_category, or admin_settingpage
8109 * @param array $data
8110 * @return array
8112 function admin_find_write_settings($node, $data) {
8113 $return = array();
8115 if (empty($data)) {
8116 return $return;
8119 if ($node instanceof admin_category) {
8120 if ($node->check_access()) {
8121 $entries = array_keys($node->children);
8122 foreach ($entries as $entry) {
8123 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
8127 } else if ($node instanceof admin_settingpage) {
8128 if ($node->check_access()) {
8129 foreach ($node->settings as $setting) {
8130 $fullname = $setting->get_full_name();
8131 if (array_key_exists($fullname, $data)) {
8132 $return[$fullname] = $setting;
8139 return $return;
8143 * Internal function - prints the search results
8145 * @param string $query String to search for
8146 * @return string empty or XHTML
8148 function admin_search_settings_html($query) {
8149 global $CFG, $OUTPUT, $PAGE;
8151 if (core_text::strlen($query) < 2) {
8152 return '';
8154 $query = core_text::strtolower($query);
8156 $adminroot = admin_get_root();
8157 $findings = $adminroot->search($query);
8158 $savebutton = false;
8160 $tpldata = (object) [
8161 'actionurl' => $PAGE->url->out(false),
8162 'results' => [],
8163 'sesskey' => sesskey(),
8166 foreach ($findings as $found) {
8167 $page = $found->page;
8168 $settings = $found->settings;
8169 if ($page->is_hidden()) {
8170 // hidden pages are not displayed in search results
8171 continue;
8174 $heading = highlight($query, $page->visiblename);
8175 $headingurl = null;
8176 if ($page instanceof admin_externalpage) {
8177 $headingurl = new moodle_url($page->url);
8178 } else if ($page instanceof admin_settingpage) {
8179 $headingurl = new moodle_url('/admin/settings.php', ['section' => $page->name]);
8180 } else {
8181 continue;
8184 $sectionsettings = [];
8185 if (!empty($settings)) {
8186 foreach ($settings as $setting) {
8187 if (empty($setting->nosave)) {
8188 $savebutton = true;
8190 $fullname = $setting->get_full_name();
8191 if (array_key_exists($fullname, $adminroot->errors)) {
8192 $data = $adminroot->errors[$fullname]->data;
8193 } else {
8194 $data = $setting->get_setting();
8195 // do not use defaults if settings not available - upgradesettings handles the defaults!
8197 $sectionsettings[] = $setting->output_html($data, $query);
8201 $tpldata->results[] = (object) [
8202 'title' => $heading,
8203 'url' => $headingurl->out(false),
8204 'settings' => $sectionsettings
8208 $tpldata->showsave = $savebutton;
8209 $tpldata->hasresults = !empty($tpldata->results);
8211 return $OUTPUT->render_from_template('core_admin/settings_search_results', $tpldata);
8215 * Internal function - returns arrays of html pages with uninitialised settings
8217 * @param object $node Instance of admin_category or admin_settingpage
8218 * @return array
8220 function admin_output_new_settings_by_page($node) {
8221 global $OUTPUT;
8222 $return = array();
8224 if ($node instanceof admin_category) {
8225 $entries = array_keys($node->children);
8226 foreach ($entries as $entry) {
8227 $return += admin_output_new_settings_by_page($node->children[$entry]);
8230 } else if ($node instanceof admin_settingpage) {
8231 $newsettings = array();
8232 foreach ($node->settings as $setting) {
8233 if (is_null($setting->get_setting())) {
8234 $newsettings[] = $setting;
8237 if (count($newsettings) > 0) {
8238 $adminroot = admin_get_root();
8239 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
8240 $page .= '<fieldset class="adminsettings">'."\n";
8241 foreach ($newsettings as $setting) {
8242 $fullname = $setting->get_full_name();
8243 if (array_key_exists($fullname, $adminroot->errors)) {
8244 $data = $adminroot->errors[$fullname]->data;
8245 } else {
8246 $data = $setting->get_setting();
8247 if (is_null($data)) {
8248 $data = $setting->get_defaultsetting();
8251 $page .= '<div class="clearer"><!-- --></div>'."\n";
8252 $page .= $setting->output_html($data);
8254 $page .= '</fieldset>';
8255 $return[$node->name] = $page;
8259 return $return;
8263 * Format admin settings
8265 * @param object $setting
8266 * @param string $title label element
8267 * @param string $form form fragment, html code - not highlighted automatically
8268 * @param string $description
8269 * @param mixed $label link label to id, true by default or string being the label to connect it to
8270 * @param string $warning warning text
8271 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
8272 * @param string $query search query to be highlighted
8273 * @return string XHTML
8275 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
8276 global $CFG, $OUTPUT;
8278 $context = (object) [
8279 'name' => empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name",
8280 'fullname' => $setting->get_full_name(),
8283 // Sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate.
8284 if ($label === true) {
8285 $context->labelfor = $setting->get_id();
8286 } else if ($label === false) {
8287 $context->labelfor = '';
8288 } else {
8289 $context->labelfor = $label;
8292 $form .= $setting->output_setting_flags();
8294 $context->warning = $warning;
8295 $context->override = '';
8296 if (empty($setting->plugin)) {
8297 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
8298 $context->override = get_string('configoverride', 'admin');
8300 } else {
8301 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
8302 $context->override = get_string('configoverride', 'admin');
8306 $defaults = array();
8307 if (!is_null($defaultinfo)) {
8308 if ($defaultinfo === '') {
8309 $defaultinfo = get_string('emptysettingvalue', 'admin');
8311 $defaults[] = $defaultinfo;
8314 $context->default = null;
8315 $setting->get_setting_flag_defaults($defaults);
8316 if (!empty($defaults)) {
8317 $defaultinfo = implode(', ', $defaults);
8318 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
8319 $context->default = get_string('defaultsettinginfo', 'admin', $defaultinfo);
8323 $context->error = '';
8324 $adminroot = admin_get_root();
8325 if (array_key_exists($context->fullname, $adminroot->errors)) {
8326 $context->error = $adminroot->errors[$context->fullname]->error;
8329 $context->id = 'admin-' . $setting->name;
8330 $context->title = highlightfast($query, $title);
8331 $context->name = highlightfast($query, $context->name);
8332 $context->description = highlight($query, markdown_to_html($description));
8333 $context->element = $form;
8334 $context->forceltr = $setting->get_force_ltr();
8336 return $OUTPUT->render_from_template('core_admin/setting', $context);
8340 * Based on find_new_settings{@link ()} in upgradesettings.php
8341 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
8343 * @param object $node Instance of admin_category, or admin_settingpage
8344 * @return boolean true if any settings haven't been initialised, false if they all have
8346 function any_new_admin_settings($node) {
8348 if ($node instanceof admin_category) {
8349 $entries = array_keys($node->children);
8350 foreach ($entries as $entry) {
8351 if (any_new_admin_settings($node->children[$entry])) {
8352 return true;
8356 } else if ($node instanceof admin_settingpage) {
8357 foreach ($node->settings as $setting) {
8358 if ($setting->get_setting() === NULL) {
8359 return true;
8364 return false;
8368 * Moved from admin/replace.php so that we can use this in cron
8370 * @param string $search string to look for
8371 * @param string $replace string to replace
8372 * @return bool success or fail
8374 function db_replace($search, $replace) {
8375 global $DB, $CFG, $OUTPUT;
8377 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
8378 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
8379 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
8380 'block_instances', '');
8382 // Turn off time limits, sometimes upgrades can be slow.
8383 core_php_time_limit::raise();
8385 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
8386 return false;
8388 foreach ($tables as $table) {
8390 if (in_array($table, $skiptables)) { // Don't process these
8391 continue;
8394 if ($columns = $DB->get_columns($table)) {
8395 $DB->set_debug(true);
8396 foreach ($columns as $column) {
8397 $DB->replace_all_text($table, $column, $search, $replace);
8399 $DB->set_debug(false);
8403 // delete modinfo caches
8404 rebuild_course_cache(0, true);
8406 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
8407 $blocks = core_component::get_plugin_list('block');
8408 foreach ($blocks as $blockname=>$fullblock) {
8409 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
8410 continue;
8413 if (!is_readable($fullblock.'/lib.php')) {
8414 continue;
8417 $function = 'block_'.$blockname.'_global_db_replace';
8418 include_once($fullblock.'/lib.php');
8419 if (!function_exists($function)) {
8420 continue;
8423 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
8424 $function($search, $replace);
8425 echo $OUTPUT->notification("...finished", 'notifysuccess');
8428 purge_all_caches();
8430 return true;
8434 * Manage repository settings
8436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8438 class admin_setting_managerepository extends admin_setting {
8439 /** @var string */
8440 private $baseurl;
8443 * calls parent::__construct with specific arguments
8445 public function __construct() {
8446 global $CFG;
8447 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
8448 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
8452 * Always returns true, does nothing
8454 * @return true
8456 public function get_setting() {
8457 return true;
8461 * Always returns true does nothing
8463 * @return true
8465 public function get_defaultsetting() {
8466 return true;
8470 * Always returns s_managerepository
8472 * @return string Always return 's_managerepository'
8474 public function get_full_name() {
8475 return 's_managerepository';
8479 * Always returns '' doesn't do anything
8481 public function write_setting($data) {
8482 $url = $this->baseurl . '&amp;new=' . $data;
8483 return '';
8484 // TODO
8485 // Should not use redirect and exit here
8486 // Find a better way to do this.
8487 // redirect($url);
8488 // exit;
8492 * Searches repository plugins for one that matches $query
8494 * @param string $query The string to search for
8495 * @return bool true if found, false if not
8497 public function is_related($query) {
8498 if (parent::is_related($query)) {
8499 return true;
8502 $repositories= core_component::get_plugin_list('repository');
8503 foreach ($repositories as $p => $dir) {
8504 if (strpos($p, $query) !== false) {
8505 return true;
8508 foreach (repository::get_types() as $instance) {
8509 $title = $instance->get_typename();
8510 if (strpos(core_text::strtolower($title), $query) !== false) {
8511 return true;
8514 return false;
8518 * Helper function that generates a moodle_url object
8519 * relevant to the repository
8522 function repository_action_url($repository) {
8523 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
8527 * Builds XHTML to display the control
8529 * @param string $data Unused
8530 * @param string $query
8531 * @return string XHTML
8533 public function output_html($data, $query='') {
8534 global $CFG, $USER, $OUTPUT;
8536 // Get strings that are used
8537 $strshow = get_string('on', 'repository');
8538 $strhide = get_string('off', 'repository');
8539 $strdelete = get_string('disabled', 'repository');
8541 $actionchoicesforexisting = array(
8542 'show' => $strshow,
8543 'hide' => $strhide,
8544 'delete' => $strdelete
8547 $actionchoicesfornew = array(
8548 'newon' => $strshow,
8549 'newoff' => $strhide,
8550 'delete' => $strdelete
8553 $return = '';
8554 $return .= $OUTPUT->box_start('generalbox');
8556 // Set strings that are used multiple times
8557 $settingsstr = get_string('settings');
8558 $disablestr = get_string('disable');
8560 // Table to list plug-ins
8561 $table = new html_table();
8562 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
8563 $table->align = array('left', 'center', 'center', 'center', 'center');
8564 $table->data = array();
8566 // Get list of used plug-ins
8567 $repositorytypes = repository::get_types();
8568 if (!empty($repositorytypes)) {
8569 // Array to store plugins being used
8570 $alreadyplugins = array();
8571 $totalrepositorytypes = count($repositorytypes);
8572 $updowncount = 1;
8573 foreach ($repositorytypes as $i) {
8574 $settings = '';
8575 $typename = $i->get_typename();
8576 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
8577 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
8578 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
8580 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
8581 // Calculate number of instances in order to display them for the Moodle administrator
8582 if (!empty($instanceoptionnames)) {
8583 $params = array();
8584 $params['context'] = array(context_system::instance());
8585 $params['onlyvisible'] = false;
8586 $params['type'] = $typename;
8587 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
8588 // site instances
8589 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
8590 $params['context'] = array();
8591 $instances = repository::static_function($typename, 'get_instances', $params);
8592 $courseinstances = array();
8593 $userinstances = array();
8595 foreach ($instances as $instance) {
8596 $repocontext = context::instance_by_id($instance->instance->contextid);
8597 if ($repocontext->contextlevel == CONTEXT_COURSE) {
8598 $courseinstances[] = $instance;
8599 } else if ($repocontext->contextlevel == CONTEXT_USER) {
8600 $userinstances[] = $instance;
8603 // course instances
8604 $instancenumber = count($courseinstances);
8605 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
8607 // user private instances
8608 $instancenumber = count($userinstances);
8609 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
8610 } else {
8611 $admininstancenumbertext = "";
8612 $courseinstancenumbertext = "";
8613 $userinstancenumbertext = "";
8616 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
8618 $settings .= $OUTPUT->container_start('mdl-left');
8619 $settings .= '<br/>';
8620 $settings .= $admininstancenumbertext;
8621 $settings .= '<br/>';
8622 $settings .= $courseinstancenumbertext;
8623 $settings .= '<br/>';
8624 $settings .= $userinstancenumbertext;
8625 $settings .= $OUTPUT->container_end();
8627 // Get the current visibility
8628 if ($i->get_visible()) {
8629 $currentaction = 'show';
8630 } else {
8631 $currentaction = 'hide';
8634 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
8636 // Display up/down link
8637 $updown = '';
8638 // Should be done with CSS instead.
8639 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
8641 if ($updowncount > 1) {
8642 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
8643 $updown .= $OUTPUT->pix_icon('t/up', get_string('moveup')) . '</a>&nbsp;';
8645 else {
8646 $updown .= $spacer;
8648 if ($updowncount < $totalrepositorytypes) {
8649 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
8650 $updown .= $OUTPUT->pix_icon('t/down', get_string('movedown')) . '</a>&nbsp;';
8652 else {
8653 $updown .= $spacer;
8656 $updowncount++;
8658 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
8660 if (!in_array($typename, $alreadyplugins)) {
8661 $alreadyplugins[] = $typename;
8666 // Get all the plugins that exist on disk
8667 $plugins = core_component::get_plugin_list('repository');
8668 if (!empty($plugins)) {
8669 foreach ($plugins as $plugin => $dir) {
8670 // Check that it has not already been listed
8671 if (!in_array($plugin, $alreadyplugins)) {
8672 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
8673 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
8678 $return .= html_writer::table($table);
8679 $return .= $OUTPUT->box_end();
8680 return highlight($query, $return);
8685 * Special checkbox for enable mobile web service
8686 * If enable then we store the service id of the mobile service into config table
8687 * If disable then we unstore the service id from the config table
8689 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
8691 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
8692 private $restuse;
8695 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
8697 * @return boolean
8699 private function is_protocol_cap_allowed() {
8700 global $DB, $CFG;
8702 // If the $this->restuse variable is not set, it needs to be set.
8703 if (empty($this->restuse) and $this->restuse!==false) {
8704 $params = array();
8705 $params['permission'] = CAP_ALLOW;
8706 $params['roleid'] = $CFG->defaultuserroleid;
8707 $params['capability'] = 'webservice/rest:use';
8708 $this->restuse = $DB->record_exists('role_capabilities', $params);
8711 return $this->restuse;
8715 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
8716 * @param type $status true to allow, false to not set
8718 private function set_protocol_cap($status) {
8719 global $CFG;
8720 if ($status and !$this->is_protocol_cap_allowed()) {
8721 //need to allow the cap
8722 $permission = CAP_ALLOW;
8723 $assign = true;
8724 } else if (!$status and $this->is_protocol_cap_allowed()){
8725 //need to disallow the cap
8726 $permission = CAP_INHERIT;
8727 $assign = true;
8729 if (!empty($assign)) {
8730 $systemcontext = context_system::instance();
8731 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8736 * Builds XHTML to display the control.
8737 * The main purpose of this overloading is to display a warning when https
8738 * is not supported by the server
8739 * @param string $data Unused
8740 * @param string $query
8741 * @return string XHTML
8743 public function output_html($data, $query='') {
8744 global $OUTPUT;
8745 $html = parent::output_html($data, $query);
8747 if ((string)$data === $this->yes) {
8748 $notifications = tool_mobile\api::get_potential_config_issues(); // Safe to call, plugin available if we reach here.
8749 foreach ($notifications as $notification) {
8750 $message = get_string($notification[0], $notification[1]);
8751 $html .= $OUTPUT->notification($message, \core\output\notification::NOTIFY_WARNING);
8755 return $html;
8759 * Retrieves the current setting using the objects name
8761 * @return string
8763 public function get_setting() {
8764 global $CFG;
8766 // First check if is not set.
8767 $result = $this->config_read($this->name);
8768 if (is_null($result)) {
8769 return null;
8772 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8773 // Or if web services aren't enabled this can't be,
8774 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8775 return 0;
8778 require_once($CFG->dirroot . '/webservice/lib.php');
8779 $webservicemanager = new webservice();
8780 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8781 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8782 return $result;
8783 } else {
8784 return 0;
8789 * Save the selected setting
8791 * @param string $data The selected site
8792 * @return string empty string or error message
8794 public function write_setting($data) {
8795 global $DB, $CFG;
8797 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8798 if (empty($CFG->defaultuserroleid)) {
8799 return '';
8802 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8804 require_once($CFG->dirroot . '/webservice/lib.php');
8805 $webservicemanager = new webservice();
8807 $updateprotocol = false;
8808 if ((string)$data === $this->yes) {
8809 //code run when enable mobile web service
8810 //enable web service systeme if necessary
8811 set_config('enablewebservices', true);
8813 //enable mobile service
8814 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8815 $mobileservice->enabled = 1;
8816 $webservicemanager->update_external_service($mobileservice);
8818 // Enable REST server.
8819 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8821 if (!in_array('rest', $activeprotocols)) {
8822 $activeprotocols[] = 'rest';
8823 $updateprotocol = true;
8826 if ($updateprotocol) {
8827 set_config('webserviceprotocols', implode(',', $activeprotocols));
8830 // Allow rest:use capability for authenticated user.
8831 $this->set_protocol_cap(true);
8833 } else {
8834 //disable web service system if no other services are enabled
8835 $otherenabledservices = $DB->get_records_select('external_services',
8836 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8837 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8838 if (empty($otherenabledservices)) {
8839 set_config('enablewebservices', false);
8841 // Also disable REST server.
8842 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8844 $protocolkey = array_search('rest', $activeprotocols);
8845 if ($protocolkey !== false) {
8846 unset($activeprotocols[$protocolkey]);
8847 $updateprotocol = true;
8850 if ($updateprotocol) {
8851 set_config('webserviceprotocols', implode(',', $activeprotocols));
8854 // Disallow rest:use capability for authenticated user.
8855 $this->set_protocol_cap(false);
8858 //disable the mobile service
8859 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8860 $mobileservice->enabled = 0;
8861 $webservicemanager->update_external_service($mobileservice);
8864 return (parent::write_setting($data));
8869 * Special class for management of external services
8871 * @author Petr Skoda (skodak)
8873 class admin_setting_manageexternalservices extends admin_setting {
8875 * Calls parent::__construct with specific arguments
8877 public function __construct() {
8878 $this->nosave = true;
8879 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8883 * Always returns true, does nothing
8885 * @return true
8887 public function get_setting() {
8888 return true;
8892 * Always returns true, does nothing
8894 * @return true
8896 public function get_defaultsetting() {
8897 return true;
8901 * Always returns '', does not write anything
8903 * @return string Always returns ''
8905 public function write_setting($data) {
8906 // do not write any setting
8907 return '';
8911 * Checks if $query is one of the available external services
8913 * @param string $query The string to search for
8914 * @return bool Returns true if found, false if not
8916 public function is_related($query) {
8917 global $DB;
8919 if (parent::is_related($query)) {
8920 return true;
8923 $services = $DB->get_records('external_services', array(), 'id, name');
8924 foreach ($services as $service) {
8925 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8926 return true;
8929 return false;
8933 * Builds the XHTML to display the control
8935 * @param string $data Unused
8936 * @param string $query
8937 * @return string
8939 public function output_html($data, $query='') {
8940 global $CFG, $OUTPUT, $DB;
8942 // display strings
8943 $stradministration = get_string('administration');
8944 $stredit = get_string('edit');
8945 $strservice = get_string('externalservice', 'webservice');
8946 $strdelete = get_string('delete');
8947 $strplugin = get_string('plugin', 'admin');
8948 $stradd = get_string('add');
8949 $strfunctions = get_string('functions', 'webservice');
8950 $strusers = get_string('users');
8951 $strserviceusers = get_string('serviceusers', 'webservice');
8953 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8954 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8955 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8957 // built in services
8958 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8959 $return = "";
8960 if (!empty($services)) {
8961 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8965 $table = new html_table();
8966 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8967 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8968 $table->id = 'builtinservices';
8969 $table->attributes['class'] = 'admintable externalservices generaltable';
8970 $table->data = array();
8972 // iterate through auth plugins and add to the display table
8973 foreach ($services as $service) {
8974 $name = $service->name;
8976 // hide/show link
8977 if ($service->enabled) {
8978 $displayname = "<span>$name</span>";
8979 } else {
8980 $displayname = "<span class=\"dimmed_text\">$name</span>";
8983 $plugin = $service->component;
8985 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8987 if ($service->restrictedusers) {
8988 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8989 } else {
8990 $users = get_string('allusers', 'webservice');
8993 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8995 // add a row to the table
8996 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
8998 $return .= html_writer::table($table);
9001 // Custom services
9002 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
9003 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
9005 $table = new html_table();
9006 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
9007 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
9008 $table->id = 'customservices';
9009 $table->attributes['class'] = 'admintable externalservices generaltable';
9010 $table->data = array();
9012 // iterate through auth plugins and add to the display table
9013 foreach ($services as $service) {
9014 $name = $service->name;
9016 // hide/show link
9017 if ($service->enabled) {
9018 $displayname = "<span>$name</span>";
9019 } else {
9020 $displayname = "<span class=\"dimmed_text\">$name</span>";
9023 // delete link
9024 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
9026 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
9028 if ($service->restrictedusers) {
9029 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
9030 } else {
9031 $users = get_string('allusers', 'webservice');
9034 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
9036 // add a row to the table
9037 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
9039 // add new custom service option
9040 $return .= html_writer::table($table);
9042 $return .= '<br />';
9043 // add a token to the table
9044 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
9046 return highlight($query, $return);
9051 * Special class for overview of external services
9053 * @author Jerome Mouneyrac
9055 class admin_setting_webservicesoverview extends admin_setting {
9058 * Calls parent::__construct with specific arguments
9060 public function __construct() {
9061 $this->nosave = true;
9062 parent::__construct('webservicesoverviewui',
9063 get_string('webservicesoverview', 'webservice'), '', '');
9067 * Always returns true, does nothing
9069 * @return true
9071 public function get_setting() {
9072 return true;
9076 * Always returns true, does nothing
9078 * @return true
9080 public function get_defaultsetting() {
9081 return true;
9085 * Always returns '', does not write anything
9087 * @return string Always returns ''
9089 public function write_setting($data) {
9090 // do not write any setting
9091 return '';
9095 * Builds the XHTML to display the control
9097 * @param string $data Unused
9098 * @param string $query
9099 * @return string
9101 public function output_html($data, $query='') {
9102 global $CFG, $OUTPUT;
9104 $return = "";
9105 $brtag = html_writer::empty_tag('br');
9107 /// One system controlling Moodle with Token
9108 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
9109 $table = new html_table();
9110 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9111 get_string('description'));
9112 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9113 $table->id = 'onesystemcontrol';
9114 $table->attributes['class'] = 'admintable wsoverview generaltable';
9115 $table->data = array();
9117 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
9118 . $brtag . $brtag;
9120 /// 1. Enable Web Services
9121 $row = array();
9122 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9123 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9124 array('href' => $url));
9125 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9126 if ($CFG->enablewebservices) {
9127 $status = get_string('yes');
9129 $row[1] = $status;
9130 $row[2] = get_string('enablewsdescription', 'webservice');
9131 $table->data[] = $row;
9133 /// 2. Enable protocols
9134 $row = array();
9135 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9136 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9137 array('href' => $url));
9138 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9139 //retrieve activated protocol
9140 $active_protocols = empty($CFG->webserviceprotocols) ?
9141 array() : explode(',', $CFG->webserviceprotocols);
9142 if (!empty($active_protocols)) {
9143 $status = "";
9144 foreach ($active_protocols as $protocol) {
9145 $status .= $protocol . $brtag;
9148 $row[1] = $status;
9149 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9150 $table->data[] = $row;
9152 /// 3. Create user account
9153 $row = array();
9154 $url = new moodle_url("/user/editadvanced.php?id=-1");
9155 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
9156 array('href' => $url));
9157 $row[1] = "";
9158 $row[2] = get_string('createuserdescription', 'webservice');
9159 $table->data[] = $row;
9161 /// 4. Add capability to users
9162 $row = array();
9163 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9164 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
9165 array('href' => $url));
9166 $row[1] = "";
9167 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
9168 $table->data[] = $row;
9170 /// 5. Select a web service
9171 $row = array();
9172 $url = new moodle_url("/admin/settings.php?section=externalservices");
9173 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9174 array('href' => $url));
9175 $row[1] = "";
9176 $row[2] = get_string('createservicedescription', 'webservice');
9177 $table->data[] = $row;
9179 /// 6. Add functions
9180 $row = array();
9181 $url = new moodle_url("/admin/settings.php?section=externalservices");
9182 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9183 array('href' => $url));
9184 $row[1] = "";
9185 $row[2] = get_string('addfunctionsdescription', 'webservice');
9186 $table->data[] = $row;
9188 /// 7. Add the specific user
9189 $row = array();
9190 $url = new moodle_url("/admin/settings.php?section=externalservices");
9191 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
9192 array('href' => $url));
9193 $row[1] = "";
9194 $row[2] = get_string('selectspecificuserdescription', 'webservice');
9195 $table->data[] = $row;
9197 /// 8. Create token for the specific user
9198 $row = array();
9199 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
9200 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
9201 array('href' => $url));
9202 $row[1] = "";
9203 $row[2] = get_string('createtokenforuserdescription', 'webservice');
9204 $table->data[] = $row;
9206 /// 9. Enable the documentation
9207 $row = array();
9208 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
9209 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
9210 array('href' => $url));
9211 $status = '<span class="warning">' . get_string('no') . '</span>';
9212 if ($CFG->enablewsdocumentation) {
9213 $status = get_string('yes');
9215 $row[1] = $status;
9216 $row[2] = get_string('enabledocumentationdescription', 'webservice');
9217 $table->data[] = $row;
9219 /// 10. Test the service
9220 $row = array();
9221 $url = new moodle_url("/admin/webservice/testclient.php");
9222 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9223 array('href' => $url));
9224 $row[1] = "";
9225 $row[2] = get_string('testwithtestclientdescription', 'webservice');
9226 $table->data[] = $row;
9228 $return .= html_writer::table($table);
9230 /// Users as clients with token
9231 $return .= $brtag . $brtag . $brtag;
9232 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
9233 $table = new html_table();
9234 $table->head = array(get_string('step', 'webservice'), get_string('status'),
9235 get_string('description'));
9236 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
9237 $table->id = 'userasclients';
9238 $table->attributes['class'] = 'admintable wsoverview generaltable';
9239 $table->data = array();
9241 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
9242 $brtag . $brtag;
9244 /// 1. Enable Web Services
9245 $row = array();
9246 $url = new moodle_url("/admin/search.php?query=enablewebservices");
9247 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
9248 array('href' => $url));
9249 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9250 if ($CFG->enablewebservices) {
9251 $status = get_string('yes');
9253 $row[1] = $status;
9254 $row[2] = get_string('enablewsdescription', 'webservice');
9255 $table->data[] = $row;
9257 /// 2. Enable protocols
9258 $row = array();
9259 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
9260 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
9261 array('href' => $url));
9262 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
9263 //retrieve activated protocol
9264 $active_protocols = empty($CFG->webserviceprotocols) ?
9265 array() : explode(',', $CFG->webserviceprotocols);
9266 if (!empty($active_protocols)) {
9267 $status = "";
9268 foreach ($active_protocols as $protocol) {
9269 $status .= $protocol . $brtag;
9272 $row[1] = $status;
9273 $row[2] = get_string('enableprotocolsdescription', 'webservice');
9274 $table->data[] = $row;
9277 /// 3. Select a web service
9278 $row = array();
9279 $url = new moodle_url("/admin/settings.php?section=externalservices");
9280 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
9281 array('href' => $url));
9282 $row[1] = "";
9283 $row[2] = get_string('createserviceforusersdescription', 'webservice');
9284 $table->data[] = $row;
9286 /// 4. Add functions
9287 $row = array();
9288 $url = new moodle_url("/admin/settings.php?section=externalservices");
9289 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
9290 array('href' => $url));
9291 $row[1] = "";
9292 $row[2] = get_string('addfunctionsdescription', 'webservice');
9293 $table->data[] = $row;
9295 /// 5. Add capability to users
9296 $row = array();
9297 $url = new moodle_url("/admin/roles/check.php?contextid=1");
9298 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
9299 array('href' => $url));
9300 $row[1] = "";
9301 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
9302 $table->data[] = $row;
9304 /// 6. Test the service
9305 $row = array();
9306 $url = new moodle_url("/admin/webservice/testclient.php");
9307 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
9308 array('href' => $url));
9309 $row[1] = "";
9310 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
9311 $table->data[] = $row;
9313 $return .= html_writer::table($table);
9315 return highlight($query, $return);
9322 * Special class for web service protocol administration.
9324 * @author Petr Skoda (skodak)
9326 class admin_setting_managewebserviceprotocols extends admin_setting {
9329 * Calls parent::__construct with specific arguments
9331 public function __construct() {
9332 $this->nosave = true;
9333 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
9337 * Always returns true, does nothing
9339 * @return true
9341 public function get_setting() {
9342 return true;
9346 * Always returns true, does nothing
9348 * @return true
9350 public function get_defaultsetting() {
9351 return true;
9355 * Always returns '', does not write anything
9357 * @return string Always returns ''
9359 public function write_setting($data) {
9360 // do not write any setting
9361 return '';
9365 * Checks if $query is one of the available webservices
9367 * @param string $query The string to search for
9368 * @return bool Returns true if found, false if not
9370 public function is_related($query) {
9371 if (parent::is_related($query)) {
9372 return true;
9375 $protocols = core_component::get_plugin_list('webservice');
9376 foreach ($protocols as $protocol=>$location) {
9377 if (strpos($protocol, $query) !== false) {
9378 return true;
9380 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
9381 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
9382 return true;
9385 return false;
9389 * Builds the XHTML to display the control
9391 * @param string $data Unused
9392 * @param string $query
9393 * @return string
9395 public function output_html($data, $query='') {
9396 global $CFG, $OUTPUT;
9398 // display strings
9399 $stradministration = get_string('administration');
9400 $strsettings = get_string('settings');
9401 $stredit = get_string('edit');
9402 $strprotocol = get_string('protocol', 'webservice');
9403 $strenable = get_string('enable');
9404 $strdisable = get_string('disable');
9405 $strversion = get_string('version');
9407 $protocols_available = core_component::get_plugin_list('webservice');
9408 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
9409 ksort($protocols_available);
9411 foreach ($active_protocols as $key=>$protocol) {
9412 if (empty($protocols_available[$protocol])) {
9413 unset($active_protocols[$key]);
9417 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
9418 $return .= $OUTPUT->box_start('generalbox webservicesui');
9420 $table = new html_table();
9421 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
9422 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
9423 $table->id = 'webserviceprotocols';
9424 $table->attributes['class'] = 'admintable generaltable';
9425 $table->data = array();
9427 // iterate through auth plugins and add to the display table
9428 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
9429 foreach ($protocols_available as $protocol => $location) {
9430 $name = get_string('pluginname', 'webservice_'.$protocol);
9432 $plugin = new stdClass();
9433 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
9434 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
9436 $version = isset($plugin->version) ? $plugin->version : '';
9438 // hide/show link
9439 if (in_array($protocol, $active_protocols)) {
9440 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
9441 $hideshow .= $OUTPUT->pix_icon('t/hide', $strdisable) . '</a>';
9442 $displayname = "<span>$name</span>";
9443 } else {
9444 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
9445 $hideshow .= $OUTPUT->pix_icon('t/show', $strenable) . '</a>';
9446 $displayname = "<span class=\"dimmed_text\">$name</span>";
9449 // settings link
9450 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
9451 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
9452 } else {
9453 $settings = '';
9456 // add a row to the table
9457 $table->data[] = array($displayname, $version, $hideshow, $settings);
9459 $return .= html_writer::table($table);
9460 $return .= get_string('configwebserviceplugins', 'webservice');
9461 $return .= $OUTPUT->box_end();
9463 return highlight($query, $return);
9469 * Special class for web service token administration.
9471 * @author Jerome Mouneyrac
9473 class admin_setting_managewebservicetokens extends admin_setting {
9476 * Calls parent::__construct with specific arguments
9478 public function __construct() {
9479 $this->nosave = true;
9480 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
9484 * Always returns true, does nothing
9486 * @return true
9488 public function get_setting() {
9489 return true;
9493 * Always returns true, does nothing
9495 * @return true
9497 public function get_defaultsetting() {
9498 return true;
9502 * Always returns '', does not write anything
9504 * @return string Always returns ''
9506 public function write_setting($data) {
9507 // do not write any setting
9508 return '';
9512 * Builds the XHTML to display the control
9514 * @param string $data Unused
9515 * @param string $query
9516 * @return string
9518 public function output_html($data, $query='') {
9519 global $CFG, $OUTPUT;
9521 require_once($CFG->dirroot . '/webservice/classes/token_table.php');
9522 $baseurl = new moodle_url('/' . $CFG->admin . '/settings.php?section=webservicetokens');
9524 $return = $OUTPUT->box_start('generalbox webservicestokenui');
9526 if (has_capability('moodle/webservice:managealltokens', context_system::instance())) {
9527 $return .= \html_writer::div(get_string('onlyseecreatedtokens', 'webservice'));
9530 $table = new \webservice\token_table('webservicetokens');
9531 $table->define_baseurl($baseurl);
9532 $table->attributes['class'] = 'admintable generaltable'; // Any need changing?
9533 $table->data = array();
9534 ob_start();
9535 $table->out(10, false);
9536 $tablehtml = ob_get_contents();
9537 ob_end_clean();
9538 $return .= $tablehtml;
9540 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
9542 $return .= $OUTPUT->box_end();
9543 // add a token to the table
9544 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
9545 $return .= get_string('add')."</a>";
9547 return highlight($query, $return);
9553 * Colour picker
9555 * @copyright 2010 Sam Hemelryk
9556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9558 class admin_setting_configcolourpicker extends admin_setting {
9561 * Information for previewing the colour
9563 * @var array|null
9565 protected $previewconfig = null;
9568 * Use default when empty.
9570 protected $usedefaultwhenempty = true;
9574 * @param string $name
9575 * @param string $visiblename
9576 * @param string $description
9577 * @param string $defaultsetting
9578 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
9580 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
9581 $usedefaultwhenempty = true) {
9582 $this->previewconfig = $previewconfig;
9583 $this->usedefaultwhenempty = $usedefaultwhenempty;
9584 parent::__construct($name, $visiblename, $description, $defaultsetting);
9585 $this->set_force_ltr(true);
9589 * Return the setting
9591 * @return mixed returns config if successful else null
9593 public function get_setting() {
9594 return $this->config_read($this->name);
9598 * Saves the setting
9600 * @param string $data
9601 * @return bool
9603 public function write_setting($data) {
9604 $data = $this->validate($data);
9605 if ($data === false) {
9606 return get_string('validateerror', 'admin');
9608 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
9612 * Validates the colour that was entered by the user
9614 * @param string $data
9615 * @return string|false
9617 protected function validate($data) {
9619 * List of valid HTML colour names
9621 * @var array
9623 $colornames = array(
9624 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
9625 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
9626 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
9627 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
9628 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
9629 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
9630 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
9631 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
9632 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
9633 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
9634 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
9635 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
9636 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
9637 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
9638 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
9639 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
9640 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
9641 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
9642 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
9643 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
9644 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
9645 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
9646 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
9647 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
9648 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
9649 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
9650 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
9651 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
9652 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
9653 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
9654 'whitesmoke', 'yellow', 'yellowgreen'
9657 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
9658 if (strpos($data, '#')!==0) {
9659 $data = '#'.$data;
9661 return $data;
9662 } else if (in_array(strtolower($data), $colornames)) {
9663 return $data;
9664 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9665 return $data;
9666 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9667 return $data;
9668 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9669 return $data;
9670 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9671 return $data;
9672 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9673 return $data;
9674 } else if (empty($data)) {
9675 if ($this->usedefaultwhenempty){
9676 return $this->defaultsetting;
9677 } else {
9678 return '';
9680 } else {
9681 return false;
9686 * Generates the HTML for the setting
9688 * @global moodle_page $PAGE
9689 * @global core_renderer $OUTPUT
9690 * @param string $data
9691 * @param string $query
9693 public function output_html($data, $query = '') {
9694 global $PAGE, $OUTPUT;
9696 $icon = new pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', ['class' => 'loadingicon']);
9697 $context = (object) [
9698 'id' => $this->get_id(),
9699 'name' => $this->get_full_name(),
9700 'value' => $data,
9701 'icon' => $icon->export_for_template($OUTPUT),
9702 'haspreviewconfig' => !empty($this->previewconfig),
9703 'forceltr' => $this->get_force_ltr()
9706 $element = $OUTPUT->render_from_template('core_admin/setting_configcolourpicker', $context);
9707 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9709 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '',
9710 $this->get_defaultsetting(), $query);
9717 * Class used for uploading of one file into file storage,
9718 * the file name is stored in config table.
9720 * Please note you need to implement your own '_pluginfile' callback function,
9721 * this setting only stores the file, it does not deal with file serving.
9723 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9726 class admin_setting_configstoredfile extends admin_setting {
9727 /** @var array file area options - should be one file only */
9728 protected $options;
9729 /** @var string name of the file area */
9730 protected $filearea;
9731 /** @var int intemid */
9732 protected $itemid;
9733 /** @var string used for detection of changes */
9734 protected $oldhashes;
9737 * Create new stored file setting.
9739 * @param string $name low level setting name
9740 * @param string $visiblename human readable setting name
9741 * @param string $description description of setting
9742 * @param mixed $filearea file area for file storage
9743 * @param int $itemid itemid for file storage
9744 * @param array $options file area options
9746 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9747 parent::__construct($name, $visiblename, $description, '');
9748 $this->filearea = $filearea;
9749 $this->itemid = $itemid;
9750 $this->options = (array)$options;
9754 * Applies defaults and returns all options.
9755 * @return array
9757 protected function get_options() {
9758 global $CFG;
9760 require_once("$CFG->libdir/filelib.php");
9761 require_once("$CFG->dirroot/repository/lib.php");
9762 $defaults = array(
9763 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9764 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9765 'context' => context_system::instance());
9766 foreach($this->options as $k => $v) {
9767 $defaults[$k] = $v;
9770 return $defaults;
9773 public function get_setting() {
9774 return $this->config_read($this->name);
9777 public function write_setting($data) {
9778 global $USER;
9780 // Let's not deal with validation here, this is for admins only.
9781 $current = $this->get_setting();
9782 if (empty($data) && $current === null) {
9783 // This will be the case when applying default settings (installation).
9784 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9785 } else if (!is_number($data)) {
9786 // Draft item id is expected here!
9787 return get_string('errorsetting', 'admin');
9790 $options = $this->get_options();
9791 $fs = get_file_storage();
9792 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9794 $this->oldhashes = null;
9795 if ($current) {
9796 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9797 if ($file = $fs->get_file_by_hash($hash)) {
9798 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9800 unset($file);
9803 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9804 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9805 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9806 // with an error because the draft area does not exist, as he did not use it.
9807 $usercontext = context_user::instance($USER->id);
9808 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9809 return get_string('errorsetting', 'admin');
9813 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9814 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9816 $filepath = '';
9817 if ($files) {
9818 /** @var stored_file $file */
9819 $file = reset($files);
9820 $filepath = $file->get_filepath().$file->get_filename();
9823 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9826 public function post_write_settings($original) {
9827 $options = $this->get_options();
9828 $fs = get_file_storage();
9829 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9831 $current = $this->get_setting();
9832 $newhashes = null;
9833 if ($current) {
9834 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9835 if ($file = $fs->get_file_by_hash($hash)) {
9836 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9838 unset($file);
9841 if ($this->oldhashes === $newhashes) {
9842 $this->oldhashes = null;
9843 return false;
9845 $this->oldhashes = null;
9847 $callbackfunction = $this->updatedcallback;
9848 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9849 $callbackfunction($this->get_full_name());
9851 return true;
9854 public function output_html($data, $query = '') {
9855 global $PAGE, $CFG;
9857 $options = $this->get_options();
9858 $id = $this->get_id();
9859 $elname = $this->get_full_name();
9860 $draftitemid = file_get_submitted_draft_itemid($elname);
9861 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9862 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9864 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9865 require_once("$CFG->dirroot/lib/form/filemanager.php");
9867 $fmoptions = new stdClass();
9868 $fmoptions->mainfile = $options['mainfile'];
9869 $fmoptions->maxbytes = $options['maxbytes'];
9870 $fmoptions->maxfiles = $options['maxfiles'];
9871 $fmoptions->client_id = uniqid();
9872 $fmoptions->itemid = $draftitemid;
9873 $fmoptions->subdirs = $options['subdirs'];
9874 $fmoptions->target = $id;
9875 $fmoptions->accepted_types = $options['accepted_types'];
9876 $fmoptions->return_types = $options['return_types'];
9877 $fmoptions->context = $options['context'];
9878 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9880 $fm = new form_filemanager($fmoptions);
9881 $output = $PAGE->get_renderer('core', 'files');
9882 $html = $output->render($fm);
9884 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9885 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9887 return format_admin_setting($this, $this->visiblename,
9888 '<div class="form-filemanager" data-fieldtype="filemanager">'.$html.'</div>',
9889 $this->description, true, '', '', $query);
9895 * Administration interface for user specified regular expressions for device detection.
9897 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9899 class admin_setting_devicedetectregex extends admin_setting {
9902 * Calls parent::__construct with specific args
9904 * @param string $name
9905 * @param string $visiblename
9906 * @param string $description
9907 * @param mixed $defaultsetting
9909 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9910 global $CFG;
9911 parent::__construct($name, $visiblename, $description, $defaultsetting);
9915 * Return the current setting(s)
9917 * @return array Current settings array
9919 public function get_setting() {
9920 global $CFG;
9922 $config = $this->config_read($this->name);
9923 if (is_null($config)) {
9924 return null;
9927 return $this->prepare_form_data($config);
9931 * Save selected settings
9933 * @param array $data Array of settings to save
9934 * @return bool
9936 public function write_setting($data) {
9937 if (empty($data)) {
9938 $data = array();
9941 if ($this->config_write($this->name, $this->process_form_data($data))) {
9942 return ''; // success
9943 } else {
9944 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9949 * Return XHTML field(s) for regexes
9951 * @param array $data Array of options to set in HTML
9952 * @return string XHTML string for the fields and wrapping div(s)
9954 public function output_html($data, $query='') {
9955 global $OUTPUT;
9957 $context = (object) [
9958 'expressions' => [],
9959 'name' => $this->get_full_name()
9962 if (empty($data)) {
9963 $looplimit = 1;
9964 } else {
9965 $looplimit = (count($data)/2)+1;
9968 for ($i=0; $i<$looplimit; $i++) {
9970 $expressionname = 'expression'.$i;
9972 if (!empty($data[$expressionname])){
9973 $expression = $data[$expressionname];
9974 } else {
9975 $expression = '';
9978 $valuename = 'value'.$i;
9980 if (!empty($data[$valuename])){
9981 $value = $data[$valuename];
9982 } else {
9983 $value= '';
9986 $context->expressions[] = [
9987 'index' => $i,
9988 'expression' => $expression,
9989 'value' => $value
9993 $element = $OUTPUT->render_from_template('core_admin/setting_devicedetectregex', $context);
9995 return format_admin_setting($this, $this->visiblename, $element, $this->description, false, '', null, $query);
9999 * Converts the string of regexes
10001 * @see self::process_form_data()
10002 * @param $regexes string of regexes
10003 * @return array of form fields and their values
10005 protected function prepare_form_data($regexes) {
10007 $regexes = json_decode($regexes);
10009 $form = array();
10011 $i = 0;
10013 foreach ($regexes as $value => $regex) {
10014 $expressionname = 'expression'.$i;
10015 $valuename = 'value'.$i;
10017 $form[$expressionname] = $regex;
10018 $form[$valuename] = $value;
10019 $i++;
10022 return $form;
10026 * Converts the data from admin settings form into a string of regexes
10028 * @see self::prepare_form_data()
10029 * @param array $data array of admin form fields and values
10030 * @return false|string of regexes
10032 protected function process_form_data(array $form) {
10034 $count = count($form); // number of form field values
10036 if ($count % 2) {
10037 // we must get five fields per expression
10038 return false;
10041 $regexes = array();
10042 for ($i = 0; $i < $count / 2; $i++) {
10043 $expressionname = "expression".$i;
10044 $valuename = "value".$i;
10046 $expression = trim($form['expression'.$i]);
10047 $value = trim($form['value'.$i]);
10049 if (empty($expression)){
10050 continue;
10053 $regexes[$value] = $expression;
10056 $regexes = json_encode($regexes);
10058 return $regexes;
10064 * Multiselect for current modules
10066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10068 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
10069 private $excludesystem;
10072 * Calls parent::__construct - note array $choices is not required
10074 * @param string $name setting name
10075 * @param string $visiblename localised setting name
10076 * @param string $description setting description
10077 * @param array $defaultsetting a plain array of default module ids
10078 * @param bool $excludesystem If true, excludes modules with 'system' archetype
10080 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
10081 $excludesystem = true) {
10082 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10083 $this->excludesystem = $excludesystem;
10087 * Loads an array of current module choices
10089 * @return bool always return true
10091 public function load_choices() {
10092 if (is_array($this->choices)) {
10093 return true;
10095 $this->choices = array();
10097 global $CFG, $DB;
10098 $records = $DB->get_records('modules', array('visible'=>1), 'name');
10099 foreach ($records as $record) {
10100 // Exclude modules if the code doesn't exist
10101 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
10102 // Also exclude system modules (if specified)
10103 if (!($this->excludesystem &&
10104 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
10105 MOD_ARCHETYPE_SYSTEM)) {
10106 $this->choices[$record->id] = $record->name;
10110 return true;
10115 * Admin setting to show if a php extension is enabled or not.
10117 * @copyright 2013 Damyon Wiese
10118 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10120 class admin_setting_php_extension_enabled extends admin_setting {
10122 /** @var string The name of the extension to check for */
10123 private $extension;
10126 * Calls parent::__construct with specific arguments
10128 public function __construct($name, $visiblename, $description, $extension) {
10129 $this->extension = $extension;
10130 $this->nosave = true;
10131 parent::__construct($name, $visiblename, $description, '');
10135 * Always returns true, does nothing
10137 * @return true
10139 public function get_setting() {
10140 return true;
10144 * Always returns true, does nothing
10146 * @return true
10148 public function get_defaultsetting() {
10149 return true;
10153 * Always returns '', does not write anything
10155 * @return string Always returns ''
10157 public function write_setting($data) {
10158 // Do not write any setting.
10159 return '';
10163 * Outputs the html for this setting.
10164 * @return string Returns an XHTML string
10166 public function output_html($data, $query='') {
10167 global $OUTPUT;
10169 $o = '';
10170 if (!extension_loaded($this->extension)) {
10171 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
10173 $o .= format_admin_setting($this, $this->visiblename, $warning);
10175 return $o;
10180 * Server timezone setting.
10182 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10184 * @author Petr Skoda <petr.skoda@totaralms.com>
10186 class admin_setting_servertimezone extends admin_setting_configselect {
10188 * Constructor.
10190 public function __construct() {
10191 $default = core_date::get_default_php_timezone();
10192 if ($default === 'UTC') {
10193 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
10194 $default = 'Europe/London';
10197 parent::__construct('timezone',
10198 new lang_string('timezone', 'core_admin'),
10199 new lang_string('configtimezone', 'core_admin'), $default, null);
10203 * Lazy load timezone options.
10204 * @return bool true if loaded, false if error
10206 public function load_choices() {
10207 global $CFG;
10208 if (is_array($this->choices)) {
10209 return true;
10212 $current = isset($CFG->timezone) ? $CFG->timezone : null;
10213 $this->choices = core_date::get_list_of_timezones($current, false);
10214 if ($current == 99) {
10215 // Do not show 99 unless it is current value, we want to get rid of it over time.
10216 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
10217 core_date::get_default_php_timezone());
10220 return true;
10225 * Forced user timezone setting.
10227 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
10228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10229 * @author Petr Skoda <petr.skoda@totaralms.com>
10231 class admin_setting_forcetimezone extends admin_setting_configselect {
10233 * Constructor.
10235 public function __construct() {
10236 parent::__construct('forcetimezone',
10237 new lang_string('forcetimezone', 'core_admin'),
10238 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
10242 * Lazy load timezone options.
10243 * @return bool true if loaded, false if error
10245 public function load_choices() {
10246 global $CFG;
10247 if (is_array($this->choices)) {
10248 return true;
10251 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
10252 $this->choices = core_date::get_list_of_timezones($current, true);
10253 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
10255 return true;
10261 * Search setup steps info.
10263 * @package core
10264 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
10265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10267 class admin_setting_searchsetupinfo extends admin_setting {
10270 * Calls parent::__construct with specific arguments
10272 public function __construct() {
10273 $this->nosave = true;
10274 parent::__construct('searchsetupinfo', '', '', '');
10278 * Always returns true, does nothing
10280 * @return true
10282 public function get_setting() {
10283 return true;
10287 * Always returns true, does nothing
10289 * @return true
10291 public function get_defaultsetting() {
10292 return true;
10296 * Always returns '', does not write anything
10298 * @param array $data
10299 * @return string Always returns ''
10301 public function write_setting($data) {
10302 // Do not write any setting.
10303 return '';
10307 * Builds the HTML to display the control
10309 * @param string $data Unused
10310 * @param string $query
10311 * @return string
10313 public function output_html($data, $query='') {
10314 global $CFG, $OUTPUT;
10316 $return = '';
10317 $brtag = html_writer::empty_tag('br');
10319 $searchareas = \core_search\manager::get_search_areas_list();
10320 $anyenabled = !empty(\core_search\manager::get_search_areas_list(true));
10321 $anyindexed = false;
10322 foreach ($searchareas as $areaid => $searcharea) {
10323 list($componentname, $varname) = $searcharea->get_config_var_name();
10324 if (get_config($componentname, $varname . '_indexingstart')) {
10325 $anyindexed = true;
10326 break;
10330 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
10332 $table = new html_table();
10333 $table->head = array(get_string('step', 'search'), get_string('status'));
10334 $table->colclasses = array('leftalign step', 'leftalign status');
10335 $table->id = 'searchsetup';
10336 $table->attributes['class'] = 'admintable generaltable';
10337 $table->data = array();
10339 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
10341 // Select a search engine.
10342 $row = array();
10343 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
10344 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
10345 array('href' => $url));
10347 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10348 if (!empty($CFG->searchengine)) {
10349 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
10350 array('class' => 'statusok'));
10353 $row[1] = $status;
10354 $table->data[] = $row;
10356 // Available areas.
10357 $row = array();
10358 $url = new moodle_url('/admin/searchareas.php');
10359 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
10360 array('href' => $url));
10362 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10363 if ($anyenabled) {
10364 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10367 $row[1] = $status;
10368 $table->data[] = $row;
10370 // Setup search engine.
10371 $row = array();
10372 if (empty($CFG->searchengine)) {
10373 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
10374 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10375 } else {
10376 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
10377 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
10378 array('href' => $url));
10379 // Check the engine status.
10380 $searchengine = \core_search\manager::search_engine_instance();
10381 try {
10382 $serverstatus = $searchengine->is_server_ready();
10383 } catch (\moodle_exception $e) {
10384 $serverstatus = $e->getMessage();
10386 if ($serverstatus === true) {
10387 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10388 } else {
10389 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
10391 $row[1] = $status;
10393 $table->data[] = $row;
10395 // Indexed data.
10396 $row = array();
10397 $url = new moodle_url('/admin/searchareas.php');
10398 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
10399 if ($anyindexed) {
10400 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10401 } else {
10402 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10404 $row[1] = $status;
10405 $table->data[] = $row;
10407 // Enable global search.
10408 $row = array();
10409 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
10410 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
10411 array('href' => $url));
10412 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
10413 if (\core_search\manager::is_global_search_enabled()) {
10414 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
10416 $row[1] = $status;
10417 $table->data[] = $row;
10419 $return .= html_writer::table($table);
10421 return highlight($query, $return);
10427 * Used to validate the contents of SCSS code and ensuring they are parsable.
10429 * It does not attempt to detect undefined SCSS variables because it is designed
10430 * to be used without knowledge of other config/scss included.
10432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10433 * @copyright 2016 Dan Poltawski <dan@moodle.com>
10435 class admin_setting_scsscode extends admin_setting_configtextarea {
10438 * Validate the contents of the SCSS to ensure its parsable. Does not
10439 * attempt to detect undefined scss variables.
10441 * @param string $data The scss code from text field.
10442 * @return mixed bool true for success or string:error on failure.
10444 public function validate($data) {
10445 if (empty($data)) {
10446 return true;
10449 $scss = new core_scss();
10450 try {
10451 $scss->compile($data);
10452 } catch (Leafo\ScssPhp\Exception\ParserException $e) {
10453 return get_string('scssinvalid', 'admin', $e->getMessage());
10454 } catch (Leafo\ScssPhp\Exception\CompilerException $e) {
10455 // Silently ignore this - it could be a scss variable defined from somewhere
10456 // else which we are not examining here.
10457 return true;
10460 return true;
10466 * Administration setting to define a list of file types.
10468 * @copyright 2016 Jonathon Fowler <fowlerj@usq.edu.au>
10469 * @copyright 2017 David Mudrák <david@moodle.com>
10470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10472 class admin_setting_filetypes extends admin_setting_configtext {
10474 /** @var array Allow selection from these file types only. */
10475 protected $onlytypes = [];
10477 /** @var bool Allow selection of 'All file types' (will be stored as '*'). */
10478 protected $allowall = true;
10480 /** @var core_form\filetypes_util instance to use as a helper. */
10481 protected $util = null;
10484 * Constructor.
10486 * @param string $name Unique ascii name like 'mycoresetting' or 'myplugin/mysetting'
10487 * @param string $visiblename Localised label of the setting
10488 * @param string $description Localised description of the setting
10489 * @param string $defaultsetting Default setting value.
10490 * @param array $options Setting widget options, an array with optional keys:
10491 * 'onlytypes' => array Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
10492 * 'allowall' => bool Allow to select 'All file types', defaults to true. Does not apply if onlytypes are set.
10494 public function __construct($name, $visiblename, $description, $defaultsetting = '', array $options = []) {
10496 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW);
10498 if (array_key_exists('onlytypes', $options) && is_array($options['onlytypes'])) {
10499 $this->onlytypes = $options['onlytypes'];
10502 if (!$this->onlytypes && array_key_exists('allowall', $options)) {
10503 $this->allowall = (bool)$options['allowall'];
10506 $this->util = new \core_form\filetypes_util();
10510 * Normalize the user's input and write it to the database as comma separated list.
10512 * Comma separated list as a text representation of the array was chosen to
10513 * make this compatible with how the $CFG->courseoverviewfilesext values are stored.
10515 * @param string $data Value submitted by the admin.
10516 * @return string Epty string if all good, error message otherwise.
10518 public function write_setting($data) {
10519 return parent::write_setting(implode(',', $this->util->normalize_file_types($data)));
10523 * Validate data before storage
10525 * @param string $data The setting values provided by the admin
10526 * @return bool|string True if ok, the string if error found
10528 public function validate($data) {
10530 // No need to call parent's validation here as we are PARAM_RAW.
10532 if ($this->util->is_whitelisted($data, $this->onlytypes)) {
10533 return true;
10535 } else {
10536 $troublemakers = $this->util->get_not_whitelisted($data, $this->onlytypes);
10537 return get_string('filetypesnotwhitelisted', 'core_form', implode(' ', $troublemakers));
10542 * Return an HTML string for the setting element.
10544 * @param string $data The current setting value
10545 * @param string $query Admin search query to be highlighted
10546 * @return string HTML to be displayed
10548 public function output_html($data, $query='') {
10549 global $OUTPUT, $PAGE;
10551 $default = $this->get_defaultsetting();
10552 $context = (object) [
10553 'id' => $this->get_id(),
10554 'name' => $this->get_full_name(),
10555 'value' => $data,
10556 'descriptions' => $this->util->describe_file_types($data),
10558 $element = $OUTPUT->render_from_template('core_admin/setting_filetypes', $context);
10560 $PAGE->requires->js_call_amd('core_form/filetypes', 'init', [
10561 $this->get_id(),
10562 $this->visiblename->out(),
10563 $this->onlytypes,
10564 $this->allowall,
10567 return format_admin_setting($this, $this->visiblename, $element, $this->description, true, '', $default, $query);
10571 * Should the values be always displayed in LTR mode?
10573 * We always return true here because these values are not RTL compatible.
10575 * @return bool True because these values are not RTL compatible.
10577 public function get_force_ltr() {
10578 return true;
10583 * Used to validate the content and format of the age of digital consent map and ensuring it is parsable.
10585 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10586 * @copyright 2018 Mihail Geshoski <mihail@moodle.com>
10588 class admin_setting_agedigitalconsentmap extends admin_setting_configtextarea {
10591 * Constructor.
10593 * @param string $name
10594 * @param string $visiblename
10595 * @param string $description
10596 * @param mixed $defaultsetting string or array
10597 * @param mixed $paramtype
10598 * @param string $cols
10599 * @param string $rows
10601 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype = PARAM_RAW,
10602 $cols = '60', $rows = '8') {
10603 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $cols, $rows);
10604 // Pre-set force LTR to false.
10605 $this->set_force_ltr(false);
10609 * Validate the content and format of the age of digital consent map to ensure it is parsable.
10611 * @param string $data The age of digital consent map from text field.
10612 * @return mixed bool true for success or string:error on failure.
10614 public function validate($data) {
10615 if (empty($data)) {
10616 return true;
10619 try {
10620 \core_auth\digital_consent::parse_age_digital_consent_map($data);
10621 } catch (\moodle_exception $e) {
10622 return get_string('invalidagedigitalconsent', 'admin', $e->getMessage());
10625 return true;
10630 * Selection of plugins that can work as site policy handlers
10632 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10633 * @copyright 2018 Marina Glancy
10635 class admin_settings_sitepolicy_handler_select extends admin_setting_configselect {
10638 * Constructor
10639 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting'
10640 * for ones in config_plugins.
10641 * @param string $visiblename localised
10642 * @param string $description long localised info
10643 * @param string $defaultsetting
10645 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
10646 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
10650 * Lazy-load the available choices for the select box
10652 public function load_choices() {
10653 if (during_initial_install()) {
10654 return false;
10656 if (is_array($this->choices)) {
10657 return true;
10660 $this->choices = ['' => new lang_string('sitepolicyhandlercore', 'core_admin')];
10661 $manager = new \core_privacy\local\sitepolicy\manager();
10662 $plugins = $manager->get_all_handlers();
10663 foreach ($plugins as $pname => $unused) {
10664 $this->choices[$pname] = new lang_string('sitepolicyhandlerplugin', 'core_admin',
10665 ['name' => new lang_string('pluginname', $pname), 'component' => $pname]);
10668 return true;