weekly release 3.1.3+
[moodle.git] / lib / adminlib.php
blob7af03b2911ba7d9c3c440b7645cc86cd0fc1de1f
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(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag areas, collections and instances associated with this plugin.
170 core_tag_area::uninstall($component);
172 // Custom plugin uninstall.
173 $plugindirectory = core_component::get_plugin_directory($type, $name);
174 $uninstalllib = $plugindirectory . '/db/uninstall.php';
175 if (file_exists($uninstalllib)) {
176 require_once($uninstalllib);
177 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
178 if (function_exists($uninstallfunction)) {
179 // Do not verify result, let plugin complain if necessary.
180 $uninstallfunction();
184 // Specific plugin type cleanup.
185 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
186 if ($plugininfo) {
187 $plugininfo->uninstall_cleanup();
188 core_plugin_manager::reset_caches();
190 $plugininfo = null;
192 // perform clean-up task common for all the plugin/subplugin types
194 //delete the web service functions and pre-built services
195 require_once($CFG->dirroot.'/lib/externallib.php');
196 external_delete_descriptions($component);
198 // delete calendar events
199 $DB->delete_records('event', array('modulename' => $pluginname));
201 // Delete scheduled tasks.
202 $DB->delete_records('task_scheduled', array('component' => $component));
204 // Delete Inbound Message datakeys.
205 $DB->delete_records_select('messageinbound_datakeys',
206 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($component));
208 // Delete Inbound Message handlers.
209 $DB->delete_records('messageinbound_handlers', array('component' => $component));
211 // delete all the logs
212 $DB->delete_records('log', array('module' => $pluginname));
214 // delete log_display information
215 $DB->delete_records('log_display', array('component' => $component));
217 // delete the module configuration records
218 unset_all_config_for_plugin($component);
219 if ($type === 'mod') {
220 unset_all_config_for_plugin($pluginname);
223 // delete message provider
224 message_provider_uninstall($component);
226 // delete the plugin tables
227 $xmldbfilepath = $plugindirectory . '/db/install.xml';
228 drop_plugin_tables($component, $xmldbfilepath, false);
229 if ($type === 'mod' or $type === 'block') {
230 // non-frankenstyle table prefixes
231 drop_plugin_tables($name, $xmldbfilepath, false);
234 // delete the capabilities that were defined by this module
235 capabilities_cleanup($component);
237 // remove event handlers and dequeue pending events
238 events_uninstall($component);
240 // Delete all remaining files in the filepool owned by the component.
241 $fs = get_file_storage();
242 $fs->delete_component_files($component);
244 // Finally purge all caches.
245 purge_all_caches();
247 // Invalidate the hash used for upgrade detections.
248 set_config('allversionshash', '');
250 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
254 * Returns the version of installed component
256 * @param string $component component name
257 * @param string $source either 'disk' or 'installed' - where to get the version information from
258 * @return string|bool version number or false if the component is not found
260 function get_component_version($component, $source='installed') {
261 global $CFG, $DB;
263 list($type, $name) = core_component::normalize_component($component);
265 // moodle core or a core subsystem
266 if ($type === 'core') {
267 if ($source === 'installed') {
268 if (empty($CFG->version)) {
269 return false;
270 } else {
271 return $CFG->version;
273 } else {
274 if (!is_readable($CFG->dirroot.'/version.php')) {
275 return false;
276 } else {
277 $version = null; //initialize variable for IDEs
278 include($CFG->dirroot.'/version.php');
279 return $version;
284 // activity module
285 if ($type === 'mod') {
286 if ($source === 'installed') {
287 if ($CFG->version < 2013092001.02) {
288 return $DB->get_field('modules', 'version', array('name'=>$name));
289 } else {
290 return get_config('mod_'.$name, 'version');
293 } else {
294 $mods = core_component::get_plugin_list('mod');
295 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
296 return false;
297 } else {
298 $plugin = new stdClass();
299 $plugin->version = null;
300 $module = $plugin;
301 include($mods[$name].'/version.php');
302 return $plugin->version;
307 // block
308 if ($type === 'block') {
309 if ($source === 'installed') {
310 if ($CFG->version < 2013092001.02) {
311 return $DB->get_field('block', 'version', array('name'=>$name));
312 } else {
313 return get_config('block_'.$name, 'version');
315 } else {
316 $blocks = core_component::get_plugin_list('block');
317 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
318 return false;
319 } else {
320 $plugin = new stdclass();
321 include($blocks[$name].'/version.php');
322 return $plugin->version;
327 // all other plugin types
328 if ($source === 'installed') {
329 return get_config($type.'_'.$name, 'version');
330 } else {
331 $plugins = core_component::get_plugin_list($type);
332 if (empty($plugins[$name])) {
333 return false;
334 } else {
335 $plugin = new stdclass();
336 include($plugins[$name].'/version.php');
337 return $plugin->version;
343 * Delete all plugin tables
345 * @param string $name Name of plugin, used as table prefix
346 * @param string $file Path to install.xml file
347 * @param bool $feedback defaults to true
348 * @return bool Always returns true
350 function drop_plugin_tables($name, $file, $feedback=true) {
351 global $CFG, $DB;
353 // first try normal delete
354 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
355 return true;
358 // then try to find all tables that start with name and are not in any xml file
359 $used_tables = get_used_table_names();
361 $tables = $DB->get_tables();
363 /// Iterate over, fixing id fields as necessary
364 foreach ($tables as $table) {
365 if (in_array($table, $used_tables)) {
366 continue;
369 if (strpos($table, $name) !== 0) {
370 continue;
373 // found orphan table --> delete it
374 if ($DB->get_manager()->table_exists($table)) {
375 $xmldb_table = new xmldb_table($table);
376 $DB->get_manager()->drop_table($xmldb_table);
380 return true;
384 * Returns names of all known tables == tables that moodle knows about.
386 * @return array Array of lowercase table names
388 function get_used_table_names() {
389 $table_names = array();
390 $dbdirs = get_db_directories();
392 foreach ($dbdirs as $dbdir) {
393 $file = $dbdir.'/install.xml';
395 $xmldb_file = new xmldb_file($file);
397 if (!$xmldb_file->fileExists()) {
398 continue;
401 $loaded = $xmldb_file->loadXMLStructure();
402 $structure = $xmldb_file->getStructure();
404 if ($loaded and $tables = $structure->getTables()) {
405 foreach($tables as $table) {
406 $table_names[] = strtolower($table->getName());
411 return $table_names;
415 * Returns list of all directories where we expect install.xml files
416 * @return array Array of paths
418 function get_db_directories() {
419 global $CFG;
421 $dbdirs = array();
423 /// First, the main one (lib/db)
424 $dbdirs[] = $CFG->libdir.'/db';
426 /// Then, all the ones defined by core_component::get_plugin_types()
427 $plugintypes = core_component::get_plugin_types();
428 foreach ($plugintypes as $plugintype => $pluginbasedir) {
429 if ($plugins = core_component::get_plugin_list($plugintype)) {
430 foreach ($plugins as $plugin => $plugindir) {
431 $dbdirs[] = $plugindir.'/db';
436 return $dbdirs;
440 * Try to obtain or release the cron lock.
441 * @param string $name name of lock
442 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
443 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
444 * @return bool true if lock obtained
446 function set_cron_lock($name, $until, $ignorecurrent=false) {
447 global $DB;
448 if (empty($name)) {
449 debugging("Tried to get a cron lock for a null fieldname");
450 return false;
453 // remove lock by force == remove from config table
454 if (is_null($until)) {
455 set_config($name, null);
456 return true;
459 if (!$ignorecurrent) {
460 // read value from db - other processes might have changed it
461 $value = $DB->get_field('config', 'value', array('name'=>$name));
463 if ($value and $value > time()) {
464 //lock active
465 return false;
469 set_config($name, $until);
470 return true;
474 * Test if and critical warnings are present
475 * @return bool
477 function admin_critical_warnings_present() {
478 global $SESSION;
480 if (!has_capability('moodle/site:config', context_system::instance())) {
481 return 0;
484 if (!isset($SESSION->admin_critical_warning)) {
485 $SESSION->admin_critical_warning = 0;
486 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
487 $SESSION->admin_critical_warning = 1;
491 return $SESSION->admin_critical_warning;
495 * Detects if float supports at least 10 decimal digits
497 * Detects if float supports at least 10 decimal digits
498 * and also if float-->string conversion works as expected.
500 * @return bool true if problem found
502 function is_float_problem() {
503 $num1 = 2009010200.01;
504 $num2 = 2009010200.02;
506 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
510 * Try to verify that dataroot is not accessible from web.
512 * Try to verify that dataroot is not accessible from web.
513 * It is not 100% correct but might help to reduce number of vulnerable sites.
514 * Protection from httpd.conf and .htaccess is not detected properly.
516 * @uses INSECURE_DATAROOT_WARNING
517 * @uses INSECURE_DATAROOT_ERROR
518 * @param bool $fetchtest try to test public access by fetching file, default false
519 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
521 function is_dataroot_insecure($fetchtest=false) {
522 global $CFG;
524 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
526 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
527 $rp = strrev(trim($rp, '/'));
528 $rp = explode('/', $rp);
529 foreach($rp as $r) {
530 if (strpos($siteroot, '/'.$r.'/') === 0) {
531 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
532 } else {
533 break; // probably alias root
537 $siteroot = strrev($siteroot);
538 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
540 if (strpos($dataroot, $siteroot) !== 0) {
541 return false;
544 if (!$fetchtest) {
545 return INSECURE_DATAROOT_WARNING;
548 // now try all methods to fetch a test file using http protocol
550 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
551 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
552 $httpdocroot = $matches[1];
553 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
554 make_upload_directory('diag');
555 $testfile = $CFG->dataroot.'/diag/public.txt';
556 if (!file_exists($testfile)) {
557 file_put_contents($testfile, 'test file, do not delete');
558 @chmod($testfile, $CFG->filepermissions);
560 $teststr = trim(file_get_contents($testfile));
561 if (empty($teststr)) {
562 // hmm, strange
563 return INSECURE_DATAROOT_WARNING;
566 $testurl = $datarooturl.'/diag/public.txt';
567 if (extension_loaded('curl') and
568 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
569 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
570 ($ch = @curl_init($testurl)) !== false) {
571 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
572 curl_setopt($ch, CURLOPT_HEADER, false);
573 $data = curl_exec($ch);
574 if (!curl_errno($ch)) {
575 $data = trim($data);
576 if ($data === $teststr) {
577 curl_close($ch);
578 return INSECURE_DATAROOT_ERROR;
581 curl_close($ch);
584 if ($data = @file_get_contents($testurl)) {
585 $data = trim($data);
586 if ($data === $teststr) {
587 return INSECURE_DATAROOT_ERROR;
591 preg_match('|https?://([^/]+)|i', $testurl, $matches);
592 $sitename = $matches[1];
593 $error = 0;
594 if ($fp = @fsockopen($sitename, 80, $error)) {
595 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
596 $localurl = $matches[1];
597 $out = "GET $localurl HTTP/1.1\r\n";
598 $out .= "Host: $sitename\r\n";
599 $out .= "Connection: Close\r\n\r\n";
600 fwrite($fp, $out);
601 $data = '';
602 $incoming = false;
603 while (!feof($fp)) {
604 if ($incoming) {
605 $data .= fgets($fp, 1024);
606 } else if (@fgets($fp, 1024) === "\r\n") {
607 $incoming = true;
610 fclose($fp);
611 $data = trim($data);
612 if ($data === $teststr) {
613 return INSECURE_DATAROOT_ERROR;
617 return INSECURE_DATAROOT_WARNING;
621 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
623 function enable_cli_maintenance_mode() {
624 global $CFG;
626 if (file_exists("$CFG->dataroot/climaintenance.html")) {
627 unlink("$CFG->dataroot/climaintenance.html");
630 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
631 $data = $CFG->maintenance_message;
632 $data = bootstrap_renderer::early_error_content($data, null, null, null);
633 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
635 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
636 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
638 } else {
639 $data = get_string('sitemaintenance', 'admin');
640 $data = bootstrap_renderer::early_error_content($data, null, null, null);
641 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
644 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
645 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
648 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
652 * Interface for anything appearing in the admin tree
654 * The interface that is implemented by anything that appears in the admin tree
655 * block. It forces inheriting classes to define a method for checking user permissions
656 * and methods for finding something in the admin tree.
658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
660 interface part_of_admin_tree {
663 * Finds a named part_of_admin_tree.
665 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
666 * and not parentable_part_of_admin_tree, then this function should only check if
667 * $this->name matches $name. If it does, it should return a reference to $this,
668 * otherwise, it should return a reference to NULL.
670 * If a class inherits parentable_part_of_admin_tree, this method should be called
671 * recursively on all child objects (assuming, of course, the parent object's name
672 * doesn't match the search criterion).
674 * @param string $name The internal name of the part_of_admin_tree we're searching for.
675 * @return mixed An object reference or a NULL reference.
677 public function locate($name);
680 * Removes named part_of_admin_tree.
682 * @param string $name The internal name of the part_of_admin_tree we want to remove.
683 * @return bool success.
685 public function prune($name);
688 * Search using query
689 * @param string $query
690 * @return mixed array-object structure of found settings and pages
692 public function search($query);
695 * Verifies current user's access to this part_of_admin_tree.
697 * Used to check if the current user has access to this part of the admin tree or
698 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
699 * then this method is usually just a call to has_capability() in the site context.
701 * If a class inherits parentable_part_of_admin_tree, this method should return the
702 * logical OR of the return of check_access() on all child objects.
704 * @return bool True if the user has access, false if she doesn't.
706 public function check_access();
709 * Mostly useful for removing of some parts of the tree in admin tree block.
711 * @return True is hidden from normal list view
713 public function is_hidden();
716 * Show we display Save button at the page bottom?
717 * @return bool
719 public function show_save();
724 * Interface implemented by any part_of_admin_tree that has children.
726 * The interface implemented by any part_of_admin_tree that can be a parent
727 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
728 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
729 * include an add method for adding other part_of_admin_tree objects as children.
731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 interface parentable_part_of_admin_tree extends part_of_admin_tree {
736 * Adds a part_of_admin_tree object to the admin tree.
738 * Used to add a part_of_admin_tree object to this object or a child of this
739 * object. $something should only be added if $destinationname matches
740 * $this->name. If it doesn't, add should be called on child objects that are
741 * also parentable_part_of_admin_tree's.
743 * $something should be appended as the last child in the $destinationname. If the
744 * $beforesibling is specified, $something should be prepended to it. If the given
745 * sibling is not found, $something should be appended to the end of $destinationname
746 * and a developer debugging message should be displayed.
748 * @param string $destinationname The internal name of the new parent for $something.
749 * @param part_of_admin_tree $something The object to be added.
750 * @return bool True on success, false on failure.
752 public function add($destinationname, $something, $beforesibling = null);
758 * The object used to represent folders (a.k.a. categories) in the admin tree block.
760 * Each admin_category object contains a number of part_of_admin_tree objects.
762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 class admin_category implements parentable_part_of_admin_tree {
766 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
767 protected $children;
768 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
769 public $name;
770 /** @var string The displayed name for this category. Usually obtained through get_string() */
771 public $visiblename;
772 /** @var bool Should this category be hidden in admin tree block? */
773 public $hidden;
774 /** @var mixed Either a string or an array or strings */
775 public $path;
776 /** @var mixed Either a string or an array or strings */
777 public $visiblepath;
779 /** @var array fast lookup category cache, all categories of one tree point to one cache */
780 protected $category_cache;
782 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
783 protected $sort = false;
784 /** @var bool If set to true children will be sorted in ascending order. */
785 protected $sortasc = true;
786 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
787 protected $sortsplit = true;
788 /** @var bool $sorted True if the children have been sorted and don't need resorting */
789 protected $sorted = false;
792 * Constructor for an empty admin category
794 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
795 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
796 * @param bool $hidden hide category in admin tree block, defaults to false
798 public function __construct($name, $visiblename, $hidden=false) {
799 $this->children = array();
800 $this->name = $name;
801 $this->visiblename = $visiblename;
802 $this->hidden = $hidden;
806 * Returns a reference to the part_of_admin_tree object with internal name $name.
808 * @param string $name The internal name of the object we want.
809 * @param bool $findpath initialize path and visiblepath arrays
810 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
811 * defaults to false
813 public function locate($name, $findpath=false) {
814 if (!isset($this->category_cache[$this->name])) {
815 // somebody much have purged the cache
816 $this->category_cache[$this->name] = $this;
819 if ($this->name == $name) {
820 if ($findpath) {
821 $this->visiblepath[] = $this->visiblename;
822 $this->path[] = $this->name;
824 return $this;
827 // quick category lookup
828 if (!$findpath and isset($this->category_cache[$name])) {
829 return $this->category_cache[$name];
832 $return = NULL;
833 foreach($this->children as $childid=>$unused) {
834 if ($return = $this->children[$childid]->locate($name, $findpath)) {
835 break;
839 if (!is_null($return) and $findpath) {
840 $return->visiblepath[] = $this->visiblename;
841 $return->path[] = $this->name;
844 return $return;
848 * Search using query
850 * @param string query
851 * @return mixed array-object structure of found settings and pages
853 public function search($query) {
854 $result = array();
855 foreach ($this->get_children() as $child) {
856 $subsearch = $child->search($query);
857 if (!is_array($subsearch)) {
858 debugging('Incorrect search result from '.$child->name);
859 continue;
861 $result = array_merge($result, $subsearch);
863 return $result;
867 * Removes part_of_admin_tree object with internal name $name.
869 * @param string $name The internal name of the object we want to remove.
870 * @return bool success
872 public function prune($name) {
874 if ($this->name == $name) {
875 return false; //can not remove itself
878 foreach($this->children as $precedence => $child) {
879 if ($child->name == $name) {
880 // clear cache and delete self
881 while($this->category_cache) {
882 // delete the cache, but keep the original array address
883 array_pop($this->category_cache);
885 unset($this->children[$precedence]);
886 return true;
887 } else if ($this->children[$precedence]->prune($name)) {
888 return true;
891 return false;
895 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
897 * By default the new part of the tree is appended as the last child of the parent. You
898 * can specify a sibling node that the new part should be prepended to. If the given
899 * sibling is not found, the part is appended to the end (as it would be by default) and
900 * a developer debugging message is displayed.
902 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
903 * @param string $destinationame The internal name of the immediate parent that we want for $something.
904 * @param mixed $something A part_of_admin_tree or setting instance to be added.
905 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
906 * @return bool True if successfully added, false if $something can not be added.
908 public function add($parentname, $something, $beforesibling = null) {
909 global $CFG;
911 $parent = $this->locate($parentname);
912 if (is_null($parent)) {
913 debugging('parent does not exist!');
914 return false;
917 if ($something instanceof part_of_admin_tree) {
918 if (!($parent instanceof parentable_part_of_admin_tree)) {
919 debugging('error - parts of tree can be inserted only into parentable parts');
920 return false;
922 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
923 // The name of the node is already used, simply warn the developer that this should not happen.
924 // It is intentional to check for the debug level before performing the check.
925 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
927 if (is_null($beforesibling)) {
928 // Append $something as the parent's last child.
929 $parent->children[] = $something;
930 } else {
931 if (!is_string($beforesibling) or trim($beforesibling) === '') {
932 throw new coding_exception('Unexpected value of the beforesibling parameter');
934 // Try to find the position of the sibling.
935 $siblingposition = null;
936 foreach ($parent->children as $childposition => $child) {
937 if ($child->name === $beforesibling) {
938 $siblingposition = $childposition;
939 break;
942 if (is_null($siblingposition)) {
943 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
944 $parent->children[] = $something;
945 } else {
946 $parent->children = array_merge(
947 array_slice($parent->children, 0, $siblingposition),
948 array($something),
949 array_slice($parent->children, $siblingposition)
953 if ($something instanceof admin_category) {
954 if (isset($this->category_cache[$something->name])) {
955 debugging('Duplicate admin category name: '.$something->name);
956 } else {
957 $this->category_cache[$something->name] = $something;
958 $something->category_cache =& $this->category_cache;
959 foreach ($something->children as $child) {
960 // just in case somebody already added subcategories
961 if ($child instanceof admin_category) {
962 if (isset($this->category_cache[$child->name])) {
963 debugging('Duplicate admin category name: '.$child->name);
964 } else {
965 $this->category_cache[$child->name] = $child;
966 $child->category_cache =& $this->category_cache;
972 return true;
974 } else {
975 debugging('error - can not add this element');
976 return false;
982 * Checks if the user has access to anything in this category.
984 * @return bool True if the user has access to at least one child in this category, false otherwise.
986 public function check_access() {
987 foreach ($this->children as $child) {
988 if ($child->check_access()) {
989 return true;
992 return false;
996 * Is this category hidden in admin tree block?
998 * @return bool True if hidden
1000 public function is_hidden() {
1001 return $this->hidden;
1005 * Show we display Save button at the page bottom?
1006 * @return bool
1008 public function show_save() {
1009 foreach ($this->children as $child) {
1010 if ($child->show_save()) {
1011 return true;
1014 return false;
1018 * Sets sorting on this category.
1020 * Please note this function doesn't actually do the sorting.
1021 * It can be called anytime.
1022 * Sorting occurs when the user calls get_children.
1023 * Code using the children array directly won't see the sorted results.
1025 * @param bool $sort If set to true children will be sorted, if false they won't be.
1026 * @param bool $asc If true sorting will be ascending, otherwise descending.
1027 * @param bool $split If true we sort pages and sub categories separately.
1029 public function set_sorting($sort, $asc = true, $split = true) {
1030 $this->sort = (bool)$sort;
1031 $this->sortasc = (bool)$asc;
1032 $this->sortsplit = (bool)$split;
1036 * Returns the children associated with this category.
1038 * @return part_of_admin_tree[]
1040 public function get_children() {
1041 // If we should sort and it hasn't already been sorted.
1042 if ($this->sort && !$this->sorted) {
1043 if ($this->sortsplit) {
1044 $categories = array();
1045 $pages = array();
1046 foreach ($this->children as $child) {
1047 if ($child instanceof admin_category) {
1048 $categories[] = $child;
1049 } else {
1050 $pages[] = $child;
1053 core_collator::asort_objects_by_property($categories, 'visiblename');
1054 core_collator::asort_objects_by_property($pages, 'visiblename');
1055 if (!$this->sortasc) {
1056 $categories = array_reverse($categories);
1057 $pages = array_reverse($pages);
1059 $this->children = array_merge($pages, $categories);
1060 } else {
1061 core_collator::asort_objects_by_property($this->children, 'visiblename');
1062 if (!$this->sortasc) {
1063 $this->children = array_reverse($this->children);
1066 $this->sorted = true;
1068 return $this->children;
1072 * Magically gets a property from this object.
1074 * @param $property
1075 * @return part_of_admin_tree[]
1076 * @throws coding_exception
1078 public function __get($property) {
1079 if ($property === 'children') {
1080 return $this->get_children();
1082 throw new coding_exception('Invalid property requested.');
1086 * Magically sets a property against this object.
1088 * @param string $property
1089 * @param mixed $value
1090 * @throws coding_exception
1092 public function __set($property, $value) {
1093 if ($property === 'children') {
1094 $this->sorted = false;
1095 $this->children = $value;
1096 } else {
1097 throw new coding_exception('Invalid property requested.');
1102 * Checks if an inaccessible property is set.
1104 * @param string $property
1105 * @return bool
1106 * @throws coding_exception
1108 public function __isset($property) {
1109 if ($property === 'children') {
1110 return isset($this->children);
1112 throw new coding_exception('Invalid property requested.');
1118 * Root of admin settings tree, does not have any parent.
1120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1122 class admin_root extends admin_category {
1123 /** @var array List of errors */
1124 public $errors;
1125 /** @var string search query */
1126 public $search;
1127 /** @var bool full tree flag - true means all settings required, false only pages required */
1128 public $fulltree;
1129 /** @var bool flag indicating loaded tree */
1130 public $loaded;
1131 /** @var mixed site custom defaults overriding defaults in settings files*/
1132 public $custom_defaults;
1135 * @param bool $fulltree true means all settings required,
1136 * false only pages required
1138 public function __construct($fulltree) {
1139 global $CFG;
1141 parent::__construct('root', get_string('administration'), false);
1142 $this->errors = array();
1143 $this->search = '';
1144 $this->fulltree = $fulltree;
1145 $this->loaded = false;
1147 $this->category_cache = array();
1149 // load custom defaults if found
1150 $this->custom_defaults = null;
1151 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1152 if (is_readable($defaultsfile)) {
1153 $defaults = array();
1154 include($defaultsfile);
1155 if (is_array($defaults) and count($defaults)) {
1156 $this->custom_defaults = $defaults;
1162 * Empties children array, and sets loaded to false
1164 * @param bool $requirefulltree
1166 public function purge_children($requirefulltree) {
1167 $this->children = array();
1168 $this->fulltree = ($requirefulltree || $this->fulltree);
1169 $this->loaded = false;
1170 //break circular dependencies - this helps PHP 5.2
1171 while($this->category_cache) {
1172 array_pop($this->category_cache);
1174 $this->category_cache = array();
1180 * Links external PHP pages into the admin tree.
1182 * See detailed usage example at the top of this document (adminlib.php)
1184 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1186 class admin_externalpage implements part_of_admin_tree {
1188 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1189 public $name;
1191 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1192 public $visiblename;
1194 /** @var string The external URL that we should link to when someone requests this external page. */
1195 public $url;
1197 /** @var string The role capability/permission a user must have to access this external page. */
1198 public $req_capability;
1200 /** @var object The context in which capability/permission should be checked, default is site context. */
1201 public $context;
1203 /** @var bool hidden in admin tree block. */
1204 public $hidden;
1206 /** @var mixed either string or array of string */
1207 public $path;
1209 /** @var array list of visible names of page parents */
1210 public $visiblepath;
1213 * Constructor for adding an external page into the admin tree.
1215 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1216 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1217 * @param string $url The external URL that we should link to when someone requests this external page.
1218 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1219 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1220 * @param stdClass $context The context the page relates to. Not sure what happens
1221 * if you specify something other than system or front page. Defaults to system.
1223 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1224 $this->name = $name;
1225 $this->visiblename = $visiblename;
1226 $this->url = $url;
1227 if (is_array($req_capability)) {
1228 $this->req_capability = $req_capability;
1229 } else {
1230 $this->req_capability = array($req_capability);
1232 $this->hidden = $hidden;
1233 $this->context = $context;
1237 * Returns a reference to the part_of_admin_tree object with internal name $name.
1239 * @param string $name The internal name of the object we want.
1240 * @param bool $findpath defaults to false
1241 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1243 public function locate($name, $findpath=false) {
1244 if ($this->name == $name) {
1245 if ($findpath) {
1246 $this->visiblepath = array($this->visiblename);
1247 $this->path = array($this->name);
1249 return $this;
1250 } else {
1251 $return = NULL;
1252 return $return;
1257 * This function always returns false, required function by interface
1259 * @param string $name
1260 * @return false
1262 public function prune($name) {
1263 return false;
1267 * Search using query
1269 * @param string $query
1270 * @return mixed array-object structure of found settings and pages
1272 public function search($query) {
1273 $found = false;
1274 if (strpos(strtolower($this->name), $query) !== false) {
1275 $found = true;
1276 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1277 $found = true;
1279 if ($found) {
1280 $result = new stdClass();
1281 $result->page = $this;
1282 $result->settings = array();
1283 return array($this->name => $result);
1284 } else {
1285 return array();
1290 * Determines if the current user has access to this external page based on $this->req_capability.
1292 * @return bool True if user has access, false otherwise.
1294 public function check_access() {
1295 global $CFG;
1296 $context = empty($this->context) ? context_system::instance() : $this->context;
1297 foreach($this->req_capability as $cap) {
1298 if (has_capability($cap, $context)) {
1299 return true;
1302 return false;
1306 * Is this external page hidden in admin tree block?
1308 * @return bool True if hidden
1310 public function is_hidden() {
1311 return $this->hidden;
1315 * Show we display Save button at the page bottom?
1316 * @return bool
1318 public function show_save() {
1319 return false;
1325 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1327 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1329 class admin_settingpage implements part_of_admin_tree {
1331 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1332 public $name;
1334 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1335 public $visiblename;
1337 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1338 public $settings;
1340 /** @var string The role capability/permission a user must have to access this external page. */
1341 public $req_capability;
1343 /** @var object The context in which capability/permission should be checked, default is site context. */
1344 public $context;
1346 /** @var bool hidden in admin tree block. */
1347 public $hidden;
1349 /** @var mixed string of paths or array of strings of paths */
1350 public $path;
1352 /** @var array list of visible names of page parents */
1353 public $visiblepath;
1356 * see admin_settingpage for details of this function
1358 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1359 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1360 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1361 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1362 * @param stdClass $context The context the page relates to. Not sure what happens
1363 * if you specify something other than system or front page. Defaults to system.
1365 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1366 $this->settings = new stdClass();
1367 $this->name = $name;
1368 $this->visiblename = $visiblename;
1369 if (is_array($req_capability)) {
1370 $this->req_capability = $req_capability;
1371 } else {
1372 $this->req_capability = array($req_capability);
1374 $this->hidden = $hidden;
1375 $this->context = $context;
1379 * see admin_category
1381 * @param string $name
1382 * @param bool $findpath
1383 * @return mixed Object (this) if name == this->name, else returns null
1385 public function locate($name, $findpath=false) {
1386 if ($this->name == $name) {
1387 if ($findpath) {
1388 $this->visiblepath = array($this->visiblename);
1389 $this->path = array($this->name);
1391 return $this;
1392 } else {
1393 $return = NULL;
1394 return $return;
1399 * Search string in settings page.
1401 * @param string $query
1402 * @return array
1404 public function search($query) {
1405 $found = array();
1407 foreach ($this->settings as $setting) {
1408 if ($setting->is_related($query)) {
1409 $found[] = $setting;
1413 if ($found) {
1414 $result = new stdClass();
1415 $result->page = $this;
1416 $result->settings = $found;
1417 return array($this->name => $result);
1420 $found = false;
1421 if (strpos(strtolower($this->name), $query) !== false) {
1422 $found = true;
1423 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1424 $found = true;
1426 if ($found) {
1427 $result = new stdClass();
1428 $result->page = $this;
1429 $result->settings = array();
1430 return array($this->name => $result);
1431 } else {
1432 return array();
1437 * This function always returns false, required by interface
1439 * @param string $name
1440 * @return bool Always false
1442 public function prune($name) {
1443 return false;
1447 * adds an admin_setting to this admin_settingpage
1449 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1450 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1452 * @param object $setting is the admin_setting object you want to add
1453 * @return bool true if successful, false if not
1455 public function add($setting) {
1456 if (!($setting instanceof admin_setting)) {
1457 debugging('error - not a setting instance');
1458 return false;
1461 $name = $setting->name;
1462 if ($setting->plugin) {
1463 $name = $setting->plugin . $name;
1465 $this->settings->{$name} = $setting;
1466 return true;
1470 * see admin_externalpage
1472 * @return bool Returns true for yes false for no
1474 public function check_access() {
1475 global $CFG;
1476 $context = empty($this->context) ? context_system::instance() : $this->context;
1477 foreach($this->req_capability as $cap) {
1478 if (has_capability($cap, $context)) {
1479 return true;
1482 return false;
1486 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1487 * @return string Returns an XHTML string
1489 public function output_html() {
1490 $adminroot = admin_get_root();
1491 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1492 foreach($this->settings as $setting) {
1493 $fullname = $setting->get_full_name();
1494 if (array_key_exists($fullname, $adminroot->errors)) {
1495 $data = $adminroot->errors[$fullname]->data;
1496 } else {
1497 $data = $setting->get_setting();
1498 // do not use defaults if settings not available - upgrade settings handles the defaults!
1500 $return .= $setting->output_html($data);
1502 $return .= '</fieldset>';
1503 return $return;
1507 * Is this settings page hidden in admin tree block?
1509 * @return bool True if hidden
1511 public function is_hidden() {
1512 return $this->hidden;
1516 * Show we display Save button at the page bottom?
1517 * @return bool
1519 public function show_save() {
1520 foreach($this->settings as $setting) {
1521 if (empty($setting->nosave)) {
1522 return true;
1525 return false;
1531 * Admin settings class. Only exists on setting pages.
1532 * Read & write happens at this level; no authentication.
1534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1536 abstract class admin_setting {
1537 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1538 public $name;
1539 /** @var string localised name */
1540 public $visiblename;
1541 /** @var string localised long description in Markdown format */
1542 public $description;
1543 /** @var mixed Can be string or array of string */
1544 public $defaultsetting;
1545 /** @var string */
1546 public $updatedcallback;
1547 /** @var mixed can be String or Null. Null means main config table */
1548 public $plugin; // null means main config table
1549 /** @var bool true indicates this setting does not actually save anything, just information */
1550 public $nosave = false;
1551 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1552 public $affectsmodinfo = false;
1553 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1554 private $flags = array();
1557 * Constructor
1558 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1559 * or 'myplugin/mysetting' for ones in config_plugins.
1560 * @param string $visiblename localised name
1561 * @param string $description localised long description
1562 * @param mixed $defaultsetting string or array depending on implementation
1564 public function __construct($name, $visiblename, $description, $defaultsetting) {
1565 $this->parse_setting_name($name);
1566 $this->visiblename = $visiblename;
1567 $this->description = $description;
1568 $this->defaultsetting = $defaultsetting;
1572 * Generic function to add a flag to this admin setting.
1574 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1575 * @param bool $default - The default for the flag
1576 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1577 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1579 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1580 if (empty($this->flags[$shortname])) {
1581 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1582 } else {
1583 $this->flags[$shortname]->set_options($enabled, $default);
1588 * Set the enabled options flag on this admin setting.
1590 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1591 * @param bool $default - The default for the flag
1593 public function set_enabled_flag_options($enabled, $default) {
1594 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1598 * Set the advanced options flag on this admin setting.
1600 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1601 * @param bool $default - The default for the flag
1603 public function set_advanced_flag_options($enabled, $default) {
1604 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1609 * Set the locked options flag on this admin setting.
1611 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1612 * @param bool $default - The default for the flag
1614 public function set_locked_flag_options($enabled, $default) {
1615 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1619 * Get the currently saved value for a setting flag
1621 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1622 * @return bool
1624 public function get_setting_flag_value(admin_setting_flag $flag) {
1625 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1626 if (!isset($value)) {
1627 $value = $flag->get_default();
1630 return !empty($value);
1634 * Get the list of defaults for the flags on this setting.
1636 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1638 public function get_setting_flag_defaults(& $defaults) {
1639 foreach ($this->flags as $flag) {
1640 if ($flag->is_enabled() && $flag->get_default()) {
1641 $defaults[] = $flag->get_displayname();
1647 * Output the input fields for the advanced and locked flags on this setting.
1649 * @param bool $adv - The current value of the advanced flag.
1650 * @param bool $locked - The current value of the locked flag.
1651 * @return string $output - The html for the flags.
1653 public function output_setting_flags() {
1654 $output = '';
1656 foreach ($this->flags as $flag) {
1657 if ($flag->is_enabled()) {
1658 $output .= $flag->output_setting_flag($this);
1662 if (!empty($output)) {
1663 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1665 return $output;
1669 * Write the values of the flags for this admin setting.
1671 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1672 * @return bool - true if successful.
1674 public function write_setting_flags($data) {
1675 $result = true;
1676 foreach ($this->flags as $flag) {
1677 $result = $result && $flag->write_setting_flag($this, $data);
1679 return $result;
1683 * Set up $this->name and potentially $this->plugin
1685 * Set up $this->name and possibly $this->plugin based on whether $name looks
1686 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1687 * on the names, that is, output a developer debug warning if the name
1688 * contains anything other than [a-zA-Z0-9_]+.
1690 * @param string $name the setting name passed in to the constructor.
1692 private function parse_setting_name($name) {
1693 $bits = explode('/', $name);
1694 if (count($bits) > 2) {
1695 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1697 $this->name = array_pop($bits);
1698 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1699 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1701 if (!empty($bits)) {
1702 $this->plugin = array_pop($bits);
1703 if ($this->plugin === 'moodle') {
1704 $this->plugin = null;
1705 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1706 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1712 * Returns the fullname prefixed by the plugin
1713 * @return string
1715 public function get_full_name() {
1716 return 's_'.$this->plugin.'_'.$this->name;
1720 * Returns the ID string based on plugin and name
1721 * @return string
1723 public function get_id() {
1724 return 'id_s_'.$this->plugin.'_'.$this->name;
1728 * @param bool $affectsmodinfo If true, changes to this setting will
1729 * cause the course cache to be rebuilt
1731 public function set_affects_modinfo($affectsmodinfo) {
1732 $this->affectsmodinfo = $affectsmodinfo;
1736 * Returns the config if possible
1738 * @return mixed returns config if successful else null
1740 public function config_read($name) {
1741 global $CFG;
1742 if (!empty($this->plugin)) {
1743 $value = get_config($this->plugin, $name);
1744 return $value === false ? NULL : $value;
1746 } else {
1747 if (isset($CFG->$name)) {
1748 return $CFG->$name;
1749 } else {
1750 return NULL;
1756 * Used to set a config pair and log change
1758 * @param string $name
1759 * @param mixed $value Gets converted to string if not null
1760 * @return bool Write setting to config table
1762 public function config_write($name, $value) {
1763 global $DB, $USER, $CFG;
1765 if ($this->nosave) {
1766 return true;
1769 // make sure it is a real change
1770 $oldvalue = get_config($this->plugin, $name);
1771 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1772 $value = is_null($value) ? null : (string)$value;
1774 if ($oldvalue === $value) {
1775 return true;
1778 // store change
1779 set_config($name, $value, $this->plugin);
1781 // Some admin settings affect course modinfo
1782 if ($this->affectsmodinfo) {
1783 // Clear course cache for all courses
1784 rebuild_course_cache(0, true);
1787 $this->add_to_config_log($name, $oldvalue, $value);
1789 return true; // BC only
1793 * Log config changes if necessary.
1794 * @param string $name
1795 * @param string $oldvalue
1796 * @param string $value
1798 protected function add_to_config_log($name, $oldvalue, $value) {
1799 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1803 * Returns current value of this setting
1804 * @return mixed array or string depending on instance, NULL means not set yet
1806 public abstract function get_setting();
1809 * Returns default setting if exists
1810 * @return mixed array or string depending on instance; NULL means no default, user must supply
1812 public function get_defaultsetting() {
1813 $adminroot = admin_get_root(false, false);
1814 if (!empty($adminroot->custom_defaults)) {
1815 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1816 if (isset($adminroot->custom_defaults[$plugin])) {
1817 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1818 return $adminroot->custom_defaults[$plugin][$this->name];
1822 return $this->defaultsetting;
1826 * Store new setting
1828 * @param mixed $data string or array, must not be NULL
1829 * @return string empty string if ok, string error message otherwise
1831 public abstract function write_setting($data);
1834 * Return part of form with setting
1835 * This function should always be overwritten
1837 * @param mixed $data array or string depending on setting
1838 * @param string $query
1839 * @return string
1841 public function output_html($data, $query='') {
1842 // should be overridden
1843 return;
1847 * Function called if setting updated - cleanup, cache reset, etc.
1848 * @param string $functionname Sets the function name
1849 * @return void
1851 public function set_updatedcallback($functionname) {
1852 $this->updatedcallback = $functionname;
1856 * Execute postupdatecallback if necessary.
1857 * @param mixed $original original value before write_setting()
1858 * @return bool true if changed, false if not.
1860 public function post_write_settings($original) {
1861 // Comparison must work for arrays too.
1862 if (serialize($original) === serialize($this->get_setting())) {
1863 return false;
1866 $callbackfunction = $this->updatedcallback;
1867 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1868 $callbackfunction($this->get_full_name());
1870 return true;
1874 * Is setting related to query text - used when searching
1875 * @param string $query
1876 * @return bool
1878 public function is_related($query) {
1879 if (strpos(strtolower($this->name), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1883 return true;
1885 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1886 return true;
1888 $current = $this->get_setting();
1889 if (!is_null($current)) {
1890 if (is_string($current)) {
1891 if (strpos(core_text::strtolower($current), $query) !== false) {
1892 return true;
1896 $default = $this->get_defaultsetting();
1897 if (!is_null($default)) {
1898 if (is_string($default)) {
1899 if (strpos(core_text::strtolower($default), $query) !== false) {
1900 return true;
1904 return false;
1909 * An additional option that can be applied to an admin setting.
1910 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1914 class admin_setting_flag {
1915 /** @var bool Flag to indicate if this option can be toggled for this setting */
1916 private $enabled = false;
1917 /** @var bool Flag to indicate if this option defaults to true or false */
1918 private $default = false;
1919 /** @var string Short string used to create setting name - e.g. 'adv' */
1920 private $shortname = '';
1921 /** @var string String used as the label for this flag */
1922 private $displayname = '';
1923 /** @const Checkbox for this flag is displayed in admin page */
1924 const ENABLED = true;
1925 /** @const Checkbox for this flag is not displayed in admin page */
1926 const DISABLED = false;
1929 * Constructor
1931 * @param bool $enabled Can this option can be toggled.
1932 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1933 * @param bool $default The default checked state for this setting option.
1934 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1935 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1937 public function __construct($enabled, $default, $shortname, $displayname) {
1938 $this->shortname = $shortname;
1939 $this->displayname = $displayname;
1940 $this->set_options($enabled, $default);
1944 * Update the values of this setting options class
1946 * @param bool $enabled Can this option can be toggled.
1947 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1948 * @param bool $default The default checked state for this setting option.
1950 public function set_options($enabled, $default) {
1951 $this->enabled = $enabled;
1952 $this->default = $default;
1956 * Should this option appear in the interface and be toggleable?
1958 * @return bool Is it enabled?
1960 public function is_enabled() {
1961 return $this->enabled;
1965 * Should this option be checked by default?
1967 * @return bool Is it on by default?
1969 public function get_default() {
1970 return $this->default;
1974 * Return the short name for this flag. e.g. 'adv' or 'locked'
1976 * @return string
1978 public function get_shortname() {
1979 return $this->shortname;
1983 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1985 * @return string
1987 public function get_displayname() {
1988 return $this->displayname;
1992 * Save the submitted data for this flag - or set it to the default if $data is null.
1994 * @param admin_setting $setting - The admin setting for this flag
1995 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1996 * @return bool
1998 public function write_setting_flag(admin_setting $setting, $data) {
1999 $result = true;
2000 if ($this->is_enabled()) {
2001 if (!isset($data)) {
2002 $value = $this->get_default();
2003 } else {
2004 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2006 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2009 return $result;
2014 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2016 * @param admin_setting $setting - The admin setting for this flag
2017 * @return string - The html for the checkbox.
2019 public function output_setting_flag(admin_setting $setting) {
2020 $value = $setting->get_setting_flag_value($this);
2021 $output = ' <input type="checkbox" class="form-checkbox" ' .
2022 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2023 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2024 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2025 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2026 $this->get_displayname() .
2027 ' </label> ';
2028 return $output;
2034 * No setting - just heading and text.
2036 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2038 class admin_setting_heading extends admin_setting {
2041 * not a setting, just text
2042 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2043 * @param string $heading heading
2044 * @param string $information text in box
2046 public function __construct($name, $heading, $information) {
2047 $this->nosave = true;
2048 parent::__construct($name, $heading, $information, '');
2052 * Always returns true
2053 * @return bool Always returns true
2055 public function get_setting() {
2056 return true;
2060 * Always returns true
2061 * @return bool Always returns true
2063 public function get_defaultsetting() {
2064 return true;
2068 * Never write settings
2069 * @return string Always returns an empty string
2071 public function write_setting($data) {
2072 // do not write any setting
2073 return '';
2077 * Returns an HTML string
2078 * @return string Returns an HTML string
2080 public function output_html($data, $query='') {
2081 global $OUTPUT;
2082 $return = '';
2083 if ($this->visiblename != '') {
2084 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2086 if ($this->description != '') {
2087 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2089 return $return;
2095 * The most flexibly setting, user is typing text
2097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2099 class admin_setting_configtext extends admin_setting {
2101 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2102 public $paramtype;
2103 /** @var int default field size */
2104 public $size;
2107 * Config text constructor
2109 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2110 * @param string $visiblename localised
2111 * @param string $description long localised info
2112 * @param string $defaultsetting
2113 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2114 * @param int $size default field size
2116 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2117 $this->paramtype = $paramtype;
2118 if (!is_null($size)) {
2119 $this->size = $size;
2120 } else {
2121 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2123 parent::__construct($name, $visiblename, $description, $defaultsetting);
2127 * Return the setting
2129 * @return mixed returns config if successful else null
2131 public function get_setting() {
2132 return $this->config_read($this->name);
2135 public function write_setting($data) {
2136 if ($this->paramtype === PARAM_INT and $data === '') {
2137 // do not complain if '' used instead of 0
2138 $data = 0;
2140 // $data is a string
2141 $validated = $this->validate($data);
2142 if ($validated !== true) {
2143 return $validated;
2145 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2149 * Validate data before storage
2150 * @param string data
2151 * @return mixed true if ok string if error found
2153 public function validate($data) {
2154 // allow paramtype to be a custom regex if it is the form of /pattern/
2155 if (preg_match('#^/.*/$#', $this->paramtype)) {
2156 if (preg_match($this->paramtype, $data)) {
2157 return true;
2158 } else {
2159 return get_string('validateerror', 'admin');
2162 } else if ($this->paramtype === PARAM_RAW) {
2163 return true;
2165 } else {
2166 $cleaned = clean_param($data, $this->paramtype);
2167 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2168 return true;
2169 } else {
2170 return get_string('validateerror', 'admin');
2176 * Return an XHTML string for the setting
2177 * @return string Returns an XHTML string
2179 public function output_html($data, $query='') {
2180 $default = $this->get_defaultsetting();
2182 return format_admin_setting($this, $this->visiblename,
2183 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2184 $this->description, true, '', $default, $query);
2189 * Text input with a maximum length constraint.
2191 * @copyright 2015 onwards Ankit Agarwal
2192 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2194 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2196 /** @var int maximum number of chars allowed. */
2197 protected $maxlength;
2200 * Config text constructor
2202 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2203 * or 'myplugin/mysetting' for ones in config_plugins.
2204 * @param string $visiblename localised
2205 * @param string $description long localised info
2206 * @param string $defaultsetting
2207 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2208 * @param int $size default field size
2209 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2211 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2212 $size=null, $maxlength = 0) {
2213 $this->maxlength = $maxlength;
2214 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2218 * Validate data before storage
2220 * @param string $data data
2221 * @return mixed true if ok string if error found
2223 public function validate($data) {
2224 $parentvalidation = parent::validate($data);
2225 if ($parentvalidation === true) {
2226 if ($this->maxlength > 0) {
2227 // Max length check.
2228 $length = core_text::strlen($data);
2229 if ($length > $this->maxlength) {
2230 return get_string('maximumchars', 'moodle', $this->maxlength);
2232 return true;
2233 } else {
2234 return true; // No max length check needed.
2236 } else {
2237 return $parentvalidation;
2243 * General text area without html editor.
2245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2247 class admin_setting_configtextarea extends admin_setting_configtext {
2248 private $rows;
2249 private $cols;
2252 * @param string $name
2253 * @param string $visiblename
2254 * @param string $description
2255 * @param mixed $defaultsetting string or array
2256 * @param mixed $paramtype
2257 * @param string $cols The number of columns to make the editor
2258 * @param string $rows The number of rows to make the editor
2260 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2261 $this->rows = $rows;
2262 $this->cols = $cols;
2263 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2267 * Returns an XHTML string for the editor
2269 * @param string $data
2270 * @param string $query
2271 * @return string XHTML string for the editor
2273 public function output_html($data, $query='') {
2274 $default = $this->get_defaultsetting();
2276 $defaultinfo = $default;
2277 if (!is_null($default) and $default !== '') {
2278 $defaultinfo = "\n".$default;
2281 return format_admin_setting($this, $this->visiblename,
2282 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2283 $this->description, true, '', $defaultinfo, $query);
2289 * General text area with html editor.
2291 class admin_setting_confightmleditor extends admin_setting_configtext {
2292 private $rows;
2293 private $cols;
2296 * @param string $name
2297 * @param string $visiblename
2298 * @param string $description
2299 * @param mixed $defaultsetting string or array
2300 * @param mixed $paramtype
2302 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2303 $this->rows = $rows;
2304 $this->cols = $cols;
2305 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2306 editors_head_setup();
2310 * Returns an XHTML string for the editor
2312 * @param string $data
2313 * @param string $query
2314 * @return string XHTML string for the editor
2316 public function output_html($data, $query='') {
2317 $default = $this->get_defaultsetting();
2319 $defaultinfo = $default;
2320 if (!is_null($default) and $default !== '') {
2321 $defaultinfo = "\n".$default;
2324 $editor = editors_get_preferred_editor(FORMAT_HTML);
2325 $editor->set_text($data);
2326 $editor->use_editor($this->get_id(), array('noclean'=>true));
2328 return format_admin_setting($this, $this->visiblename,
2329 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2330 $this->description, true, '', $defaultinfo, $query);
2336 * Password field, allows unmasking of password
2338 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2340 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2342 * Constructor
2343 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2344 * @param string $visiblename localised
2345 * @param string $description long localised info
2346 * @param string $defaultsetting default password
2348 public function __construct($name, $visiblename, $description, $defaultsetting) {
2349 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2353 * Log config changes if necessary.
2354 * @param string $name
2355 * @param string $oldvalue
2356 * @param string $value
2358 protected function add_to_config_log($name, $oldvalue, $value) {
2359 if ($value !== '') {
2360 $value = '********';
2362 if ($oldvalue !== '' and $oldvalue !== null) {
2363 $oldvalue = '********';
2365 parent::add_to_config_log($name, $oldvalue, $value);
2369 * Returns XHTML for the field
2370 * Writes Javascript into the HTML below right before the last div
2372 * @todo Make javascript available through newer methods if possible
2373 * @param string $data Value for the field
2374 * @param string $query Passed as final argument for format_admin_setting
2375 * @return string XHTML field
2377 public function output_html($data, $query='') {
2378 $id = $this->get_id();
2379 $unmask = get_string('unmaskpassword', 'form');
2380 $unmaskjs = '<script type="text/javascript">
2381 //<![CDATA[
2382 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2384 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2386 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2388 var unmaskchb = document.createElement("input");
2389 unmaskchb.setAttribute("type", "checkbox");
2390 unmaskchb.setAttribute("id", "'.$id.'unmask");
2391 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2392 unmaskdiv.appendChild(unmaskchb);
2394 var unmasklbl = document.createElement("label");
2395 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2396 if (is_ie) {
2397 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2398 } else {
2399 unmasklbl.setAttribute("for", "'.$id.'unmask");
2401 unmaskdiv.appendChild(unmasklbl);
2403 if (is_ie) {
2404 // ugly hack to work around the famous onchange IE bug
2405 unmaskchb.onclick = function() {this.blur();};
2406 unmaskdiv.onclick = function() {this.blur();};
2408 //]]>
2409 </script>';
2410 return format_admin_setting($this, $this->visiblename,
2411 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
2412 $this->description, true, '', NULL, $query);
2417 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2418 * Note: Only advanced makes sense right now - locked does not.
2420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2422 class admin_setting_configempty extends admin_setting_configtext {
2425 * @param string $name
2426 * @param string $visiblename
2427 * @param string $description
2429 public function __construct($name, $visiblename, $description) {
2430 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2434 * Returns an XHTML string for the hidden field
2436 * @param string $data
2437 * @param string $query
2438 * @return string XHTML string for the editor
2440 public function output_html($data, $query='') {
2441 return format_admin_setting($this,
2442 $this->visiblename,
2443 '<div class="form-empty" >' .
2444 '<input type="hidden"' .
2445 ' id="'. $this->get_id() .'"' .
2446 ' name="'. $this->get_full_name() .'"' .
2447 ' value=""/></div>',
2448 $this->description,
2449 true,
2451 get_string('none'),
2452 $query);
2458 * Path to directory
2460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2462 class admin_setting_configfile extends admin_setting_configtext {
2464 * Constructor
2465 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2466 * @param string $visiblename localised
2467 * @param string $description long localised info
2468 * @param string $defaultdirectory default directory location
2470 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2471 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2475 * Returns XHTML for the field
2477 * Returns XHTML for the field and also checks whether the file
2478 * specified in $data exists using file_exists()
2480 * @param string $data File name and path to use in value attr
2481 * @param string $query
2482 * @return string XHTML field
2484 public function output_html($data, $query='') {
2485 global $CFG;
2486 $default = $this->get_defaultsetting();
2488 if ($data) {
2489 if (file_exists($data)) {
2490 $executable = '<span class="pathok">&#x2714;</span>';
2491 } else {
2492 $executable = '<span class="patherror">&#x2718;</span>';
2494 } else {
2495 $executable = '';
2497 $readonly = '';
2498 if (!empty($CFG->preventexecpath)) {
2499 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2500 $readonly = 'readonly="readonly"';
2503 return format_admin_setting($this, $this->visiblename,
2504 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2505 $this->description, true, '', $default, $query);
2509 * Checks if execpatch has been disabled in config.php
2511 public function write_setting($data) {
2512 global $CFG;
2513 if (!empty($CFG->preventexecpath)) {
2514 if ($this->get_setting() === null) {
2515 // Use default during installation.
2516 $data = $this->get_defaultsetting();
2517 if ($data === null) {
2518 $data = '';
2520 } else {
2521 return '';
2524 return parent::write_setting($data);
2530 * Path to executable file
2532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2534 class admin_setting_configexecutable extends admin_setting_configfile {
2537 * Returns an XHTML field
2539 * @param string $data This is the value for the field
2540 * @param string $query
2541 * @return string XHTML field
2543 public function output_html($data, $query='') {
2544 global $CFG;
2545 $default = $this->get_defaultsetting();
2546 require_once("$CFG->libdir/filelib.php");
2548 if ($data) {
2549 if (file_exists($data) and !is_dir($data) and file_is_executable($data)) {
2550 $executable = '<span class="pathok">&#x2714;</span>';
2551 } else {
2552 $executable = '<span class="patherror">&#x2718;</span>';
2554 } else {
2555 $executable = '';
2557 $readonly = '';
2558 if (!empty($CFG->preventexecpath)) {
2559 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2560 $readonly = 'readonly="readonly"';
2563 return format_admin_setting($this, $this->visiblename,
2564 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2565 $this->description, true, '', $default, $query);
2571 * Path to directory
2573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2575 class admin_setting_configdirectory extends admin_setting_configfile {
2578 * Returns an XHTML field
2580 * @param string $data This is the value for the field
2581 * @param string $query
2582 * @return string XHTML
2584 public function output_html($data, $query='') {
2585 global $CFG;
2586 $default = $this->get_defaultsetting();
2588 if ($data) {
2589 if (file_exists($data) and is_dir($data)) {
2590 $executable = '<span class="pathok">&#x2714;</span>';
2591 } else {
2592 $executable = '<span class="patherror">&#x2718;</span>';
2594 } else {
2595 $executable = '';
2597 $readonly = '';
2598 if (!empty($CFG->preventexecpath)) {
2599 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2600 $readonly = 'readonly="readonly"';
2603 return format_admin_setting($this, $this->visiblename,
2604 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2605 $this->description, true, '', $default, $query);
2611 * Checkbox
2613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2615 class admin_setting_configcheckbox extends admin_setting {
2616 /** @var string Value used when checked */
2617 public $yes;
2618 /** @var string Value used when not checked */
2619 public $no;
2622 * Constructor
2623 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2624 * @param string $visiblename localised
2625 * @param string $description long localised info
2626 * @param string $defaultsetting
2627 * @param string $yes value used when checked
2628 * @param string $no value used when not checked
2630 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2631 parent::__construct($name, $visiblename, $description, $defaultsetting);
2632 $this->yes = (string)$yes;
2633 $this->no = (string)$no;
2637 * Retrieves the current setting using the objects name
2639 * @return string
2641 public function get_setting() {
2642 return $this->config_read($this->name);
2646 * Sets the value for the setting
2648 * Sets the value for the setting to either the yes or no values
2649 * of the object by comparing $data to yes
2651 * @param mixed $data Gets converted to str for comparison against yes value
2652 * @return string empty string or error
2654 public function write_setting($data) {
2655 if ((string)$data === $this->yes) { // convert to strings before comparison
2656 $data = $this->yes;
2657 } else {
2658 $data = $this->no;
2660 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2664 * Returns an XHTML checkbox field
2666 * @param string $data If $data matches yes then checkbox is checked
2667 * @param string $query
2668 * @return string XHTML field
2670 public function output_html($data, $query='') {
2671 $default = $this->get_defaultsetting();
2673 if (!is_null($default)) {
2674 if ((string)$default === $this->yes) {
2675 $defaultinfo = get_string('checkboxyes', 'admin');
2676 } else {
2677 $defaultinfo = get_string('checkboxno', 'admin');
2679 } else {
2680 $defaultinfo = NULL;
2683 if ((string)$data === $this->yes) { // convert to strings before comparison
2684 $checked = 'checked="checked"';
2685 } else {
2686 $checked = '';
2689 return format_admin_setting($this, $this->visiblename,
2690 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2691 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2692 $this->description, true, '', $defaultinfo, $query);
2698 * Multiple checkboxes, each represents different value, stored in csv format
2700 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2702 class admin_setting_configmulticheckbox extends admin_setting {
2703 /** @var array Array of choices value=>label */
2704 public $choices;
2707 * Constructor: uses parent::__construct
2709 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2710 * @param string $visiblename localised
2711 * @param string $description long localised info
2712 * @param array $defaultsetting array of selected
2713 * @param array $choices array of $value=>$label for each checkbox
2715 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2716 $this->choices = $choices;
2717 parent::__construct($name, $visiblename, $description, $defaultsetting);
2721 * This public function may be used in ancestors for lazy loading of choices
2723 * @todo Check if this function is still required content commented out only returns true
2724 * @return bool true if loaded, false if error
2726 public function load_choices() {
2728 if (is_array($this->choices)) {
2729 return true;
2731 .... load choices here
2733 return true;
2737 * Is setting related to query text - used when searching
2739 * @param string $query
2740 * @return bool true on related, false on not or failure
2742 public function is_related($query) {
2743 if (!$this->load_choices() or empty($this->choices)) {
2744 return false;
2746 if (parent::is_related($query)) {
2747 return true;
2750 foreach ($this->choices as $desc) {
2751 if (strpos(core_text::strtolower($desc), $query) !== false) {
2752 return true;
2755 return false;
2759 * Returns the current setting if it is set
2761 * @return mixed null if null, else an array
2763 public function get_setting() {
2764 $result = $this->config_read($this->name);
2766 if (is_null($result)) {
2767 return NULL;
2769 if ($result === '') {
2770 return array();
2772 $enabled = explode(',', $result);
2773 $setting = array();
2774 foreach ($enabled as $option) {
2775 $setting[$option] = 1;
2777 return $setting;
2781 * Saves the setting(s) provided in $data
2783 * @param array $data An array of data, if not array returns empty str
2784 * @return mixed empty string on useless data or bool true=success, false=failed
2786 public function write_setting($data) {
2787 if (!is_array($data)) {
2788 return ''; // ignore it
2790 if (!$this->load_choices() or empty($this->choices)) {
2791 return '';
2793 unset($data['xxxxx']);
2794 $result = array();
2795 foreach ($data as $key => $value) {
2796 if ($value and array_key_exists($key, $this->choices)) {
2797 $result[] = $key;
2800 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2804 * Returns XHTML field(s) as required by choices
2806 * Relies on data being an array should data ever be another valid vartype with
2807 * acceptable value this may cause a warning/error
2808 * if (!is_array($data)) would fix the problem
2810 * @todo Add vartype handling to ensure $data is an array
2812 * @param array $data An array of checked values
2813 * @param string $query
2814 * @return string XHTML field
2816 public function output_html($data, $query='') {
2817 if (!$this->load_choices() or empty($this->choices)) {
2818 return '';
2820 $default = $this->get_defaultsetting();
2821 if (is_null($default)) {
2822 $default = array();
2824 if (is_null($data)) {
2825 $data = array();
2827 $options = array();
2828 $defaults = array();
2829 foreach ($this->choices as $key=>$description) {
2830 if (!empty($data[$key])) {
2831 $checked = 'checked="checked"';
2832 } else {
2833 $checked = '';
2835 if (!empty($default[$key])) {
2836 $defaults[] = $description;
2839 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2840 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2843 if (is_null($default)) {
2844 $defaultinfo = NULL;
2845 } else if (!empty($defaults)) {
2846 $defaultinfo = implode(', ', $defaults);
2847 } else {
2848 $defaultinfo = get_string('none');
2851 $return = '<div class="form-multicheckbox">';
2852 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2853 if ($options) {
2854 $return .= '<ul>';
2855 foreach ($options as $option) {
2856 $return .= '<li>'.$option.'</li>';
2858 $return .= '</ul>';
2860 $return .= '</div>';
2862 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2869 * Multiple checkboxes 2, value stored as string 00101011
2871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2873 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2876 * Returns the setting if set
2878 * @return mixed null if not set, else an array of set settings
2880 public function get_setting() {
2881 $result = $this->config_read($this->name);
2882 if (is_null($result)) {
2883 return NULL;
2885 if (!$this->load_choices()) {
2886 return NULL;
2888 $result = str_pad($result, count($this->choices), '0');
2889 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2890 $setting = array();
2891 foreach ($this->choices as $key=>$unused) {
2892 $value = array_shift($result);
2893 if ($value) {
2894 $setting[$key] = 1;
2897 return $setting;
2901 * Save setting(s) provided in $data param
2903 * @param array $data An array of settings to save
2904 * @return mixed empty string for bad data or bool true=>success, false=>error
2906 public function write_setting($data) {
2907 if (!is_array($data)) {
2908 return ''; // ignore it
2910 if (!$this->load_choices() or empty($this->choices)) {
2911 return '';
2913 $result = '';
2914 foreach ($this->choices as $key=>$unused) {
2915 if (!empty($data[$key])) {
2916 $result .= '1';
2917 } else {
2918 $result .= '0';
2921 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2927 * Select one value from list
2929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2931 class admin_setting_configselect extends admin_setting {
2932 /** @var array Array of choices value=>label */
2933 public $choices;
2936 * Constructor
2937 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2938 * @param string $visiblename localised
2939 * @param string $description long localised info
2940 * @param string|int $defaultsetting
2941 * @param array $choices array of $value=>$label for each selection
2943 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2944 $this->choices = $choices;
2945 parent::__construct($name, $visiblename, $description, $defaultsetting);
2949 * This function may be used in ancestors for lazy loading of choices
2951 * Override this method if loading of choices is expensive, such
2952 * as when it requires multiple db requests.
2954 * @return bool true if loaded, false if error
2956 public function load_choices() {
2958 if (is_array($this->choices)) {
2959 return true;
2961 .... load choices here
2963 return true;
2967 * Check if this is $query is related to a choice
2969 * @param string $query
2970 * @return bool true if related, false if not
2972 public function is_related($query) {
2973 if (parent::is_related($query)) {
2974 return true;
2976 if (!$this->load_choices()) {
2977 return false;
2979 foreach ($this->choices as $key=>$value) {
2980 if (strpos(core_text::strtolower($key), $query) !== false) {
2981 return true;
2983 if (strpos(core_text::strtolower($value), $query) !== false) {
2984 return true;
2987 return false;
2991 * Return the setting
2993 * @return mixed returns config if successful else null
2995 public function get_setting() {
2996 return $this->config_read($this->name);
3000 * Save a setting
3002 * @param string $data
3003 * @return string empty of error string
3005 public function write_setting($data) {
3006 if (!$this->load_choices() or empty($this->choices)) {
3007 return '';
3009 if (!array_key_exists($data, $this->choices)) {
3010 return ''; // ignore it
3013 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3017 * Returns XHTML select field
3019 * Ensure the options are loaded, and generate the XHTML for the select
3020 * element and any warning message. Separating this out from output_html
3021 * makes it easier to subclass this class.
3023 * @param string $data the option to show as selected.
3024 * @param string $current the currently selected option in the database, null if none.
3025 * @param string $default the default selected option.
3026 * @return array the HTML for the select element, and a warning message.
3028 public function output_select_html($data, $current, $default, $extraname = '') {
3029 if (!$this->load_choices() or empty($this->choices)) {
3030 return array('', '');
3033 $warning = '';
3034 if (is_null($current)) {
3035 // first run
3036 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
3037 // no warning
3038 } else if (!array_key_exists($current, $this->choices)) {
3039 $warning = get_string('warningcurrentsetting', 'admin', s($current));
3040 if (!is_null($default) and $data == $current) {
3041 $data = $default; // use default instead of first value when showing the form
3045 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
3046 foreach ($this->choices as $key => $value) {
3047 // the string cast is needed because key may be integer - 0 is equal to most strings!
3048 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
3050 $selecthtml .= '</select>';
3051 return array($selecthtml, $warning);
3055 * Returns XHTML select field and wrapping div(s)
3057 * @see output_select_html()
3059 * @param string $data the option to show as selected
3060 * @param string $query
3061 * @return string XHTML field and wrapping div
3063 public function output_html($data, $query='') {
3064 $default = $this->get_defaultsetting();
3065 $current = $this->get_setting();
3067 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3068 if (!$selecthtml) {
3069 return '';
3072 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3073 $defaultinfo = $this->choices[$default];
3074 } else {
3075 $defaultinfo = NULL;
3078 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3080 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3086 * Select multiple items from list
3088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3090 class admin_setting_configmultiselect extends admin_setting_configselect {
3092 * Constructor
3093 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3094 * @param string $visiblename localised
3095 * @param string $description long localised info
3096 * @param array $defaultsetting array of selected items
3097 * @param array $choices array of $value=>$label for each list item
3099 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3100 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3104 * Returns the select setting(s)
3106 * @return mixed null or array. Null if no settings else array of setting(s)
3108 public function get_setting() {
3109 $result = $this->config_read($this->name);
3110 if (is_null($result)) {
3111 return NULL;
3113 if ($result === '') {
3114 return array();
3116 return explode(',', $result);
3120 * Saves setting(s) provided through $data
3122 * Potential bug in the works should anyone call with this function
3123 * using a vartype that is not an array
3125 * @param array $data
3127 public function write_setting($data) {
3128 if (!is_array($data)) {
3129 return ''; //ignore it
3131 if (!$this->load_choices() or empty($this->choices)) {
3132 return '';
3135 unset($data['xxxxx']);
3137 $save = array();
3138 foreach ($data as $value) {
3139 if (!array_key_exists($value, $this->choices)) {
3140 continue; // ignore it
3142 $save[] = $value;
3145 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3149 * Is setting related to query text - used when searching
3151 * @param string $query
3152 * @return bool true if related, false if not
3154 public function is_related($query) {
3155 if (!$this->load_choices() or empty($this->choices)) {
3156 return false;
3158 if (parent::is_related($query)) {
3159 return true;
3162 foreach ($this->choices as $desc) {
3163 if (strpos(core_text::strtolower($desc), $query) !== false) {
3164 return true;
3167 return false;
3171 * Returns XHTML multi-select field
3173 * @todo Add vartype handling to ensure $data is an array
3174 * @param array $data Array of values to select by default
3175 * @param string $query
3176 * @return string XHTML multi-select field
3178 public function output_html($data, $query='') {
3179 if (!$this->load_choices() or empty($this->choices)) {
3180 return '';
3182 $choices = $this->choices;
3183 $default = $this->get_defaultsetting();
3184 if (is_null($default)) {
3185 $default = array();
3187 if (is_null($data)) {
3188 $data = array();
3191 $defaults = array();
3192 $size = min(10, count($this->choices));
3193 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3194 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3195 foreach ($this->choices as $key => $description) {
3196 if (in_array($key, $data)) {
3197 $selected = 'selected="selected"';
3198 } else {
3199 $selected = '';
3201 if (in_array($key, $default)) {
3202 $defaults[] = $description;
3205 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3208 if (is_null($default)) {
3209 $defaultinfo = NULL;
3210 } if (!empty($defaults)) {
3211 $defaultinfo = implode(', ', $defaults);
3212 } else {
3213 $defaultinfo = get_string('none');
3216 $return .= '</select></div>';
3217 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3222 * Time selector
3224 * This is a liiitle bit messy. we're using two selects, but we're returning
3225 * them as an array named after $name (so we only use $name2 internally for the setting)
3227 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3229 class admin_setting_configtime extends admin_setting {
3230 /** @var string Used for setting second select (minutes) */
3231 public $name2;
3234 * Constructor
3235 * @param string $hoursname setting for hours
3236 * @param string $minutesname setting for hours
3237 * @param string $visiblename localised
3238 * @param string $description long localised info
3239 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3241 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3242 $this->name2 = $minutesname;
3243 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3247 * Get the selected time
3249 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3251 public function get_setting() {
3252 $result1 = $this->config_read($this->name);
3253 $result2 = $this->config_read($this->name2);
3254 if (is_null($result1) or is_null($result2)) {
3255 return NULL;
3258 return array('h' => $result1, 'm' => $result2);
3262 * Store the time (hours and minutes)
3264 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3265 * @return bool true if success, false if not
3267 public function write_setting($data) {
3268 if (!is_array($data)) {
3269 return '';
3272 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3273 return ($result ? '' : get_string('errorsetting', 'admin'));
3277 * Returns XHTML time select fields
3279 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3280 * @param string $query
3281 * @return string XHTML time select fields and wrapping div(s)
3283 public function output_html($data, $query='') {
3284 $default = $this->get_defaultsetting();
3286 if (is_array($default)) {
3287 $defaultinfo = $default['h'].':'.$default['m'];
3288 } else {
3289 $defaultinfo = NULL;
3292 $return = '<div class="form-time defaultsnext">';
3293 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3294 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3295 for ($i = 0; $i < 24; $i++) {
3296 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3298 $return .= '</select>:';
3299 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3300 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3301 for ($i = 0; $i < 60; $i += 5) {
3302 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3304 $return .= '</select>';
3305 $return .= '</div>';
3306 return format_admin_setting($this, $this->visiblename, $return, $this->description,
3307 $this->get_id() . 'h', '', $defaultinfo, $query);
3314 * Seconds duration setting.
3316 * @copyright 2012 Petr Skoda (http://skodak.org)
3317 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3319 class admin_setting_configduration extends admin_setting {
3321 /** @var int default duration unit */
3322 protected $defaultunit;
3325 * Constructor
3326 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3327 * or 'myplugin/mysetting' for ones in config_plugins.
3328 * @param string $visiblename localised name
3329 * @param string $description localised long description
3330 * @param mixed $defaultsetting string or array depending on implementation
3331 * @param int $defaultunit - day, week, etc. (in seconds)
3333 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3334 if (is_number($defaultsetting)) {
3335 $defaultsetting = self::parse_seconds($defaultsetting);
3337 $units = self::get_units();
3338 if (isset($units[$defaultunit])) {
3339 $this->defaultunit = $defaultunit;
3340 } else {
3341 $this->defaultunit = 86400;
3343 parent::__construct($name, $visiblename, $description, $defaultsetting);
3347 * Returns selectable units.
3348 * @static
3349 * @return array
3351 protected static function get_units() {
3352 return array(
3353 604800 => get_string('weeks'),
3354 86400 => get_string('days'),
3355 3600 => get_string('hours'),
3356 60 => get_string('minutes'),
3357 1 => get_string('seconds'),
3362 * Converts seconds to some more user friendly string.
3363 * @static
3364 * @param int $seconds
3365 * @return string
3367 protected static function get_duration_text($seconds) {
3368 if (empty($seconds)) {
3369 return get_string('none');
3371 $data = self::parse_seconds($seconds);
3372 switch ($data['u']) {
3373 case (60*60*24*7):
3374 return get_string('numweeks', '', $data['v']);
3375 case (60*60*24):
3376 return get_string('numdays', '', $data['v']);
3377 case (60*60):
3378 return get_string('numhours', '', $data['v']);
3379 case (60):
3380 return get_string('numminutes', '', $data['v']);
3381 default:
3382 return get_string('numseconds', '', $data['v']*$data['u']);
3387 * Finds suitable units for given duration.
3388 * @static
3389 * @param int $seconds
3390 * @return array
3392 protected static function parse_seconds($seconds) {
3393 foreach (self::get_units() as $unit => $unused) {
3394 if ($seconds % $unit === 0) {
3395 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3398 return array('v'=>(int)$seconds, 'u'=>1);
3402 * Get the selected duration as array.
3404 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3406 public function get_setting() {
3407 $seconds = $this->config_read($this->name);
3408 if (is_null($seconds)) {
3409 return null;
3412 return self::parse_seconds($seconds);
3416 * Store the duration as seconds.
3418 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3419 * @return bool true if success, false if not
3421 public function write_setting($data) {
3422 if (!is_array($data)) {
3423 return '';
3426 $seconds = (int)($data['v']*$data['u']);
3427 if ($seconds < 0) {
3428 return get_string('errorsetting', 'admin');
3431 $result = $this->config_write($this->name, $seconds);
3432 return ($result ? '' : get_string('errorsetting', 'admin'));
3436 * Returns duration text+select fields.
3438 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3439 * @param string $query
3440 * @return string duration text+select fields and wrapping div(s)
3442 public function output_html($data, $query='') {
3443 $default = $this->get_defaultsetting();
3445 if (is_number($default)) {
3446 $defaultinfo = self::get_duration_text($default);
3447 } else if (is_array($default)) {
3448 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3449 } else {
3450 $defaultinfo = null;
3453 $units = self::get_units();
3455 $inputid = $this->get_id() . 'v';
3457 $return = '<div class="form-duration defaultsnext">';
3458 $return .= '<input type="text" size="5" id="' . $inputid . '" name="' . $this->get_full_name() .
3459 '[v]" value="' . s($data['v']) . '" />';
3460 $return .= '<label for="' . $this->get_id() . 'u" class="accesshide">' .
3461 get_string('durationunits', 'admin') . '</label>';
3462 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3463 foreach ($units as $val => $text) {
3464 $selected = '';
3465 if ($data['v'] == 0) {
3466 if ($val == $this->defaultunit) {
3467 $selected = ' selected="selected"';
3469 } else if ($val == $data['u']) {
3470 $selected = ' selected="selected"';
3472 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3474 $return .= '</select></div>';
3475 return format_admin_setting($this, $this->visiblename, $return, $this->description, $inputid, '', $defaultinfo, $query);
3481 * Seconds duration setting with an advanced checkbox, that controls a additional
3482 * $name.'_adv' setting.
3484 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3485 * @copyright 2014 The Open University
3487 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3489 * Constructor
3490 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3491 * or 'myplugin/mysetting' for ones in config_plugins.
3492 * @param string $visiblename localised name
3493 * @param string $description localised long description
3494 * @param array $defaultsetting array of int value, and bool whether it is
3495 * is advanced by default.
3496 * @param int $defaultunit - day, week, etc. (in seconds)
3498 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3499 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3500 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3506 * Used to validate a textarea used for ip addresses
3508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3509 * @copyright 2011 Petr Skoda (http://skodak.org)
3511 class admin_setting_configiplist extends admin_setting_configtextarea {
3514 * Validate the contents of the textarea as IP addresses
3516 * Used to validate a new line separated list of IP addresses collected from
3517 * a textarea control
3519 * @param string $data A list of IP Addresses separated by new lines
3520 * @return mixed bool true for success or string:error on failure
3522 public function validate($data) {
3523 if(!empty($data)) {
3524 $ips = explode("\n", $data);
3525 } else {
3526 return true;
3528 $result = true;
3529 foreach($ips as $ip) {
3530 $ip = trim($ip);
3531 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3532 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3533 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3534 $result = true;
3535 } else {
3536 $result = false;
3537 break;
3540 if($result) {
3541 return true;
3542 } else {
3543 return get_string('validateerror', 'admin');
3550 * An admin setting for selecting one or more users who have a capability
3551 * in the system context
3553 * An admin setting for selecting one or more users, who have a particular capability
3554 * in the system context. Warning, make sure the list will never be too long. There is
3555 * no paging or searching of this list.
3557 * To correctly get a list of users from this config setting, you need to call the
3558 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3562 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3563 /** @var string The capabilities name */
3564 protected $capability;
3565 /** @var int include admin users too */
3566 protected $includeadmins;
3569 * Constructor.
3571 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3572 * @param string $visiblename localised name
3573 * @param string $description localised long description
3574 * @param array $defaultsetting array of usernames
3575 * @param string $capability string capability name.
3576 * @param bool $includeadmins include administrators
3578 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3579 $this->capability = $capability;
3580 $this->includeadmins = $includeadmins;
3581 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3585 * Load all of the uses who have the capability into choice array
3587 * @return bool Always returns true
3589 function load_choices() {
3590 if (is_array($this->choices)) {
3591 return true;
3593 list($sort, $sortparams) = users_order_by_sql('u');
3594 if (!empty($sortparams)) {
3595 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3596 'This is unexpected, and a problem because there is no way to pass these ' .
3597 'parameters to get_users_by_capability. See MDL-34657.');
3599 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3600 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3601 $this->choices = array(
3602 '$@NONE@$' => get_string('nobody'),
3603 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3605 if ($this->includeadmins) {
3606 $admins = get_admins();
3607 foreach ($admins as $user) {
3608 $this->choices[$user->id] = fullname($user);
3611 if (is_array($users)) {
3612 foreach ($users as $user) {
3613 $this->choices[$user->id] = fullname($user);
3616 return true;
3620 * Returns the default setting for class
3622 * @return mixed Array, or string. Empty string if no default
3624 public function get_defaultsetting() {
3625 $this->load_choices();
3626 $defaultsetting = parent::get_defaultsetting();
3627 if (empty($defaultsetting)) {
3628 return array('$@NONE@$');
3629 } else if (array_key_exists($defaultsetting, $this->choices)) {
3630 return $defaultsetting;
3631 } else {
3632 return '';
3637 * Returns the current setting
3639 * @return mixed array or string
3641 public function get_setting() {
3642 $result = parent::get_setting();
3643 if ($result === null) {
3644 // this is necessary for settings upgrade
3645 return null;
3647 if (empty($result)) {
3648 $result = array('$@NONE@$');
3650 return $result;
3654 * Save the chosen setting provided as $data
3656 * @param array $data
3657 * @return mixed string or array
3659 public function write_setting($data) {
3660 // If all is selected, remove any explicit options.
3661 if (in_array('$@ALL@$', $data)) {
3662 $data = array('$@ALL@$');
3664 // None never needs to be written to the DB.
3665 if (in_array('$@NONE@$', $data)) {
3666 unset($data[array_search('$@NONE@$', $data)]);
3668 return parent::write_setting($data);
3674 * Special checkbox for calendar - resets SESSION vars.
3676 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3678 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3680 * Calls the parent::__construct with default values
3682 * name => calendar_adminseesall
3683 * visiblename => get_string('adminseesall', 'admin')
3684 * description => get_string('helpadminseesall', 'admin')
3685 * defaultsetting => 0
3687 public function __construct() {
3688 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3689 get_string('helpadminseesall', 'admin'), '0');
3693 * Stores the setting passed in $data
3695 * @param mixed gets converted to string for comparison
3696 * @return string empty string or error message
3698 public function write_setting($data) {
3699 global $SESSION;
3700 return parent::write_setting($data);
3705 * Special select for settings that are altered in setup.php and can not be altered on the fly
3707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3709 class admin_setting_special_selectsetup extends admin_setting_configselect {
3711 * Reads the setting directly from the database
3713 * @return mixed
3715 public function get_setting() {
3716 // read directly from db!
3717 return get_config(NULL, $this->name);
3721 * Save the setting passed in $data
3723 * @param string $data The setting to save
3724 * @return string empty or error message
3726 public function write_setting($data) {
3727 global $CFG;
3728 // do not change active CFG setting!
3729 $current = $CFG->{$this->name};
3730 $result = parent::write_setting($data);
3731 $CFG->{$this->name} = $current;
3732 return $result;
3738 * Special select for frontpage - stores data in course table
3740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3742 class admin_setting_sitesetselect extends admin_setting_configselect {
3744 * Returns the site name for the selected site
3746 * @see get_site()
3747 * @return string The site name of the selected site
3749 public function get_setting() {
3750 $site = course_get_format(get_site())->get_course();
3751 return $site->{$this->name};
3755 * Updates the database and save the setting
3757 * @param string data
3758 * @return string empty or error message
3760 public function write_setting($data) {
3761 global $DB, $SITE, $COURSE;
3762 if (!in_array($data, array_keys($this->choices))) {
3763 return get_string('errorsetting', 'admin');
3765 $record = new stdClass();
3766 $record->id = SITEID;
3767 $temp = $this->name;
3768 $record->$temp = $data;
3769 $record->timemodified = time();
3771 course_get_format($SITE)->update_course_format_options($record);
3772 $DB->update_record('course', $record);
3774 // Reset caches.
3775 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3776 if ($SITE->id == $COURSE->id) {
3777 $COURSE = $SITE;
3779 format_base::reset_course_cache($SITE->id);
3781 return '';
3788 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3789 * block to hidden.
3791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3793 class admin_setting_bloglevel extends admin_setting_configselect {
3795 * Updates the database and save the setting
3797 * @param string data
3798 * @return string empty or error message
3800 public function write_setting($data) {
3801 global $DB, $CFG;
3802 if ($data == 0) {
3803 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3804 foreach ($blogblocks as $block) {
3805 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3807 } else {
3808 // reenable all blocks only when switching from disabled blogs
3809 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3810 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3811 foreach ($blogblocks as $block) {
3812 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3816 return parent::write_setting($data);
3822 * Special select - lists on the frontpage - hacky
3824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3826 class admin_setting_courselist_frontpage extends admin_setting {
3827 /** @var array Array of choices value=>label */
3828 public $choices;
3831 * Construct override, requires one param
3833 * @param bool $loggedin Is the user logged in
3835 public function __construct($loggedin) {
3836 global $CFG;
3837 require_once($CFG->dirroot.'/course/lib.php');
3838 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3839 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3840 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3841 $defaults = array(FRONTPAGEALLCOURSELIST);
3842 parent::__construct($name, $visiblename, $description, $defaults);
3846 * Loads the choices available
3848 * @return bool always returns true
3850 public function load_choices() {
3851 if (is_array($this->choices)) {
3852 return true;
3854 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3855 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3856 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3857 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3858 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3859 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3860 'none' => get_string('none'));
3861 if ($this->name === 'frontpage') {
3862 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3864 return true;
3868 * Returns the selected settings
3870 * @param mixed array or setting or null
3872 public function get_setting() {
3873 $result = $this->config_read($this->name);
3874 if (is_null($result)) {
3875 return NULL;
3877 if ($result === '') {
3878 return array();
3880 return explode(',', $result);
3884 * Save the selected options
3886 * @param array $data
3887 * @return mixed empty string (data is not an array) or bool true=success false=failure
3889 public function write_setting($data) {
3890 if (!is_array($data)) {
3891 return '';
3893 $this->load_choices();
3894 $save = array();
3895 foreach($data as $datum) {
3896 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3897 continue;
3899 $save[$datum] = $datum; // no duplicates
3901 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3905 * Return XHTML select field and wrapping div
3907 * @todo Add vartype handling to make sure $data is an array
3908 * @param array $data Array of elements to select by default
3909 * @return string XHTML select field and wrapping div
3911 public function output_html($data, $query='') {
3912 $this->load_choices();
3913 $currentsetting = array();
3914 foreach ($data as $key) {
3915 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3916 $currentsetting[] = $key; // already selected first
3920 $return = '<div class="form-group">';
3921 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3922 if (!array_key_exists($i, $currentsetting)) {
3923 $currentsetting[$i] = 'none'; //none
3925 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3926 foreach ($this->choices as $key => $value) {
3927 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3929 $return .= '</select>';
3930 if ($i !== count($this->choices) - 2) {
3931 $return .= '<br />';
3934 $return .= '</div>';
3936 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3942 * Special checkbox for frontpage - stores data in course table
3944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3946 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3948 * Returns the current sites name
3950 * @return string
3952 public function get_setting() {
3953 $site = course_get_format(get_site())->get_course();
3954 return $site->{$this->name};
3958 * Save the selected setting
3960 * @param string $data The selected site
3961 * @return string empty string or error message
3963 public function write_setting($data) {
3964 global $DB, $SITE, $COURSE;
3965 $record = new stdClass();
3966 $record->id = $SITE->id;
3967 $record->{$this->name} = ($data == '1' ? 1 : 0);
3968 $record->timemodified = time();
3970 course_get_format($SITE)->update_course_format_options($record);
3971 $DB->update_record('course', $record);
3973 // Reset caches.
3974 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3975 if ($SITE->id == $COURSE->id) {
3976 $COURSE = $SITE;
3978 format_base::reset_course_cache($SITE->id);
3980 return '';
3985 * Special text for frontpage - stores data in course table.
3986 * Empty string means not set here. Manual setting is required.
3988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3990 class admin_setting_sitesettext extends admin_setting_configtext {
3992 * Return the current setting
3994 * @return mixed string or null
3996 public function get_setting() {
3997 $site = course_get_format(get_site())->get_course();
3998 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
4002 * Validate the selected data
4004 * @param string $data The selected value to validate
4005 * @return mixed true or message string
4007 public function validate($data) {
4008 global $DB, $SITE;
4009 $cleaned = clean_param($data, PARAM_TEXT);
4010 if ($cleaned === '') {
4011 return get_string('required');
4013 if ($this->name ==='shortname' &&
4014 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4015 return get_string('shortnametaken', 'error', $data);
4017 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4018 return true;
4019 } else {
4020 return get_string('validateerror', 'admin');
4025 * Save the selected setting
4027 * @param string $data The selected value
4028 * @return string empty or error message
4030 public function write_setting($data) {
4031 global $DB, $SITE, $COURSE;
4032 $data = trim($data);
4033 $validated = $this->validate($data);
4034 if ($validated !== true) {
4035 return $validated;
4038 $record = new stdClass();
4039 $record->id = $SITE->id;
4040 $record->{$this->name} = $data;
4041 $record->timemodified = time();
4043 course_get_format($SITE)->update_course_format_options($record);
4044 $DB->update_record('course', $record);
4046 // Reset caches.
4047 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4048 if ($SITE->id == $COURSE->id) {
4049 $COURSE = $SITE;
4051 format_base::reset_course_cache($SITE->id);
4053 return '';
4059 * Special text editor for site description.
4061 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4063 class admin_setting_special_frontpagedesc extends admin_setting {
4065 * Calls parent::__construct with specific arguments
4067 public function __construct() {
4068 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
4069 editors_head_setup();
4073 * Return the current setting
4074 * @return string The current setting
4076 public function get_setting() {
4077 $site = course_get_format(get_site())->get_course();
4078 return $site->{$this->name};
4082 * Save the new setting
4084 * @param string $data The new value to save
4085 * @return string empty or error message
4087 public function write_setting($data) {
4088 global $DB, $SITE, $COURSE;
4089 $record = new stdClass();
4090 $record->id = $SITE->id;
4091 $record->{$this->name} = $data;
4092 $record->timemodified = time();
4094 course_get_format($SITE)->update_course_format_options($record);
4095 $DB->update_record('course', $record);
4097 // Reset caches.
4098 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4099 if ($SITE->id == $COURSE->id) {
4100 $COURSE = $SITE;
4102 format_base::reset_course_cache($SITE->id);
4104 return '';
4108 * Returns XHTML for the field plus wrapping div
4110 * @param string $data The current value
4111 * @param string $query
4112 * @return string The XHTML output
4114 public function output_html($data, $query='') {
4115 global $CFG;
4117 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4119 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4125 * Administration interface for emoticon_manager settings.
4127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4129 class admin_setting_emoticons extends admin_setting {
4132 * Calls parent::__construct with specific args
4134 public function __construct() {
4135 global $CFG;
4137 $manager = get_emoticon_manager();
4138 $defaults = $this->prepare_form_data($manager->default_emoticons());
4139 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4143 * Return the current setting(s)
4145 * @return array Current settings array
4147 public function get_setting() {
4148 global $CFG;
4150 $manager = get_emoticon_manager();
4152 $config = $this->config_read($this->name);
4153 if (is_null($config)) {
4154 return null;
4157 $config = $manager->decode_stored_config($config);
4158 if (is_null($config)) {
4159 return null;
4162 return $this->prepare_form_data($config);
4166 * Save selected settings
4168 * @param array $data Array of settings to save
4169 * @return bool
4171 public function write_setting($data) {
4173 $manager = get_emoticon_manager();
4174 $emoticons = $this->process_form_data($data);
4176 if ($emoticons === false) {
4177 return false;
4180 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4181 return ''; // success
4182 } else {
4183 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4188 * Return XHTML field(s) for options
4190 * @param array $data Array of options to set in HTML
4191 * @return string XHTML string for the fields and wrapping div(s)
4193 public function output_html($data, $query='') {
4194 global $OUTPUT;
4196 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4197 $out .= html_writer::start_tag('thead');
4198 $out .= html_writer::start_tag('tr');
4199 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4200 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4201 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4202 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4203 $out .= html_writer::tag('th', '');
4204 $out .= html_writer::end_tag('tr');
4205 $out .= html_writer::end_tag('thead');
4206 $out .= html_writer::start_tag('tbody');
4207 $i = 0;
4208 foreach($data as $field => $value) {
4209 switch ($i) {
4210 case 0:
4211 $out .= html_writer::start_tag('tr');
4212 $current_text = $value;
4213 $current_filename = '';
4214 $current_imagecomponent = '';
4215 $current_altidentifier = '';
4216 $current_altcomponent = '';
4217 case 1:
4218 $current_filename = $value;
4219 case 2:
4220 $current_imagecomponent = $value;
4221 case 3:
4222 $current_altidentifier = $value;
4223 case 4:
4224 $current_altcomponent = $value;
4227 $out .= html_writer::tag('td',
4228 html_writer::empty_tag('input',
4229 array(
4230 'type' => 'text',
4231 'class' => 'form-text',
4232 'name' => $this->get_full_name().'['.$field.']',
4233 'value' => $value,
4235 ), array('class' => 'c'.$i)
4238 if ($i == 4) {
4239 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4240 $alt = get_string($current_altidentifier, $current_altcomponent);
4241 } else {
4242 $alt = $current_text;
4244 if ($current_filename) {
4245 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4246 } else {
4247 $out .= html_writer::tag('td', '');
4249 $out .= html_writer::end_tag('tr');
4250 $i = 0;
4251 } else {
4252 $i++;
4256 $out .= html_writer::end_tag('tbody');
4257 $out .= html_writer::end_tag('table');
4258 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4259 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4261 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4265 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4267 * @see self::process_form_data()
4268 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4269 * @return array of form fields and their values
4271 protected function prepare_form_data(array $emoticons) {
4273 $form = array();
4274 $i = 0;
4275 foreach ($emoticons as $emoticon) {
4276 $form['text'.$i] = $emoticon->text;
4277 $form['imagename'.$i] = $emoticon->imagename;
4278 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4279 $form['altidentifier'.$i] = $emoticon->altidentifier;
4280 $form['altcomponent'.$i] = $emoticon->altcomponent;
4281 $i++;
4283 // add one more blank field set for new object
4284 $form['text'.$i] = '';
4285 $form['imagename'.$i] = '';
4286 $form['imagecomponent'.$i] = '';
4287 $form['altidentifier'.$i] = '';
4288 $form['altcomponent'.$i] = '';
4290 return $form;
4294 * Converts the data from admin settings form into an array of emoticon objects
4296 * @see self::prepare_form_data()
4297 * @param array $data array of admin form fields and values
4298 * @return false|array of emoticon objects
4300 protected function process_form_data(array $form) {
4302 $count = count($form); // number of form field values
4304 if ($count % 5) {
4305 // we must get five fields per emoticon object
4306 return false;
4309 $emoticons = array();
4310 for ($i = 0; $i < $count / 5; $i++) {
4311 $emoticon = new stdClass();
4312 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4313 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4314 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4315 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4316 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4318 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4319 // prevent from breaking http://url.addresses by accident
4320 $emoticon->text = '';
4323 if (strlen($emoticon->text) < 2) {
4324 // do not allow single character emoticons
4325 $emoticon->text = '';
4328 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4329 // emoticon text must contain some non-alphanumeric character to prevent
4330 // breaking HTML tags
4331 $emoticon->text = '';
4334 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4335 $emoticons[] = $emoticon;
4338 return $emoticons;
4344 * Special setting for limiting of the list of available languages.
4346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4348 class admin_setting_langlist extends admin_setting_configtext {
4350 * Calls parent::__construct with specific arguments
4352 public function __construct() {
4353 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4357 * Save the new setting
4359 * @param string $data The new setting
4360 * @return bool
4362 public function write_setting($data) {
4363 $return = parent::write_setting($data);
4364 get_string_manager()->reset_caches();
4365 return $return;
4371 * Selection of one of the recognised countries using the list
4372 * returned by {@link get_list_of_countries()}.
4374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4376 class admin_settings_country_select extends admin_setting_configselect {
4377 protected $includeall;
4378 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4379 $this->includeall = $includeall;
4380 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4384 * Lazy-load the available choices for the select box
4386 public function load_choices() {
4387 global $CFG;
4388 if (is_array($this->choices)) {
4389 return true;
4391 $this->choices = array_merge(
4392 array('0' => get_string('choosedots')),
4393 get_string_manager()->get_list_of_countries($this->includeall));
4394 return true;
4400 * admin_setting_configselect for the default number of sections in a course,
4401 * simply so we can lazy-load the choices.
4403 * @copyright 2011 The Open University
4404 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4406 class admin_settings_num_course_sections extends admin_setting_configselect {
4407 public function __construct($name, $visiblename, $description, $defaultsetting) {
4408 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4411 /** Lazy-load the available choices for the select box */
4412 public function load_choices() {
4413 $max = get_config('moodlecourse', 'maxsections');
4414 if (!isset($max) || !is_numeric($max)) {
4415 $max = 52;
4417 for ($i = 0; $i <= $max; $i++) {
4418 $this->choices[$i] = "$i";
4420 return true;
4426 * Course category selection
4428 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4430 class admin_settings_coursecat_select extends admin_setting_configselect {
4432 * Calls parent::__construct with specific arguments
4434 public function __construct($name, $visiblename, $description, $defaultsetting) {
4435 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4439 * Load the available choices for the select box
4441 * @return bool
4443 public function load_choices() {
4444 global $CFG;
4445 require_once($CFG->dirroot.'/course/lib.php');
4446 if (is_array($this->choices)) {
4447 return true;
4449 $this->choices = make_categories_options();
4450 return true;
4456 * Special control for selecting days to backup
4458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4460 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4462 * Calls parent::__construct with specific arguments
4464 public function __construct() {
4465 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4466 $this->plugin = 'backup';
4470 * Load the available choices for the select box
4472 * @return bool Always returns true
4474 public function load_choices() {
4475 if (is_array($this->choices)) {
4476 return true;
4478 $this->choices = array();
4479 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4480 foreach ($days as $day) {
4481 $this->choices[$day] = get_string($day, 'calendar');
4483 return true;
4488 * Special setting for backup auto destination.
4490 * @package core
4491 * @subpackage admin
4492 * @copyright 2014 Frédéric Massart - FMCorz.net
4493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4495 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4498 * Calls parent::__construct with specific arguments.
4500 public function __construct() {
4501 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4505 * Check if the directory must be set, depending on backup/backup_auto_storage.
4507 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4508 * there will be conflicts if this validation happens before the other one.
4510 * @param string $data Form data.
4511 * @return string Empty when no errors.
4513 public function write_setting($data) {
4514 $storage = (int) get_config('backup', 'backup_auto_storage');
4515 if ($storage !== 0) {
4516 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4517 // The directory must exist and be writable.
4518 return get_string('backuperrorinvaliddestination');
4521 return parent::write_setting($data);
4527 * Special debug setting
4529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4531 class admin_setting_special_debug extends admin_setting_configselect {
4533 * Calls parent::__construct with specific arguments
4535 public function __construct() {
4536 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4540 * Load the available choices for the select box
4542 * @return bool
4544 public function load_choices() {
4545 if (is_array($this->choices)) {
4546 return true;
4548 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4549 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4550 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4551 DEBUG_ALL => get_string('debugall', 'admin'),
4552 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4553 return true;
4559 * Special admin control
4561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4563 class admin_setting_special_calendar_weekend extends admin_setting {
4565 * Calls parent::__construct with specific arguments
4567 public function __construct() {
4568 $name = 'calendar_weekend';
4569 $visiblename = get_string('calendar_weekend', 'admin');
4570 $description = get_string('helpweekenddays', 'admin');
4571 $default = array ('0', '6'); // Saturdays and Sundays
4572 parent::__construct($name, $visiblename, $description, $default);
4576 * Gets the current settings as an array
4578 * @return mixed Null if none, else array of settings
4580 public function get_setting() {
4581 $result = $this->config_read($this->name);
4582 if (is_null($result)) {
4583 return NULL;
4585 if ($result === '') {
4586 return array();
4588 $settings = array();
4589 for ($i=0; $i<7; $i++) {
4590 if ($result & (1 << $i)) {
4591 $settings[] = $i;
4594 return $settings;
4598 * Save the new settings
4600 * @param array $data Array of new settings
4601 * @return bool
4603 public function write_setting($data) {
4604 if (!is_array($data)) {
4605 return '';
4607 unset($data['xxxxx']);
4608 $result = 0;
4609 foreach($data as $index) {
4610 $result |= 1 << $index;
4612 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4616 * Return XHTML to display the control
4618 * @param array $data array of selected days
4619 * @param string $query
4620 * @return string XHTML for display (field + wrapping div(s)
4622 public function output_html($data, $query='') {
4623 // The order matters very much because of the implied numeric keys
4624 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4625 $return = '<table><thead><tr>';
4626 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4627 foreach($days as $index => $day) {
4628 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4630 $return .= '</tr></thead><tbody><tr>';
4631 foreach($days as $index => $day) {
4632 $return .= '<td><input type="checkbox" class="form-checkbox" id="'.$this->get_id().$index.'" name="'.$this->get_full_name().'[]" value="'.$index.'" '.(in_array("$index", $data) ? 'checked="checked"' : '').' /></td>';
4634 $return .= '</tr></tbody></table>';
4636 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4643 * Admin setting that allows a user to pick a behaviour.
4645 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4647 class admin_setting_question_behaviour extends admin_setting_configselect {
4649 * @param string $name name of config variable
4650 * @param string $visiblename display name
4651 * @param string $description description
4652 * @param string $default default.
4654 public function __construct($name, $visiblename, $description, $default) {
4655 parent::__construct($name, $visiblename, $description, $default, NULL);
4659 * Load list of behaviours as choices
4660 * @return bool true => success, false => error.
4662 public function load_choices() {
4663 global $CFG;
4664 require_once($CFG->dirroot . '/question/engine/lib.php');
4665 $this->choices = question_engine::get_behaviour_options('');
4666 return true;
4672 * Admin setting that allows a user to pick appropriate roles for something.
4674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4676 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4677 /** @var array Array of capabilities which identify roles */
4678 private $types;
4681 * @param string $name Name of config variable
4682 * @param string $visiblename Display name
4683 * @param string $description Description
4684 * @param array $types Array of archetypes which identify
4685 * roles that will be enabled by default.
4687 public function __construct($name, $visiblename, $description, $types) {
4688 parent::__construct($name, $visiblename, $description, NULL, NULL);
4689 $this->types = $types;
4693 * Load roles as choices
4695 * @return bool true=>success, false=>error
4697 public function load_choices() {
4698 global $CFG, $DB;
4699 if (during_initial_install()) {
4700 return false;
4702 if (is_array($this->choices)) {
4703 return true;
4705 if ($roles = get_all_roles()) {
4706 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4707 return true;
4708 } else {
4709 return false;
4714 * Return the default setting for this control
4716 * @return array Array of default settings
4718 public function get_defaultsetting() {
4719 global $CFG;
4721 if (during_initial_install()) {
4722 return null;
4724 $result = array();
4725 foreach($this->types as $archetype) {
4726 if ($caproles = get_archetype_roles($archetype)) {
4727 foreach ($caproles as $caprole) {
4728 $result[$caprole->id] = 1;
4732 return $result;
4738 * Admin setting that is a list of installed filter plugins.
4740 * @copyright 2015 The Open University
4741 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4743 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
4746 * Constructor
4748 * @param string $name unique ascii name, either 'mysetting' for settings
4749 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
4750 * @param string $visiblename localised name
4751 * @param string $description localised long description
4752 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
4754 public function __construct($name, $visiblename, $description, $default) {
4755 if (empty($default)) {
4756 $default = array();
4758 $this->load_choices();
4759 foreach ($default as $plugin) {
4760 if (!isset($this->choices[$plugin])) {
4761 unset($default[$plugin]);
4764 parent::__construct($name, $visiblename, $description, $default, null);
4767 public function load_choices() {
4768 if (is_array($this->choices)) {
4769 return true;
4771 $this->choices = array();
4773 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
4774 $this->choices[$plugin] = filter_get_name($plugin);
4776 return true;
4782 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4786 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4788 * Constructor
4789 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4790 * @param string $visiblename localised
4791 * @param string $description long localised info
4792 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4793 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4794 * @param int $size default field size
4796 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4797 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4798 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4804 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4806 * @copyright 2009 Petr Skoda (http://skodak.org)
4807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4809 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4812 * Constructor
4813 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4814 * @param string $visiblename localised
4815 * @param string $description long localised info
4816 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4817 * @param string $yes value used when checked
4818 * @param string $no value used when not checked
4820 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4821 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4822 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4829 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4831 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4833 * @copyright 2010 Sam Hemelryk
4834 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4836 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4838 * Constructor
4839 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4840 * @param string $visiblename localised
4841 * @param string $description long localised info
4842 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4843 * @param string $yes value used when checked
4844 * @param string $no value used when not checked
4846 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4847 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4848 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4855 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4857 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4859 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4861 * Calls parent::__construct with specific arguments
4863 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4864 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4865 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4872 * Graded roles in gradebook
4874 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4876 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4878 * Calls parent::__construct with specific arguments
4880 public function __construct() {
4881 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4882 get_string('configgradebookroles', 'admin'),
4883 array('student'));
4890 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4892 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4894 * Saves the new settings passed in $data
4896 * @param string $data
4897 * @return mixed string or Array
4899 public function write_setting($data) {
4900 global $CFG, $DB;
4902 $oldvalue = $this->config_read($this->name);
4903 $return = parent::write_setting($data);
4904 $newvalue = $this->config_read($this->name);
4906 if ($oldvalue !== $newvalue) {
4907 // force full regrading
4908 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4911 return $return;
4917 * Which roles to show on course description page
4919 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4921 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4923 * Calls parent::__construct with specific arguments
4925 public function __construct() {
4926 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4927 get_string('coursecontact_desc', 'admin'),
4928 array('editingteacher'));
4929 $this->set_updatedcallback(create_function('',
4930 "cache::make('core', 'coursecontacts')->purge();"));
4937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4939 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4941 * Calls parent::__construct with specific arguments
4943 public function __construct() {
4944 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4945 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4949 * Old syntax of class constructor. Deprecated in PHP7.
4951 * @deprecated since Moodle 3.1
4953 public function admin_setting_special_gradelimiting() {
4954 debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
4955 self::__construct();
4959 * Force site regrading
4961 function regrade_all() {
4962 global $CFG;
4963 require_once("$CFG->libdir/gradelib.php");
4964 grade_force_site_regrading();
4968 * Saves the new settings
4970 * @param mixed $data
4971 * @return string empty string or error message
4973 function write_setting($data) {
4974 $previous = $this->get_setting();
4976 if ($previous === null) {
4977 if ($data) {
4978 $this->regrade_all();
4980 } else {
4981 if ($data != $previous) {
4982 $this->regrade_all();
4985 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4991 * Special setting for $CFG->grade_minmaxtouse.
4993 * @package core
4994 * @copyright 2015 Frédéric Massart - FMCorz.net
4995 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4997 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
5000 * Constructor.
5002 public function __construct() {
5003 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
5004 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
5005 array(
5006 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5007 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5013 * Saves the new setting.
5015 * @param mixed $data
5016 * @return string empty string or error message
5018 function write_setting($data) {
5019 global $CFG;
5021 $previous = $this->get_setting();
5022 $result = parent::write_setting($data);
5024 // If saved and the value has changed.
5025 if (empty($result) && $previous != $data) {
5026 require_once($CFG->libdir . '/gradelib.php');
5027 grade_force_site_regrading();
5030 return $result;
5037 * Primary grade export plugin - has state tracking.
5039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5041 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5043 * Calls parent::__construct with specific arguments
5045 public function __construct() {
5046 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5047 get_string('configgradeexport', 'admin'), array(), NULL);
5051 * Load the available choices for the multicheckbox
5053 * @return bool always returns true
5055 public function load_choices() {
5056 if (is_array($this->choices)) {
5057 return true;
5059 $this->choices = array();
5061 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5062 foreach($plugins as $plugin => $unused) {
5063 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5066 return true;
5072 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5074 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5076 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5078 * Config gradepointmax constructor
5080 * @param string $name Overidden by "gradepointmax"
5081 * @param string $visiblename Overridden by "gradepointmax" language string.
5082 * @param string $description Overridden by "gradepointmax_help" language string.
5083 * @param string $defaultsetting Not used, overridden by 100.
5084 * @param mixed $paramtype Overridden by PARAM_INT.
5085 * @param int $size Overridden by 5.
5087 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5088 $name = 'gradepointdefault';
5089 $visiblename = get_string('gradepointdefault', 'grades');
5090 $description = get_string('gradepointdefault_help', 'grades');
5091 $defaultsetting = 100;
5092 $paramtype = PARAM_INT;
5093 $size = 5;
5094 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5098 * Validate data before storage
5099 * @param string $data The submitted data
5100 * @return bool|string true if ok, string if error found
5102 public function validate($data) {
5103 global $CFG;
5104 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5105 return true;
5106 } else {
5107 return get_string('gradepointdefault_validateerror', 'grades');
5114 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5118 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5121 * Config gradepointmax constructor
5123 * @param string $name Overidden by "gradepointmax"
5124 * @param string $visiblename Overridden by "gradepointmax" language string.
5125 * @param string $description Overridden by "gradepointmax_help" language string.
5126 * @param string $defaultsetting Not used, overridden by 100.
5127 * @param mixed $paramtype Overridden by PARAM_INT.
5128 * @param int $size Overridden by 5.
5130 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5131 $name = 'gradepointmax';
5132 $visiblename = get_string('gradepointmax', 'grades');
5133 $description = get_string('gradepointmax_help', 'grades');
5134 $defaultsetting = 100;
5135 $paramtype = PARAM_INT;
5136 $size = 5;
5137 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5141 * Save the selected setting
5143 * @param string $data The selected site
5144 * @return string empty string or error message
5146 public function write_setting($data) {
5147 if ($data === '') {
5148 $data = (int)$this->defaultsetting;
5149 } else {
5150 $data = $data;
5152 return parent::write_setting($data);
5156 * Validate data before storage
5157 * @param string $data The submitted data
5158 * @return bool|string true if ok, string if error found
5160 public function validate($data) {
5161 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5162 return true;
5163 } else {
5164 return get_string('gradepointmax_validateerror', 'grades');
5169 * Return an XHTML string for the setting
5170 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5171 * @param string $query search query to be highlighted
5172 * @return string XHTML to display control
5174 public function output_html($data, $query = '') {
5175 $default = $this->get_defaultsetting();
5177 $attr = array(
5178 'type' => 'text',
5179 'size' => $this->size,
5180 'id' => $this->get_id(),
5181 'name' => $this->get_full_name(),
5182 'value' => s($data),
5183 'maxlength' => '5'
5185 $input = html_writer::empty_tag('input', $attr);
5187 $attr = array('class' => 'form-text defaultsnext');
5188 $div = html_writer::tag('div', $input, $attr);
5189 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
5195 * Grade category settings
5197 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5199 class admin_setting_gradecat_combo extends admin_setting {
5200 /** @var array Array of choices */
5201 public $choices;
5204 * Sets choices and calls parent::__construct with passed arguments
5205 * @param string $name
5206 * @param string $visiblename
5207 * @param string $description
5208 * @param mixed $defaultsetting string or array depending on implementation
5209 * @param array $choices An array of choices for the control
5211 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5212 $this->choices = $choices;
5213 parent::__construct($name, $visiblename, $description, $defaultsetting);
5217 * Return the current setting(s) array
5219 * @return array Array of value=>xx, forced=>xx, adv=>xx
5221 public function get_setting() {
5222 global $CFG;
5224 $value = $this->config_read($this->name);
5225 $flag = $this->config_read($this->name.'_flag');
5227 if (is_null($value) or is_null($flag)) {
5228 return NULL;
5231 $flag = (int)$flag;
5232 $forced = (boolean)(1 & $flag); // first bit
5233 $adv = (boolean)(2 & $flag); // second bit
5235 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5239 * Save the new settings passed in $data
5241 * @todo Add vartype handling to ensure $data is array
5242 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5243 * @return string empty or error message
5245 public function write_setting($data) {
5246 global $CFG;
5248 $value = $data['value'];
5249 $forced = empty($data['forced']) ? 0 : 1;
5250 $adv = empty($data['adv']) ? 0 : 2;
5251 $flag = ($forced | $adv); //bitwise or
5253 if (!in_array($value, array_keys($this->choices))) {
5254 return 'Error setting ';
5257 $oldvalue = $this->config_read($this->name);
5258 $oldflag = (int)$this->config_read($this->name.'_flag');
5259 $oldforced = (1 & $oldflag); // first bit
5261 $result1 = $this->config_write($this->name, $value);
5262 $result2 = $this->config_write($this->name.'_flag', $flag);
5264 // force regrade if needed
5265 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5266 require_once($CFG->libdir.'/gradelib.php');
5267 grade_category::updated_forced_settings();
5270 if ($result1 and $result2) {
5271 return '';
5272 } else {
5273 return get_string('errorsetting', 'admin');
5278 * Return XHTML to display the field and wrapping div
5280 * @todo Add vartype handling to ensure $data is array
5281 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5282 * @param string $query
5283 * @return string XHTML to display control
5285 public function output_html($data, $query='') {
5286 $value = $data['value'];
5287 $forced = !empty($data['forced']);
5288 $adv = !empty($data['adv']);
5290 $default = $this->get_defaultsetting();
5291 if (!is_null($default)) {
5292 $defaultinfo = array();
5293 if (isset($this->choices[$default['value']])) {
5294 $defaultinfo[] = $this->choices[$default['value']];
5296 if (!empty($default['forced'])) {
5297 $defaultinfo[] = get_string('force');
5299 if (!empty($default['adv'])) {
5300 $defaultinfo[] = get_string('advanced');
5302 $defaultinfo = implode(', ', $defaultinfo);
5304 } else {
5305 $defaultinfo = NULL;
5309 $return = '<div class="form-group">';
5310 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5311 foreach ($this->choices as $key => $val) {
5312 // the string cast is needed because key may be integer - 0 is equal to most strings!
5313 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5315 $return .= '</select>';
5316 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5317 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5318 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5319 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5320 $return .= '</div>';
5322 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5328 * Selection of grade report in user profiles
5330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5332 class admin_setting_grade_profilereport extends admin_setting_configselect {
5334 * Calls parent::__construct with specific arguments
5336 public function __construct() {
5337 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5341 * Loads an array of choices for the configselect control
5343 * @return bool always return true
5345 public function load_choices() {
5346 if (is_array($this->choices)) {
5347 return true;
5349 $this->choices = array();
5351 global $CFG;
5352 require_once($CFG->libdir.'/gradelib.php');
5354 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5355 if (file_exists($plugindir.'/lib.php')) {
5356 require_once($plugindir.'/lib.php');
5357 $functionname = 'grade_report_'.$plugin.'_profilereport';
5358 if (function_exists($functionname)) {
5359 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5363 return true;
5368 * Provides a selection of grade reports to be used for "grades".
5370 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5371 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5373 class admin_setting_my_grades_report extends admin_setting_configselect {
5376 * Calls parent::__construct with specific arguments.
5378 public function __construct() {
5379 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5380 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5384 * Loads an array of choices for the configselect control.
5386 * @return bool always returns true.
5388 public function load_choices() {
5389 global $CFG; // Remove this line and behold the horror of behat test failures!
5390 $this->choices = array();
5391 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5392 if (file_exists($plugindir . '/lib.php')) {
5393 require_once($plugindir . '/lib.php');
5394 // Check to see if the class exists. Check the correct plugin convention first.
5395 if (class_exists('gradereport_' . $plugin)) {
5396 $classname = 'gradereport_' . $plugin;
5397 } else if (class_exists('grade_report_' . $plugin)) {
5398 // We are using the old plugin naming convention.
5399 $classname = 'grade_report_' . $plugin;
5400 } else {
5401 continue;
5403 if ($classname::supports_mygrades()) {
5404 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5408 // Add an option to specify an external url.
5409 $this->choices['external'] = get_string('externalurl', 'grades');
5410 return true;
5415 * Special class for register auth selection
5417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5419 class admin_setting_special_registerauth extends admin_setting_configselect {
5421 * Calls parent::__construct with specific arguments
5423 public function __construct() {
5424 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5428 * Returns the default option
5430 * @return string empty or default option
5432 public function get_defaultsetting() {
5433 $this->load_choices();
5434 $defaultsetting = parent::get_defaultsetting();
5435 if (array_key_exists($defaultsetting, $this->choices)) {
5436 return $defaultsetting;
5437 } else {
5438 return '';
5443 * Loads the possible choices for the array
5445 * @return bool always returns true
5447 public function load_choices() {
5448 global $CFG;
5450 if (is_array($this->choices)) {
5451 return true;
5453 $this->choices = array();
5454 $this->choices[''] = get_string('disable');
5456 $authsenabled = get_enabled_auth_plugins(true);
5458 foreach ($authsenabled as $auth) {
5459 $authplugin = get_auth_plugin($auth);
5460 if (!$authplugin->can_signup()) {
5461 continue;
5463 // Get the auth title (from core or own auth lang files)
5464 $authtitle = $authplugin->get_title();
5465 $this->choices[$auth] = $authtitle;
5467 return true;
5473 * General plugins manager
5475 class admin_page_pluginsoverview extends admin_externalpage {
5478 * Sets basic information about the external page
5480 public function __construct() {
5481 global $CFG;
5482 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5483 "$CFG->wwwroot/$CFG->admin/plugins.php");
5488 * Module manage page
5490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5492 class admin_page_managemods extends admin_externalpage {
5494 * Calls parent::__construct with specific arguments
5496 public function __construct() {
5497 global $CFG;
5498 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5502 * Try to find the specified module
5504 * @param string $query The module to search for
5505 * @return array
5507 public function search($query) {
5508 global $CFG, $DB;
5509 if ($result = parent::search($query)) {
5510 return $result;
5513 $found = false;
5514 if ($modules = $DB->get_records('modules')) {
5515 foreach ($modules as $module) {
5516 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5517 continue;
5519 if (strpos($module->name, $query) !== false) {
5520 $found = true;
5521 break;
5523 $strmodulename = get_string('modulename', $module->name);
5524 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5525 $found = true;
5526 break;
5530 if ($found) {
5531 $result = new stdClass();
5532 $result->page = $this;
5533 $result->settings = array();
5534 return array($this->name => $result);
5535 } else {
5536 return array();
5543 * Special class for enrol plugins management.
5545 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5548 class admin_setting_manageenrols extends admin_setting {
5550 * Calls parent::__construct with specific arguments
5552 public function __construct() {
5553 $this->nosave = true;
5554 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5558 * Always returns true, does nothing
5560 * @return true
5562 public function get_setting() {
5563 return true;
5567 * Always returns true, does nothing
5569 * @return true
5571 public function get_defaultsetting() {
5572 return true;
5576 * Always returns '', does not write anything
5578 * @return string Always returns ''
5580 public function write_setting($data) {
5581 // do not write any setting
5582 return '';
5586 * Checks if $query is one of the available enrol plugins
5588 * @param string $query The string to search for
5589 * @return bool Returns true if found, false if not
5591 public function is_related($query) {
5592 if (parent::is_related($query)) {
5593 return true;
5596 $query = core_text::strtolower($query);
5597 $enrols = enrol_get_plugins(false);
5598 foreach ($enrols as $name=>$enrol) {
5599 $localised = get_string('pluginname', 'enrol_'.$name);
5600 if (strpos(core_text::strtolower($name), $query) !== false) {
5601 return true;
5603 if (strpos(core_text::strtolower($localised), $query) !== false) {
5604 return true;
5607 return false;
5611 * Builds the XHTML to display the control
5613 * @param string $data Unused
5614 * @param string $query
5615 * @return string
5617 public function output_html($data, $query='') {
5618 global $CFG, $OUTPUT, $DB, $PAGE;
5620 // Display strings.
5621 $strup = get_string('up');
5622 $strdown = get_string('down');
5623 $strsettings = get_string('settings');
5624 $strenable = get_string('enable');
5625 $strdisable = get_string('disable');
5626 $struninstall = get_string('uninstallplugin', 'core_admin');
5627 $strusage = get_string('enrolusage', 'enrol');
5628 $strversion = get_string('version');
5629 $strtest = get_string('testsettings', 'core_enrol');
5631 $pluginmanager = core_plugin_manager::instance();
5633 $enrols_available = enrol_get_plugins(false);
5634 $active_enrols = enrol_get_plugins(true);
5636 $allenrols = array();
5637 foreach ($active_enrols as $key=>$enrol) {
5638 $allenrols[$key] = true;
5640 foreach ($enrols_available as $key=>$enrol) {
5641 $allenrols[$key] = true;
5643 // Now find all borked plugins and at least allow then to uninstall.
5644 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5645 foreach ($condidates as $candidate) {
5646 if (empty($allenrols[$candidate])) {
5647 $allenrols[$candidate] = true;
5651 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5652 $return .= $OUTPUT->box_start('generalbox enrolsui');
5654 $table = new html_table();
5655 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5656 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5657 $table->id = 'courseenrolmentplugins';
5658 $table->attributes['class'] = 'admintable generaltable';
5659 $table->data = array();
5661 // Iterate through enrol plugins and add to the display table.
5662 $updowncount = 1;
5663 $enrolcount = count($active_enrols);
5664 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5665 $printed = array();
5666 foreach($allenrols as $enrol => $unused) {
5667 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5668 $version = get_config('enrol_'.$enrol, 'version');
5669 if ($version === false) {
5670 $version = '';
5673 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5674 $name = get_string('pluginname', 'enrol_'.$enrol);
5675 } else {
5676 $name = $enrol;
5678 // Usage.
5679 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5680 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5681 $usage = "$ci / $cp";
5683 // Hide/show links.
5684 $class = '';
5685 if (isset($active_enrols[$enrol])) {
5686 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5687 $hideshow = "<a href=\"$aurl\">";
5688 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5689 $enabled = true;
5690 $displayname = $name;
5691 } else if (isset($enrols_available[$enrol])) {
5692 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5693 $hideshow = "<a href=\"$aurl\">";
5694 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5695 $enabled = false;
5696 $displayname = $name;
5697 $class = 'dimmed_text';
5698 } else {
5699 $hideshow = '';
5700 $enabled = false;
5701 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5703 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5704 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5705 } else {
5706 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5709 // Up/down link (only if enrol is enabled).
5710 $updown = '';
5711 if ($enabled) {
5712 if ($updowncount > 1) {
5713 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5714 $updown .= "<a href=\"$aurl\">";
5715 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5716 } else {
5717 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5719 if ($updowncount < $enrolcount) {
5720 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5721 $updown .= "<a href=\"$aurl\">";
5722 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5723 } else {
5724 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5726 ++$updowncount;
5729 // Add settings link.
5730 if (!$version) {
5731 $settings = '';
5732 } else if ($surl = $plugininfo->get_settings_url()) {
5733 $settings = html_writer::link($surl, $strsettings);
5734 } else {
5735 $settings = '';
5738 // Add uninstall info.
5739 $uninstall = '';
5740 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5741 $uninstall = html_writer::link($uninstallurl, $struninstall);
5744 $test = '';
5745 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5746 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5747 $test = html_writer::link($testsettingsurl, $strtest);
5750 // Add a row to the table.
5751 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5752 if ($class) {
5753 $row->attributes['class'] = $class;
5755 $table->data[] = $row;
5757 $printed[$enrol] = true;
5760 $return .= html_writer::table($table);
5761 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5762 $return .= $OUTPUT->box_end();
5763 return highlight($query, $return);
5769 * Blocks manage page
5771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5773 class admin_page_manageblocks extends admin_externalpage {
5775 * Calls parent::__construct with specific arguments
5777 public function __construct() {
5778 global $CFG;
5779 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5783 * Search for a specific block
5785 * @param string $query The string to search for
5786 * @return array
5788 public function search($query) {
5789 global $CFG, $DB;
5790 if ($result = parent::search($query)) {
5791 return $result;
5794 $found = false;
5795 if ($blocks = $DB->get_records('block')) {
5796 foreach ($blocks as $block) {
5797 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5798 continue;
5800 if (strpos($block->name, $query) !== false) {
5801 $found = true;
5802 break;
5804 $strblockname = get_string('pluginname', 'block_'.$block->name);
5805 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5806 $found = true;
5807 break;
5811 if ($found) {
5812 $result = new stdClass();
5813 $result->page = $this;
5814 $result->settings = array();
5815 return array($this->name => $result);
5816 } else {
5817 return array();
5823 * Message outputs configuration
5825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5827 class admin_page_managemessageoutputs extends admin_externalpage {
5829 * Calls parent::__construct with specific arguments
5831 public function __construct() {
5832 global $CFG;
5833 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5837 * Search for a specific message processor
5839 * @param string $query The string to search for
5840 * @return array
5842 public function search($query) {
5843 global $CFG, $DB;
5844 if ($result = parent::search($query)) {
5845 return $result;
5848 $found = false;
5849 if ($processors = get_message_processors()) {
5850 foreach ($processors as $processor) {
5851 if (!$processor->available) {
5852 continue;
5854 if (strpos($processor->name, $query) !== false) {
5855 $found = true;
5856 break;
5858 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5859 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5860 $found = true;
5861 break;
5865 if ($found) {
5866 $result = new stdClass();
5867 $result->page = $this;
5868 $result->settings = array();
5869 return array($this->name => $result);
5870 } else {
5871 return array();
5877 * Default message outputs configuration
5879 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5881 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5883 * Calls parent::__construct with specific arguments
5885 public function __construct() {
5886 global $CFG;
5887 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5893 * Manage question behaviours page
5895 * @copyright 2011 The Open University
5896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5898 class admin_page_manageqbehaviours extends admin_externalpage {
5900 * Constructor
5902 public function __construct() {
5903 global $CFG;
5904 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5905 new moodle_url('/admin/qbehaviours.php'));
5909 * Search question behaviours for the specified string
5911 * @param string $query The string to search for in question behaviours
5912 * @return array
5914 public function search($query) {
5915 global $CFG;
5916 if ($result = parent::search($query)) {
5917 return $result;
5920 $found = false;
5921 require_once($CFG->dirroot . '/question/engine/lib.php');
5922 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5923 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5924 $query) !== false) {
5925 $found = true;
5926 break;
5929 if ($found) {
5930 $result = new stdClass();
5931 $result->page = $this;
5932 $result->settings = array();
5933 return array($this->name => $result);
5934 } else {
5935 return array();
5942 * Question type manage page
5944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5946 class admin_page_manageqtypes extends admin_externalpage {
5948 * Calls parent::__construct with specific arguments
5950 public function __construct() {
5951 global $CFG;
5952 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5953 new moodle_url('/admin/qtypes.php'));
5957 * Search question types for the specified string
5959 * @param string $query The string to search for in question types
5960 * @return array
5962 public function search($query) {
5963 global $CFG;
5964 if ($result = parent::search($query)) {
5965 return $result;
5968 $found = false;
5969 require_once($CFG->dirroot . '/question/engine/bank.php');
5970 foreach (question_bank::get_all_qtypes() as $qtype) {
5971 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5972 $found = true;
5973 break;
5976 if ($found) {
5977 $result = new stdClass();
5978 $result->page = $this;
5979 $result->settings = array();
5980 return array($this->name => $result);
5981 } else {
5982 return array();
5988 class admin_page_manageportfolios extends admin_externalpage {
5990 * Calls parent::__construct with specific arguments
5992 public function __construct() {
5993 global $CFG;
5994 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5995 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5999 * Searches page for the specified string.
6000 * @param string $query The string to search for
6001 * @return bool True if it is found on this page
6003 public function search($query) {
6004 global $CFG;
6005 if ($result = parent::search($query)) {
6006 return $result;
6009 $found = false;
6010 $portfolios = core_component::get_plugin_list('portfolio');
6011 foreach ($portfolios as $p => $dir) {
6012 if (strpos($p, $query) !== false) {
6013 $found = true;
6014 break;
6017 if (!$found) {
6018 foreach (portfolio_instances(false, false) as $instance) {
6019 $title = $instance->get('name');
6020 if (strpos(core_text::strtolower($title), $query) !== false) {
6021 $found = true;
6022 break;
6027 if ($found) {
6028 $result = new stdClass();
6029 $result->page = $this;
6030 $result->settings = array();
6031 return array($this->name => $result);
6032 } else {
6033 return array();
6039 class admin_page_managerepositories extends admin_externalpage {
6041 * Calls parent::__construct with specific arguments
6043 public function __construct() {
6044 global $CFG;
6045 parent::__construct('managerepositories', get_string('manage',
6046 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6050 * Searches page for the specified string.
6051 * @param string $query The string to search for
6052 * @return bool True if it is found on this page
6054 public function search($query) {
6055 global $CFG;
6056 if ($result = parent::search($query)) {
6057 return $result;
6060 $found = false;
6061 $repositories= core_component::get_plugin_list('repository');
6062 foreach ($repositories as $p => $dir) {
6063 if (strpos($p, $query) !== false) {
6064 $found = true;
6065 break;
6068 if (!$found) {
6069 foreach (repository::get_types() as $instance) {
6070 $title = $instance->get_typename();
6071 if (strpos(core_text::strtolower($title), $query) !== false) {
6072 $found = true;
6073 break;
6078 if ($found) {
6079 $result = new stdClass();
6080 $result->page = $this;
6081 $result->settings = array();
6082 return array($this->name => $result);
6083 } else {
6084 return array();
6091 * Special class for authentication administration.
6093 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6095 class admin_setting_manageauths extends admin_setting {
6097 * Calls parent::__construct with specific arguments
6099 public function __construct() {
6100 $this->nosave = true;
6101 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6105 * Always returns true
6107 * @return true
6109 public function get_setting() {
6110 return true;
6114 * Always returns true
6116 * @return true
6118 public function get_defaultsetting() {
6119 return true;
6123 * Always returns '' and doesn't write anything
6125 * @return string Always returns ''
6127 public function write_setting($data) {
6128 // do not write any setting
6129 return '';
6133 * Search to find if Query is related to auth plugin
6135 * @param string $query The string to search for
6136 * @return bool true for related false for not
6138 public function is_related($query) {
6139 if (parent::is_related($query)) {
6140 return true;
6143 $authsavailable = core_component::get_plugin_list('auth');
6144 foreach ($authsavailable as $auth => $dir) {
6145 if (strpos($auth, $query) !== false) {
6146 return true;
6148 $authplugin = get_auth_plugin($auth);
6149 $authtitle = $authplugin->get_title();
6150 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6151 return true;
6154 return false;
6158 * Return XHTML to display control
6160 * @param mixed $data Unused
6161 * @param string $query
6162 * @return string highlight
6164 public function output_html($data, $query='') {
6165 global $CFG, $OUTPUT, $DB;
6167 // display strings
6168 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6169 'settings', 'edit', 'name', 'enable', 'disable',
6170 'up', 'down', 'none', 'users'));
6171 $txt->updown = "$txt->up/$txt->down";
6172 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6173 $txt->testsettings = get_string('testsettings', 'core_auth');
6175 $authsavailable = core_component::get_plugin_list('auth');
6176 get_enabled_auth_plugins(true); // fix the list of enabled auths
6177 if (empty($CFG->auth)) {
6178 $authsenabled = array();
6179 } else {
6180 $authsenabled = explode(',', $CFG->auth);
6183 // construct the display array, with enabled auth plugins at the top, in order
6184 $displayauths = array();
6185 $registrationauths = array();
6186 $registrationauths[''] = $txt->disable;
6187 $authplugins = array();
6188 foreach ($authsenabled as $auth) {
6189 $authplugin = get_auth_plugin($auth);
6190 $authplugins[$auth] = $authplugin;
6191 /// Get the auth title (from core or own auth lang files)
6192 $authtitle = $authplugin->get_title();
6193 /// Apply titles
6194 $displayauths[$auth] = $authtitle;
6195 if ($authplugin->can_signup()) {
6196 $registrationauths[$auth] = $authtitle;
6200 foreach ($authsavailable as $auth => $dir) {
6201 if (array_key_exists($auth, $displayauths)) {
6202 continue; //already in the list
6204 $authplugin = get_auth_plugin($auth);
6205 $authplugins[$auth] = $authplugin;
6206 /// Get the auth title (from core or own auth lang files)
6207 $authtitle = $authplugin->get_title();
6208 /// Apply titles
6209 $displayauths[$auth] = $authtitle;
6210 if ($authplugin->can_signup()) {
6211 $registrationauths[$auth] = $authtitle;
6215 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6216 $return .= $OUTPUT->box_start('generalbox authsui');
6218 $table = new html_table();
6219 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6220 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6221 $table->data = array();
6222 $table->attributes['class'] = 'admintable generaltable';
6223 $table->id = 'manageauthtable';
6225 //add always enabled plugins first
6226 $displayname = $displayauths['manual'];
6227 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6228 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6229 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6230 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6231 $displayname = $displayauths['nologin'];
6232 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6233 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6234 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6237 // iterate through auth plugins and add to the display table
6238 $updowncount = 1;
6239 $authcount = count($authsenabled);
6240 $url = "auth.php?sesskey=" . sesskey();
6241 foreach ($displayauths as $auth => $name) {
6242 if ($auth == 'manual' or $auth == 'nologin') {
6243 continue;
6245 $class = '';
6246 // hide/show link
6247 if (in_array($auth, $authsenabled)) {
6248 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6249 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6250 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6251 $enabled = true;
6252 $displayname = $name;
6254 else {
6255 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6256 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6257 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6258 $enabled = false;
6259 $displayname = $name;
6260 $class = 'dimmed_text';
6263 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6265 // up/down link (only if auth is enabled)
6266 $updown = '';
6267 if ($enabled) {
6268 if ($updowncount > 1) {
6269 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6270 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6272 else {
6273 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6275 if ($updowncount < $authcount) {
6276 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6277 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6279 else {
6280 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6282 ++ $updowncount;
6285 // settings link
6286 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6287 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6288 } else {
6289 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6292 // Uninstall link.
6293 $uninstall = '';
6294 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6295 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6298 $test = '';
6299 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6300 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6301 $test = html_writer::link($testurl, $txt->testsettings);
6304 // Add a row to the table.
6305 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6306 if ($class) {
6307 $row->attributes['class'] = $class;
6309 $table->data[] = $row;
6311 $return .= html_writer::table($table);
6312 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6313 $return .= $OUTPUT->box_end();
6314 return highlight($query, $return);
6320 * Special class for authentication administration.
6322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6324 class admin_setting_manageeditors extends admin_setting {
6326 * Calls parent::__construct with specific arguments
6328 public function __construct() {
6329 $this->nosave = true;
6330 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6334 * Always returns true, does nothing
6336 * @return true
6338 public function get_setting() {
6339 return true;
6343 * Always returns true, does nothing
6345 * @return true
6347 public function get_defaultsetting() {
6348 return true;
6352 * Always returns '', does not write anything
6354 * @return string Always returns ''
6356 public function write_setting($data) {
6357 // do not write any setting
6358 return '';
6362 * Checks if $query is one of the available editors
6364 * @param string $query The string to search for
6365 * @return bool Returns true if found, false if not
6367 public function is_related($query) {
6368 if (parent::is_related($query)) {
6369 return true;
6372 $editors_available = editors_get_available();
6373 foreach ($editors_available as $editor=>$editorstr) {
6374 if (strpos($editor, $query) !== false) {
6375 return true;
6377 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6378 return true;
6381 return false;
6385 * Builds the XHTML to display the control
6387 * @param string $data Unused
6388 * @param string $query
6389 * @return string
6391 public function output_html($data, $query='') {
6392 global $CFG, $OUTPUT;
6394 // display strings
6395 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6396 'up', 'down', 'none'));
6397 $struninstall = get_string('uninstallplugin', 'core_admin');
6399 $txt->updown = "$txt->up/$txt->down";
6401 $editors_available = editors_get_available();
6402 $active_editors = explode(',', $CFG->texteditors);
6404 $active_editors = array_reverse($active_editors);
6405 foreach ($active_editors as $key=>$editor) {
6406 if (empty($editors_available[$editor])) {
6407 unset($active_editors[$key]);
6408 } else {
6409 $name = $editors_available[$editor];
6410 unset($editors_available[$editor]);
6411 $editors_available[$editor] = $name;
6414 if (empty($active_editors)) {
6415 //$active_editors = array('textarea');
6417 $editors_available = array_reverse($editors_available, true);
6418 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6419 $return .= $OUTPUT->box_start('generalbox editorsui');
6421 $table = new html_table();
6422 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6423 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6424 $table->id = 'editormanagement';
6425 $table->attributes['class'] = 'admintable generaltable';
6426 $table->data = array();
6428 // iterate through auth plugins and add to the display table
6429 $updowncount = 1;
6430 $editorcount = count($active_editors);
6431 $url = "editors.php?sesskey=" . sesskey();
6432 foreach ($editors_available as $editor => $name) {
6433 // hide/show link
6434 $class = '';
6435 if (in_array($editor, $active_editors)) {
6436 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6437 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6438 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6439 $enabled = true;
6440 $displayname = $name;
6442 else {
6443 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6444 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6445 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6446 $enabled = false;
6447 $displayname = $name;
6448 $class = 'dimmed_text';
6451 // up/down link (only if auth is enabled)
6452 $updown = '';
6453 if ($enabled) {
6454 if ($updowncount > 1) {
6455 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6456 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6458 else {
6459 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6461 if ($updowncount < $editorcount) {
6462 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6463 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6465 else {
6466 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6468 ++ $updowncount;
6471 // settings link
6472 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6473 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6474 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6475 } else {
6476 $settings = '';
6479 $uninstall = '';
6480 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6481 $uninstall = html_writer::link($uninstallurl, $struninstall);
6484 // Add a row to the table.
6485 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6486 if ($class) {
6487 $row->attributes['class'] = $class;
6489 $table->data[] = $row;
6491 $return .= html_writer::table($table);
6492 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6493 $return .= $OUTPUT->box_end();
6494 return highlight($query, $return);
6499 * Special class for antiviruses administration.
6501 * @copyright 2015 Ruslan Kabalin, Lancaster University.
6502 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6504 class admin_setting_manageantiviruses extends admin_setting {
6506 * Calls parent::__construct with specific arguments
6508 public function __construct() {
6509 $this->nosave = true;
6510 parent::__construct('antivirusesui', get_string('antivirussettings', 'antivirus'), '', '');
6514 * Always returns true, does nothing
6516 * @return true
6518 public function get_setting() {
6519 return true;
6523 * Always returns true, does nothing
6525 * @return true
6527 public function get_defaultsetting() {
6528 return true;
6532 * Always returns '', does not write anything
6534 * @param string $data Unused
6535 * @return string Always returns ''
6537 public function write_setting($data) {
6538 // Do not write any setting.
6539 return '';
6543 * Checks if $query is one of the available editors
6545 * @param string $query The string to search for
6546 * @return bool Returns true if found, false if not
6548 public function is_related($query) {
6549 if (parent::is_related($query)) {
6550 return true;
6553 $antivirusesavailable = \core\antivirus\manager::get_available();
6554 foreach ($antivirusesavailable as $antivirus => $antivirusstr) {
6555 if (strpos($antivirus, $query) !== false) {
6556 return true;
6558 if (strpos(core_text::strtolower($antivirusstr), $query) !== false) {
6559 return true;
6562 return false;
6566 * Builds the XHTML to display the control
6568 * @param string $data Unused
6569 * @param string $query
6570 * @return string
6572 public function output_html($data, $query='') {
6573 global $CFG, $OUTPUT;
6575 // Display strings.
6576 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6577 'up', 'down', 'none'));
6578 $struninstall = get_string('uninstallplugin', 'core_admin');
6580 $txt->updown = "$txt->up/$txt->down";
6582 $antivirusesavailable = \core\antivirus\manager::get_available();
6583 $activeantiviruses = explode(',', $CFG->antiviruses);
6585 $activeantiviruses = array_reverse($activeantiviruses);
6586 foreach ($activeantiviruses as $key => $antivirus) {
6587 if (empty($antivirusesavailable[$antivirus])) {
6588 unset($activeantiviruses[$key]);
6589 } else {
6590 $name = $antivirusesavailable[$antivirus];
6591 unset($antivirusesavailable[$antivirus]);
6592 $antivirusesavailable[$antivirus] = $name;
6595 $antivirusesavailable = array_reverse($antivirusesavailable, true);
6596 $return = $OUTPUT->heading(get_string('actantivirushdr', 'antivirus'), 3, 'main', true);
6597 $return .= $OUTPUT->box_start('generalbox antivirusesui');
6599 $table = new html_table();
6600 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6601 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6602 $table->id = 'antivirusmanagement';
6603 $table->attributes['class'] = 'admintable generaltable';
6604 $table->data = array();
6606 // Iterate through auth plugins and add to the display table.
6607 $updowncount = 1;
6608 $antiviruscount = count($activeantiviruses);
6609 $baseurl = new moodle_url('/admin/antiviruses.php', array('sesskey' => sesskey()));
6610 foreach ($antivirusesavailable as $antivirus => $name) {
6611 // Hide/show link.
6612 $class = '';
6613 if (in_array($antivirus, $activeantiviruses)) {
6614 $hideshowurl = $baseurl;
6615 $hideshowurl->params(array('action' => 'disable', 'antivirus' => $antivirus));
6616 $hideshowimg = html_writer::img($OUTPUT->pix_url('t/hide'), 'disable', array('class' => 'iconsmall'));
6617 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6618 $enabled = true;
6619 $displayname = $name;
6620 } else {
6621 $hideshowurl = $baseurl;
6622 $hideshowurl->params(array('action' => 'enable', 'antivirus' => $antivirus));
6623 $hideshowimg = html_writer::img($OUTPUT->pix_url('t/show'), 'enable', array('class' => 'iconsmall'));
6624 $hideshow = html_writer::link($hideshowurl, $hideshowimg);
6625 $enabled = false;
6626 $displayname = $name;
6627 $class = 'dimmed_text';
6630 // Up/down link.
6631 $updown = '';
6632 if ($enabled) {
6633 if ($updowncount > 1) {
6634 $updownurl = $baseurl;
6635 $updownurl->params(array('action' => 'up', 'antivirus' => $antivirus));
6636 $updownimg = html_writer::img($OUTPUT->pix_url('t/up'), 'up', array('class' => 'iconsmall'));
6637 $updown = html_writer::link($updownurl, $updownimg);
6638 } else {
6639 $updown .= html_writer::img($OUTPUT->pix_url('spacer'), '', array('class' => 'iconsmall'));
6641 if ($updowncount < $antiviruscount) {
6642 $updownurl = $baseurl;
6643 $updownurl->params(array('action' => 'down', 'antivirus' => $antivirus));
6644 $updownimg = html_writer::img($OUTPUT->pix_url('t/down'), 'down', array('class' => 'iconsmall'));
6645 $updown = html_writer::link($updownurl, $updownimg);
6646 } else {
6647 $updown .= html_writer::img($OUTPUT->pix_url('spacer'), '', array('class' => 'iconsmall'));
6649 ++ $updowncount;
6652 // Settings link.
6653 if (file_exists($CFG->dirroot.'/lib/antivirus/'.$antivirus.'/settings.php')) {
6654 $eurl = new moodle_url('/admin/settings.php', array('section' => 'antivirussettings'.$antivirus));
6655 $settings = html_writer::link($eurl, $txt->settings);
6656 } else {
6657 $settings = '';
6660 $uninstall = '';
6661 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('antivirus_'.$antivirus, 'manage')) {
6662 $uninstall = html_writer::link($uninstallurl, $struninstall);
6665 // Add a row to the table.
6666 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6667 if ($class) {
6668 $row->attributes['class'] = $class;
6670 $table->data[] = $row;
6672 $return .= html_writer::table($table);
6673 $return .= get_string('configantivirusplugins', 'antivirus') . html_writer::empty_tag('br') . get_string('tablenosave', 'admin');
6674 $return .= $OUTPUT->box_end();
6675 return highlight($query, $return);
6680 * Special class for license administration.
6682 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6684 class admin_setting_managelicenses extends admin_setting {
6686 * Calls parent::__construct with specific arguments
6688 public function __construct() {
6689 $this->nosave = true;
6690 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6694 * Always returns true, does nothing
6696 * @return true
6698 public function get_setting() {
6699 return true;
6703 * Always returns true, does nothing
6705 * @return true
6707 public function get_defaultsetting() {
6708 return true;
6712 * Always returns '', does not write anything
6714 * @return string Always returns ''
6716 public function write_setting($data) {
6717 // do not write any setting
6718 return '';
6722 * Builds the XHTML to display the control
6724 * @param string $data Unused
6725 * @param string $query
6726 * @return string
6728 public function output_html($data, $query='') {
6729 global $CFG, $OUTPUT;
6730 require_once($CFG->libdir . '/licenselib.php');
6731 $url = "licenses.php?sesskey=" . sesskey();
6733 // display strings
6734 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6735 $licenses = license_manager::get_licenses();
6737 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6739 $return .= $OUTPUT->box_start('generalbox editorsui');
6741 $table = new html_table();
6742 $table->head = array($txt->name, $txt->enable);
6743 $table->colclasses = array('leftalign', 'centeralign');
6744 $table->id = 'availablelicenses';
6745 $table->attributes['class'] = 'admintable generaltable';
6746 $table->data = array();
6748 foreach ($licenses as $value) {
6749 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6751 if ($value->enabled == 1) {
6752 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6753 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6754 } else {
6755 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6756 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6759 if ($value->shortname == $CFG->sitedefaultlicense) {
6760 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6761 $hideshow = '';
6764 $enabled = true;
6766 $table->data[] =array($displayname, $hideshow);
6768 $return .= html_writer::table($table);
6769 $return .= $OUTPUT->box_end();
6770 return highlight($query, $return);
6775 * Course formats manager. Allows to enable/disable formats and jump to settings
6777 class admin_setting_manageformats extends admin_setting {
6780 * Calls parent::__construct with specific arguments
6782 public function __construct() {
6783 $this->nosave = true;
6784 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6788 * Always returns true
6790 * @return true
6792 public function get_setting() {
6793 return true;
6797 * Always returns true
6799 * @return true
6801 public function get_defaultsetting() {
6802 return true;
6806 * Always returns '' and doesn't write anything
6808 * @param mixed $data string or array, must not be NULL
6809 * @return string Always returns ''
6811 public function write_setting($data) {
6812 // do not write any setting
6813 return '';
6817 * Search to find if Query is related to format plugin
6819 * @param string $query The string to search for
6820 * @return bool true for related false for not
6822 public function is_related($query) {
6823 if (parent::is_related($query)) {
6824 return true;
6826 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6827 foreach ($formats as $format) {
6828 if (strpos($format->component, $query) !== false ||
6829 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6830 return true;
6833 return false;
6837 * Return XHTML to display control
6839 * @param mixed $data Unused
6840 * @param string $query
6841 * @return string highlight
6843 public function output_html($data, $query='') {
6844 global $CFG, $OUTPUT;
6845 $return = '';
6846 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6847 $return .= $OUTPUT->box_start('generalbox formatsui');
6849 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6851 // display strings
6852 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6853 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6854 $txt->updown = "$txt->up/$txt->down";
6856 $table = new html_table();
6857 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6858 $table->align = array('left', 'center', 'center', 'center', 'center');
6859 $table->attributes['class'] = 'manageformattable generaltable admintable';
6860 $table->data = array();
6862 $cnt = 0;
6863 $defaultformat = get_config('moodlecourse', 'format');
6864 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6865 foreach ($formats as $format) {
6866 $url = new moodle_url('/admin/courseformats.php',
6867 array('sesskey' => sesskey(), 'format' => $format->name));
6868 $isdefault = '';
6869 $class = '';
6870 if ($format->is_enabled()) {
6871 $strformatname = $format->displayname;
6872 if ($defaultformat === $format->name) {
6873 $hideshow = $txt->default;
6874 } else {
6875 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6876 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6878 } else {
6879 $strformatname = $format->displayname;
6880 $class = 'dimmed_text';
6881 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6882 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6884 $updown = '';
6885 if ($cnt) {
6886 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6887 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6888 } else {
6889 $updown .= $spacer;
6891 if ($cnt < count($formats) - 1) {
6892 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6893 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6894 } else {
6895 $updown .= $spacer;
6897 $cnt++;
6898 $settings = '';
6899 if ($format->get_settings_url()) {
6900 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6902 $uninstall = '';
6903 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6904 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6906 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6907 if ($class) {
6908 $row->attributes['class'] = $class;
6910 $table->data[] = $row;
6912 $return .= html_writer::table($table);
6913 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6914 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6915 $return .= $OUTPUT->box_end();
6916 return highlight($query, $return);
6921 * Data formats manager. Allow reorder and to enable/disable data formats and jump to settings
6923 * @copyright 2016 Brendan Heywood (brendan@catalyst-au.net)
6924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6926 class admin_setting_managedataformats extends admin_setting {
6929 * Calls parent::__construct with specific arguments
6931 public function __construct() {
6932 $this->nosave = true;
6933 parent::__construct('managedataformats', new lang_string('managedataformats'), '', '');
6937 * Always returns true
6939 * @return true
6941 public function get_setting() {
6942 return true;
6946 * Always returns true
6948 * @return true
6950 public function get_defaultsetting() {
6951 return true;
6955 * Always returns '' and doesn't write anything
6957 * @param mixed $data string or array, must not be NULL
6958 * @return string Always returns ''
6960 public function write_setting($data) {
6961 // Do not write any setting.
6962 return '';
6966 * Search to find if Query is related to format plugin
6968 * @param string $query The string to search for
6969 * @return bool true for related false for not
6971 public function is_related($query) {
6972 if (parent::is_related($query)) {
6973 return true;
6975 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
6976 foreach ($formats as $format) {
6977 if (strpos($format->component, $query) !== false ||
6978 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6979 return true;
6982 return false;
6986 * Return XHTML to display control
6988 * @param mixed $data Unused
6989 * @param string $query
6990 * @return string highlight
6992 public function output_html($data, $query='') {
6993 global $CFG, $OUTPUT;
6994 $return = '';
6996 $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
6998 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6999 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
7000 $txt->updown = "$txt->up/$txt->down";
7002 $table = new html_table();
7003 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
7004 $table->align = array('left', 'center', 'center', 'center', 'center');
7005 $table->attributes['class'] = 'manageformattable generaltable admintable';
7006 $table->data = array();
7008 $cnt = 0;
7009 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
7010 $totalenabled = 0;
7011 foreach ($formats as $format) {
7012 if ($format->is_enabled() && $format->is_installed_and_upgraded()) {
7013 $totalenabled++;
7016 foreach ($formats as $format) {
7017 $status = $format->get_status();
7018 $url = new moodle_url('/admin/dataformats.php',
7019 array('sesskey' => sesskey(), 'name' => $format->name));
7021 $class = '';
7022 if ($format->is_enabled()) {
7023 $strformatname = $format->displayname;
7024 if ($totalenabled == 1&& $format->is_enabled()) {
7025 $hideshow = '';
7026 } else {
7027 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
7028 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
7030 } else {
7031 $class = 'dimmed_text';
7032 $strformatname = $format->displayname;
7033 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
7034 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
7037 $updown = '';
7038 if ($cnt) {
7039 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
7040 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
7041 } else {
7042 $updown .= $spacer;
7044 if ($cnt < count($formats) - 1) {
7045 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
7046 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
7047 } else {
7048 $updown .= $spacer;
7051 $uninstall = '';
7052 if ($status === core_plugin_manager::PLUGIN_STATUS_MISSING) {
7053 $uninstall = get_string('status_missing', 'core_plugin');
7054 } else if ($status === core_plugin_manager::PLUGIN_STATUS_NEW) {
7055 $uninstall = get_string('status_new', 'core_plugin');
7056 } else if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('dataformat_'.$format->name, 'manage')) {
7057 if ($totalenabled != 1 || !$format->is_enabled()) {
7058 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
7062 $settings = '';
7063 if ($format->get_settings_url()) {
7064 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
7067 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
7068 if ($class) {
7069 $row->attributes['class'] = $class;
7071 $table->data[] = $row;
7072 $cnt++;
7074 $return .= html_writer::table($table);
7075 return highlight($query, $return);
7080 * Special class for filter administration.
7082 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7084 class admin_page_managefilters extends admin_externalpage {
7086 * Calls parent::__construct with specific arguments
7088 public function __construct() {
7089 global $CFG;
7090 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
7094 * Searches all installed filters for specified filter
7096 * @param string $query The filter(string) to search for
7097 * @param string $query
7099 public function search($query) {
7100 global $CFG;
7101 if ($result = parent::search($query)) {
7102 return $result;
7105 $found = false;
7106 $filternames = filter_get_all_installed();
7107 foreach ($filternames as $path => $strfiltername) {
7108 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
7109 $found = true;
7110 break;
7112 if (strpos($path, $query) !== false) {
7113 $found = true;
7114 break;
7118 if ($found) {
7119 $result = new stdClass;
7120 $result->page = $this;
7121 $result->settings = array();
7122 return array($this->name => $result);
7123 } else {
7124 return array();
7131 * Initialise admin page - this function does require login and permission
7132 * checks specified in page definition.
7134 * This function must be called on each admin page before other code.
7136 * @global moodle_page $PAGE
7138 * @param string $section name of page
7139 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
7140 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
7141 * added to the turn blocks editing on/off form, so this page reloads correctly.
7142 * @param string $actualurl if the actual page being viewed is not the normal one for this
7143 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
7144 * @param array $options Additional options that can be specified for page setup.
7145 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
7147 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
7148 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
7150 $PAGE->set_context(null); // hack - set context to something, by default to system context
7152 $site = get_site();
7153 require_login();
7155 if (!empty($options['pagelayout'])) {
7156 // A specific page layout has been requested.
7157 $PAGE->set_pagelayout($options['pagelayout']);
7158 } else if ($section === 'upgradesettings') {
7159 $PAGE->set_pagelayout('maintenance');
7160 } else {
7161 $PAGE->set_pagelayout('admin');
7164 $adminroot = admin_get_root(false, false); // settings not required for external pages
7165 $extpage = $adminroot->locate($section, true);
7167 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
7168 // The requested section isn't in the admin tree
7169 // It could be because the user has inadequate capapbilities or because the section doesn't exist
7170 if (!has_capability('moodle/site:config', context_system::instance())) {
7171 // The requested section could depend on a different capability
7172 // but most likely the user has inadequate capabilities
7173 print_error('accessdenied', 'admin');
7174 } else {
7175 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
7179 // this eliminates our need to authenticate on the actual pages
7180 if (!$extpage->check_access()) {
7181 print_error('accessdenied', 'admin');
7182 die;
7185 navigation_node::require_admin_tree();
7187 // $PAGE->set_extra_button($extrabutton); TODO
7189 if (!$actualurl) {
7190 $actualurl = $extpage->url;
7193 $PAGE->set_url($actualurl, $extraurlparams);
7194 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
7195 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
7198 if (empty($SITE->fullname) || empty($SITE->shortname)) {
7199 // During initial install.
7200 $strinstallation = get_string('installation', 'install');
7201 $strsettings = get_string('settings');
7202 $PAGE->navbar->add($strsettings);
7203 $PAGE->set_title($strinstallation);
7204 $PAGE->set_heading($strinstallation);
7205 $PAGE->set_cacheable(false);
7206 return;
7209 // Locate the current item on the navigation and make it active when found.
7210 $path = $extpage->path;
7211 $node = $PAGE->settingsnav;
7212 while ($node && count($path) > 0) {
7213 $node = $node->get(array_pop($path));
7215 if ($node) {
7216 $node->make_active();
7219 // Normal case.
7220 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
7221 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
7222 $USER->editing = $adminediting;
7225 $visiblepathtosection = array_reverse($extpage->visiblepath);
7227 if ($PAGE->user_allowed_editing()) {
7228 if ($PAGE->user_is_editing()) {
7229 $caption = get_string('blockseditoff');
7230 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
7231 } else {
7232 $caption = get_string('blocksediton');
7233 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
7235 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
7238 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
7239 $PAGE->set_heading($SITE->fullname);
7241 // prevent caching in nav block
7242 $PAGE->navigation->clear_cache();
7246 * Returns the reference to admin tree root
7248 * @return object admin_root object
7250 function admin_get_root($reload=false, $requirefulltree=true) {
7251 global $CFG, $DB, $OUTPUT;
7253 static $ADMIN = NULL;
7255 if (is_null($ADMIN)) {
7256 // create the admin tree!
7257 $ADMIN = new admin_root($requirefulltree);
7260 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
7261 $ADMIN->purge_children($requirefulltree);
7264 if (!$ADMIN->loaded) {
7265 // we process this file first to create categories first and in correct order
7266 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
7268 // now we process all other files in admin/settings to build the admin tree
7269 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
7270 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
7271 continue;
7273 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
7274 // plugins are loaded last - they may insert pages anywhere
7275 continue;
7277 require($file);
7279 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
7281 $ADMIN->loaded = true;
7284 return $ADMIN;
7287 /// settings utility functions
7290 * This function applies default settings.
7292 * @param object $node, NULL means complete tree, null by default
7293 * @param bool $unconditional if true overrides all values with defaults, null buy default
7295 function admin_apply_default_settings($node=NULL, $unconditional=true) {
7296 global $CFG;
7298 if (is_null($node)) {
7299 core_plugin_manager::reset_caches();
7300 $node = admin_get_root(true, true);
7303 if ($node instanceof admin_category) {
7304 $entries = array_keys($node->children);
7305 foreach ($entries as $entry) {
7306 admin_apply_default_settings($node->children[$entry], $unconditional);
7309 } else if ($node instanceof admin_settingpage) {
7310 foreach ($node->settings as $setting) {
7311 if (!$unconditional and !is_null($setting->get_setting())) {
7312 //do not override existing defaults
7313 continue;
7315 $defaultsetting = $setting->get_defaultsetting();
7316 if (is_null($defaultsetting)) {
7317 // no value yet - default maybe applied after admin user creation or in upgradesettings
7318 continue;
7320 $setting->write_setting($defaultsetting);
7321 $setting->write_setting_flags(null);
7324 // Just in case somebody modifies the list of active plugins directly.
7325 core_plugin_manager::reset_caches();
7329 * Store changed settings, this function updates the errors variable in $ADMIN
7331 * @param object $formdata from form
7332 * @return int number of changed settings
7334 function admin_write_settings($formdata) {
7335 global $CFG, $SITE, $DB;
7337 $olddbsessions = !empty($CFG->dbsessions);
7338 $formdata = (array)$formdata;
7340 $data = array();
7341 foreach ($formdata as $fullname=>$value) {
7342 if (strpos($fullname, 's_') !== 0) {
7343 continue; // not a config value
7345 $data[$fullname] = $value;
7348 $adminroot = admin_get_root();
7349 $settings = admin_find_write_settings($adminroot, $data);
7351 $count = 0;
7352 foreach ($settings as $fullname=>$setting) {
7353 /** @var $setting admin_setting */
7354 $original = $setting->get_setting();
7355 $error = $setting->write_setting($data[$fullname]);
7356 if ($error !== '') {
7357 $adminroot->errors[$fullname] = new stdClass();
7358 $adminroot->errors[$fullname]->data = $data[$fullname];
7359 $adminroot->errors[$fullname]->id = $setting->get_id();
7360 $adminroot->errors[$fullname]->error = $error;
7361 } else {
7362 $setting->write_setting_flags($data);
7364 if ($setting->post_write_settings($original)) {
7365 $count++;
7369 if ($olddbsessions != !empty($CFG->dbsessions)) {
7370 require_logout();
7373 // Now update $SITE - just update the fields, in case other people have a
7374 // a reference to it (e.g. $PAGE, $COURSE).
7375 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
7376 foreach (get_object_vars($newsite) as $field => $value) {
7377 $SITE->$field = $value;
7380 // now reload all settings - some of them might depend on the changed
7381 admin_get_root(true);
7382 return $count;
7386 * Internal recursive function - finds all settings from submitted form
7388 * @param object $node Instance of admin_category, or admin_settingpage
7389 * @param array $data
7390 * @return array
7392 function admin_find_write_settings($node, $data) {
7393 $return = array();
7395 if (empty($data)) {
7396 return $return;
7399 if ($node instanceof admin_category) {
7400 $entries = array_keys($node->children);
7401 foreach ($entries as $entry) {
7402 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
7405 } else if ($node instanceof admin_settingpage) {
7406 foreach ($node->settings as $setting) {
7407 $fullname = $setting->get_full_name();
7408 if (array_key_exists($fullname, $data)) {
7409 $return[$fullname] = $setting;
7415 return $return;
7419 * Internal function - prints the search results
7421 * @param string $query String to search for
7422 * @return string empty or XHTML
7424 function admin_search_settings_html($query) {
7425 global $CFG, $OUTPUT;
7427 if (core_text::strlen($query) < 2) {
7428 return '';
7430 $query = core_text::strtolower($query);
7432 $adminroot = admin_get_root();
7433 $findings = $adminroot->search($query);
7434 $return = '';
7435 $savebutton = false;
7437 foreach ($findings as $found) {
7438 $page = $found->page;
7439 $settings = $found->settings;
7440 if ($page->is_hidden()) {
7441 // hidden pages are not displayed in search results
7442 continue;
7444 if ($page instanceof admin_externalpage) {
7445 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
7446 } else if ($page instanceof admin_settingpage) {
7447 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/settings.php?section='.$page->name.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
7448 } else {
7449 continue;
7451 if (!empty($settings)) {
7452 $return .= '<fieldset class="adminsettings">'."\n";
7453 foreach ($settings as $setting) {
7454 if (empty($setting->nosave)) {
7455 $savebutton = true;
7457 $return .= '<div class="clearer"><!-- --></div>'."\n";
7458 $fullname = $setting->get_full_name();
7459 if (array_key_exists($fullname, $adminroot->errors)) {
7460 $data = $adminroot->errors[$fullname]->data;
7461 } else {
7462 $data = $setting->get_setting();
7463 // do not use defaults if settings not available - upgradesettings handles the defaults!
7465 $return .= $setting->output_html($data, $query);
7467 $return .= '</fieldset>';
7471 if ($savebutton) {
7472 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
7475 return $return;
7479 * Internal function - returns arrays of html pages with uninitialised settings
7481 * @param object $node Instance of admin_category or admin_settingpage
7482 * @return array
7484 function admin_output_new_settings_by_page($node) {
7485 global $OUTPUT;
7486 $return = array();
7488 if ($node instanceof admin_category) {
7489 $entries = array_keys($node->children);
7490 foreach ($entries as $entry) {
7491 $return += admin_output_new_settings_by_page($node->children[$entry]);
7494 } else if ($node instanceof admin_settingpage) {
7495 $newsettings = array();
7496 foreach ($node->settings as $setting) {
7497 if (is_null($setting->get_setting())) {
7498 $newsettings[] = $setting;
7501 if (count($newsettings) > 0) {
7502 $adminroot = admin_get_root();
7503 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
7504 $page .= '<fieldset class="adminsettings">'."\n";
7505 foreach ($newsettings as $setting) {
7506 $fullname = $setting->get_full_name();
7507 if (array_key_exists($fullname, $adminroot->errors)) {
7508 $data = $adminroot->errors[$fullname]->data;
7509 } else {
7510 $data = $setting->get_setting();
7511 if (is_null($data)) {
7512 $data = $setting->get_defaultsetting();
7515 $page .= '<div class="clearer"><!-- --></div>'."\n";
7516 $page .= $setting->output_html($data);
7518 $page .= '</fieldset>';
7519 $return[$node->name] = $page;
7523 return $return;
7527 * Format admin settings
7529 * @param object $setting
7530 * @param string $title label element
7531 * @param string $form form fragment, html code - not highlighted automatically
7532 * @param string $description
7533 * @param mixed $label link label to id, true by default or string being the label to connect it to
7534 * @param string $warning warning text
7535 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
7536 * @param string $query search query to be highlighted
7537 * @return string XHTML
7539 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
7540 global $CFG;
7542 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
7543 $fullname = $setting->get_full_name();
7545 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
7546 if ($label === true) {
7547 $labelfor = 'for = "'.$setting->get_id().'"';
7548 } else if ($label === false) {
7549 $labelfor = '';
7550 } else {
7551 $labelfor = 'for="' . $label . '"';
7553 $form .= $setting->output_setting_flags();
7555 $override = '';
7556 if (empty($setting->plugin)) {
7557 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
7558 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7560 } else {
7561 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
7562 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7566 if ($warning !== '') {
7567 $warning = '<div class="form-warning">'.$warning.'</div>';
7570 $defaults = array();
7571 if (!is_null($defaultinfo)) {
7572 if ($defaultinfo === '') {
7573 $defaultinfo = get_string('emptysettingvalue', 'admin');
7575 $defaults[] = $defaultinfo;
7578 $setting->get_setting_flag_defaults($defaults);
7580 if (!empty($defaults)) {
7581 $defaultinfo = implode(', ', $defaults);
7582 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7583 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
7587 $adminroot = admin_get_root();
7588 $error = '';
7589 if (array_key_exists($fullname, $adminroot->errors)) {
7590 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
7593 $str = '
7594 <div class="form-item clearfix" id="admin-'.$setting->name.'">
7595 <div class="form-label">
7596 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
7597 <span class="form-shortname">'.highlightfast($query, $name).'</span>
7598 </div>
7599 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
7600 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
7601 </div>';
7603 return $str;
7607 * Based on find_new_settings{@link ()} in upgradesettings.php
7608 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7610 * @param object $node Instance of admin_category, or admin_settingpage
7611 * @return boolean true if any settings haven't been initialised, false if they all have
7613 function any_new_admin_settings($node) {
7615 if ($node instanceof admin_category) {
7616 $entries = array_keys($node->children);
7617 foreach ($entries as $entry) {
7618 if (any_new_admin_settings($node->children[$entry])) {
7619 return true;
7623 } else if ($node instanceof admin_settingpage) {
7624 foreach ($node->settings as $setting) {
7625 if ($setting->get_setting() === NULL) {
7626 return true;
7631 return false;
7635 * Moved from admin/replace.php so that we can use this in cron
7637 * @param string $search string to look for
7638 * @param string $replace string to replace
7639 * @return bool success or fail
7641 function db_replace($search, $replace) {
7642 global $DB, $CFG, $OUTPUT;
7644 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7645 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7646 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7647 'block_instances', '');
7649 // Turn off time limits, sometimes upgrades can be slow.
7650 core_php_time_limit::raise();
7652 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7653 return false;
7655 foreach ($tables as $table) {
7657 if (in_array($table, $skiptables)) { // Don't process these
7658 continue;
7661 if ($columns = $DB->get_columns($table)) {
7662 $DB->set_debug(true);
7663 foreach ($columns as $column) {
7664 $DB->replace_all_text($table, $column, $search, $replace);
7666 $DB->set_debug(false);
7670 // delete modinfo caches
7671 rebuild_course_cache(0, true);
7673 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7674 $blocks = core_component::get_plugin_list('block');
7675 foreach ($blocks as $blockname=>$fullblock) {
7676 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7677 continue;
7680 if (!is_readable($fullblock.'/lib.php')) {
7681 continue;
7684 $function = 'block_'.$blockname.'_global_db_replace';
7685 include_once($fullblock.'/lib.php');
7686 if (!function_exists($function)) {
7687 continue;
7690 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7691 $function($search, $replace);
7692 echo $OUTPUT->notification("...finished", 'notifysuccess');
7695 purge_all_caches();
7697 return true;
7701 * Manage repository settings
7703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7705 class admin_setting_managerepository extends admin_setting {
7706 /** @var string */
7707 private $baseurl;
7710 * calls parent::__construct with specific arguments
7712 public function __construct() {
7713 global $CFG;
7714 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7715 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7719 * Always returns true, does nothing
7721 * @return true
7723 public function get_setting() {
7724 return true;
7728 * Always returns true does nothing
7730 * @return true
7732 public function get_defaultsetting() {
7733 return true;
7737 * Always returns s_managerepository
7739 * @return string Always return 's_managerepository'
7741 public function get_full_name() {
7742 return 's_managerepository';
7746 * Always returns '' doesn't do anything
7748 public function write_setting($data) {
7749 $url = $this->baseurl . '&amp;new=' . $data;
7750 return '';
7751 // TODO
7752 // Should not use redirect and exit here
7753 // Find a better way to do this.
7754 // redirect($url);
7755 // exit;
7759 * Searches repository plugins for one that matches $query
7761 * @param string $query The string to search for
7762 * @return bool true if found, false if not
7764 public function is_related($query) {
7765 if (parent::is_related($query)) {
7766 return true;
7769 $repositories= core_component::get_plugin_list('repository');
7770 foreach ($repositories as $p => $dir) {
7771 if (strpos($p, $query) !== false) {
7772 return true;
7775 foreach (repository::get_types() as $instance) {
7776 $title = $instance->get_typename();
7777 if (strpos(core_text::strtolower($title), $query) !== false) {
7778 return true;
7781 return false;
7785 * Helper function that generates a moodle_url object
7786 * relevant to the repository
7789 function repository_action_url($repository) {
7790 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7794 * Builds XHTML to display the control
7796 * @param string $data Unused
7797 * @param string $query
7798 * @return string XHTML
7800 public function output_html($data, $query='') {
7801 global $CFG, $USER, $OUTPUT;
7803 // Get strings that are used
7804 $strshow = get_string('on', 'repository');
7805 $strhide = get_string('off', 'repository');
7806 $strdelete = get_string('disabled', 'repository');
7808 $actionchoicesforexisting = array(
7809 'show' => $strshow,
7810 'hide' => $strhide,
7811 'delete' => $strdelete
7814 $actionchoicesfornew = array(
7815 'newon' => $strshow,
7816 'newoff' => $strhide,
7817 'delete' => $strdelete
7820 $return = '';
7821 $return .= $OUTPUT->box_start('generalbox');
7823 // Set strings that are used multiple times
7824 $settingsstr = get_string('settings');
7825 $disablestr = get_string('disable');
7827 // Table to list plug-ins
7828 $table = new html_table();
7829 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7830 $table->align = array('left', 'center', 'center', 'center', 'center');
7831 $table->data = array();
7833 // Get list of used plug-ins
7834 $repositorytypes = repository::get_types();
7835 if (!empty($repositorytypes)) {
7836 // Array to store plugins being used
7837 $alreadyplugins = array();
7838 $totalrepositorytypes = count($repositorytypes);
7839 $updowncount = 1;
7840 foreach ($repositorytypes as $i) {
7841 $settings = '';
7842 $typename = $i->get_typename();
7843 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7844 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7845 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7847 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7848 // Calculate number of instances in order to display them for the Moodle administrator
7849 if (!empty($instanceoptionnames)) {
7850 $params = array();
7851 $params['context'] = array(context_system::instance());
7852 $params['onlyvisible'] = false;
7853 $params['type'] = $typename;
7854 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7855 // site instances
7856 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7857 $params['context'] = array();
7858 $instances = repository::static_function($typename, 'get_instances', $params);
7859 $courseinstances = array();
7860 $userinstances = array();
7862 foreach ($instances as $instance) {
7863 $repocontext = context::instance_by_id($instance->instance->contextid);
7864 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7865 $courseinstances[] = $instance;
7866 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7867 $userinstances[] = $instance;
7870 // course instances
7871 $instancenumber = count($courseinstances);
7872 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7874 // user private instances
7875 $instancenumber = count($userinstances);
7876 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7877 } else {
7878 $admininstancenumbertext = "";
7879 $courseinstancenumbertext = "";
7880 $userinstancenumbertext = "";
7883 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7885 $settings .= $OUTPUT->container_start('mdl-left');
7886 $settings .= '<br/>';
7887 $settings .= $admininstancenumbertext;
7888 $settings .= '<br/>';
7889 $settings .= $courseinstancenumbertext;
7890 $settings .= '<br/>';
7891 $settings .= $userinstancenumbertext;
7892 $settings .= $OUTPUT->container_end();
7894 // Get the current visibility
7895 if ($i->get_visible()) {
7896 $currentaction = 'show';
7897 } else {
7898 $currentaction = 'hide';
7901 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7903 // Display up/down link
7904 $updown = '';
7905 // Should be done with CSS instead.
7906 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7908 if ($updowncount > 1) {
7909 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7910 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7912 else {
7913 $updown .= $spacer;
7915 if ($updowncount < $totalrepositorytypes) {
7916 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7917 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7919 else {
7920 $updown .= $spacer;
7923 $updowncount++;
7925 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7927 if (!in_array($typename, $alreadyplugins)) {
7928 $alreadyplugins[] = $typename;
7933 // Get all the plugins that exist on disk
7934 $plugins = core_component::get_plugin_list('repository');
7935 if (!empty($plugins)) {
7936 foreach ($plugins as $plugin => $dir) {
7937 // Check that it has not already been listed
7938 if (!in_array($plugin, $alreadyplugins)) {
7939 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7940 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7945 $return .= html_writer::table($table);
7946 $return .= $OUTPUT->box_end();
7947 return highlight($query, $return);
7952 * Special checkbox for enable mobile web service
7953 * If enable then we store the service id of the mobile service into config table
7954 * If disable then we unstore the service id from the config table
7956 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7958 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7959 private $restuse;
7962 * Return true if Authenticated user role has the capability 'webservice/rest:use', otherwise false.
7964 * @return boolean
7966 private function is_protocol_cap_allowed() {
7967 global $DB, $CFG;
7969 // If the $this->restuse variable is not set, it needs to be set.
7970 if (empty($this->restuse) and $this->restuse!==false) {
7971 $params = array();
7972 $params['permission'] = CAP_ALLOW;
7973 $params['roleid'] = $CFG->defaultuserroleid;
7974 $params['capability'] = 'webservice/rest:use';
7975 $this->restuse = $DB->record_exists('role_capabilities', $params);
7978 return $this->restuse;
7982 * Set the 'webservice/rest:use' to the Authenticated user role (allow or not)
7983 * @param type $status true to allow, false to not set
7985 private function set_protocol_cap($status) {
7986 global $CFG;
7987 if ($status and !$this->is_protocol_cap_allowed()) {
7988 //need to allow the cap
7989 $permission = CAP_ALLOW;
7990 $assign = true;
7991 } else if (!$status and $this->is_protocol_cap_allowed()){
7992 //need to disallow the cap
7993 $permission = CAP_INHERIT;
7994 $assign = true;
7996 if (!empty($assign)) {
7997 $systemcontext = context_system::instance();
7998 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
8003 * Builds XHTML to display the control.
8004 * The main purpose of this overloading is to display a warning when https
8005 * is not supported by the server
8006 * @param string $data Unused
8007 * @param string $query
8008 * @return string XHTML
8010 public function output_html($data, $query='') {
8011 global $CFG, $OUTPUT;
8012 $html = parent::output_html($data, $query);
8014 if ((string)$data === $this->yes) {
8015 require_once($CFG->dirroot . "/lib/filelib.php");
8016 $curl = new curl();
8017 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
8018 $curl->head($httpswwwroot . "/login/index.php");
8019 $info = $curl->get_info();
8020 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
8021 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
8025 return $html;
8029 * Retrieves the current setting using the objects name
8031 * @return string
8033 public function get_setting() {
8034 global $CFG;
8036 // First check if is not set.
8037 $result = $this->config_read($this->name);
8038 if (is_null($result)) {
8039 return null;
8042 // For install cli script, $CFG->defaultuserroleid is not set so return 0
8043 // Or if web services aren't enabled this can't be,
8044 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
8045 return 0;
8048 require_once($CFG->dirroot . '/webservice/lib.php');
8049 $webservicemanager = new webservice();
8050 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8051 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
8052 return $result;
8053 } else {
8054 return 0;
8059 * Save the selected setting
8061 * @param string $data The selected site
8062 * @return string empty string or error message
8064 public function write_setting($data) {
8065 global $DB, $CFG;
8067 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
8068 if (empty($CFG->defaultuserroleid)) {
8069 return '';
8072 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
8074 require_once($CFG->dirroot . '/webservice/lib.php');
8075 $webservicemanager = new webservice();
8077 $updateprotocol = false;
8078 if ((string)$data === $this->yes) {
8079 //code run when enable mobile web service
8080 //enable web service systeme if necessary
8081 set_config('enablewebservices', true);
8083 //enable mobile service
8084 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8085 $mobileservice->enabled = 1;
8086 $webservicemanager->update_external_service($mobileservice);
8088 // Enable REST server.
8089 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8091 if (!in_array('rest', $activeprotocols)) {
8092 $activeprotocols[] = 'rest';
8093 $updateprotocol = true;
8096 if ($updateprotocol) {
8097 set_config('webserviceprotocols', implode(',', $activeprotocols));
8100 // Allow rest:use capability for authenticated user.
8101 $this->set_protocol_cap(true);
8103 } else {
8104 //disable web service system if no other services are enabled
8105 $otherenabledservices = $DB->get_records_select('external_services',
8106 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
8107 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
8108 if (empty($otherenabledservices)) {
8109 set_config('enablewebservices', false);
8111 // Also disable REST server.
8112 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8114 $protocolkey = array_search('rest', $activeprotocols);
8115 if ($protocolkey !== false) {
8116 unset($activeprotocols[$protocolkey]);
8117 $updateprotocol = true;
8120 if ($updateprotocol) {
8121 set_config('webserviceprotocols', implode(',', $activeprotocols));
8124 // Disallow rest:use capability for authenticated user.
8125 $this->set_protocol_cap(false);
8128 //disable the mobile service
8129 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
8130 $mobileservice->enabled = 0;
8131 $webservicemanager->update_external_service($mobileservice);
8134 return (parent::write_setting($data));
8139 * Special class for management of external services
8141 * @author Petr Skoda (skodak)
8143 class admin_setting_manageexternalservices extends admin_setting {
8145 * Calls parent::__construct with specific arguments
8147 public function __construct() {
8148 $this->nosave = true;
8149 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
8153 * Always returns true, does nothing
8155 * @return true
8157 public function get_setting() {
8158 return true;
8162 * Always returns true, does nothing
8164 * @return true
8166 public function get_defaultsetting() {
8167 return true;
8171 * Always returns '', does not write anything
8173 * @return string Always returns ''
8175 public function write_setting($data) {
8176 // do not write any setting
8177 return '';
8181 * Checks if $query is one of the available external services
8183 * @param string $query The string to search for
8184 * @return bool Returns true if found, false if not
8186 public function is_related($query) {
8187 global $DB;
8189 if (parent::is_related($query)) {
8190 return true;
8193 $services = $DB->get_records('external_services', array(), 'id, name');
8194 foreach ($services as $service) {
8195 if (strpos(core_text::strtolower($service->name), $query) !== false) {
8196 return true;
8199 return false;
8203 * Builds the XHTML to display the control
8205 * @param string $data Unused
8206 * @param string $query
8207 * @return string
8209 public function output_html($data, $query='') {
8210 global $CFG, $OUTPUT, $DB;
8212 // display strings
8213 $stradministration = get_string('administration');
8214 $stredit = get_string('edit');
8215 $strservice = get_string('externalservice', 'webservice');
8216 $strdelete = get_string('delete');
8217 $strplugin = get_string('plugin', 'admin');
8218 $stradd = get_string('add');
8219 $strfunctions = get_string('functions', 'webservice');
8220 $strusers = get_string('users');
8221 $strserviceusers = get_string('serviceusers', 'webservice');
8223 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
8224 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
8225 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
8227 // built in services
8228 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
8229 $return = "";
8230 if (!empty($services)) {
8231 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
8235 $table = new html_table();
8236 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
8237 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8238 $table->id = 'builtinservices';
8239 $table->attributes['class'] = 'admintable externalservices generaltable';
8240 $table->data = array();
8242 // iterate through auth plugins and add to the display table
8243 foreach ($services as $service) {
8244 $name = $service->name;
8246 // hide/show link
8247 if ($service->enabled) {
8248 $displayname = "<span>$name</span>";
8249 } else {
8250 $displayname = "<span class=\"dimmed_text\">$name</span>";
8253 $plugin = $service->component;
8255 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8257 if ($service->restrictedusers) {
8258 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8259 } else {
8260 $users = get_string('allusers', 'webservice');
8263 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8265 // add a row to the table
8266 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
8268 $return .= html_writer::table($table);
8271 // Custom services
8272 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
8273 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
8275 $table = new html_table();
8276 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
8277 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
8278 $table->id = 'customservices';
8279 $table->attributes['class'] = 'admintable externalservices generaltable';
8280 $table->data = array();
8282 // iterate through auth plugins and add to the display table
8283 foreach ($services as $service) {
8284 $name = $service->name;
8286 // hide/show link
8287 if ($service->enabled) {
8288 $displayname = "<span>$name</span>";
8289 } else {
8290 $displayname = "<span class=\"dimmed_text\">$name</span>";
8293 // delete link
8294 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
8296 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
8298 if ($service->restrictedusers) {
8299 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
8300 } else {
8301 $users = get_string('allusers', 'webservice');
8304 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
8306 // add a row to the table
8307 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
8309 // add new custom service option
8310 $return .= html_writer::table($table);
8312 $return .= '<br />';
8313 // add a token to the table
8314 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
8316 return highlight($query, $return);
8321 * Special class for overview of external services
8323 * @author Jerome Mouneyrac
8325 class admin_setting_webservicesoverview extends admin_setting {
8328 * Calls parent::__construct with specific arguments
8330 public function __construct() {
8331 $this->nosave = true;
8332 parent::__construct('webservicesoverviewui',
8333 get_string('webservicesoverview', 'webservice'), '', '');
8337 * Always returns true, does nothing
8339 * @return true
8341 public function get_setting() {
8342 return true;
8346 * Always returns true, does nothing
8348 * @return true
8350 public function get_defaultsetting() {
8351 return true;
8355 * Always returns '', does not write anything
8357 * @return string Always returns ''
8359 public function write_setting($data) {
8360 // do not write any setting
8361 return '';
8365 * Builds the XHTML to display the control
8367 * @param string $data Unused
8368 * @param string $query
8369 * @return string
8371 public function output_html($data, $query='') {
8372 global $CFG, $OUTPUT;
8374 $return = "";
8375 $brtag = html_writer::empty_tag('br');
8377 // Enable mobile web service
8378 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
8379 get_string('enablemobilewebservice', 'admin'),
8380 get_string('configenablemobilewebservice',
8381 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
8382 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
8383 $wsmobileparam = new stdClass();
8384 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
8385 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
8386 get_string('mobile', 'admin'));
8387 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
8388 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
8389 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
8390 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
8391 . $brtag . $brtag;
8393 /// One system controlling Moodle with Token
8394 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
8395 $table = new html_table();
8396 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8397 get_string('description'));
8398 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8399 $table->id = 'onesystemcontrol';
8400 $table->attributes['class'] = 'admintable wsoverview generaltable';
8401 $table->data = array();
8403 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
8404 . $brtag . $brtag;
8406 /// 1. Enable Web Services
8407 $row = array();
8408 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8409 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8410 array('href' => $url));
8411 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8412 if ($CFG->enablewebservices) {
8413 $status = get_string('yes');
8415 $row[1] = $status;
8416 $row[2] = get_string('enablewsdescription', 'webservice');
8417 $table->data[] = $row;
8419 /// 2. Enable protocols
8420 $row = array();
8421 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8422 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8423 array('href' => $url));
8424 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8425 //retrieve activated protocol
8426 $active_protocols = empty($CFG->webserviceprotocols) ?
8427 array() : explode(',', $CFG->webserviceprotocols);
8428 if (!empty($active_protocols)) {
8429 $status = "";
8430 foreach ($active_protocols as $protocol) {
8431 $status .= $protocol . $brtag;
8434 $row[1] = $status;
8435 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8436 $table->data[] = $row;
8438 /// 3. Create user account
8439 $row = array();
8440 $url = new moodle_url("/user/editadvanced.php?id=-1");
8441 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
8442 array('href' => $url));
8443 $row[1] = "";
8444 $row[2] = get_string('createuserdescription', 'webservice');
8445 $table->data[] = $row;
8447 /// 4. Add capability to users
8448 $row = array();
8449 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8450 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
8451 array('href' => $url));
8452 $row[1] = "";
8453 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
8454 $table->data[] = $row;
8456 /// 5. Select a web service
8457 $row = array();
8458 $url = new moodle_url("/admin/settings.php?section=externalservices");
8459 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8460 array('href' => $url));
8461 $row[1] = "";
8462 $row[2] = get_string('createservicedescription', 'webservice');
8463 $table->data[] = $row;
8465 /// 6. Add functions
8466 $row = array();
8467 $url = new moodle_url("/admin/settings.php?section=externalservices");
8468 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8469 array('href' => $url));
8470 $row[1] = "";
8471 $row[2] = get_string('addfunctionsdescription', 'webservice');
8472 $table->data[] = $row;
8474 /// 7. Add the specific user
8475 $row = array();
8476 $url = new moodle_url("/admin/settings.php?section=externalservices");
8477 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
8478 array('href' => $url));
8479 $row[1] = "";
8480 $row[2] = get_string('selectspecificuserdescription', 'webservice');
8481 $table->data[] = $row;
8483 /// 8. Create token for the specific user
8484 $row = array();
8485 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
8486 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
8487 array('href' => $url));
8488 $row[1] = "";
8489 $row[2] = get_string('createtokenforuserdescription', 'webservice');
8490 $table->data[] = $row;
8492 /// 9. Enable the documentation
8493 $row = array();
8494 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
8495 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
8496 array('href' => $url));
8497 $status = '<span class="warning">' . get_string('no') . '</span>';
8498 if ($CFG->enablewsdocumentation) {
8499 $status = get_string('yes');
8501 $row[1] = $status;
8502 $row[2] = get_string('enabledocumentationdescription', 'webservice');
8503 $table->data[] = $row;
8505 /// 10. Test the service
8506 $row = array();
8507 $url = new moodle_url("/admin/webservice/testclient.php");
8508 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8509 array('href' => $url));
8510 $row[1] = "";
8511 $row[2] = get_string('testwithtestclientdescription', 'webservice');
8512 $table->data[] = $row;
8514 $return .= html_writer::table($table);
8516 /// Users as clients with token
8517 $return .= $brtag . $brtag . $brtag;
8518 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
8519 $table = new html_table();
8520 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8521 get_string('description'));
8522 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8523 $table->id = 'userasclients';
8524 $table->attributes['class'] = 'admintable wsoverview generaltable';
8525 $table->data = array();
8527 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
8528 $brtag . $brtag;
8530 /// 1. Enable Web Services
8531 $row = array();
8532 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8533 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8534 array('href' => $url));
8535 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8536 if ($CFG->enablewebservices) {
8537 $status = get_string('yes');
8539 $row[1] = $status;
8540 $row[2] = get_string('enablewsdescription', 'webservice');
8541 $table->data[] = $row;
8543 /// 2. Enable protocols
8544 $row = array();
8545 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8546 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8547 array('href' => $url));
8548 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8549 //retrieve activated protocol
8550 $active_protocols = empty($CFG->webserviceprotocols) ?
8551 array() : explode(',', $CFG->webserviceprotocols);
8552 if (!empty($active_protocols)) {
8553 $status = "";
8554 foreach ($active_protocols as $protocol) {
8555 $status .= $protocol . $brtag;
8558 $row[1] = $status;
8559 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8560 $table->data[] = $row;
8563 /// 3. Select a web service
8564 $row = array();
8565 $url = new moodle_url("/admin/settings.php?section=externalservices");
8566 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8567 array('href' => $url));
8568 $row[1] = "";
8569 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8570 $table->data[] = $row;
8572 /// 4. Add functions
8573 $row = array();
8574 $url = new moodle_url("/admin/settings.php?section=externalservices");
8575 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8576 array('href' => $url));
8577 $row[1] = "";
8578 $row[2] = get_string('addfunctionsdescription', 'webservice');
8579 $table->data[] = $row;
8581 /// 5. Add capability to users
8582 $row = array();
8583 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8584 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8585 array('href' => $url));
8586 $row[1] = "";
8587 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8588 $table->data[] = $row;
8590 /// 6. Test the service
8591 $row = array();
8592 $url = new moodle_url("/admin/webservice/testclient.php");
8593 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8594 array('href' => $url));
8595 $row[1] = "";
8596 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8597 $table->data[] = $row;
8599 $return .= html_writer::table($table);
8601 return highlight($query, $return);
8608 * Special class for web service protocol administration.
8610 * @author Petr Skoda (skodak)
8612 class admin_setting_managewebserviceprotocols extends admin_setting {
8615 * Calls parent::__construct with specific arguments
8617 public function __construct() {
8618 $this->nosave = true;
8619 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8623 * Always returns true, does nothing
8625 * @return true
8627 public function get_setting() {
8628 return true;
8632 * Always returns true, does nothing
8634 * @return true
8636 public function get_defaultsetting() {
8637 return true;
8641 * Always returns '', does not write anything
8643 * @return string Always returns ''
8645 public function write_setting($data) {
8646 // do not write any setting
8647 return '';
8651 * Checks if $query is one of the available webservices
8653 * @param string $query The string to search for
8654 * @return bool Returns true if found, false if not
8656 public function is_related($query) {
8657 if (parent::is_related($query)) {
8658 return true;
8661 $protocols = core_component::get_plugin_list('webservice');
8662 foreach ($protocols as $protocol=>$location) {
8663 if (strpos($protocol, $query) !== false) {
8664 return true;
8666 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8667 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8668 return true;
8671 return false;
8675 * Builds the XHTML to display the control
8677 * @param string $data Unused
8678 * @param string $query
8679 * @return string
8681 public function output_html($data, $query='') {
8682 global $CFG, $OUTPUT;
8684 // display strings
8685 $stradministration = get_string('administration');
8686 $strsettings = get_string('settings');
8687 $stredit = get_string('edit');
8688 $strprotocol = get_string('protocol', 'webservice');
8689 $strenable = get_string('enable');
8690 $strdisable = get_string('disable');
8691 $strversion = get_string('version');
8693 $protocols_available = core_component::get_plugin_list('webservice');
8694 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8695 ksort($protocols_available);
8697 foreach ($active_protocols as $key=>$protocol) {
8698 if (empty($protocols_available[$protocol])) {
8699 unset($active_protocols[$key]);
8703 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8704 $return .= $OUTPUT->box_start('generalbox webservicesui');
8706 $table = new html_table();
8707 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8708 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8709 $table->id = 'webserviceprotocols';
8710 $table->attributes['class'] = 'admintable generaltable';
8711 $table->data = array();
8713 // iterate through auth plugins and add to the display table
8714 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8715 foreach ($protocols_available as $protocol => $location) {
8716 $name = get_string('pluginname', 'webservice_'.$protocol);
8718 $plugin = new stdClass();
8719 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8720 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8722 $version = isset($plugin->version) ? $plugin->version : '';
8724 // hide/show link
8725 if (in_array($protocol, $active_protocols)) {
8726 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8727 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8728 $displayname = "<span>$name</span>";
8729 } else {
8730 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8731 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8732 $displayname = "<span class=\"dimmed_text\">$name</span>";
8735 // settings link
8736 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8737 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8738 } else {
8739 $settings = '';
8742 // add a row to the table
8743 $table->data[] = array($displayname, $version, $hideshow, $settings);
8745 $return .= html_writer::table($table);
8746 $return .= get_string('configwebserviceplugins', 'webservice');
8747 $return .= $OUTPUT->box_end();
8749 return highlight($query, $return);
8755 * Special class for web service token administration.
8757 * @author Jerome Mouneyrac
8759 class admin_setting_managewebservicetokens extends admin_setting {
8762 * Calls parent::__construct with specific arguments
8764 public function __construct() {
8765 $this->nosave = true;
8766 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8770 * Always returns true, does nothing
8772 * @return true
8774 public function get_setting() {
8775 return true;
8779 * Always returns true, does nothing
8781 * @return true
8783 public function get_defaultsetting() {
8784 return true;
8788 * Always returns '', does not write anything
8790 * @return string Always returns ''
8792 public function write_setting($data) {
8793 // do not write any setting
8794 return '';
8798 * Builds the XHTML to display the control
8800 * @param string $data Unused
8801 * @param string $query
8802 * @return string
8804 public function output_html($data, $query='') {
8805 global $CFG, $OUTPUT, $DB, $USER;
8807 // display strings
8808 $stroperation = get_string('operation', 'webservice');
8809 $strtoken = get_string('token', 'webservice');
8810 $strservice = get_string('service', 'webservice');
8811 $struser = get_string('user');
8812 $strcontext = get_string('context', 'webservice');
8813 $strvaliduntil = get_string('validuntil', 'webservice');
8814 $striprestriction = get_string('iprestriction', 'webservice');
8816 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8818 $table = new html_table();
8819 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8820 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8821 $table->id = 'webservicetokens';
8822 $table->attributes['class'] = 'admintable generaltable';
8823 $table->data = array();
8825 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8827 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8829 //here retrieve token list (including linked users firstname/lastname and linked services name)
8830 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8831 FROM {external_tokens} t, {user} u, {external_services} s
8832 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8833 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8834 if (!empty($tokens)) {
8835 foreach ($tokens as $token) {
8836 //TODO: retrieve context
8838 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8839 $delete .= get_string('delete')."</a>";
8841 $validuntil = '';
8842 if (!empty($token->validuntil)) {
8843 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8846 $iprestriction = '';
8847 if (!empty($token->iprestriction)) {
8848 $iprestriction = $token->iprestriction;
8851 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8852 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8853 $useratag .= $token->firstname." ".$token->lastname;
8854 $useratag .= html_writer::end_tag('a');
8856 //check user missing capabilities
8857 require_once($CFG->dirroot . '/webservice/lib.php');
8858 $webservicemanager = new webservice();
8859 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8860 array(array('id' => $token->userid)), $token->serviceid);
8862 if (!is_siteadmin($token->userid) and
8863 array_key_exists($token->userid, $usermissingcaps)) {
8864 $missingcapabilities = implode(', ',
8865 $usermissingcaps[$token->userid]);
8866 if (!empty($missingcapabilities)) {
8867 $useratag .= html_writer::tag('div',
8868 get_string('usermissingcaps', 'webservice',
8869 $missingcapabilities)
8870 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8871 array('class' => 'missingcaps'));
8875 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8878 $return .= html_writer::table($table);
8879 } else {
8880 $return .= get_string('notoken', 'webservice');
8883 $return .= $OUTPUT->box_end();
8884 // add a token to the table
8885 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8886 $return .= get_string('add')."</a>";
8888 return highlight($query, $return);
8894 * Colour picker
8896 * @copyright 2010 Sam Hemelryk
8897 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8899 class admin_setting_configcolourpicker extends admin_setting {
8902 * Information for previewing the colour
8904 * @var array|null
8906 protected $previewconfig = null;
8909 * Use default when empty.
8911 protected $usedefaultwhenempty = true;
8915 * @param string $name
8916 * @param string $visiblename
8917 * @param string $description
8918 * @param string $defaultsetting
8919 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8921 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8922 $usedefaultwhenempty = true) {
8923 $this->previewconfig = $previewconfig;
8924 $this->usedefaultwhenempty = $usedefaultwhenempty;
8925 parent::__construct($name, $visiblename, $description, $defaultsetting);
8929 * Return the setting
8931 * @return mixed returns config if successful else null
8933 public function get_setting() {
8934 return $this->config_read($this->name);
8938 * Saves the setting
8940 * @param string $data
8941 * @return bool
8943 public function write_setting($data) {
8944 $data = $this->validate($data);
8945 if ($data === false) {
8946 return get_string('validateerror', 'admin');
8948 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8952 * Validates the colour that was entered by the user
8954 * @param string $data
8955 * @return string|false
8957 protected function validate($data) {
8959 * List of valid HTML colour names
8961 * @var array
8963 $colornames = array(
8964 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8965 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8966 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8967 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8968 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8969 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8970 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8971 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8972 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8973 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8974 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8975 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8976 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8977 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8978 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8979 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8980 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8981 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8982 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8983 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8984 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8985 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8986 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8987 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8988 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8989 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8990 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8991 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8992 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8993 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8994 'whitesmoke', 'yellow', 'yellowgreen'
8997 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8998 if (strpos($data, '#')!==0) {
8999 $data = '#'.$data;
9001 return $data;
9002 } else if (in_array(strtolower($data), $colornames)) {
9003 return $data;
9004 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
9005 return $data;
9006 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
9007 return $data;
9008 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
9009 return $data;
9010 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
9011 return $data;
9012 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
9013 return $data;
9014 } else if (empty($data)) {
9015 if ($this->usedefaultwhenempty){
9016 return $this->defaultsetting;
9017 } else {
9018 return '';
9020 } else {
9021 return false;
9026 * Generates the HTML for the setting
9028 * @global moodle_page $PAGE
9029 * @global core_renderer $OUTPUT
9030 * @param string $data
9031 * @param string $query
9033 public function output_html($data, $query = '') {
9034 global $PAGE, $OUTPUT;
9035 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
9036 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
9037 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
9038 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
9039 if (!empty($this->previewconfig)) {
9040 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
9042 $content .= html_writer::end_tag('div');
9043 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
9049 * Class used for uploading of one file into file storage,
9050 * the file name is stored in config table.
9052 * Please note you need to implement your own '_pluginfile' callback function,
9053 * this setting only stores the file, it does not deal with file serving.
9055 * @copyright 2013 Petr Skoda {@link http://skodak.org}
9056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9058 class admin_setting_configstoredfile extends admin_setting {
9059 /** @var array file area options - should be one file only */
9060 protected $options;
9061 /** @var string name of the file area */
9062 protected $filearea;
9063 /** @var int intemid */
9064 protected $itemid;
9065 /** @var string used for detection of changes */
9066 protected $oldhashes;
9069 * Create new stored file setting.
9071 * @param string $name low level setting name
9072 * @param string $visiblename human readable setting name
9073 * @param string $description description of setting
9074 * @param mixed $filearea file area for file storage
9075 * @param int $itemid itemid for file storage
9076 * @param array $options file area options
9078 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
9079 parent::__construct($name, $visiblename, $description, '');
9080 $this->filearea = $filearea;
9081 $this->itemid = $itemid;
9082 $this->options = (array)$options;
9086 * Applies defaults and returns all options.
9087 * @return array
9089 protected function get_options() {
9090 global $CFG;
9092 require_once("$CFG->libdir/filelib.php");
9093 require_once("$CFG->dirroot/repository/lib.php");
9094 $defaults = array(
9095 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
9096 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
9097 'context' => context_system::instance());
9098 foreach($this->options as $k => $v) {
9099 $defaults[$k] = $v;
9102 return $defaults;
9105 public function get_setting() {
9106 return $this->config_read($this->name);
9109 public function write_setting($data) {
9110 global $USER;
9112 // Let's not deal with validation here, this is for admins only.
9113 $current = $this->get_setting();
9114 if (empty($data) && $current === null) {
9115 // This will be the case when applying default settings (installation).
9116 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
9117 } else if (!is_number($data)) {
9118 // Draft item id is expected here!
9119 return get_string('errorsetting', 'admin');
9122 $options = $this->get_options();
9123 $fs = get_file_storage();
9124 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9126 $this->oldhashes = null;
9127 if ($current) {
9128 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9129 if ($file = $fs->get_file_by_hash($hash)) {
9130 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
9132 unset($file);
9135 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
9136 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
9137 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
9138 // with an error because the draft area does not exist, as he did not use it.
9139 $usercontext = context_user::instance($USER->id);
9140 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
9141 return get_string('errorsetting', 'admin');
9145 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9146 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
9148 $filepath = '';
9149 if ($files) {
9150 /** @var stored_file $file */
9151 $file = reset($files);
9152 $filepath = $file->get_filepath().$file->get_filename();
9155 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
9158 public function post_write_settings($original) {
9159 $options = $this->get_options();
9160 $fs = get_file_storage();
9161 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9163 $current = $this->get_setting();
9164 $newhashes = null;
9165 if ($current) {
9166 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
9167 if ($file = $fs->get_file_by_hash($hash)) {
9168 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
9170 unset($file);
9173 if ($this->oldhashes === $newhashes) {
9174 $this->oldhashes = null;
9175 return false;
9177 $this->oldhashes = null;
9179 $callbackfunction = $this->updatedcallback;
9180 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
9181 $callbackfunction($this->get_full_name());
9183 return true;
9186 public function output_html($data, $query = '') {
9187 global $PAGE, $CFG;
9189 $options = $this->get_options();
9190 $id = $this->get_id();
9191 $elname = $this->get_full_name();
9192 $draftitemid = file_get_submitted_draft_itemid($elname);
9193 $component = is_null($this->plugin) ? 'core' : $this->plugin;
9194 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
9196 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
9197 require_once("$CFG->dirroot/lib/form/filemanager.php");
9199 $fmoptions = new stdClass();
9200 $fmoptions->mainfile = $options['mainfile'];
9201 $fmoptions->maxbytes = $options['maxbytes'];
9202 $fmoptions->maxfiles = $options['maxfiles'];
9203 $fmoptions->client_id = uniqid();
9204 $fmoptions->itemid = $draftitemid;
9205 $fmoptions->subdirs = $options['subdirs'];
9206 $fmoptions->target = $id;
9207 $fmoptions->accepted_types = $options['accepted_types'];
9208 $fmoptions->return_types = $options['return_types'];
9209 $fmoptions->context = $options['context'];
9210 $fmoptions->areamaxbytes = $options['areamaxbytes'];
9212 $fm = new form_filemanager($fmoptions);
9213 $output = $PAGE->get_renderer('core', 'files');
9214 $html = $output->render($fm);
9216 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
9217 $html .= '<input value="" id="'.$id.'" type="hidden" />';
9219 return format_admin_setting($this, $this->visiblename,
9220 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
9226 * Administration interface for user specified regular expressions for device detection.
9228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9230 class admin_setting_devicedetectregex extends admin_setting {
9233 * Calls parent::__construct with specific args
9235 * @param string $name
9236 * @param string $visiblename
9237 * @param string $description
9238 * @param mixed $defaultsetting
9240 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
9241 global $CFG;
9242 parent::__construct($name, $visiblename, $description, $defaultsetting);
9246 * Return the current setting(s)
9248 * @return array Current settings array
9250 public function get_setting() {
9251 global $CFG;
9253 $config = $this->config_read($this->name);
9254 if (is_null($config)) {
9255 return null;
9258 return $this->prepare_form_data($config);
9262 * Save selected settings
9264 * @param array $data Array of settings to save
9265 * @return bool
9267 public function write_setting($data) {
9268 if (empty($data)) {
9269 $data = array();
9272 if ($this->config_write($this->name, $this->process_form_data($data))) {
9273 return ''; // success
9274 } else {
9275 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
9280 * Return XHTML field(s) for regexes
9282 * @param array $data Array of options to set in HTML
9283 * @return string XHTML string for the fields and wrapping div(s)
9285 public function output_html($data, $query='') {
9286 global $OUTPUT;
9288 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
9289 $out .= html_writer::start_tag('thead');
9290 $out .= html_writer::start_tag('tr');
9291 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
9292 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
9293 $out .= html_writer::end_tag('tr');
9294 $out .= html_writer::end_tag('thead');
9295 $out .= html_writer::start_tag('tbody');
9297 if (empty($data)) {
9298 $looplimit = 1;
9299 } else {
9300 $looplimit = (count($data)/2)+1;
9303 for ($i=0; $i<$looplimit; $i++) {
9304 $out .= html_writer::start_tag('tr');
9306 $expressionname = 'expression'.$i;
9308 if (!empty($data[$expressionname])){
9309 $expression = $data[$expressionname];
9310 } else {
9311 $expression = '';
9314 $out .= html_writer::tag('td',
9315 html_writer::empty_tag('input',
9316 array(
9317 'type' => 'text',
9318 'class' => 'form-text',
9319 'name' => $this->get_full_name().'[expression'.$i.']',
9320 'value' => $expression,
9322 ), array('class' => 'c'.$i)
9325 $valuename = 'value'.$i;
9327 if (!empty($data[$valuename])){
9328 $value = $data[$valuename];
9329 } else {
9330 $value= '';
9333 $out .= html_writer::tag('td',
9334 html_writer::empty_tag('input',
9335 array(
9336 'type' => 'text',
9337 'class' => 'form-text',
9338 'name' => $this->get_full_name().'[value'.$i.']',
9339 'value' => $value,
9341 ), array('class' => 'c'.$i)
9344 $out .= html_writer::end_tag('tr');
9347 $out .= html_writer::end_tag('tbody');
9348 $out .= html_writer::end_tag('table');
9350 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
9354 * Converts the string of regexes
9356 * @see self::process_form_data()
9357 * @param $regexes string of regexes
9358 * @return array of form fields and their values
9360 protected function prepare_form_data($regexes) {
9362 $regexes = json_decode($regexes);
9364 $form = array();
9366 $i = 0;
9368 foreach ($regexes as $value => $regex) {
9369 $expressionname = 'expression'.$i;
9370 $valuename = 'value'.$i;
9372 $form[$expressionname] = $regex;
9373 $form[$valuename] = $value;
9374 $i++;
9377 return $form;
9381 * Converts the data from admin settings form into a string of regexes
9383 * @see self::prepare_form_data()
9384 * @param array $data array of admin form fields and values
9385 * @return false|string of regexes
9387 protected function process_form_data(array $form) {
9389 $count = count($form); // number of form field values
9391 if ($count % 2) {
9392 // we must get five fields per expression
9393 return false;
9396 $regexes = array();
9397 for ($i = 0; $i < $count / 2; $i++) {
9398 $expressionname = "expression".$i;
9399 $valuename = "value".$i;
9401 $expression = trim($form['expression'.$i]);
9402 $value = trim($form['value'.$i]);
9404 if (empty($expression)){
9405 continue;
9408 $regexes[$value] = $expression;
9411 $regexes = json_encode($regexes);
9413 return $regexes;
9418 * Multiselect for current modules
9420 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9422 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
9423 private $excludesystem;
9426 * Calls parent::__construct - note array $choices is not required
9428 * @param string $name setting name
9429 * @param string $visiblename localised setting name
9430 * @param string $description setting description
9431 * @param array $defaultsetting a plain array of default module ids
9432 * @param bool $excludesystem If true, excludes modules with 'system' archetype
9434 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
9435 $excludesystem = true) {
9436 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
9437 $this->excludesystem = $excludesystem;
9441 * Loads an array of current module choices
9443 * @return bool always return true
9445 public function load_choices() {
9446 if (is_array($this->choices)) {
9447 return true;
9449 $this->choices = array();
9451 global $CFG, $DB;
9452 $records = $DB->get_records('modules', array('visible'=>1), 'name');
9453 foreach ($records as $record) {
9454 // Exclude modules if the code doesn't exist
9455 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
9456 // Also exclude system modules (if specified)
9457 if (!($this->excludesystem &&
9458 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
9459 MOD_ARCHETYPE_SYSTEM)) {
9460 $this->choices[$record->id] = $record->name;
9464 return true;
9469 * Admin setting to show if a php extension is enabled or not.
9471 * @copyright 2013 Damyon Wiese
9472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9474 class admin_setting_php_extension_enabled extends admin_setting {
9476 /** @var string The name of the extension to check for */
9477 private $extension;
9480 * Calls parent::__construct with specific arguments
9482 public function __construct($name, $visiblename, $description, $extension) {
9483 $this->extension = $extension;
9484 $this->nosave = true;
9485 parent::__construct($name, $visiblename, $description, '');
9489 * Always returns true, does nothing
9491 * @return true
9493 public function get_setting() {
9494 return true;
9498 * Always returns true, does nothing
9500 * @return true
9502 public function get_defaultsetting() {
9503 return true;
9507 * Always returns '', does not write anything
9509 * @return string Always returns ''
9511 public function write_setting($data) {
9512 // Do not write any setting.
9513 return '';
9517 * Outputs the html for this setting.
9518 * @return string Returns an XHTML string
9520 public function output_html($data, $query='') {
9521 global $OUTPUT;
9523 $o = '';
9524 if (!extension_loaded($this->extension)) {
9525 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
9527 $o .= format_admin_setting($this, $this->visiblename, $warning);
9529 return $o;
9534 * Server timezone setting.
9536 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9538 * @author Petr Skoda <petr.skoda@totaralms.com>
9540 class admin_setting_servertimezone extends admin_setting_configselect {
9542 * Constructor.
9544 public function __construct() {
9545 $default = core_date::get_default_php_timezone();
9546 if ($default === 'UTC') {
9547 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
9548 $default = 'Europe/London';
9551 parent::__construct('timezone',
9552 new lang_string('timezone', 'core_admin'),
9553 new lang_string('configtimezone', 'core_admin'), $default, null);
9557 * Lazy load timezone options.
9558 * @return bool true if loaded, false if error
9560 public function load_choices() {
9561 global $CFG;
9562 if (is_array($this->choices)) {
9563 return true;
9566 $current = isset($CFG->timezone) ? $CFG->timezone : null;
9567 $this->choices = core_date::get_list_of_timezones($current, false);
9568 if ($current == 99) {
9569 // Do not show 99 unless it is current value, we want to get rid of it over time.
9570 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
9571 core_date::get_default_php_timezone());
9574 return true;
9579 * Forced user timezone setting.
9581 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9583 * @author Petr Skoda <petr.skoda@totaralms.com>
9585 class admin_setting_forcetimezone extends admin_setting_configselect {
9587 * Constructor.
9589 public function __construct() {
9590 parent::__construct('forcetimezone',
9591 new lang_string('forcetimezone', 'core_admin'),
9592 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
9596 * Lazy load timezone options.
9597 * @return bool true if loaded, false if error
9599 public function load_choices() {
9600 global $CFG;
9601 if (is_array($this->choices)) {
9602 return true;
9605 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
9606 $this->choices = core_date::get_list_of_timezones($current, true);
9607 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
9609 return true;
9615 * Search setup steps info.
9617 * @package core
9618 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
9619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9621 class admin_setting_searchsetupinfo extends admin_setting {
9624 * Calls parent::__construct with specific arguments
9626 public function __construct() {
9627 $this->nosave = true;
9628 parent::__construct('searchsetupinfo', '', '', '');
9632 * Always returns true, does nothing
9634 * @return true
9636 public function get_setting() {
9637 return true;
9641 * Always returns true, does nothing
9643 * @return true
9645 public function get_defaultsetting() {
9646 return true;
9650 * Always returns '', does not write anything
9652 * @param array $data
9653 * @return string Always returns ''
9655 public function write_setting($data) {
9656 // Do not write any setting.
9657 return '';
9661 * Builds the HTML to display the control
9663 * @param string $data Unused
9664 * @param string $query
9665 * @return string
9667 public function output_html($data, $query='') {
9668 global $CFG, $OUTPUT;
9670 $return = '';
9671 $brtag = html_writer::empty_tag('br');
9673 // Available search areas.
9674 $searchareas = \core_search\manager::get_search_areas_list();
9675 $anyenabled = false;
9676 $anyindexed = false;
9677 foreach ($searchareas as $areaid => $searcharea) {
9678 list($componentname, $varname) = $searcharea->get_config_var_name();
9679 if (!$anyenabled) {
9680 $anyenabled = get_config($componentname, $varname . '_enabled');
9682 if (!$anyindexed) {
9683 $anyindexed = get_config($componentname, $varname . '_indexingstart');
9685 if ($anyenabled && $anyindexed) {
9686 break;
9690 $return .= $OUTPUT->heading(get_string('searchsetupinfo', 'admin'), 3, 'main');
9692 $table = new html_table();
9693 $table->head = array(get_string('step', 'search'), get_string('status'));
9694 $table->colclasses = array('leftalign step', 'leftalign status');
9695 $table->id = 'searchsetup';
9696 $table->attributes['class'] = 'admintable generaltable';
9697 $table->data = array();
9699 $return .= $brtag . get_string('searchsetupdescription', 'search') . $brtag . $brtag;
9701 // Select a search engine.
9702 $row = array();
9703 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
9704 $row[0] = '1. ' . html_writer::tag('a', get_string('selectsearchengine', 'admin'),
9705 array('href' => $url));
9707 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9708 if (!empty($CFG->searchengine)) {
9709 $status = html_writer::tag('span', get_string('pluginname', 'search_' . $CFG->searchengine),
9710 array('class' => 'statusok'));
9713 $row[1] = $status;
9714 $table->data[] = $row;
9716 // Available areas.
9717 $row = array();
9718 $url = new moodle_url('/admin/settings.php?section=manageglobalsearch#admin-searchengine');
9719 $row[0] = '2. ' . html_writer::tag('a', get_string('enablesearchareas', 'admin'),
9720 array('href' => $url));
9722 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9723 if ($anyenabled) {
9724 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9727 $row[1] = $status;
9728 $table->data[] = $row;
9730 // Setup search engine.
9731 $row = array();
9732 if (empty($CFG->searchengine)) {
9733 $row[0] = '3. ' . get_string('setupsearchengine', 'admin');
9734 $row[1] = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9735 } else {
9736 $url = new moodle_url('/admin/settings.php?section=search' . $CFG->searchengine);
9737 $row[0] = '3. ' . html_writer::tag('a', get_string('setupsearchengine', 'admin'),
9738 array('href' => $url));
9739 // Check the engine status.
9740 $searchengine = \core_search\manager::search_engine_instance();
9741 $serverstatus = $searchengine->is_server_ready();
9742 if ($serverstatus === true) {
9743 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9744 } else {
9745 $status = html_writer::tag('span', $serverstatus, array('class' => 'statuscritical'));
9747 $row[1] = $status;
9749 $table->data[] = $row;
9751 // Indexed data.
9752 $row = array();
9753 $url = new moodle_url('/report/search/index.php#searchindexform');
9754 $row[0] = '4. ' . html_writer::tag('a', get_string('indexdata', 'admin'), array('href' => $url));
9755 if ($anyindexed) {
9756 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9757 } else {
9758 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9760 $row[1] = $status;
9761 $table->data[] = $row;
9763 // Enable global search.
9764 $row = array();
9765 $url = new moodle_url("/admin/search.php?query=enableglobalsearch");
9766 $row[0] = '5. ' . html_writer::tag('a', get_string('enableglobalsearch', 'admin'),
9767 array('href' => $url));
9768 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
9769 if (\core_search\manager::is_global_search_enabled()) {
9770 $status = html_writer::tag('span', get_string('yes'), array('class' => 'statusok'));
9772 $row[1] = $status;
9773 $table->data[] = $row;
9775 $return .= html_writer::table($table);
9777 return highlight($query, $return);