Merge branch 'MDL-52573-30' of git://github.com/danpoltawski/moodle into MOODLE_30_STABLE
[moodle.git] / lib / adminlib.php
blob552da2bfb9bb0586df9b4e12689b11debf8a024c
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 instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // Delete Inbound Message datakeys.
206 $DB->delete_records_select('messageinbound_datakeys',
207 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($pluginname));
209 // Delete Inbound Message handlers.
210 $DB->delete_records('messageinbound_handlers', array('component' => $pluginname));
212 // delete all the logs
213 $DB->delete_records('log', array('module' => $pluginname));
215 // delete log_display information
216 $DB->delete_records('log_display', array('component' => $component));
218 // delete the module configuration records
219 unset_all_config_for_plugin($component);
220 if ($type === 'mod') {
221 unset_all_config_for_plugin($pluginname);
224 // delete message provider
225 message_provider_uninstall($component);
227 // delete the plugin tables
228 $xmldbfilepath = $plugindirectory . '/db/install.xml';
229 drop_plugin_tables($component, $xmldbfilepath, false);
230 if ($type === 'mod' or $type === 'block') {
231 // non-frankenstyle table prefixes
232 drop_plugin_tables($name, $xmldbfilepath, false);
235 // delete the capabilities that were defined by this module
236 capabilities_cleanup($component);
238 // remove event handlers and dequeue pending events
239 events_uninstall($component);
241 // Delete all remaining files in the filepool owned by the component.
242 $fs = get_file_storage();
243 $fs->delete_component_files($component);
245 // Finally purge all caches.
246 purge_all_caches();
248 // Invalidate the hash used for upgrade detections.
249 set_config('allversionshash', '');
251 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
255 * Returns the version of installed component
257 * @param string $component component name
258 * @param string $source either 'disk' or 'installed' - where to get the version information from
259 * @return string|bool version number or false if the component is not found
261 function get_component_version($component, $source='installed') {
262 global $CFG, $DB;
264 list($type, $name) = core_component::normalize_component($component);
266 // moodle core or a core subsystem
267 if ($type === 'core') {
268 if ($source === 'installed') {
269 if (empty($CFG->version)) {
270 return false;
271 } else {
272 return $CFG->version;
274 } else {
275 if (!is_readable($CFG->dirroot.'/version.php')) {
276 return false;
277 } else {
278 $version = null; //initialize variable for IDEs
279 include($CFG->dirroot.'/version.php');
280 return $version;
285 // activity module
286 if ($type === 'mod') {
287 if ($source === 'installed') {
288 if ($CFG->version < 2013092001.02) {
289 return $DB->get_field('modules', 'version', array('name'=>$name));
290 } else {
291 return get_config('mod_'.$name, 'version');
294 } else {
295 $mods = core_component::get_plugin_list('mod');
296 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
297 return false;
298 } else {
299 $plugin = new stdClass();
300 $plugin->version = null;
301 $module = $plugin;
302 include($mods[$name].'/version.php');
303 return $plugin->version;
308 // block
309 if ($type === 'block') {
310 if ($source === 'installed') {
311 if ($CFG->version < 2013092001.02) {
312 return $DB->get_field('block', 'version', array('name'=>$name));
313 } else {
314 return get_config('block_'.$name, 'version');
316 } else {
317 $blocks = core_component::get_plugin_list('block');
318 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
319 return false;
320 } else {
321 $plugin = new stdclass();
322 include($blocks[$name].'/version.php');
323 return $plugin->version;
328 // all other plugin types
329 if ($source === 'installed') {
330 return get_config($type.'_'.$name, 'version');
331 } else {
332 $plugins = core_component::get_plugin_list($type);
333 if (empty($plugins[$name])) {
334 return false;
335 } else {
336 $plugin = new stdclass();
337 include($plugins[$name].'/version.php');
338 return $plugin->version;
344 * Delete all plugin tables
346 * @param string $name Name of plugin, used as table prefix
347 * @param string $file Path to install.xml file
348 * @param bool $feedback defaults to true
349 * @return bool Always returns true
351 function drop_plugin_tables($name, $file, $feedback=true) {
352 global $CFG, $DB;
354 // first try normal delete
355 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
356 return true;
359 // then try to find all tables that start with name and are not in any xml file
360 $used_tables = get_used_table_names();
362 $tables = $DB->get_tables();
364 /// Iterate over, fixing id fields as necessary
365 foreach ($tables as $table) {
366 if (in_array($table, $used_tables)) {
367 continue;
370 if (strpos($table, $name) !== 0) {
371 continue;
374 // found orphan table --> delete it
375 if ($DB->get_manager()->table_exists($table)) {
376 $xmldb_table = new xmldb_table($table);
377 $DB->get_manager()->drop_table($xmldb_table);
381 return true;
385 * Returns names of all known tables == tables that moodle knows about.
387 * @return array Array of lowercase table names
389 function get_used_table_names() {
390 $table_names = array();
391 $dbdirs = get_db_directories();
393 foreach ($dbdirs as $dbdir) {
394 $file = $dbdir.'/install.xml';
396 $xmldb_file = new xmldb_file($file);
398 if (!$xmldb_file->fileExists()) {
399 continue;
402 $loaded = $xmldb_file->loadXMLStructure();
403 $structure = $xmldb_file->getStructure();
405 if ($loaded and $tables = $structure->getTables()) {
406 foreach($tables as $table) {
407 $table_names[] = strtolower($table->getName());
412 return $table_names;
416 * Returns list of all directories where we expect install.xml files
417 * @return array Array of paths
419 function get_db_directories() {
420 global $CFG;
422 $dbdirs = array();
424 /// First, the main one (lib/db)
425 $dbdirs[] = $CFG->libdir.'/db';
427 /// Then, all the ones defined by core_component::get_plugin_types()
428 $plugintypes = core_component::get_plugin_types();
429 foreach ($plugintypes as $plugintype => $pluginbasedir) {
430 if ($plugins = core_component::get_plugin_list($plugintype)) {
431 foreach ($plugins as $plugin => $plugindir) {
432 $dbdirs[] = $plugindir.'/db';
437 return $dbdirs;
441 * Try to obtain or release the cron lock.
442 * @param string $name name of lock
443 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
444 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
445 * @return bool true if lock obtained
447 function set_cron_lock($name, $until, $ignorecurrent=false) {
448 global $DB;
449 if (empty($name)) {
450 debugging("Tried to get a cron lock for a null fieldname");
451 return false;
454 // remove lock by force == remove from config table
455 if (is_null($until)) {
456 set_config($name, null);
457 return true;
460 if (!$ignorecurrent) {
461 // read value from db - other processes might have changed it
462 $value = $DB->get_field('config', 'value', array('name'=>$name));
464 if ($value and $value > time()) {
465 //lock active
466 return false;
470 set_config($name, $until);
471 return true;
475 * Test if and critical warnings are present
476 * @return bool
478 function admin_critical_warnings_present() {
479 global $SESSION;
481 if (!has_capability('moodle/site:config', context_system::instance())) {
482 return 0;
485 if (!isset($SESSION->admin_critical_warning)) {
486 $SESSION->admin_critical_warning = 0;
487 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
488 $SESSION->admin_critical_warning = 1;
492 return $SESSION->admin_critical_warning;
496 * Detects if float supports at least 10 decimal digits
498 * Detects if float supports at least 10 decimal digits
499 * and also if float-->string conversion works as expected.
501 * @return bool true if problem found
503 function is_float_problem() {
504 $num1 = 2009010200.01;
505 $num2 = 2009010200.02;
507 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
511 * Try to verify that dataroot is not accessible from web.
513 * Try to verify that dataroot is not accessible from web.
514 * It is not 100% correct but might help to reduce number of vulnerable sites.
515 * Protection from httpd.conf and .htaccess is not detected properly.
517 * @uses INSECURE_DATAROOT_WARNING
518 * @uses INSECURE_DATAROOT_ERROR
519 * @param bool $fetchtest try to test public access by fetching file, default false
520 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
522 function is_dataroot_insecure($fetchtest=false) {
523 global $CFG;
525 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
527 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
528 $rp = strrev(trim($rp, '/'));
529 $rp = explode('/', $rp);
530 foreach($rp as $r) {
531 if (strpos($siteroot, '/'.$r.'/') === 0) {
532 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
533 } else {
534 break; // probably alias root
538 $siteroot = strrev($siteroot);
539 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
541 if (strpos($dataroot, $siteroot) !== 0) {
542 return false;
545 if (!$fetchtest) {
546 return INSECURE_DATAROOT_WARNING;
549 // now try all methods to fetch a test file using http protocol
551 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
552 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
553 $httpdocroot = $matches[1];
554 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
555 make_upload_directory('diag');
556 $testfile = $CFG->dataroot.'/diag/public.txt';
557 if (!file_exists($testfile)) {
558 file_put_contents($testfile, 'test file, do not delete');
559 @chmod($testfile, $CFG->filepermissions);
561 $teststr = trim(file_get_contents($testfile));
562 if (empty($teststr)) {
563 // hmm, strange
564 return INSECURE_DATAROOT_WARNING;
567 $testurl = $datarooturl.'/diag/public.txt';
568 if (extension_loaded('curl') and
569 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
570 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
571 ($ch = @curl_init($testurl)) !== false) {
572 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
573 curl_setopt($ch, CURLOPT_HEADER, false);
574 $data = curl_exec($ch);
575 if (!curl_errno($ch)) {
576 $data = trim($data);
577 if ($data === $teststr) {
578 curl_close($ch);
579 return INSECURE_DATAROOT_ERROR;
582 curl_close($ch);
585 if ($data = @file_get_contents($testurl)) {
586 $data = trim($data);
587 if ($data === $teststr) {
588 return INSECURE_DATAROOT_ERROR;
592 preg_match('|https?://([^/]+)|i', $testurl, $matches);
593 $sitename = $matches[1];
594 $error = 0;
595 if ($fp = @fsockopen($sitename, 80, $error)) {
596 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
597 $localurl = $matches[1];
598 $out = "GET $localurl HTTP/1.1\r\n";
599 $out .= "Host: $sitename\r\n";
600 $out .= "Connection: Close\r\n\r\n";
601 fwrite($fp, $out);
602 $data = '';
603 $incoming = false;
604 while (!feof($fp)) {
605 if ($incoming) {
606 $data .= fgets($fp, 1024);
607 } else if (@fgets($fp, 1024) === "\r\n") {
608 $incoming = true;
611 fclose($fp);
612 $data = trim($data);
613 if ($data === $teststr) {
614 return INSECURE_DATAROOT_ERROR;
618 return INSECURE_DATAROOT_WARNING;
622 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
624 function enable_cli_maintenance_mode() {
625 global $CFG;
627 if (file_exists("$CFG->dataroot/climaintenance.html")) {
628 unlink("$CFG->dataroot/climaintenance.html");
631 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
632 $data = $CFG->maintenance_message;
633 $data = bootstrap_renderer::early_error_content($data, null, null, null);
634 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
636 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
637 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
639 } else {
640 $data = get_string('sitemaintenance', 'admin');
641 $data = bootstrap_renderer::early_error_content($data, null, null, null);
642 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
645 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
646 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
649 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
653 * Interface for anything appearing in the admin tree
655 * The interface that is implemented by anything that appears in the admin tree
656 * block. It forces inheriting classes to define a method for checking user permissions
657 * and methods for finding something in the admin tree.
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
661 interface part_of_admin_tree {
664 * Finds a named part_of_admin_tree.
666 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
667 * and not parentable_part_of_admin_tree, then this function should only check if
668 * $this->name matches $name. If it does, it should return a reference to $this,
669 * otherwise, it should return a reference to NULL.
671 * If a class inherits parentable_part_of_admin_tree, this method should be called
672 * recursively on all child objects (assuming, of course, the parent object's name
673 * doesn't match the search criterion).
675 * @param string $name The internal name of the part_of_admin_tree we're searching for.
676 * @return mixed An object reference or a NULL reference.
678 public function locate($name);
681 * Removes named part_of_admin_tree.
683 * @param string $name The internal name of the part_of_admin_tree we want to remove.
684 * @return bool success.
686 public function prune($name);
689 * Search using query
690 * @param string $query
691 * @return mixed array-object structure of found settings and pages
693 public function search($query);
696 * Verifies current user's access to this part_of_admin_tree.
698 * Used to check if the current user has access to this part of the admin tree or
699 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
700 * then this method is usually just a call to has_capability() in the site context.
702 * If a class inherits parentable_part_of_admin_tree, this method should return the
703 * logical OR of the return of check_access() on all child objects.
705 * @return bool True if the user has access, false if she doesn't.
707 public function check_access();
710 * Mostly useful for removing of some parts of the tree in admin tree block.
712 * @return True is hidden from normal list view
714 public function is_hidden();
717 * Show we display Save button at the page bottom?
718 * @return bool
720 public function show_save();
725 * Interface implemented by any part_of_admin_tree that has children.
727 * The interface implemented by any part_of_admin_tree that can be a parent
728 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
729 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
730 * include an add method for adding other part_of_admin_tree objects as children.
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 interface parentable_part_of_admin_tree extends part_of_admin_tree {
737 * Adds a part_of_admin_tree object to the admin tree.
739 * Used to add a part_of_admin_tree object to this object or a child of this
740 * object. $something should only be added if $destinationname matches
741 * $this->name. If it doesn't, add should be called on child objects that are
742 * also parentable_part_of_admin_tree's.
744 * $something should be appended as the last child in the $destinationname. If the
745 * $beforesibling is specified, $something should be prepended to it. If the given
746 * sibling is not found, $something should be appended to the end of $destinationname
747 * and a developer debugging message should be displayed.
749 * @param string $destinationname The internal name of the new parent for $something.
750 * @param part_of_admin_tree $something The object to be added.
751 * @return bool True on success, false on failure.
753 public function add($destinationname, $something, $beforesibling = null);
759 * The object used to represent folders (a.k.a. categories) in the admin tree block.
761 * Each admin_category object contains a number of part_of_admin_tree objects.
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class admin_category implements parentable_part_of_admin_tree {
767 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
768 protected $children;
769 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
770 public $name;
771 /** @var string The displayed name for this category. Usually obtained through get_string() */
772 public $visiblename;
773 /** @var bool Should this category be hidden in admin tree block? */
774 public $hidden;
775 /** @var mixed Either a string or an array or strings */
776 public $path;
777 /** @var mixed Either a string or an array or strings */
778 public $visiblepath;
780 /** @var array fast lookup category cache, all categories of one tree point to one cache */
781 protected $category_cache;
783 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
784 protected $sort = false;
785 /** @var bool If set to true children will be sorted in ascending order. */
786 protected $sortasc = true;
787 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
788 protected $sortsplit = true;
789 /** @var bool $sorted True if the children have been sorted and don't need resorting */
790 protected $sorted = false;
793 * Constructor for an empty admin category
795 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
796 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
797 * @param bool $hidden hide category in admin tree block, defaults to false
799 public function __construct($name, $visiblename, $hidden=false) {
800 $this->children = array();
801 $this->name = $name;
802 $this->visiblename = $visiblename;
803 $this->hidden = $hidden;
807 * Returns a reference to the part_of_admin_tree object with internal name $name.
809 * @param string $name The internal name of the object we want.
810 * @param bool $findpath initialize path and visiblepath arrays
811 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
812 * defaults to false
814 public function locate($name, $findpath=false) {
815 if (!isset($this->category_cache[$this->name])) {
816 // somebody much have purged the cache
817 $this->category_cache[$this->name] = $this;
820 if ($this->name == $name) {
821 if ($findpath) {
822 $this->visiblepath[] = $this->visiblename;
823 $this->path[] = $this->name;
825 return $this;
828 // quick category lookup
829 if (!$findpath and isset($this->category_cache[$name])) {
830 return $this->category_cache[$name];
833 $return = NULL;
834 foreach($this->children as $childid=>$unused) {
835 if ($return = $this->children[$childid]->locate($name, $findpath)) {
836 break;
840 if (!is_null($return) and $findpath) {
841 $return->visiblepath[] = $this->visiblename;
842 $return->path[] = $this->name;
845 return $return;
849 * Search using query
851 * @param string query
852 * @return mixed array-object structure of found settings and pages
854 public function search($query) {
855 $result = array();
856 foreach ($this->get_children() as $child) {
857 $subsearch = $child->search($query);
858 if (!is_array($subsearch)) {
859 debugging('Incorrect search result from '.$child->name);
860 continue;
862 $result = array_merge($result, $subsearch);
864 return $result;
868 * Removes part_of_admin_tree object with internal name $name.
870 * @param string $name The internal name of the object we want to remove.
871 * @return bool success
873 public function prune($name) {
875 if ($this->name == $name) {
876 return false; //can not remove itself
879 foreach($this->children as $precedence => $child) {
880 if ($child->name == $name) {
881 // clear cache and delete self
882 while($this->category_cache) {
883 // delete the cache, but keep the original array address
884 array_pop($this->category_cache);
886 unset($this->children[$precedence]);
887 return true;
888 } else if ($this->children[$precedence]->prune($name)) {
889 return true;
892 return false;
896 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
898 * By default the new part of the tree is appended as the last child of the parent. You
899 * can specify a sibling node that the new part should be prepended to. If the given
900 * sibling is not found, the part is appended to the end (as it would be by default) and
901 * a developer debugging message is displayed.
903 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
904 * @param string $destinationame The internal name of the immediate parent that we want for $something.
905 * @param mixed $something A part_of_admin_tree or setting instance to be added.
906 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something, $beforesibling = null) {
910 global $CFG;
912 $parent = $this->locate($parentname);
913 if (is_null($parent)) {
914 debugging('parent does not exist!');
915 return false;
918 if ($something instanceof part_of_admin_tree) {
919 if (!($parent instanceof parentable_part_of_admin_tree)) {
920 debugging('error - parts of tree can be inserted only into parentable parts');
921 return false;
923 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
924 // The name of the node is already used, simply warn the developer that this should not happen.
925 // It is intentional to check for the debug level before performing the check.
926 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
928 if (is_null($beforesibling)) {
929 // Append $something as the parent's last child.
930 $parent->children[] = $something;
931 } else {
932 if (!is_string($beforesibling) or trim($beforesibling) === '') {
933 throw new coding_exception('Unexpected value of the beforesibling parameter');
935 // Try to find the position of the sibling.
936 $siblingposition = null;
937 foreach ($parent->children as $childposition => $child) {
938 if ($child->name === $beforesibling) {
939 $siblingposition = $childposition;
940 break;
943 if (is_null($siblingposition)) {
944 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
945 $parent->children[] = $something;
946 } else {
947 $parent->children = array_merge(
948 array_slice($parent->children, 0, $siblingposition),
949 array($something),
950 array_slice($parent->children, $siblingposition)
954 if ($something instanceof admin_category) {
955 if (isset($this->category_cache[$something->name])) {
956 debugging('Duplicate admin category name: '.$something->name);
957 } else {
958 $this->category_cache[$something->name] = $something;
959 $something->category_cache =& $this->category_cache;
960 foreach ($something->children as $child) {
961 // just in case somebody already added subcategories
962 if ($child instanceof admin_category) {
963 if (isset($this->category_cache[$child->name])) {
964 debugging('Duplicate admin category name: '.$child->name);
965 } else {
966 $this->category_cache[$child->name] = $child;
967 $child->category_cache =& $this->category_cache;
973 return true;
975 } else {
976 debugging('error - can not add this element');
977 return false;
983 * Checks if the user has access to anything in this category.
985 * @return bool True if the user has access to at least one child in this category, false otherwise.
987 public function check_access() {
988 foreach ($this->children as $child) {
989 if ($child->check_access()) {
990 return true;
993 return false;
997 * Is this category hidden in admin tree block?
999 * @return bool True if hidden
1001 public function is_hidden() {
1002 return $this->hidden;
1006 * Show we display Save button at the page bottom?
1007 * @return bool
1009 public function show_save() {
1010 foreach ($this->children as $child) {
1011 if ($child->show_save()) {
1012 return true;
1015 return false;
1019 * Sets sorting on this category.
1021 * Please note this function doesn't actually do the sorting.
1022 * It can be called anytime.
1023 * Sorting occurs when the user calls get_children.
1024 * Code using the children array directly won't see the sorted results.
1026 * @param bool $sort If set to true children will be sorted, if false they won't be.
1027 * @param bool $asc If true sorting will be ascending, otherwise descending.
1028 * @param bool $split If true we sort pages and sub categories separately.
1030 public function set_sorting($sort, $asc = true, $split = true) {
1031 $this->sort = (bool)$sort;
1032 $this->sortasc = (bool)$asc;
1033 $this->sortsplit = (bool)$split;
1037 * Returns the children associated with this category.
1039 * @return part_of_admin_tree[]
1041 public function get_children() {
1042 // If we should sort and it hasn't already been sorted.
1043 if ($this->sort && !$this->sorted) {
1044 if ($this->sortsplit) {
1045 $categories = array();
1046 $pages = array();
1047 foreach ($this->children as $child) {
1048 if ($child instanceof admin_category) {
1049 $categories[] = $child;
1050 } else {
1051 $pages[] = $child;
1054 core_collator::asort_objects_by_property($categories, 'visiblename');
1055 core_collator::asort_objects_by_property($pages, 'visiblename');
1056 if (!$this->sortasc) {
1057 $categories = array_reverse($categories);
1058 $pages = array_reverse($pages);
1060 $this->children = array_merge($pages, $categories);
1061 } else {
1062 core_collator::asort_objects_by_property($this->children, 'visiblename');
1063 if (!$this->sortasc) {
1064 $this->children = array_reverse($this->children);
1067 $this->sorted = true;
1069 return $this->children;
1073 * Magically gets a property from this object.
1075 * @param $property
1076 * @return part_of_admin_tree[]
1077 * @throws coding_exception
1079 public function __get($property) {
1080 if ($property === 'children') {
1081 return $this->get_children();
1083 throw new coding_exception('Invalid property requested.');
1087 * Magically sets a property against this object.
1089 * @param string $property
1090 * @param mixed $value
1091 * @throws coding_exception
1093 public function __set($property, $value) {
1094 if ($property === 'children') {
1095 $this->sorted = false;
1096 $this->children = $value;
1097 } else {
1098 throw new coding_exception('Invalid property requested.');
1103 * Checks if an inaccessible property is set.
1105 * @param string $property
1106 * @return bool
1107 * @throws coding_exception
1109 public function __isset($property) {
1110 if ($property === 'children') {
1111 return isset($this->children);
1113 throw new coding_exception('Invalid property requested.');
1119 * Root of admin settings tree, does not have any parent.
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class admin_root extends admin_category {
1124 /** @var array List of errors */
1125 public $errors;
1126 /** @var string search query */
1127 public $search;
1128 /** @var bool full tree flag - true means all settings required, false only pages required */
1129 public $fulltree;
1130 /** @var bool flag indicating loaded tree */
1131 public $loaded;
1132 /** @var mixed site custom defaults overriding defaults in settings files*/
1133 public $custom_defaults;
1136 * @param bool $fulltree true means all settings required,
1137 * false only pages required
1139 public function __construct($fulltree) {
1140 global $CFG;
1142 parent::__construct('root', get_string('administration'), false);
1143 $this->errors = array();
1144 $this->search = '';
1145 $this->fulltree = $fulltree;
1146 $this->loaded = false;
1148 $this->category_cache = array();
1150 // load custom defaults if found
1151 $this->custom_defaults = null;
1152 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1153 if (is_readable($defaultsfile)) {
1154 $defaults = array();
1155 include($defaultsfile);
1156 if (is_array($defaults) and count($defaults)) {
1157 $this->custom_defaults = $defaults;
1163 * Empties children array, and sets loaded to false
1165 * @param bool $requirefulltree
1167 public function purge_children($requirefulltree) {
1168 $this->children = array();
1169 $this->fulltree = ($requirefulltree || $this->fulltree);
1170 $this->loaded = false;
1171 //break circular dependencies - this helps PHP 5.2
1172 while($this->category_cache) {
1173 array_pop($this->category_cache);
1175 $this->category_cache = array();
1181 * Links external PHP pages into the admin tree.
1183 * See detailed usage example at the top of this document (adminlib.php)
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1187 class admin_externalpage implements part_of_admin_tree {
1189 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1190 public $name;
1192 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1193 public $visiblename;
1195 /** @var string The external URL that we should link to when someone requests this external page. */
1196 public $url;
1198 /** @var string The role capability/permission a user must have to access this external page. */
1199 public $req_capability;
1201 /** @var object The context in which capability/permission should be checked, default is site context. */
1202 public $context;
1204 /** @var bool hidden in admin tree block. */
1205 public $hidden;
1207 /** @var mixed either string or array of string */
1208 public $path;
1210 /** @var array list of visible names of page parents */
1211 public $visiblepath;
1214 * Constructor for adding an external page into the admin tree.
1216 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1217 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1218 * @param string $url The external URL that we should link to when someone requests this external page.
1219 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1220 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1221 * @param stdClass $context The context the page relates to. Not sure what happens
1222 * if you specify something other than system or front page. Defaults to system.
1224 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1225 $this->name = $name;
1226 $this->visiblename = $visiblename;
1227 $this->url = $url;
1228 if (is_array($req_capability)) {
1229 $this->req_capability = $req_capability;
1230 } else {
1231 $this->req_capability = array($req_capability);
1233 $this->hidden = $hidden;
1234 $this->context = $context;
1238 * Returns a reference to the part_of_admin_tree object with internal name $name.
1240 * @param string $name The internal name of the object we want.
1241 * @param bool $findpath defaults to false
1242 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1244 public function locate($name, $findpath=false) {
1245 if ($this->name == $name) {
1246 if ($findpath) {
1247 $this->visiblepath = array($this->visiblename);
1248 $this->path = array($this->name);
1250 return $this;
1251 } else {
1252 $return = NULL;
1253 return $return;
1258 * This function always returns false, required function by interface
1260 * @param string $name
1261 * @return false
1263 public function prune($name) {
1264 return false;
1268 * Search using query
1270 * @param string $query
1271 * @return mixed array-object structure of found settings and pages
1273 public function search($query) {
1274 $found = false;
1275 if (strpos(strtolower($this->name), $query) !== false) {
1276 $found = true;
1277 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1278 $found = true;
1280 if ($found) {
1281 $result = new stdClass();
1282 $result->page = $this;
1283 $result->settings = array();
1284 return array($this->name => $result);
1285 } else {
1286 return array();
1291 * Determines if the current user has access to this external page based on $this->req_capability.
1293 * @return bool True if user has access, false otherwise.
1295 public function check_access() {
1296 global $CFG;
1297 $context = empty($this->context) ? context_system::instance() : $this->context;
1298 foreach($this->req_capability as $cap) {
1299 if (has_capability($cap, $context)) {
1300 return true;
1303 return false;
1307 * Is this external page hidden in admin tree block?
1309 * @return bool True if hidden
1311 public function is_hidden() {
1312 return $this->hidden;
1316 * Show we display Save button at the page bottom?
1317 * @return bool
1319 public function show_save() {
1320 return false;
1326 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 class admin_settingpage implements part_of_admin_tree {
1332 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1333 public $name;
1335 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1336 public $visiblename;
1338 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1339 public $settings;
1341 /** @var string The role capability/permission a user must have to access this external page. */
1342 public $req_capability;
1344 /** @var object The context in which capability/permission should be checked, default is site context. */
1345 public $context;
1347 /** @var bool hidden in admin tree block. */
1348 public $hidden;
1350 /** @var mixed string of paths or array of strings of paths */
1351 public $path;
1353 /** @var array list of visible names of page parents */
1354 public $visiblepath;
1357 * see admin_settingpage for details of this function
1359 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1360 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1361 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1362 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1363 * @param stdClass $context The context the page relates to. Not sure what happens
1364 * if you specify something other than system or front page. Defaults to system.
1366 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1367 $this->settings = new stdClass();
1368 $this->name = $name;
1369 $this->visiblename = $visiblename;
1370 if (is_array($req_capability)) {
1371 $this->req_capability = $req_capability;
1372 } else {
1373 $this->req_capability = array($req_capability);
1375 $this->hidden = $hidden;
1376 $this->context = $context;
1380 * see admin_category
1382 * @param string $name
1383 * @param bool $findpath
1384 * @return mixed Object (this) if name == this->name, else returns null
1386 public function locate($name, $findpath=false) {
1387 if ($this->name == $name) {
1388 if ($findpath) {
1389 $this->visiblepath = array($this->visiblename);
1390 $this->path = array($this->name);
1392 return $this;
1393 } else {
1394 $return = NULL;
1395 return $return;
1400 * Search string in settings page.
1402 * @param string $query
1403 * @return array
1405 public function search($query) {
1406 $found = array();
1408 foreach ($this->settings as $setting) {
1409 if ($setting->is_related($query)) {
1410 $found[] = $setting;
1414 if ($found) {
1415 $result = new stdClass();
1416 $result->page = $this;
1417 $result->settings = $found;
1418 return array($this->name => $result);
1421 $found = false;
1422 if (strpos(strtolower($this->name), $query) !== false) {
1423 $found = true;
1424 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1425 $found = true;
1427 if ($found) {
1428 $result = new stdClass();
1429 $result->page = $this;
1430 $result->settings = array();
1431 return array($this->name => $result);
1432 } else {
1433 return array();
1438 * This function always returns false, required by interface
1440 * @param string $name
1441 * @return bool Always false
1443 public function prune($name) {
1444 return false;
1448 * adds an admin_setting to this admin_settingpage
1450 * 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
1451 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1453 * @param object $setting is the admin_setting object you want to add
1454 * @return bool true if successful, false if not
1456 public function add($setting) {
1457 if (!($setting instanceof admin_setting)) {
1458 debugging('error - not a setting instance');
1459 return false;
1462 $this->settings->{$setting->name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1554 * Constructor
1555 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1556 * or 'myplugin/mysetting' for ones in config_plugins.
1557 * @param string $visiblename localised name
1558 * @param string $description localised long description
1559 * @param mixed $defaultsetting string or array depending on implementation
1561 public function __construct($name, $visiblename, $description, $defaultsetting) {
1562 $this->parse_setting_name($name);
1563 $this->visiblename = $visiblename;
1564 $this->description = $description;
1565 $this->defaultsetting = $defaultsetting;
1569 * Generic function to add a flag to this admin setting.
1571 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1572 * @param bool $default - The default for the flag
1573 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1574 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1576 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1577 if (empty($this->flags[$shortname])) {
1578 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1579 } else {
1580 $this->flags[$shortname]->set_options($enabled, $default);
1585 * Set the enabled options flag on this admin setting.
1587 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1588 * @param bool $default - The default for the flag
1590 public function set_enabled_flag_options($enabled, $default) {
1591 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1595 * Set the advanced options flag on this admin setting.
1597 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1598 * @param bool $default - The default for the flag
1600 public function set_advanced_flag_options($enabled, $default) {
1601 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1606 * Set the locked options flag on this admin setting.
1608 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1609 * @param bool $default - The default for the flag
1611 public function set_locked_flag_options($enabled, $default) {
1612 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1616 * Get the currently saved value for a setting flag
1618 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1619 * @return bool
1621 public function get_setting_flag_value(admin_setting_flag $flag) {
1622 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1623 if (!isset($value)) {
1624 $value = $flag->get_default();
1627 return !empty($value);
1631 * Get the list of defaults for the flags on this setting.
1633 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1635 public function get_setting_flag_defaults(& $defaults) {
1636 foreach ($this->flags as $flag) {
1637 if ($flag->is_enabled() && $flag->get_default()) {
1638 $defaults[] = $flag->get_displayname();
1644 * Output the input fields for the advanced and locked flags on this setting.
1646 * @param bool $adv - The current value of the advanced flag.
1647 * @param bool $locked - The current value of the locked flag.
1648 * @return string $output - The html for the flags.
1650 public function output_setting_flags() {
1651 $output = '';
1653 foreach ($this->flags as $flag) {
1654 if ($flag->is_enabled()) {
1655 $output .= $flag->output_setting_flag($this);
1659 if (!empty($output)) {
1660 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1662 return $output;
1666 * Write the values of the flags for this admin setting.
1668 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1669 * @return bool - true if successful.
1671 public function write_setting_flags($data) {
1672 $result = true;
1673 foreach ($this->flags as $flag) {
1674 $result = $result && $flag->write_setting_flag($this, $data);
1676 return $result;
1680 * Set up $this->name and potentially $this->plugin
1682 * Set up $this->name and possibly $this->plugin based on whether $name looks
1683 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1684 * on the names, that is, output a developer debug warning if the name
1685 * contains anything other than [a-zA-Z0-9_]+.
1687 * @param string $name the setting name passed in to the constructor.
1689 private function parse_setting_name($name) {
1690 $bits = explode('/', $name);
1691 if (count($bits) > 2) {
1692 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1694 $this->name = array_pop($bits);
1695 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1698 if (!empty($bits)) {
1699 $this->plugin = array_pop($bits);
1700 if ($this->plugin === 'moodle') {
1701 $this->plugin = null;
1702 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1703 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1709 * Returns the fullname prefixed by the plugin
1710 * @return string
1712 public function get_full_name() {
1713 return 's_'.$this->plugin.'_'.$this->name;
1717 * Returns the ID string based on plugin and name
1718 * @return string
1720 public function get_id() {
1721 return 'id_s_'.$this->plugin.'_'.$this->name;
1725 * @param bool $affectsmodinfo If true, changes to this setting will
1726 * cause the course cache to be rebuilt
1728 public function set_affects_modinfo($affectsmodinfo) {
1729 $this->affectsmodinfo = $affectsmodinfo;
1733 * Returns the config if possible
1735 * @return mixed returns config if successful else null
1737 public function config_read($name) {
1738 global $CFG;
1739 if (!empty($this->plugin)) {
1740 $value = get_config($this->plugin, $name);
1741 return $value === false ? NULL : $value;
1743 } else {
1744 if (isset($CFG->$name)) {
1745 return $CFG->$name;
1746 } else {
1747 return NULL;
1753 * Used to set a config pair and log change
1755 * @param string $name
1756 * @param mixed $value Gets converted to string if not null
1757 * @return bool Write setting to config table
1759 public function config_write($name, $value) {
1760 global $DB, $USER, $CFG;
1762 if ($this->nosave) {
1763 return true;
1766 // make sure it is a real change
1767 $oldvalue = get_config($this->plugin, $name);
1768 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1769 $value = is_null($value) ? null : (string)$value;
1771 if ($oldvalue === $value) {
1772 return true;
1775 // store change
1776 set_config($name, $value, $this->plugin);
1778 // Some admin settings affect course modinfo
1779 if ($this->affectsmodinfo) {
1780 // Clear course cache for all courses
1781 rebuild_course_cache(0, true);
1784 $this->add_to_config_log($name, $oldvalue, $value);
1786 return true; // BC only
1790 * Log config changes if necessary.
1791 * @param string $name
1792 * @param string $oldvalue
1793 * @param string $value
1795 protected function add_to_config_log($name, $oldvalue, $value) {
1796 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1800 * Returns current value of this setting
1801 * @return mixed array or string depending on instance, NULL means not set yet
1803 public abstract function get_setting();
1806 * Returns default setting if exists
1807 * @return mixed array or string depending on instance; NULL means no default, user must supply
1809 public function get_defaultsetting() {
1810 $adminroot = admin_get_root(false, false);
1811 if (!empty($adminroot->custom_defaults)) {
1812 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1813 if (isset($adminroot->custom_defaults[$plugin])) {
1814 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1815 return $adminroot->custom_defaults[$plugin][$this->name];
1819 return $this->defaultsetting;
1823 * Store new setting
1825 * @param mixed $data string or array, must not be NULL
1826 * @return string empty string if ok, string error message otherwise
1828 public abstract function write_setting($data);
1831 * Return part of form with setting
1832 * This function should always be overwritten
1834 * @param mixed $data array or string depending on setting
1835 * @param string $query
1836 * @return string
1838 public function output_html($data, $query='') {
1839 // should be overridden
1840 return;
1844 * Function called if setting updated - cleanup, cache reset, etc.
1845 * @param string $functionname Sets the function name
1846 * @return void
1848 public function set_updatedcallback($functionname) {
1849 $this->updatedcallback = $functionname;
1853 * Execute postupdatecallback if necessary.
1854 * @param mixed $original original value before write_setting()
1855 * @return bool true if changed, false if not.
1857 public function post_write_settings($original) {
1858 // Comparison must work for arrays too.
1859 if (serialize($original) === serialize($this->get_setting())) {
1860 return false;
1863 $callbackfunction = $this->updatedcallback;
1864 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1865 $callbackfunction($this->get_full_name());
1867 return true;
1871 * Is setting related to query text - used when searching
1872 * @param string $query
1873 * @return bool
1875 public function is_related($query) {
1876 if (strpos(strtolower($this->name), $query) !== false) {
1877 return true;
1879 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1883 return true;
1885 $current = $this->get_setting();
1886 if (!is_null($current)) {
1887 if (is_string($current)) {
1888 if (strpos(core_text::strtolower($current), $query) !== false) {
1889 return true;
1893 $default = $this->get_defaultsetting();
1894 if (!is_null($default)) {
1895 if (is_string($default)) {
1896 if (strpos(core_text::strtolower($default), $query) !== false) {
1897 return true;
1901 return false;
1906 * An additional option that can be applied to an admin setting.
1907 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class admin_setting_flag {
1912 /** @var bool Flag to indicate if this option can be toggled for this setting */
1913 private $enabled = false;
1914 /** @var bool Flag to indicate if this option defaults to true or false */
1915 private $default = false;
1916 /** @var string Short string used to create setting name - e.g. 'adv' */
1917 private $shortname = '';
1918 /** @var string String used as the label for this flag */
1919 private $displayname = '';
1920 /** @const Checkbox for this flag is displayed in admin page */
1921 const ENABLED = true;
1922 /** @const Checkbox for this flag is not displayed in admin page */
1923 const DISABLED = false;
1926 * Constructor
1928 * @param bool $enabled Can this option can be toggled.
1929 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1930 * @param bool $default The default checked state for this setting option.
1931 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1932 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1934 public function __construct($enabled, $default, $shortname, $displayname) {
1935 $this->shortname = $shortname;
1936 $this->displayname = $displayname;
1937 $this->set_options($enabled, $default);
1941 * Update the values of this setting options class
1943 * @param bool $enabled Can this option can be toggled.
1944 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1945 * @param bool $default The default checked state for this setting option.
1947 public function set_options($enabled, $default) {
1948 $this->enabled = $enabled;
1949 $this->default = $default;
1953 * Should this option appear in the interface and be toggleable?
1955 * @return bool Is it enabled?
1957 public function is_enabled() {
1958 return $this->enabled;
1962 * Should this option be checked by default?
1964 * @return bool Is it on by default?
1966 public function get_default() {
1967 return $this->default;
1971 * Return the short name for this flag. e.g. 'adv' or 'locked'
1973 * @return string
1975 public function get_shortname() {
1976 return $this->shortname;
1980 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1982 * @return string
1984 public function get_displayname() {
1985 return $this->displayname;
1989 * Save the submitted data for this flag - or set it to the default if $data is null.
1991 * @param admin_setting $setting - The admin setting for this flag
1992 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1993 * @return bool
1995 public function write_setting_flag(admin_setting $setting, $data) {
1996 $result = true;
1997 if ($this->is_enabled()) {
1998 if (!isset($data)) {
1999 $value = $this->get_default();
2000 } else {
2001 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2003 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2006 return $result;
2011 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2013 * @param admin_setting $setting - The admin setting for this flag
2014 * @return string - The html for the checkbox.
2016 public function output_setting_flag(admin_setting $setting) {
2017 $value = $setting->get_setting_flag_value($this);
2018 $output = ' <input type="checkbox" class="form-checkbox" ' .
2019 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2020 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2021 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2022 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2023 $this->get_displayname() .
2024 ' </label> ';
2025 return $output;
2031 * No setting - just heading and text.
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class admin_setting_heading extends admin_setting {
2038 * not a setting, just text
2039 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2040 * @param string $heading heading
2041 * @param string $information text in box
2043 public function __construct($name, $heading, $information) {
2044 $this->nosave = true;
2045 parent::__construct($name, $heading, $information, '');
2049 * Always returns true
2050 * @return bool Always returns true
2052 public function get_setting() {
2053 return true;
2057 * Always returns true
2058 * @return bool Always returns true
2060 public function get_defaultsetting() {
2061 return true;
2065 * Never write settings
2066 * @return string Always returns an empty string
2068 public function write_setting($data) {
2069 // do not write any setting
2070 return '';
2074 * Returns an HTML string
2075 * @return string Returns an HTML string
2077 public function output_html($data, $query='') {
2078 global $OUTPUT;
2079 $return = '';
2080 if ($this->visiblename != '') {
2081 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2083 if ($this->description != '') {
2084 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2086 return $return;
2092 * The most flexibly setting, user is typing text
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configtext extends admin_setting {
2098 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2099 public $paramtype;
2100 /** @var int default field size */
2101 public $size;
2104 * Config text constructor
2106 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2107 * @param string $visiblename localised
2108 * @param string $description long localised info
2109 * @param string $defaultsetting
2110 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2111 * @param int $size default field size
2113 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2114 $this->paramtype = $paramtype;
2115 if (!is_null($size)) {
2116 $this->size = $size;
2117 } else {
2118 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2120 parent::__construct($name, $visiblename, $description, $defaultsetting);
2124 * Return the setting
2126 * @return mixed returns config if successful else null
2128 public function get_setting() {
2129 return $this->config_read($this->name);
2132 public function write_setting($data) {
2133 if ($this->paramtype === PARAM_INT and $data === '') {
2134 // do not complain if '' used instead of 0
2135 $data = 0;
2137 // $data is a string
2138 $validated = $this->validate($data);
2139 if ($validated !== true) {
2140 return $validated;
2142 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2146 * Validate data before storage
2147 * @param string data
2148 * @return mixed true if ok string if error found
2150 public function validate($data) {
2151 // allow paramtype to be a custom regex if it is the form of /pattern/
2152 if (preg_match('#^/.*/$#', $this->paramtype)) {
2153 if (preg_match($this->paramtype, $data)) {
2154 return true;
2155 } else {
2156 return get_string('validateerror', 'admin');
2159 } else if ($this->paramtype === PARAM_RAW) {
2160 return true;
2162 } else {
2163 $cleaned = clean_param($data, $this->paramtype);
2164 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2165 return true;
2166 } else {
2167 return get_string('validateerror', 'admin');
2173 * Return an XHTML string for the setting
2174 * @return string Returns an XHTML string
2176 public function output_html($data, $query='') {
2177 $default = $this->get_defaultsetting();
2179 return format_admin_setting($this, $this->visiblename,
2180 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2181 $this->description, true, '', $default, $query);
2186 * Text input with a maximum length constraint.
2188 * @copyright 2015 onwards Ankit Agarwal
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2193 /** @var int maximum number of chars allowed. */
2194 protected $maxlength;
2197 * Config text constructor
2199 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2200 * or 'myplugin/mysetting' for ones in config_plugins.
2201 * @param string $visiblename localised
2202 * @param string $description long localised info
2203 * @param string $defaultsetting
2204 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2205 * @param int $size default field size
2206 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2208 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2209 $size=null, $maxlength = 0) {
2210 $this->maxlength = $maxlength;
2211 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2215 * Validate data before storage
2217 * @param string $data data
2218 * @return mixed true if ok string if error found
2220 public function validate($data) {
2221 $parentvalidation = parent::validate($data);
2222 if ($parentvalidation === true) {
2223 if ($this->maxlength > 0) {
2224 // Max length check.
2225 $length = core_text::strlen($data);
2226 if ($length > $this->maxlength) {
2227 return get_string('maximumchars', 'moodle', $this->maxlength);
2229 return true;
2230 } else {
2231 return true; // No max length check needed.
2233 } else {
2234 return $parentvalidation;
2240 * General text area without html editor.
2242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2244 class admin_setting_configtextarea extends admin_setting_configtext {
2245 private $rows;
2246 private $cols;
2249 * @param string $name
2250 * @param string $visiblename
2251 * @param string $description
2252 * @param mixed $defaultsetting string or array
2253 * @param mixed $paramtype
2254 * @param string $cols The number of columns to make the editor
2255 * @param string $rows The number of rows to make the editor
2257 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2258 $this->rows = $rows;
2259 $this->cols = $cols;
2260 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2264 * Returns an XHTML string for the editor
2266 * @param string $data
2267 * @param string $query
2268 * @return string XHTML string for the editor
2270 public function output_html($data, $query='') {
2271 $default = $this->get_defaultsetting();
2273 $defaultinfo = $default;
2274 if (!is_null($default) and $default !== '') {
2275 $defaultinfo = "\n".$default;
2278 return format_admin_setting($this, $this->visiblename,
2279 '<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>',
2280 $this->description, true, '', $defaultinfo, $query);
2286 * General text area with html editor.
2288 class admin_setting_confightmleditor extends admin_setting_configtext {
2289 private $rows;
2290 private $cols;
2293 * @param string $name
2294 * @param string $visiblename
2295 * @param string $description
2296 * @param mixed $defaultsetting string or array
2297 * @param mixed $paramtype
2299 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2300 $this->rows = $rows;
2301 $this->cols = $cols;
2302 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2303 editors_head_setup();
2307 * Returns an XHTML string for the editor
2309 * @param string $data
2310 * @param string $query
2311 * @return string XHTML string for the editor
2313 public function output_html($data, $query='') {
2314 $default = $this->get_defaultsetting();
2316 $defaultinfo = $default;
2317 if (!is_null($default) and $default !== '') {
2318 $defaultinfo = "\n".$default;
2321 $editor = editors_get_preferred_editor(FORMAT_HTML);
2322 $editor->set_text($data);
2323 $editor->use_editor($this->get_id(), array('noclean'=>true));
2325 return format_admin_setting($this, $this->visiblename,
2326 '<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>',
2327 $this->description, true, '', $defaultinfo, $query);
2333 * Password field, allows unmasking of password
2335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2337 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2339 * Constructor
2340 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2341 * @param string $visiblename localised
2342 * @param string $description long localised info
2343 * @param string $defaultsetting default password
2345 public function __construct($name, $visiblename, $description, $defaultsetting) {
2346 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2350 * Log config changes if necessary.
2351 * @param string $name
2352 * @param string $oldvalue
2353 * @param string $value
2355 protected function add_to_config_log($name, $oldvalue, $value) {
2356 if ($value !== '') {
2357 $value = '********';
2359 if ($oldvalue !== '' and $oldvalue !== null) {
2360 $oldvalue = '********';
2362 parent::add_to_config_log($name, $oldvalue, $value);
2366 * Returns XHTML for the field
2367 * Writes Javascript into the HTML below right before the last div
2369 * @todo Make javascript available through newer methods if possible
2370 * @param string $data Value for the field
2371 * @param string $query Passed as final argument for format_admin_setting
2372 * @return string XHTML field
2374 public function output_html($data, $query='') {
2375 $id = $this->get_id();
2376 $unmask = get_string('unmaskpassword', 'form');
2377 $unmaskjs = '<script type="text/javascript">
2378 //<![CDATA[
2379 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2381 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2383 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2385 var unmaskchb = document.createElement("input");
2386 unmaskchb.setAttribute("type", "checkbox");
2387 unmaskchb.setAttribute("id", "'.$id.'unmask");
2388 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2389 unmaskdiv.appendChild(unmaskchb);
2391 var unmasklbl = document.createElement("label");
2392 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2393 if (is_ie) {
2394 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2395 } else {
2396 unmasklbl.setAttribute("for", "'.$id.'unmask");
2398 unmaskdiv.appendChild(unmasklbl);
2400 if (is_ie) {
2401 // ugly hack to work around the famous onchange IE bug
2402 unmaskchb.onclick = function() {this.blur();};
2403 unmaskdiv.onclick = function() {this.blur();};
2405 //]]>
2406 </script>';
2407 return format_admin_setting($this, $this->visiblename,
2408 '<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>',
2409 $this->description, true, '', NULL, $query);
2414 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2415 * Note: Only advanced makes sense right now - locked does not.
2417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2419 class admin_setting_configempty extends admin_setting_configtext {
2422 * @param string $name
2423 * @param string $visiblename
2424 * @param string $description
2426 public function __construct($name, $visiblename, $description) {
2427 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2431 * Returns an XHTML string for the hidden field
2433 * @param string $data
2434 * @param string $query
2435 * @return string XHTML string for the editor
2437 public function output_html($data, $query='') {
2438 return format_admin_setting($this,
2439 $this->visiblename,
2440 '<div class="form-empty" >' .
2441 '<input type="hidden"' .
2442 ' id="'. $this->get_id() .'"' .
2443 ' name="'. $this->get_full_name() .'"' .
2444 ' value=""/></div>',
2445 $this->description,
2446 true,
2448 get_string('none'),
2449 $query);
2455 * Path to directory
2457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2459 class admin_setting_configfile extends admin_setting_configtext {
2461 * Constructor
2462 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2463 * @param string $visiblename localised
2464 * @param string $description long localised info
2465 * @param string $defaultdirectory default directory location
2467 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2468 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2472 * Returns XHTML for the field
2474 * Returns XHTML for the field and also checks whether the file
2475 * specified in $data exists using file_exists()
2477 * @param string $data File name and path to use in value attr
2478 * @param string $query
2479 * @return string XHTML field
2481 public function output_html($data, $query='') {
2482 global $CFG;
2483 $default = $this->get_defaultsetting();
2485 if ($data) {
2486 if (file_exists($data)) {
2487 $executable = '<span class="pathok">&#x2714;</span>';
2488 } else {
2489 $executable = '<span class="patherror">&#x2718;</span>';
2491 } else {
2492 $executable = '';
2494 $readonly = '';
2495 if (!empty($CFG->preventexecpath)) {
2496 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2497 $readonly = 'readonly="readonly"';
2500 return format_admin_setting($this, $this->visiblename,
2501 '<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>',
2502 $this->description, true, '', $default, $query);
2506 * Checks if execpatch has been disabled in config.php
2508 public function write_setting($data) {
2509 global $CFG;
2510 if (!empty($CFG->preventexecpath)) {
2511 if ($this->get_setting() === null) {
2512 // Use default during installation.
2513 $data = $this->get_defaultsetting();
2514 if ($data === null) {
2515 $data = '';
2517 } else {
2518 return '';
2521 return parent::write_setting($data);
2527 * Path to executable file
2529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 class admin_setting_configexecutable extends admin_setting_configfile {
2534 * Returns an XHTML field
2536 * @param string $data This is the value for the field
2537 * @param string $query
2538 * @return string XHTML field
2540 public function output_html($data, $query='') {
2541 global $CFG;
2542 $default = $this->get_defaultsetting();
2544 if ($data) {
2545 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2546 $executable = '<span class="pathok">&#x2714;</span>';
2547 } else {
2548 $executable = '<span class="patherror">&#x2718;</span>';
2550 } else {
2551 $executable = '';
2553 $readonly = '';
2554 if (!empty($CFG->preventexecpath)) {
2555 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2556 $readonly = 'readonly="readonly"';
2559 return format_admin_setting($this, $this->visiblename,
2560 '<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>',
2561 $this->description, true, '', $default, $query);
2567 * Path to directory
2569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2571 class admin_setting_configdirectory extends admin_setting_configfile {
2574 * Returns an XHTML field
2576 * @param string $data This is the value for the field
2577 * @param string $query
2578 * @return string XHTML
2580 public function output_html($data, $query='') {
2581 global $CFG;
2582 $default = $this->get_defaultsetting();
2584 if ($data) {
2585 if (file_exists($data) and is_dir($data)) {
2586 $executable = '<span class="pathok">&#x2714;</span>';
2587 } else {
2588 $executable = '<span class="patherror">&#x2718;</span>';
2590 } else {
2591 $executable = '';
2593 $readonly = '';
2594 if (!empty($CFG->preventexecpath)) {
2595 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2596 $readonly = 'readonly="readonly"';
2599 return format_admin_setting($this, $this->visiblename,
2600 '<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>',
2601 $this->description, true, '', $default, $query);
2607 * Checkbox
2609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2611 class admin_setting_configcheckbox extends admin_setting {
2612 /** @var string Value used when checked */
2613 public $yes;
2614 /** @var string Value used when not checked */
2615 public $no;
2618 * Constructor
2619 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2620 * @param string $visiblename localised
2621 * @param string $description long localised info
2622 * @param string $defaultsetting
2623 * @param string $yes value used when checked
2624 * @param string $no value used when not checked
2626 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2627 parent::__construct($name, $visiblename, $description, $defaultsetting);
2628 $this->yes = (string)$yes;
2629 $this->no = (string)$no;
2633 * Retrieves the current setting using the objects name
2635 * @return string
2637 public function get_setting() {
2638 return $this->config_read($this->name);
2642 * Sets the value for the setting
2644 * Sets the value for the setting to either the yes or no values
2645 * of the object by comparing $data to yes
2647 * @param mixed $data Gets converted to str for comparison against yes value
2648 * @return string empty string or error
2650 public function write_setting($data) {
2651 if ((string)$data === $this->yes) { // convert to strings before comparison
2652 $data = $this->yes;
2653 } else {
2654 $data = $this->no;
2656 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2660 * Returns an XHTML checkbox field
2662 * @param string $data If $data matches yes then checkbox is checked
2663 * @param string $query
2664 * @return string XHTML field
2666 public function output_html($data, $query='') {
2667 $default = $this->get_defaultsetting();
2669 if (!is_null($default)) {
2670 if ((string)$default === $this->yes) {
2671 $defaultinfo = get_string('checkboxyes', 'admin');
2672 } else {
2673 $defaultinfo = get_string('checkboxno', 'admin');
2675 } else {
2676 $defaultinfo = NULL;
2679 if ((string)$data === $this->yes) { // convert to strings before comparison
2680 $checked = 'checked="checked"';
2681 } else {
2682 $checked = '';
2685 return format_admin_setting($this, $this->visiblename,
2686 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2687 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2688 $this->description, true, '', $defaultinfo, $query);
2694 * Multiple checkboxes, each represents different value, stored in csv format
2696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2698 class admin_setting_configmulticheckbox extends admin_setting {
2699 /** @var array Array of choices value=>label */
2700 public $choices;
2703 * Constructor: uses parent::__construct
2705 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2706 * @param string $visiblename localised
2707 * @param string $description long localised info
2708 * @param array $defaultsetting array of selected
2709 * @param array $choices array of $value=>$label for each checkbox
2711 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2712 $this->choices = $choices;
2713 parent::__construct($name, $visiblename, $description, $defaultsetting);
2717 * This public function may be used in ancestors for lazy loading of choices
2719 * @todo Check if this function is still required content commented out only returns true
2720 * @return bool true if loaded, false if error
2722 public function load_choices() {
2724 if (is_array($this->choices)) {
2725 return true;
2727 .... load choices here
2729 return true;
2733 * Is setting related to query text - used when searching
2735 * @param string $query
2736 * @return bool true on related, false on not or failure
2738 public function is_related($query) {
2739 if (!$this->load_choices() or empty($this->choices)) {
2740 return false;
2742 if (parent::is_related($query)) {
2743 return true;
2746 foreach ($this->choices as $desc) {
2747 if (strpos(core_text::strtolower($desc), $query) !== false) {
2748 return true;
2751 return false;
2755 * Returns the current setting if it is set
2757 * @return mixed null if null, else an array
2759 public function get_setting() {
2760 $result = $this->config_read($this->name);
2762 if (is_null($result)) {
2763 return NULL;
2765 if ($result === '') {
2766 return array();
2768 $enabled = explode(',', $result);
2769 $setting = array();
2770 foreach ($enabled as $option) {
2771 $setting[$option] = 1;
2773 return $setting;
2777 * Saves the setting(s) provided in $data
2779 * @param array $data An array of data, if not array returns empty str
2780 * @return mixed empty string on useless data or bool true=success, false=failed
2782 public function write_setting($data) {
2783 if (!is_array($data)) {
2784 return ''; // ignore it
2786 if (!$this->load_choices() or empty($this->choices)) {
2787 return '';
2789 unset($data['xxxxx']);
2790 $result = array();
2791 foreach ($data as $key => $value) {
2792 if ($value and array_key_exists($key, $this->choices)) {
2793 $result[] = $key;
2796 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2800 * Returns XHTML field(s) as required by choices
2802 * Relies on data being an array should data ever be another valid vartype with
2803 * acceptable value this may cause a warning/error
2804 * if (!is_array($data)) would fix the problem
2806 * @todo Add vartype handling to ensure $data is an array
2808 * @param array $data An array of checked values
2809 * @param string $query
2810 * @return string XHTML field
2812 public function output_html($data, $query='') {
2813 if (!$this->load_choices() or empty($this->choices)) {
2814 return '';
2816 $default = $this->get_defaultsetting();
2817 if (is_null($default)) {
2818 $default = array();
2820 if (is_null($data)) {
2821 $data = array();
2823 $options = array();
2824 $defaults = array();
2825 foreach ($this->choices as $key=>$description) {
2826 if (!empty($data[$key])) {
2827 $checked = 'checked="checked"';
2828 } else {
2829 $checked = '';
2831 if (!empty($default[$key])) {
2832 $defaults[] = $description;
2835 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2836 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2839 if (is_null($default)) {
2840 $defaultinfo = NULL;
2841 } else if (!empty($defaults)) {
2842 $defaultinfo = implode(', ', $defaults);
2843 } else {
2844 $defaultinfo = get_string('none');
2847 $return = '<div class="form-multicheckbox">';
2848 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2849 if ($options) {
2850 $return .= '<ul>';
2851 foreach ($options as $option) {
2852 $return .= '<li>'.$option.'</li>';
2854 $return .= '</ul>';
2856 $return .= '</div>';
2858 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2865 * Multiple checkboxes 2, value stored as string 00101011
2867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2869 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2872 * Returns the setting if set
2874 * @return mixed null if not set, else an array of set settings
2876 public function get_setting() {
2877 $result = $this->config_read($this->name);
2878 if (is_null($result)) {
2879 return NULL;
2881 if (!$this->load_choices()) {
2882 return NULL;
2884 $result = str_pad($result, count($this->choices), '0');
2885 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2886 $setting = array();
2887 foreach ($this->choices as $key=>$unused) {
2888 $value = array_shift($result);
2889 if ($value) {
2890 $setting[$key] = 1;
2893 return $setting;
2897 * Save setting(s) provided in $data param
2899 * @param array $data An array of settings to save
2900 * @return mixed empty string for bad data or bool true=>success, false=>error
2902 public function write_setting($data) {
2903 if (!is_array($data)) {
2904 return ''; // ignore it
2906 if (!$this->load_choices() or empty($this->choices)) {
2907 return '';
2909 $result = '';
2910 foreach ($this->choices as $key=>$unused) {
2911 if (!empty($data[$key])) {
2912 $result .= '1';
2913 } else {
2914 $result .= '0';
2917 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2923 * Select one value from list
2925 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2927 class admin_setting_configselect extends admin_setting {
2928 /** @var array Array of choices value=>label */
2929 public $choices;
2932 * Constructor
2933 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2934 * @param string $visiblename localised
2935 * @param string $description long localised info
2936 * @param string|int $defaultsetting
2937 * @param array $choices array of $value=>$label for each selection
2939 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2940 $this->choices = $choices;
2941 parent::__construct($name, $visiblename, $description, $defaultsetting);
2945 * This function may be used in ancestors for lazy loading of choices
2947 * Override this method if loading of choices is expensive, such
2948 * as when it requires multiple db requests.
2950 * @return bool true if loaded, false if error
2952 public function load_choices() {
2954 if (is_array($this->choices)) {
2955 return true;
2957 .... load choices here
2959 return true;
2963 * Check if this is $query is related to a choice
2965 * @param string $query
2966 * @return bool true if related, false if not
2968 public function is_related($query) {
2969 if (parent::is_related($query)) {
2970 return true;
2972 if (!$this->load_choices()) {
2973 return false;
2975 foreach ($this->choices as $key=>$value) {
2976 if (strpos(core_text::strtolower($key), $query) !== false) {
2977 return true;
2979 if (strpos(core_text::strtolower($value), $query) !== false) {
2980 return true;
2983 return false;
2987 * Return the setting
2989 * @return mixed returns config if successful else null
2991 public function get_setting() {
2992 return $this->config_read($this->name);
2996 * Save a setting
2998 * @param string $data
2999 * @return string empty of error string
3001 public function write_setting($data) {
3002 if (!$this->load_choices() or empty($this->choices)) {
3003 return '';
3005 if (!array_key_exists($data, $this->choices)) {
3006 return ''; // ignore it
3009 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3013 * Returns XHTML select field
3015 * Ensure the options are loaded, and generate the XHTML for the select
3016 * element and any warning message. Separating this out from output_html
3017 * makes it easier to subclass this class.
3019 * @param string $data the option to show as selected.
3020 * @param string $current the currently selected option in the database, null if none.
3021 * @param string $default the default selected option.
3022 * @return array the HTML for the select element, and a warning message.
3024 public function output_select_html($data, $current, $default, $extraname = '') {
3025 if (!$this->load_choices() or empty($this->choices)) {
3026 return array('', '');
3029 $warning = '';
3030 if (is_null($current)) {
3031 // first run
3032 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
3033 // no warning
3034 } else if (!array_key_exists($current, $this->choices)) {
3035 $warning = get_string('warningcurrentsetting', 'admin', s($current));
3036 if (!is_null($default) and $data == $current) {
3037 $data = $default; // use default instead of first value when showing the form
3041 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
3042 foreach ($this->choices as $key => $value) {
3043 // the string cast is needed because key may be integer - 0 is equal to most strings!
3044 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
3046 $selecthtml .= '</select>';
3047 return array($selecthtml, $warning);
3051 * Returns XHTML select field and wrapping div(s)
3053 * @see output_select_html()
3055 * @param string $data the option to show as selected
3056 * @param string $query
3057 * @return string XHTML field and wrapping div
3059 public function output_html($data, $query='') {
3060 $default = $this->get_defaultsetting();
3061 $current = $this->get_setting();
3063 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3064 if (!$selecthtml) {
3065 return '';
3068 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3069 $defaultinfo = $this->choices[$default];
3070 } else {
3071 $defaultinfo = NULL;
3074 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3076 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3082 * Select multiple items from list
3084 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3086 class admin_setting_configmultiselect extends admin_setting_configselect {
3088 * Constructor
3089 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3090 * @param string $visiblename localised
3091 * @param string $description long localised info
3092 * @param array $defaultsetting array of selected items
3093 * @param array $choices array of $value=>$label for each list item
3095 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3096 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3100 * Returns the select setting(s)
3102 * @return mixed null or array. Null if no settings else array of setting(s)
3104 public function get_setting() {
3105 $result = $this->config_read($this->name);
3106 if (is_null($result)) {
3107 return NULL;
3109 if ($result === '') {
3110 return array();
3112 return explode(',', $result);
3116 * Saves setting(s) provided through $data
3118 * Potential bug in the works should anyone call with this function
3119 * using a vartype that is not an array
3121 * @param array $data
3123 public function write_setting($data) {
3124 if (!is_array($data)) {
3125 return ''; //ignore it
3127 if (!$this->load_choices() or empty($this->choices)) {
3128 return '';
3131 unset($data['xxxxx']);
3133 $save = array();
3134 foreach ($data as $value) {
3135 if (!array_key_exists($value, $this->choices)) {
3136 continue; // ignore it
3138 $save[] = $value;
3141 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3145 * Is setting related to query text - used when searching
3147 * @param string $query
3148 * @return bool true if related, false if not
3150 public function is_related($query) {
3151 if (!$this->load_choices() or empty($this->choices)) {
3152 return false;
3154 if (parent::is_related($query)) {
3155 return true;
3158 foreach ($this->choices as $desc) {
3159 if (strpos(core_text::strtolower($desc), $query) !== false) {
3160 return true;
3163 return false;
3167 * Returns XHTML multi-select field
3169 * @todo Add vartype handling to ensure $data is an array
3170 * @param array $data Array of values to select by default
3171 * @param string $query
3172 * @return string XHTML multi-select field
3174 public function output_html($data, $query='') {
3175 if (!$this->load_choices() or empty($this->choices)) {
3176 return '';
3178 $choices = $this->choices;
3179 $default = $this->get_defaultsetting();
3180 if (is_null($default)) {
3181 $default = array();
3183 if (is_null($data)) {
3184 $data = array();
3187 $defaults = array();
3188 $size = min(10, count($this->choices));
3189 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3190 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3191 foreach ($this->choices as $key => $description) {
3192 if (in_array($key, $data)) {
3193 $selected = 'selected="selected"';
3194 } else {
3195 $selected = '';
3197 if (in_array($key, $default)) {
3198 $defaults[] = $description;
3201 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3204 if (is_null($default)) {
3205 $defaultinfo = NULL;
3206 } if (!empty($defaults)) {
3207 $defaultinfo = implode(', ', $defaults);
3208 } else {
3209 $defaultinfo = get_string('none');
3212 $return .= '</select></div>';
3213 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3218 * Time selector
3220 * This is a liiitle bit messy. we're using two selects, but we're returning
3221 * them as an array named after $name (so we only use $name2 internally for the setting)
3223 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3225 class admin_setting_configtime extends admin_setting {
3226 /** @var string Used for setting second select (minutes) */
3227 public $name2;
3230 * Constructor
3231 * @param string $hoursname setting for hours
3232 * @param string $minutesname setting for hours
3233 * @param string $visiblename localised
3234 * @param string $description long localised info
3235 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3237 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3238 $this->name2 = $minutesname;
3239 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3243 * Get the selected time
3245 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3247 public function get_setting() {
3248 $result1 = $this->config_read($this->name);
3249 $result2 = $this->config_read($this->name2);
3250 if (is_null($result1) or is_null($result2)) {
3251 return NULL;
3254 return array('h' => $result1, 'm' => $result2);
3258 * Store the time (hours and minutes)
3260 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3261 * @return bool true if success, false if not
3263 public function write_setting($data) {
3264 if (!is_array($data)) {
3265 return '';
3268 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3269 return ($result ? '' : get_string('errorsetting', 'admin'));
3273 * Returns XHTML time select fields
3275 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3276 * @param string $query
3277 * @return string XHTML time select fields and wrapping div(s)
3279 public function output_html($data, $query='') {
3280 $default = $this->get_defaultsetting();
3282 if (is_array($default)) {
3283 $defaultinfo = $default['h'].':'.$default['m'];
3284 } else {
3285 $defaultinfo = NULL;
3288 $return = '<div class="form-time defaultsnext">';
3289 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3290 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3291 for ($i = 0; $i < 24; $i++) {
3292 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3294 $return .= '</select>:';
3295 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3296 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3297 for ($i = 0; $i < 60; $i += 5) {
3298 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3300 $return .= '</select>';
3301 $return .= '</div>';
3302 return format_admin_setting($this, $this->visiblename, $return, $this->description,
3303 $this->get_id() . 'h', '', $defaultinfo, $query);
3310 * Seconds duration setting.
3312 * @copyright 2012 Petr Skoda (http://skodak.org)
3313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3315 class admin_setting_configduration extends admin_setting {
3317 /** @var int default duration unit */
3318 protected $defaultunit;
3321 * Constructor
3322 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3323 * or 'myplugin/mysetting' for ones in config_plugins.
3324 * @param string $visiblename localised name
3325 * @param string $description localised long description
3326 * @param mixed $defaultsetting string or array depending on implementation
3327 * @param int $defaultunit - day, week, etc. (in seconds)
3329 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3330 if (is_number($defaultsetting)) {
3331 $defaultsetting = self::parse_seconds($defaultsetting);
3333 $units = self::get_units();
3334 if (isset($units[$defaultunit])) {
3335 $this->defaultunit = $defaultunit;
3336 } else {
3337 $this->defaultunit = 86400;
3339 parent::__construct($name, $visiblename, $description, $defaultsetting);
3343 * Returns selectable units.
3344 * @static
3345 * @return array
3347 protected static function get_units() {
3348 return array(
3349 604800 => get_string('weeks'),
3350 86400 => get_string('days'),
3351 3600 => get_string('hours'),
3352 60 => get_string('minutes'),
3353 1 => get_string('seconds'),
3358 * Converts seconds to some more user friendly string.
3359 * @static
3360 * @param int $seconds
3361 * @return string
3363 protected static function get_duration_text($seconds) {
3364 if (empty($seconds)) {
3365 return get_string('none');
3367 $data = self::parse_seconds($seconds);
3368 switch ($data['u']) {
3369 case (60*60*24*7):
3370 return get_string('numweeks', '', $data['v']);
3371 case (60*60*24):
3372 return get_string('numdays', '', $data['v']);
3373 case (60*60):
3374 return get_string('numhours', '', $data['v']);
3375 case (60):
3376 return get_string('numminutes', '', $data['v']);
3377 default:
3378 return get_string('numseconds', '', $data['v']*$data['u']);
3383 * Finds suitable units for given duration.
3384 * @static
3385 * @param int $seconds
3386 * @return array
3388 protected static function parse_seconds($seconds) {
3389 foreach (self::get_units() as $unit => $unused) {
3390 if ($seconds % $unit === 0) {
3391 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3394 return array('v'=>(int)$seconds, 'u'=>1);
3398 * Get the selected duration as array.
3400 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3402 public function get_setting() {
3403 $seconds = $this->config_read($this->name);
3404 if (is_null($seconds)) {
3405 return null;
3408 return self::parse_seconds($seconds);
3412 * Store the duration as seconds.
3414 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3415 * @return bool true if success, false if not
3417 public function write_setting($data) {
3418 if (!is_array($data)) {
3419 return '';
3422 $seconds = (int)($data['v']*$data['u']);
3423 if ($seconds < 0) {
3424 return get_string('errorsetting', 'admin');
3427 $result = $this->config_write($this->name, $seconds);
3428 return ($result ? '' : get_string('errorsetting', 'admin'));
3432 * Returns duration text+select fields.
3434 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3435 * @param string $query
3436 * @return string duration text+select fields and wrapping div(s)
3438 public function output_html($data, $query='') {
3439 $default = $this->get_defaultsetting();
3441 if (is_number($default)) {
3442 $defaultinfo = self::get_duration_text($default);
3443 } else if (is_array($default)) {
3444 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3445 } else {
3446 $defaultinfo = null;
3449 $units = self::get_units();
3451 $inputid = $this->get_id() . 'v';
3453 $return = '<div class="form-duration defaultsnext">';
3454 $return .= '<input type="text" size="5" id="' . $inputid . '" name="' . $this->get_full_name() .
3455 '[v]" value="' . s($data['v']) . '" />';
3456 $return .= '<label for="' . $this->get_id() . 'u" class="accesshide">' .
3457 get_string('durationunits', 'admin') . '</label>';
3458 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3459 foreach ($units as $val => $text) {
3460 $selected = '';
3461 if ($data['v'] == 0) {
3462 if ($val == $this->defaultunit) {
3463 $selected = ' selected="selected"';
3465 } else if ($val == $data['u']) {
3466 $selected = ' selected="selected"';
3468 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3470 $return .= '</select></div>';
3471 return format_admin_setting($this, $this->visiblename, $return, $this->description, $inputid, '', $defaultinfo, $query);
3477 * Seconds duration setting with an advanced checkbox, that controls a additional
3478 * $name.'_adv' setting.
3480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3481 * @copyright 2014 The Open University
3483 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3485 * Constructor
3486 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3487 * or 'myplugin/mysetting' for ones in config_plugins.
3488 * @param string $visiblename localised name
3489 * @param string $description localised long description
3490 * @param array $defaultsetting array of int value, and bool whether it is
3491 * is advanced by default.
3492 * @param int $defaultunit - day, week, etc. (in seconds)
3494 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3495 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3496 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3502 * Used to validate a textarea used for ip addresses
3504 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3505 * @copyright 2011 Petr Skoda (http://skodak.org)
3507 class admin_setting_configiplist extends admin_setting_configtextarea {
3510 * Validate the contents of the textarea as IP addresses
3512 * Used to validate a new line separated list of IP addresses collected from
3513 * a textarea control
3515 * @param string $data A list of IP Addresses separated by new lines
3516 * @return mixed bool true for success or string:error on failure
3518 public function validate($data) {
3519 if(!empty($data)) {
3520 $ips = explode("\n", $data);
3521 } else {
3522 return true;
3524 $result = true;
3525 foreach($ips as $ip) {
3526 $ip = trim($ip);
3527 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3528 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3529 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3530 $result = true;
3531 } else {
3532 $result = false;
3533 break;
3536 if($result) {
3537 return true;
3538 } else {
3539 return get_string('validateerror', 'admin');
3546 * An admin setting for selecting one or more users who have a capability
3547 * in the system context
3549 * An admin setting for selecting one or more users, who have a particular capability
3550 * in the system context. Warning, make sure the list will never be too long. There is
3551 * no paging or searching of this list.
3553 * To correctly get a list of users from this config setting, you need to call the
3554 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3556 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3558 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3559 /** @var string The capabilities name */
3560 protected $capability;
3561 /** @var int include admin users too */
3562 protected $includeadmins;
3565 * Constructor.
3567 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3568 * @param string $visiblename localised name
3569 * @param string $description localised long description
3570 * @param array $defaultsetting array of usernames
3571 * @param string $capability string capability name.
3572 * @param bool $includeadmins include administrators
3574 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3575 $this->capability = $capability;
3576 $this->includeadmins = $includeadmins;
3577 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3581 * Load all of the uses who have the capability into choice array
3583 * @return bool Always returns true
3585 function load_choices() {
3586 if (is_array($this->choices)) {
3587 return true;
3589 list($sort, $sortparams) = users_order_by_sql('u');
3590 if (!empty($sortparams)) {
3591 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3592 'This is unexpected, and a problem because there is no way to pass these ' .
3593 'parameters to get_users_by_capability. See MDL-34657.');
3595 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3596 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3597 $this->choices = array(
3598 '$@NONE@$' => get_string('nobody'),
3599 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3601 if ($this->includeadmins) {
3602 $admins = get_admins();
3603 foreach ($admins as $user) {
3604 $this->choices[$user->id] = fullname($user);
3607 if (is_array($users)) {
3608 foreach ($users as $user) {
3609 $this->choices[$user->id] = fullname($user);
3612 return true;
3616 * Returns the default setting for class
3618 * @return mixed Array, or string. Empty string if no default
3620 public function get_defaultsetting() {
3621 $this->load_choices();
3622 $defaultsetting = parent::get_defaultsetting();
3623 if (empty($defaultsetting)) {
3624 return array('$@NONE@$');
3625 } else if (array_key_exists($defaultsetting, $this->choices)) {
3626 return $defaultsetting;
3627 } else {
3628 return '';
3633 * Returns the current setting
3635 * @return mixed array or string
3637 public function get_setting() {
3638 $result = parent::get_setting();
3639 if ($result === null) {
3640 // this is necessary for settings upgrade
3641 return null;
3643 if (empty($result)) {
3644 $result = array('$@NONE@$');
3646 return $result;
3650 * Save the chosen setting provided as $data
3652 * @param array $data
3653 * @return mixed string or array
3655 public function write_setting($data) {
3656 // If all is selected, remove any explicit options.
3657 if (in_array('$@ALL@$', $data)) {
3658 $data = array('$@ALL@$');
3660 // None never needs to be written to the DB.
3661 if (in_array('$@NONE@$', $data)) {
3662 unset($data[array_search('$@NONE@$', $data)]);
3664 return parent::write_setting($data);
3670 * Special checkbox for calendar - resets SESSION vars.
3672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3674 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3676 * Calls the parent::__construct with default values
3678 * name => calendar_adminseesall
3679 * visiblename => get_string('adminseesall', 'admin')
3680 * description => get_string('helpadminseesall', 'admin')
3681 * defaultsetting => 0
3683 public function __construct() {
3684 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3685 get_string('helpadminseesall', 'admin'), '0');
3689 * Stores the setting passed in $data
3691 * @param mixed gets converted to string for comparison
3692 * @return string empty string or error message
3694 public function write_setting($data) {
3695 global $SESSION;
3696 return parent::write_setting($data);
3701 * Special select for settings that are altered in setup.php and can not be altered on the fly
3703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3705 class admin_setting_special_selectsetup extends admin_setting_configselect {
3707 * Reads the setting directly from the database
3709 * @return mixed
3711 public function get_setting() {
3712 // read directly from db!
3713 return get_config(NULL, $this->name);
3717 * Save the setting passed in $data
3719 * @param string $data The setting to save
3720 * @return string empty or error message
3722 public function write_setting($data) {
3723 global $CFG;
3724 // do not change active CFG setting!
3725 $current = $CFG->{$this->name};
3726 $result = parent::write_setting($data);
3727 $CFG->{$this->name} = $current;
3728 return $result;
3734 * Special select for frontpage - stores data in course table
3736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3738 class admin_setting_sitesetselect extends admin_setting_configselect {
3740 * Returns the site name for the selected site
3742 * @see get_site()
3743 * @return string The site name of the selected site
3745 public function get_setting() {
3746 $site = course_get_format(get_site())->get_course();
3747 return $site->{$this->name};
3751 * Updates the database and save the setting
3753 * @param string data
3754 * @return string empty or error message
3756 public function write_setting($data) {
3757 global $DB, $SITE, $COURSE;
3758 if (!in_array($data, array_keys($this->choices))) {
3759 return get_string('errorsetting', 'admin');
3761 $record = new stdClass();
3762 $record->id = SITEID;
3763 $temp = $this->name;
3764 $record->$temp = $data;
3765 $record->timemodified = time();
3767 course_get_format($SITE)->update_course_format_options($record);
3768 $DB->update_record('course', $record);
3770 // Reset caches.
3771 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3772 if ($SITE->id == $COURSE->id) {
3773 $COURSE = $SITE;
3775 format_base::reset_course_cache($SITE->id);
3777 return '';
3784 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3785 * block to hidden.
3787 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3789 class admin_setting_bloglevel extends admin_setting_configselect {
3791 * Updates the database and save the setting
3793 * @param string data
3794 * @return string empty or error message
3796 public function write_setting($data) {
3797 global $DB, $CFG;
3798 if ($data == 0) {
3799 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3800 foreach ($blogblocks as $block) {
3801 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3803 } else {
3804 // reenable all blocks only when switching from disabled blogs
3805 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3806 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3807 foreach ($blogblocks as $block) {
3808 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3812 return parent::write_setting($data);
3818 * Special select - lists on the frontpage - hacky
3820 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3822 class admin_setting_courselist_frontpage extends admin_setting {
3823 /** @var array Array of choices value=>label */
3824 public $choices;
3827 * Construct override, requires one param
3829 * @param bool $loggedin Is the user logged in
3831 public function __construct($loggedin) {
3832 global $CFG;
3833 require_once($CFG->dirroot.'/course/lib.php');
3834 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3835 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3836 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3837 $defaults = array(FRONTPAGEALLCOURSELIST);
3838 parent::__construct($name, $visiblename, $description, $defaults);
3842 * Loads the choices available
3844 * @return bool always returns true
3846 public function load_choices() {
3847 if (is_array($this->choices)) {
3848 return true;
3850 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3851 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3852 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3853 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3854 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3855 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3856 'none' => get_string('none'));
3857 if ($this->name === 'frontpage') {
3858 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3860 return true;
3864 * Returns the selected settings
3866 * @param mixed array or setting or null
3868 public function get_setting() {
3869 $result = $this->config_read($this->name);
3870 if (is_null($result)) {
3871 return NULL;
3873 if ($result === '') {
3874 return array();
3876 return explode(',', $result);
3880 * Save the selected options
3882 * @param array $data
3883 * @return mixed empty string (data is not an array) or bool true=success false=failure
3885 public function write_setting($data) {
3886 if (!is_array($data)) {
3887 return '';
3889 $this->load_choices();
3890 $save = array();
3891 foreach($data as $datum) {
3892 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3893 continue;
3895 $save[$datum] = $datum; // no duplicates
3897 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3901 * Return XHTML select field and wrapping div
3903 * @todo Add vartype handling to make sure $data is an array
3904 * @param array $data Array of elements to select by default
3905 * @return string XHTML select field and wrapping div
3907 public function output_html($data, $query='') {
3908 $this->load_choices();
3909 $currentsetting = array();
3910 foreach ($data as $key) {
3911 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3912 $currentsetting[] = $key; // already selected first
3916 $return = '<div class="form-group">';
3917 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3918 if (!array_key_exists($i, $currentsetting)) {
3919 $currentsetting[$i] = 'none'; //none
3921 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3922 foreach ($this->choices as $key => $value) {
3923 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3925 $return .= '</select>';
3926 if ($i !== count($this->choices) - 2) {
3927 $return .= '<br />';
3930 $return .= '</div>';
3932 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3938 * Special checkbox for frontpage - stores data in course table
3940 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3942 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3944 * Returns the current sites name
3946 * @return string
3948 public function get_setting() {
3949 $site = course_get_format(get_site())->get_course();
3950 return $site->{$this->name};
3954 * Save the selected setting
3956 * @param string $data The selected site
3957 * @return string empty string or error message
3959 public function write_setting($data) {
3960 global $DB, $SITE, $COURSE;
3961 $record = new stdClass();
3962 $record->id = $SITE->id;
3963 $record->{$this->name} = ($data == '1' ? 1 : 0);
3964 $record->timemodified = time();
3966 course_get_format($SITE)->update_course_format_options($record);
3967 $DB->update_record('course', $record);
3969 // Reset caches.
3970 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3971 if ($SITE->id == $COURSE->id) {
3972 $COURSE = $SITE;
3974 format_base::reset_course_cache($SITE->id);
3976 return '';
3981 * Special text for frontpage - stores data in course table.
3982 * Empty string means not set here. Manual setting is required.
3984 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3986 class admin_setting_sitesettext extends admin_setting_configtext {
3988 * Return the current setting
3990 * @return mixed string or null
3992 public function get_setting() {
3993 $site = course_get_format(get_site())->get_course();
3994 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3998 * Validate the selected data
4000 * @param string $data The selected value to validate
4001 * @return mixed true or message string
4003 public function validate($data) {
4004 global $DB, $SITE;
4005 $cleaned = clean_param($data, PARAM_TEXT);
4006 if ($cleaned === '') {
4007 return get_string('required');
4009 if ($this->name ==='shortname' &&
4010 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
4011 return get_string('shortnametaken', 'error', $data);
4013 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
4014 return true;
4015 } else {
4016 return get_string('validateerror', 'admin');
4021 * Save the selected setting
4023 * @param string $data The selected value
4024 * @return string empty or error message
4026 public function write_setting($data) {
4027 global $DB, $SITE, $COURSE;
4028 $data = trim($data);
4029 $validated = $this->validate($data);
4030 if ($validated !== true) {
4031 return $validated;
4034 $record = new stdClass();
4035 $record->id = $SITE->id;
4036 $record->{$this->name} = $data;
4037 $record->timemodified = time();
4039 course_get_format($SITE)->update_course_format_options($record);
4040 $DB->update_record('course', $record);
4042 // Reset caches.
4043 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4044 if ($SITE->id == $COURSE->id) {
4045 $COURSE = $SITE;
4047 format_base::reset_course_cache($SITE->id);
4049 return '';
4055 * Special text editor for site description.
4057 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4059 class admin_setting_special_frontpagedesc extends admin_setting {
4061 * Calls parent::__construct with specific arguments
4063 public function __construct() {
4064 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
4065 editors_head_setup();
4069 * Return the current setting
4070 * @return string The current setting
4072 public function get_setting() {
4073 $site = course_get_format(get_site())->get_course();
4074 return $site->{$this->name};
4078 * Save the new setting
4080 * @param string $data The new value to save
4081 * @return string empty or error message
4083 public function write_setting($data) {
4084 global $DB, $SITE, $COURSE;
4085 $record = new stdClass();
4086 $record->id = $SITE->id;
4087 $record->{$this->name} = $data;
4088 $record->timemodified = time();
4090 course_get_format($SITE)->update_course_format_options($record);
4091 $DB->update_record('course', $record);
4093 // Reset caches.
4094 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4095 if ($SITE->id == $COURSE->id) {
4096 $COURSE = $SITE;
4098 format_base::reset_course_cache($SITE->id);
4100 return '';
4104 * Returns XHTML for the field plus wrapping div
4106 * @param string $data The current value
4107 * @param string $query
4108 * @return string The XHTML output
4110 public function output_html($data, $query='') {
4111 global $CFG;
4113 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4115 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4121 * Administration interface for emoticon_manager settings.
4123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4125 class admin_setting_emoticons extends admin_setting {
4128 * Calls parent::__construct with specific args
4130 public function __construct() {
4131 global $CFG;
4133 $manager = get_emoticon_manager();
4134 $defaults = $this->prepare_form_data($manager->default_emoticons());
4135 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4139 * Return the current setting(s)
4141 * @return array Current settings array
4143 public function get_setting() {
4144 global $CFG;
4146 $manager = get_emoticon_manager();
4148 $config = $this->config_read($this->name);
4149 if (is_null($config)) {
4150 return null;
4153 $config = $manager->decode_stored_config($config);
4154 if (is_null($config)) {
4155 return null;
4158 return $this->prepare_form_data($config);
4162 * Save selected settings
4164 * @param array $data Array of settings to save
4165 * @return bool
4167 public function write_setting($data) {
4169 $manager = get_emoticon_manager();
4170 $emoticons = $this->process_form_data($data);
4172 if ($emoticons === false) {
4173 return false;
4176 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4177 return ''; // success
4178 } else {
4179 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4184 * Return XHTML field(s) for options
4186 * @param array $data Array of options to set in HTML
4187 * @return string XHTML string for the fields and wrapping div(s)
4189 public function output_html($data, $query='') {
4190 global $OUTPUT;
4192 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4193 $out .= html_writer::start_tag('thead');
4194 $out .= html_writer::start_tag('tr');
4195 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4196 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4197 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4198 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4199 $out .= html_writer::tag('th', '');
4200 $out .= html_writer::end_tag('tr');
4201 $out .= html_writer::end_tag('thead');
4202 $out .= html_writer::start_tag('tbody');
4203 $i = 0;
4204 foreach($data as $field => $value) {
4205 switch ($i) {
4206 case 0:
4207 $out .= html_writer::start_tag('tr');
4208 $current_text = $value;
4209 $current_filename = '';
4210 $current_imagecomponent = '';
4211 $current_altidentifier = '';
4212 $current_altcomponent = '';
4213 case 1:
4214 $current_filename = $value;
4215 case 2:
4216 $current_imagecomponent = $value;
4217 case 3:
4218 $current_altidentifier = $value;
4219 case 4:
4220 $current_altcomponent = $value;
4223 $out .= html_writer::tag('td',
4224 html_writer::empty_tag('input',
4225 array(
4226 'type' => 'text',
4227 'class' => 'form-text',
4228 'name' => $this->get_full_name().'['.$field.']',
4229 'value' => $value,
4231 ), array('class' => 'c'.$i)
4234 if ($i == 4) {
4235 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4236 $alt = get_string($current_altidentifier, $current_altcomponent);
4237 } else {
4238 $alt = $current_text;
4240 if ($current_filename) {
4241 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4242 } else {
4243 $out .= html_writer::tag('td', '');
4245 $out .= html_writer::end_tag('tr');
4246 $i = 0;
4247 } else {
4248 $i++;
4252 $out .= html_writer::end_tag('tbody');
4253 $out .= html_writer::end_tag('table');
4254 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4255 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4257 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4261 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4263 * @see self::process_form_data()
4264 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4265 * @return array of form fields and their values
4267 protected function prepare_form_data(array $emoticons) {
4269 $form = array();
4270 $i = 0;
4271 foreach ($emoticons as $emoticon) {
4272 $form['text'.$i] = $emoticon->text;
4273 $form['imagename'.$i] = $emoticon->imagename;
4274 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4275 $form['altidentifier'.$i] = $emoticon->altidentifier;
4276 $form['altcomponent'.$i] = $emoticon->altcomponent;
4277 $i++;
4279 // add one more blank field set for new object
4280 $form['text'.$i] = '';
4281 $form['imagename'.$i] = '';
4282 $form['imagecomponent'.$i] = '';
4283 $form['altidentifier'.$i] = '';
4284 $form['altcomponent'.$i] = '';
4286 return $form;
4290 * Converts the data from admin settings form into an array of emoticon objects
4292 * @see self::prepare_form_data()
4293 * @param array $data array of admin form fields and values
4294 * @return false|array of emoticon objects
4296 protected function process_form_data(array $form) {
4298 $count = count($form); // number of form field values
4300 if ($count % 5) {
4301 // we must get five fields per emoticon object
4302 return false;
4305 $emoticons = array();
4306 for ($i = 0; $i < $count / 5; $i++) {
4307 $emoticon = new stdClass();
4308 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4309 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4310 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4311 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4312 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4314 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4315 // prevent from breaking http://url.addresses by accident
4316 $emoticon->text = '';
4319 if (strlen($emoticon->text) < 2) {
4320 // do not allow single character emoticons
4321 $emoticon->text = '';
4324 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4325 // emoticon text must contain some non-alphanumeric character to prevent
4326 // breaking HTML tags
4327 $emoticon->text = '';
4330 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4331 $emoticons[] = $emoticon;
4334 return $emoticons;
4340 * Special setting for limiting of the list of available languages.
4342 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4344 class admin_setting_langlist extends admin_setting_configtext {
4346 * Calls parent::__construct with specific arguments
4348 public function __construct() {
4349 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4353 * Save the new setting
4355 * @param string $data The new setting
4356 * @return bool
4358 public function write_setting($data) {
4359 $return = parent::write_setting($data);
4360 get_string_manager()->reset_caches();
4361 return $return;
4367 * Selection of one of the recognised countries using the list
4368 * returned by {@link get_list_of_countries()}.
4370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4372 class admin_settings_country_select extends admin_setting_configselect {
4373 protected $includeall;
4374 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4375 $this->includeall = $includeall;
4376 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4380 * Lazy-load the available choices for the select box
4382 public function load_choices() {
4383 global $CFG;
4384 if (is_array($this->choices)) {
4385 return true;
4387 $this->choices = array_merge(
4388 array('0' => get_string('choosedots')),
4389 get_string_manager()->get_list_of_countries($this->includeall));
4390 return true;
4396 * admin_setting_configselect for the default number of sections in a course,
4397 * simply so we can lazy-load the choices.
4399 * @copyright 2011 The Open University
4400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4402 class admin_settings_num_course_sections extends admin_setting_configselect {
4403 public function __construct($name, $visiblename, $description, $defaultsetting) {
4404 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4407 /** Lazy-load the available choices for the select box */
4408 public function load_choices() {
4409 $max = get_config('moodlecourse', 'maxsections');
4410 if (!isset($max) || !is_numeric($max)) {
4411 $max = 52;
4413 for ($i = 0; $i <= $max; $i++) {
4414 $this->choices[$i] = "$i";
4416 return true;
4422 * Course category selection
4424 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4426 class admin_settings_coursecat_select extends admin_setting_configselect {
4428 * Calls parent::__construct with specific arguments
4430 public function __construct($name, $visiblename, $description, $defaultsetting) {
4431 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4435 * Load the available choices for the select box
4437 * @return bool
4439 public function load_choices() {
4440 global $CFG;
4441 require_once($CFG->dirroot.'/course/lib.php');
4442 if (is_array($this->choices)) {
4443 return true;
4445 $this->choices = make_categories_options();
4446 return true;
4452 * Special control for selecting days to backup
4454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4456 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4458 * Calls parent::__construct with specific arguments
4460 public function __construct() {
4461 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4462 $this->plugin = 'backup';
4466 * Load the available choices for the select box
4468 * @return bool Always returns true
4470 public function load_choices() {
4471 if (is_array($this->choices)) {
4472 return true;
4474 $this->choices = array();
4475 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4476 foreach ($days as $day) {
4477 $this->choices[$day] = get_string($day, 'calendar');
4479 return true;
4484 * Special setting for backup auto destination.
4486 * @package core
4487 * @subpackage admin
4488 * @copyright 2014 Frédéric Massart - FMCorz.net
4489 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4491 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4494 * Calls parent::__construct with specific arguments.
4496 public function __construct() {
4497 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4501 * Check if the directory must be set, depending on backup/backup_auto_storage.
4503 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4504 * there will be conflicts if this validation happens before the other one.
4506 * @param string $data Form data.
4507 * @return string Empty when no errors.
4509 public function write_setting($data) {
4510 $storage = (int) get_config('backup', 'backup_auto_storage');
4511 if ($storage !== 0) {
4512 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4513 // The directory must exist and be writable.
4514 return get_string('backuperrorinvaliddestination');
4517 return parent::write_setting($data);
4523 * Special debug setting
4525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4527 class admin_setting_special_debug extends admin_setting_configselect {
4529 * Calls parent::__construct with specific arguments
4531 public function __construct() {
4532 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4536 * Load the available choices for the select box
4538 * @return bool
4540 public function load_choices() {
4541 if (is_array($this->choices)) {
4542 return true;
4544 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4545 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4546 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4547 DEBUG_ALL => get_string('debugall', 'admin'),
4548 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4549 return true;
4555 * Special admin control
4557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4559 class admin_setting_special_calendar_weekend extends admin_setting {
4561 * Calls parent::__construct with specific arguments
4563 public function __construct() {
4564 $name = 'calendar_weekend';
4565 $visiblename = get_string('calendar_weekend', 'admin');
4566 $description = get_string('helpweekenddays', 'admin');
4567 $default = array ('0', '6'); // Saturdays and Sundays
4568 parent::__construct($name, $visiblename, $description, $default);
4572 * Gets the current settings as an array
4574 * @return mixed Null if none, else array of settings
4576 public function get_setting() {
4577 $result = $this->config_read($this->name);
4578 if (is_null($result)) {
4579 return NULL;
4581 if ($result === '') {
4582 return array();
4584 $settings = array();
4585 for ($i=0; $i<7; $i++) {
4586 if ($result & (1 << $i)) {
4587 $settings[] = $i;
4590 return $settings;
4594 * Save the new settings
4596 * @param array $data Array of new settings
4597 * @return bool
4599 public function write_setting($data) {
4600 if (!is_array($data)) {
4601 return '';
4603 unset($data['xxxxx']);
4604 $result = 0;
4605 foreach($data as $index) {
4606 $result |= 1 << $index;
4608 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4612 * Return XHTML to display the control
4614 * @param array $data array of selected days
4615 * @param string $query
4616 * @return string XHTML for display (field + wrapping div(s)
4618 public function output_html($data, $query='') {
4619 // The order matters very much because of the implied numeric keys
4620 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4621 $return = '<table><thead><tr>';
4622 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4623 foreach($days as $index => $day) {
4624 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4626 $return .= '</tr></thead><tbody><tr>';
4627 foreach($days as $index => $day) {
4628 $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>';
4630 $return .= '</tr></tbody></table>';
4632 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4639 * Admin setting that allows a user to pick a behaviour.
4641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4643 class admin_setting_question_behaviour extends admin_setting_configselect {
4645 * @param string $name name of config variable
4646 * @param string $visiblename display name
4647 * @param string $description description
4648 * @param string $default default.
4650 public function __construct($name, $visiblename, $description, $default) {
4651 parent::__construct($name, $visiblename, $description, $default, NULL);
4655 * Load list of behaviours as choices
4656 * @return bool true => success, false => error.
4658 public function load_choices() {
4659 global $CFG;
4660 require_once($CFG->dirroot . '/question/engine/lib.php');
4661 $this->choices = question_engine::get_behaviour_options('');
4662 return true;
4668 * Admin setting that allows a user to pick appropriate roles for something.
4670 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4672 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4673 /** @var array Array of capabilities which identify roles */
4674 private $types;
4677 * @param string $name Name of config variable
4678 * @param string $visiblename Display name
4679 * @param string $description Description
4680 * @param array $types Array of archetypes which identify
4681 * roles that will be enabled by default.
4683 public function __construct($name, $visiblename, $description, $types) {
4684 parent::__construct($name, $visiblename, $description, NULL, NULL);
4685 $this->types = $types;
4689 * Load roles as choices
4691 * @return bool true=>success, false=>error
4693 public function load_choices() {
4694 global $CFG, $DB;
4695 if (during_initial_install()) {
4696 return false;
4698 if (is_array($this->choices)) {
4699 return true;
4701 if ($roles = get_all_roles()) {
4702 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4703 return true;
4704 } else {
4705 return false;
4710 * Return the default setting for this control
4712 * @return array Array of default settings
4714 public function get_defaultsetting() {
4715 global $CFG;
4717 if (during_initial_install()) {
4718 return null;
4720 $result = array();
4721 foreach($this->types as $archetype) {
4722 if ($caproles = get_archetype_roles($archetype)) {
4723 foreach ($caproles as $caprole) {
4724 $result[$caprole->id] = 1;
4728 return $result;
4734 * Admin setting that is a list of installed filter plugins.
4736 * @copyright 2015 The Open University
4737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4739 class admin_setting_pickfilters extends admin_setting_configmulticheckbox {
4742 * Constructor
4744 * @param string $name unique ascii name, either 'mysetting' for settings
4745 * that in config, or 'myplugin/mysetting' for ones in config_plugins.
4746 * @param string $visiblename localised name
4747 * @param string $description localised long description
4748 * @param array $default the default. E.g. array('urltolink' => 1, 'emoticons' => 1)
4750 public function __construct($name, $visiblename, $description, $default) {
4751 if (empty($default)) {
4752 $default = array();
4754 $this->load_choices();
4755 foreach ($default as $plugin) {
4756 if (!isset($this->choices[$plugin])) {
4757 unset($default[$plugin]);
4760 parent::__construct($name, $visiblename, $description, $default, null);
4763 public function load_choices() {
4764 if (is_array($this->choices)) {
4765 return true;
4767 $this->choices = array();
4769 foreach (core_component::get_plugin_list('filter') as $plugin => $unused) {
4770 $this->choices[$plugin] = filter_get_name($plugin);
4772 return true;
4778 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4780 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4782 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4784 * Constructor
4785 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4786 * @param string $visiblename localised
4787 * @param string $description long localised info
4788 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4789 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4790 * @param int $size default field size
4792 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4793 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4794 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4800 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4802 * @copyright 2009 Petr Skoda (http://skodak.org)
4803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4805 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4808 * Constructor
4809 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4810 * @param string $visiblename localised
4811 * @param string $description long localised info
4812 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4813 * @param string $yes value used when checked
4814 * @param string $no value used when not checked
4816 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4817 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4818 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4825 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4827 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4829 * @copyright 2010 Sam Hemelryk
4830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4832 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4834 * Constructor
4835 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4836 * @param string $visiblename localised
4837 * @param string $description long localised info
4838 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4839 * @param string $yes value used when checked
4840 * @param string $no value used when not checked
4842 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4843 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4844 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4851 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4855 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4857 * Calls parent::__construct with specific arguments
4859 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4860 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4861 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4868 * Graded roles in gradebook
4870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4872 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4874 * Calls parent::__construct with specific arguments
4876 public function __construct() {
4877 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4878 get_string('configgradebookroles', 'admin'),
4879 array('student'));
4886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4888 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4890 * Saves the new settings passed in $data
4892 * @param string $data
4893 * @return mixed string or Array
4895 public function write_setting($data) {
4896 global $CFG, $DB;
4898 $oldvalue = $this->config_read($this->name);
4899 $return = parent::write_setting($data);
4900 $newvalue = $this->config_read($this->name);
4902 if ($oldvalue !== $newvalue) {
4903 // force full regrading
4904 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4907 return $return;
4913 * Which roles to show on course description page
4915 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4917 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4919 * Calls parent::__construct with specific arguments
4921 public function __construct() {
4922 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4923 get_string('coursecontact_desc', 'admin'),
4924 array('editingteacher'));
4925 $this->set_updatedcallback(create_function('',
4926 "cache::make('core', 'coursecontacts')->purge();"));
4933 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4935 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4937 * Calls parent::__construct with specific arguments
4939 public function __construct() {
4940 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4941 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4945 * Old syntax of class constructor. Deprecated in PHP7.
4947 public function admin_setting_special_gradelimiting() {
4948 self::__construct();
4952 * Force site regrading
4954 function regrade_all() {
4955 global $CFG;
4956 require_once("$CFG->libdir/gradelib.php");
4957 grade_force_site_regrading();
4961 * Saves the new settings
4963 * @param mixed $data
4964 * @return string empty string or error message
4966 function write_setting($data) {
4967 $previous = $this->get_setting();
4969 if ($previous === null) {
4970 if ($data) {
4971 $this->regrade_all();
4973 } else {
4974 if ($data != $previous) {
4975 $this->regrade_all();
4978 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4984 * Special setting for $CFG->grade_minmaxtouse.
4986 * @package core
4987 * @copyright 2015 Frédéric Massart - FMCorz.net
4988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4990 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
4993 * Constructor.
4995 public function __construct() {
4996 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
4997 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
4998 array(
4999 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
5000 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
5006 * Saves the new setting.
5008 * @param mixed $data
5009 * @return string empty string or error message
5011 function write_setting($data) {
5012 global $CFG;
5014 $previous = $this->get_setting();
5015 $result = parent::write_setting($data);
5017 // If saved and the value has changed.
5018 if (empty($result) && $previous != $data) {
5019 require_once($CFG->libdir . '/gradelib.php');
5020 grade_force_site_regrading();
5023 return $result;
5030 * Primary grade export plugin - has state tracking.
5032 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5034 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
5036 * Calls parent::__construct with specific arguments
5038 public function __construct() {
5039 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
5040 get_string('configgradeexport', 'admin'), array(), NULL);
5044 * Load the available choices for the multicheckbox
5046 * @return bool always returns true
5048 public function load_choices() {
5049 if (is_array($this->choices)) {
5050 return true;
5052 $this->choices = array();
5054 if ($plugins = core_component::get_plugin_list('gradeexport')) {
5055 foreach($plugins as $plugin => $unused) {
5056 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
5059 return true;
5065 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
5067 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5069 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
5071 * Config gradepointmax constructor
5073 * @param string $name Overidden by "gradepointmax"
5074 * @param string $visiblename Overridden by "gradepointmax" language string.
5075 * @param string $description Overridden by "gradepointmax_help" language string.
5076 * @param string $defaultsetting Not used, overridden by 100.
5077 * @param mixed $paramtype Overridden by PARAM_INT.
5078 * @param int $size Overridden by 5.
5080 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5081 $name = 'gradepointdefault';
5082 $visiblename = get_string('gradepointdefault', 'grades');
5083 $description = get_string('gradepointdefault_help', 'grades');
5084 $defaultsetting = 100;
5085 $paramtype = PARAM_INT;
5086 $size = 5;
5087 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5091 * Validate data before storage
5092 * @param string $data The submitted data
5093 * @return bool|string true if ok, string if error found
5095 public function validate($data) {
5096 global $CFG;
5097 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
5098 return true;
5099 } else {
5100 return get_string('gradepointdefault_validateerror', 'grades');
5107 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
5109 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5111 class admin_setting_special_gradepointmax extends admin_setting_configtext {
5114 * Config gradepointmax constructor
5116 * @param string $name Overidden by "gradepointmax"
5117 * @param string $visiblename Overridden by "gradepointmax" language string.
5118 * @param string $description Overridden by "gradepointmax_help" language string.
5119 * @param string $defaultsetting Not used, overridden by 100.
5120 * @param mixed $paramtype Overridden by PARAM_INT.
5121 * @param int $size Overridden by 5.
5123 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5124 $name = 'gradepointmax';
5125 $visiblename = get_string('gradepointmax', 'grades');
5126 $description = get_string('gradepointmax_help', 'grades');
5127 $defaultsetting = 100;
5128 $paramtype = PARAM_INT;
5129 $size = 5;
5130 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5134 * Save the selected setting
5136 * @param string $data The selected site
5137 * @return string empty string or error message
5139 public function write_setting($data) {
5140 if ($data === '') {
5141 $data = (int)$this->defaultsetting;
5142 } else {
5143 $data = $data;
5145 return parent::write_setting($data);
5149 * Validate data before storage
5150 * @param string $data The submitted data
5151 * @return bool|string true if ok, string if error found
5153 public function validate($data) {
5154 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5155 return true;
5156 } else {
5157 return get_string('gradepointmax_validateerror', 'grades');
5162 * Return an XHTML string for the setting
5163 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5164 * @param string $query search query to be highlighted
5165 * @return string XHTML to display control
5167 public function output_html($data, $query = '') {
5168 $default = $this->get_defaultsetting();
5170 $attr = array(
5171 'type' => 'text',
5172 'size' => $this->size,
5173 'id' => $this->get_id(),
5174 'name' => $this->get_full_name(),
5175 'value' => s($data),
5176 'maxlength' => '5'
5178 $input = html_writer::empty_tag('input', $attr);
5180 $attr = array('class' => 'form-text defaultsnext');
5181 $div = html_writer::tag('div', $input, $attr);
5182 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
5188 * Grade category settings
5190 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5192 class admin_setting_gradecat_combo extends admin_setting {
5193 /** @var array Array of choices */
5194 public $choices;
5197 * Sets choices and calls parent::__construct with passed arguments
5198 * @param string $name
5199 * @param string $visiblename
5200 * @param string $description
5201 * @param mixed $defaultsetting string or array depending on implementation
5202 * @param array $choices An array of choices for the control
5204 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5205 $this->choices = $choices;
5206 parent::__construct($name, $visiblename, $description, $defaultsetting);
5210 * Return the current setting(s) array
5212 * @return array Array of value=>xx, forced=>xx, adv=>xx
5214 public function get_setting() {
5215 global $CFG;
5217 $value = $this->config_read($this->name);
5218 $flag = $this->config_read($this->name.'_flag');
5220 if (is_null($value) or is_null($flag)) {
5221 return NULL;
5224 $flag = (int)$flag;
5225 $forced = (boolean)(1 & $flag); // first bit
5226 $adv = (boolean)(2 & $flag); // second bit
5228 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5232 * Save the new settings passed in $data
5234 * @todo Add vartype handling to ensure $data is array
5235 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5236 * @return string empty or error message
5238 public function write_setting($data) {
5239 global $CFG;
5241 $value = $data['value'];
5242 $forced = empty($data['forced']) ? 0 : 1;
5243 $adv = empty($data['adv']) ? 0 : 2;
5244 $flag = ($forced | $adv); //bitwise or
5246 if (!in_array($value, array_keys($this->choices))) {
5247 return 'Error setting ';
5250 $oldvalue = $this->config_read($this->name);
5251 $oldflag = (int)$this->config_read($this->name.'_flag');
5252 $oldforced = (1 & $oldflag); // first bit
5254 $result1 = $this->config_write($this->name, $value);
5255 $result2 = $this->config_write($this->name.'_flag', $flag);
5257 // force regrade if needed
5258 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5259 require_once($CFG->libdir.'/gradelib.php');
5260 grade_category::updated_forced_settings();
5263 if ($result1 and $result2) {
5264 return '';
5265 } else {
5266 return get_string('errorsetting', 'admin');
5271 * Return XHTML to display the field and wrapping div
5273 * @todo Add vartype handling to ensure $data is array
5274 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5275 * @param string $query
5276 * @return string XHTML to display control
5278 public function output_html($data, $query='') {
5279 $value = $data['value'];
5280 $forced = !empty($data['forced']);
5281 $adv = !empty($data['adv']);
5283 $default = $this->get_defaultsetting();
5284 if (!is_null($default)) {
5285 $defaultinfo = array();
5286 if (isset($this->choices[$default['value']])) {
5287 $defaultinfo[] = $this->choices[$default['value']];
5289 if (!empty($default['forced'])) {
5290 $defaultinfo[] = get_string('force');
5292 if (!empty($default['adv'])) {
5293 $defaultinfo[] = get_string('advanced');
5295 $defaultinfo = implode(', ', $defaultinfo);
5297 } else {
5298 $defaultinfo = NULL;
5302 $return = '<div class="form-group">';
5303 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5304 foreach ($this->choices as $key => $val) {
5305 // the string cast is needed because key may be integer - 0 is equal to most strings!
5306 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5308 $return .= '</select>';
5309 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5310 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5311 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5312 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5313 $return .= '</div>';
5315 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5321 * Selection of grade report in user profiles
5323 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5325 class admin_setting_grade_profilereport extends admin_setting_configselect {
5327 * Calls parent::__construct with specific arguments
5329 public function __construct() {
5330 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5334 * Loads an array of choices for the configselect control
5336 * @return bool always return true
5338 public function load_choices() {
5339 if (is_array($this->choices)) {
5340 return true;
5342 $this->choices = array();
5344 global $CFG;
5345 require_once($CFG->libdir.'/gradelib.php');
5347 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5348 if (file_exists($plugindir.'/lib.php')) {
5349 require_once($plugindir.'/lib.php');
5350 $functionname = 'grade_report_'.$plugin.'_profilereport';
5351 if (function_exists($functionname)) {
5352 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5356 return true;
5361 * Provides a selection of grade reports to be used for "grades".
5363 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5364 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5366 class admin_setting_my_grades_report extends admin_setting_configselect {
5369 * Calls parent::__construct with specific arguments.
5371 public function __construct() {
5372 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5373 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5377 * Loads an array of choices for the configselect control.
5379 * @return bool always returns true.
5381 public function load_choices() {
5382 global $CFG; // Remove this line and behold the horror of behat test failures!
5383 $this->choices = array();
5384 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5385 if (file_exists($plugindir . '/lib.php')) {
5386 require_once($plugindir . '/lib.php');
5387 // Check to see if the class exists. Check the correct plugin convention first.
5388 if (class_exists('gradereport_' . $plugin)) {
5389 $classname = 'gradereport_' . $plugin;
5390 } else if (class_exists('grade_report_' . $plugin)) {
5391 // We are using the old plugin naming convention.
5392 $classname = 'grade_report_' . $plugin;
5393 } else {
5394 continue;
5396 if ($classname::supports_mygrades()) {
5397 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5401 // Add an option to specify an external url.
5402 $this->choices['external'] = get_string('externalurl', 'grades');
5403 return true;
5408 * Special class for register auth selection
5410 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5412 class admin_setting_special_registerauth extends admin_setting_configselect {
5414 * Calls parent::__construct with specific arguments
5416 public function __construct() {
5417 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5421 * Returns the default option
5423 * @return string empty or default option
5425 public function get_defaultsetting() {
5426 $this->load_choices();
5427 $defaultsetting = parent::get_defaultsetting();
5428 if (array_key_exists($defaultsetting, $this->choices)) {
5429 return $defaultsetting;
5430 } else {
5431 return '';
5436 * Loads the possible choices for the array
5438 * @return bool always returns true
5440 public function load_choices() {
5441 global $CFG;
5443 if (is_array($this->choices)) {
5444 return true;
5446 $this->choices = array();
5447 $this->choices[''] = get_string('disable');
5449 $authsenabled = get_enabled_auth_plugins(true);
5451 foreach ($authsenabled as $auth) {
5452 $authplugin = get_auth_plugin($auth);
5453 if (!$authplugin->can_signup()) {
5454 continue;
5456 // Get the auth title (from core or own auth lang files)
5457 $authtitle = $authplugin->get_title();
5458 $this->choices[$auth] = $authtitle;
5460 return true;
5466 * General plugins manager
5468 class admin_page_pluginsoverview extends admin_externalpage {
5471 * Sets basic information about the external page
5473 public function __construct() {
5474 global $CFG;
5475 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5476 "$CFG->wwwroot/$CFG->admin/plugins.php");
5481 * Module manage page
5483 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5485 class admin_page_managemods extends admin_externalpage {
5487 * Calls parent::__construct with specific arguments
5489 public function __construct() {
5490 global $CFG;
5491 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5495 * Try to find the specified module
5497 * @param string $query The module to search for
5498 * @return array
5500 public function search($query) {
5501 global $CFG, $DB;
5502 if ($result = parent::search($query)) {
5503 return $result;
5506 $found = false;
5507 if ($modules = $DB->get_records('modules')) {
5508 foreach ($modules as $module) {
5509 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5510 continue;
5512 if (strpos($module->name, $query) !== false) {
5513 $found = true;
5514 break;
5516 $strmodulename = get_string('modulename', $module->name);
5517 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5518 $found = true;
5519 break;
5523 if ($found) {
5524 $result = new stdClass();
5525 $result->page = $this;
5526 $result->settings = array();
5527 return array($this->name => $result);
5528 } else {
5529 return array();
5536 * Special class for enrol plugins management.
5538 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5539 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5541 class admin_setting_manageenrols extends admin_setting {
5543 * Calls parent::__construct with specific arguments
5545 public function __construct() {
5546 $this->nosave = true;
5547 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5551 * Always returns true, does nothing
5553 * @return true
5555 public function get_setting() {
5556 return true;
5560 * Always returns true, does nothing
5562 * @return true
5564 public function get_defaultsetting() {
5565 return true;
5569 * Always returns '', does not write anything
5571 * @return string Always returns ''
5573 public function write_setting($data) {
5574 // do not write any setting
5575 return '';
5579 * Checks if $query is one of the available enrol plugins
5581 * @param string $query The string to search for
5582 * @return bool Returns true if found, false if not
5584 public function is_related($query) {
5585 if (parent::is_related($query)) {
5586 return true;
5589 $query = core_text::strtolower($query);
5590 $enrols = enrol_get_plugins(false);
5591 foreach ($enrols as $name=>$enrol) {
5592 $localised = get_string('pluginname', 'enrol_'.$name);
5593 if (strpos(core_text::strtolower($name), $query) !== false) {
5594 return true;
5596 if (strpos(core_text::strtolower($localised), $query) !== false) {
5597 return true;
5600 return false;
5604 * Builds the XHTML to display the control
5606 * @param string $data Unused
5607 * @param string $query
5608 * @return string
5610 public function output_html($data, $query='') {
5611 global $CFG, $OUTPUT, $DB, $PAGE;
5613 // Display strings.
5614 $strup = get_string('up');
5615 $strdown = get_string('down');
5616 $strsettings = get_string('settings');
5617 $strenable = get_string('enable');
5618 $strdisable = get_string('disable');
5619 $struninstall = get_string('uninstallplugin', 'core_admin');
5620 $strusage = get_string('enrolusage', 'enrol');
5621 $strversion = get_string('version');
5622 $strtest = get_string('testsettings', 'core_enrol');
5624 $pluginmanager = core_plugin_manager::instance();
5626 $enrols_available = enrol_get_plugins(false);
5627 $active_enrols = enrol_get_plugins(true);
5629 $allenrols = array();
5630 foreach ($active_enrols as $key=>$enrol) {
5631 $allenrols[$key] = true;
5633 foreach ($enrols_available as $key=>$enrol) {
5634 $allenrols[$key] = true;
5636 // Now find all borked plugins and at least allow then to uninstall.
5637 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5638 foreach ($condidates as $candidate) {
5639 if (empty($allenrols[$candidate])) {
5640 $allenrols[$candidate] = true;
5644 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5645 $return .= $OUTPUT->box_start('generalbox enrolsui');
5647 $table = new html_table();
5648 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5649 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5650 $table->id = 'courseenrolmentplugins';
5651 $table->attributes['class'] = 'admintable generaltable';
5652 $table->data = array();
5654 // Iterate through enrol plugins and add to the display table.
5655 $updowncount = 1;
5656 $enrolcount = count($active_enrols);
5657 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5658 $printed = array();
5659 foreach($allenrols as $enrol => $unused) {
5660 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5661 $version = get_config('enrol_'.$enrol, 'version');
5662 if ($version === false) {
5663 $version = '';
5666 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5667 $name = get_string('pluginname', 'enrol_'.$enrol);
5668 } else {
5669 $name = $enrol;
5671 // Usage.
5672 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5673 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5674 $usage = "$ci / $cp";
5676 // Hide/show links.
5677 $class = '';
5678 if (isset($active_enrols[$enrol])) {
5679 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5680 $hideshow = "<a href=\"$aurl\">";
5681 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5682 $enabled = true;
5683 $displayname = $name;
5684 } else if (isset($enrols_available[$enrol])) {
5685 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5686 $hideshow = "<a href=\"$aurl\">";
5687 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5688 $enabled = false;
5689 $displayname = $name;
5690 $class = 'dimmed_text';
5691 } else {
5692 $hideshow = '';
5693 $enabled = false;
5694 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5696 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5697 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5698 } else {
5699 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5702 // Up/down link (only if enrol is enabled).
5703 $updown = '';
5704 if ($enabled) {
5705 if ($updowncount > 1) {
5706 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5707 $updown .= "<a href=\"$aurl\">";
5708 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5709 } else {
5710 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5712 if ($updowncount < $enrolcount) {
5713 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5714 $updown .= "<a href=\"$aurl\">";
5715 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5716 } else {
5717 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5719 ++$updowncount;
5722 // Add settings link.
5723 if (!$version) {
5724 $settings = '';
5725 } else if ($surl = $plugininfo->get_settings_url()) {
5726 $settings = html_writer::link($surl, $strsettings);
5727 } else {
5728 $settings = '';
5731 // Add uninstall info.
5732 $uninstall = '';
5733 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5734 $uninstall = html_writer::link($uninstallurl, $struninstall);
5737 $test = '';
5738 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5739 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5740 $test = html_writer::link($testsettingsurl, $strtest);
5743 // Add a row to the table.
5744 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5745 if ($class) {
5746 $row->attributes['class'] = $class;
5748 $table->data[] = $row;
5750 $printed[$enrol] = true;
5753 $return .= html_writer::table($table);
5754 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5755 $return .= $OUTPUT->box_end();
5756 return highlight($query, $return);
5762 * Blocks manage page
5764 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5766 class admin_page_manageblocks extends admin_externalpage {
5768 * Calls parent::__construct with specific arguments
5770 public function __construct() {
5771 global $CFG;
5772 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5776 * Search for a specific block
5778 * @param string $query The string to search for
5779 * @return array
5781 public function search($query) {
5782 global $CFG, $DB;
5783 if ($result = parent::search($query)) {
5784 return $result;
5787 $found = false;
5788 if ($blocks = $DB->get_records('block')) {
5789 foreach ($blocks as $block) {
5790 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5791 continue;
5793 if (strpos($block->name, $query) !== false) {
5794 $found = true;
5795 break;
5797 $strblockname = get_string('pluginname', 'block_'.$block->name);
5798 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5799 $found = true;
5800 break;
5804 if ($found) {
5805 $result = new stdClass();
5806 $result->page = $this;
5807 $result->settings = array();
5808 return array($this->name => $result);
5809 } else {
5810 return array();
5816 * Message outputs configuration
5818 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5820 class admin_page_managemessageoutputs extends admin_externalpage {
5822 * Calls parent::__construct with specific arguments
5824 public function __construct() {
5825 global $CFG;
5826 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5830 * Search for a specific message processor
5832 * @param string $query The string to search for
5833 * @return array
5835 public function search($query) {
5836 global $CFG, $DB;
5837 if ($result = parent::search($query)) {
5838 return $result;
5841 $found = false;
5842 if ($processors = get_message_processors()) {
5843 foreach ($processors as $processor) {
5844 if (!$processor->available) {
5845 continue;
5847 if (strpos($processor->name, $query) !== false) {
5848 $found = true;
5849 break;
5851 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5852 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5853 $found = true;
5854 break;
5858 if ($found) {
5859 $result = new stdClass();
5860 $result->page = $this;
5861 $result->settings = array();
5862 return array($this->name => $result);
5863 } else {
5864 return array();
5870 * Default message outputs configuration
5872 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5874 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5876 * Calls parent::__construct with specific arguments
5878 public function __construct() {
5879 global $CFG;
5880 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5886 * Manage question behaviours page
5888 * @copyright 2011 The Open University
5889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5891 class admin_page_manageqbehaviours extends admin_externalpage {
5893 * Constructor
5895 public function __construct() {
5896 global $CFG;
5897 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5898 new moodle_url('/admin/qbehaviours.php'));
5902 * Search question behaviours for the specified string
5904 * @param string $query The string to search for in question behaviours
5905 * @return array
5907 public function search($query) {
5908 global $CFG;
5909 if ($result = parent::search($query)) {
5910 return $result;
5913 $found = false;
5914 require_once($CFG->dirroot . '/question/engine/lib.php');
5915 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5916 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5917 $query) !== false) {
5918 $found = true;
5919 break;
5922 if ($found) {
5923 $result = new stdClass();
5924 $result->page = $this;
5925 $result->settings = array();
5926 return array($this->name => $result);
5927 } else {
5928 return array();
5935 * Question type manage page
5937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5939 class admin_page_manageqtypes extends admin_externalpage {
5941 * Calls parent::__construct with specific arguments
5943 public function __construct() {
5944 global $CFG;
5945 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5946 new moodle_url('/admin/qtypes.php'));
5950 * Search question types for the specified string
5952 * @param string $query The string to search for in question types
5953 * @return array
5955 public function search($query) {
5956 global $CFG;
5957 if ($result = parent::search($query)) {
5958 return $result;
5961 $found = false;
5962 require_once($CFG->dirroot . '/question/engine/bank.php');
5963 foreach (question_bank::get_all_qtypes() as $qtype) {
5964 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5965 $found = true;
5966 break;
5969 if ($found) {
5970 $result = new stdClass();
5971 $result->page = $this;
5972 $result->settings = array();
5973 return array($this->name => $result);
5974 } else {
5975 return array();
5981 class admin_page_manageportfolios extends admin_externalpage {
5983 * Calls parent::__construct with specific arguments
5985 public function __construct() {
5986 global $CFG;
5987 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5988 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5992 * Searches page for the specified string.
5993 * @param string $query The string to search for
5994 * @return bool True if it is found on this page
5996 public function search($query) {
5997 global $CFG;
5998 if ($result = parent::search($query)) {
5999 return $result;
6002 $found = false;
6003 $portfolios = core_component::get_plugin_list('portfolio');
6004 foreach ($portfolios as $p => $dir) {
6005 if (strpos($p, $query) !== false) {
6006 $found = true;
6007 break;
6010 if (!$found) {
6011 foreach (portfolio_instances(false, false) as $instance) {
6012 $title = $instance->get('name');
6013 if (strpos(core_text::strtolower($title), $query) !== false) {
6014 $found = true;
6015 break;
6020 if ($found) {
6021 $result = new stdClass();
6022 $result->page = $this;
6023 $result->settings = array();
6024 return array($this->name => $result);
6025 } else {
6026 return array();
6032 class admin_page_managerepositories extends admin_externalpage {
6034 * Calls parent::__construct with specific arguments
6036 public function __construct() {
6037 global $CFG;
6038 parent::__construct('managerepositories', get_string('manage',
6039 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
6043 * Searches page for the specified string.
6044 * @param string $query The string to search for
6045 * @return bool True if it is found on this page
6047 public function search($query) {
6048 global $CFG;
6049 if ($result = parent::search($query)) {
6050 return $result;
6053 $found = false;
6054 $repositories= core_component::get_plugin_list('repository');
6055 foreach ($repositories as $p => $dir) {
6056 if (strpos($p, $query) !== false) {
6057 $found = true;
6058 break;
6061 if (!$found) {
6062 foreach (repository::get_types() as $instance) {
6063 $title = $instance->get_typename();
6064 if (strpos(core_text::strtolower($title), $query) !== false) {
6065 $found = true;
6066 break;
6071 if ($found) {
6072 $result = new stdClass();
6073 $result->page = $this;
6074 $result->settings = array();
6075 return array($this->name => $result);
6076 } else {
6077 return array();
6084 * Special class for authentication administration.
6086 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6088 class admin_setting_manageauths extends admin_setting {
6090 * Calls parent::__construct with specific arguments
6092 public function __construct() {
6093 $this->nosave = true;
6094 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
6098 * Always returns true
6100 * @return true
6102 public function get_setting() {
6103 return true;
6107 * Always returns true
6109 * @return true
6111 public function get_defaultsetting() {
6112 return true;
6116 * Always returns '' and doesn't write anything
6118 * @return string Always returns ''
6120 public function write_setting($data) {
6121 // do not write any setting
6122 return '';
6126 * Search to find if Query is related to auth plugin
6128 * @param string $query The string to search for
6129 * @return bool true for related false for not
6131 public function is_related($query) {
6132 if (parent::is_related($query)) {
6133 return true;
6136 $authsavailable = core_component::get_plugin_list('auth');
6137 foreach ($authsavailable as $auth => $dir) {
6138 if (strpos($auth, $query) !== false) {
6139 return true;
6141 $authplugin = get_auth_plugin($auth);
6142 $authtitle = $authplugin->get_title();
6143 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
6144 return true;
6147 return false;
6151 * Return XHTML to display control
6153 * @param mixed $data Unused
6154 * @param string $query
6155 * @return string highlight
6157 public function output_html($data, $query='') {
6158 global $CFG, $OUTPUT, $DB;
6160 // display strings
6161 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6162 'settings', 'edit', 'name', 'enable', 'disable',
6163 'up', 'down', 'none', 'users'));
6164 $txt->updown = "$txt->up/$txt->down";
6165 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6166 $txt->testsettings = get_string('testsettings', 'core_auth');
6168 $authsavailable = core_component::get_plugin_list('auth');
6169 get_enabled_auth_plugins(true); // fix the list of enabled auths
6170 if (empty($CFG->auth)) {
6171 $authsenabled = array();
6172 } else {
6173 $authsenabled = explode(',', $CFG->auth);
6176 // construct the display array, with enabled auth plugins at the top, in order
6177 $displayauths = array();
6178 $registrationauths = array();
6179 $registrationauths[''] = $txt->disable;
6180 $authplugins = array();
6181 foreach ($authsenabled as $auth) {
6182 $authplugin = get_auth_plugin($auth);
6183 $authplugins[$auth] = $authplugin;
6184 /// Get the auth title (from core or own auth lang files)
6185 $authtitle = $authplugin->get_title();
6186 /// Apply titles
6187 $displayauths[$auth] = $authtitle;
6188 if ($authplugin->can_signup()) {
6189 $registrationauths[$auth] = $authtitle;
6193 foreach ($authsavailable as $auth => $dir) {
6194 if (array_key_exists($auth, $displayauths)) {
6195 continue; //already in the list
6197 $authplugin = get_auth_plugin($auth);
6198 $authplugins[$auth] = $authplugin;
6199 /// Get the auth title (from core or own auth lang files)
6200 $authtitle = $authplugin->get_title();
6201 /// Apply titles
6202 $displayauths[$auth] = $authtitle;
6203 if ($authplugin->can_signup()) {
6204 $registrationauths[$auth] = $authtitle;
6208 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6209 $return .= $OUTPUT->box_start('generalbox authsui');
6211 $table = new html_table();
6212 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6213 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6214 $table->data = array();
6215 $table->attributes['class'] = 'admintable generaltable';
6216 $table->id = 'manageauthtable';
6218 //add always enabled plugins first
6219 $displayname = $displayauths['manual'];
6220 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6221 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6222 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6223 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6224 $displayname = $displayauths['nologin'];
6225 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6226 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6227 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6230 // iterate through auth plugins and add to the display table
6231 $updowncount = 1;
6232 $authcount = count($authsenabled);
6233 $url = "auth.php?sesskey=" . sesskey();
6234 foreach ($displayauths as $auth => $name) {
6235 if ($auth == 'manual' or $auth == 'nologin') {
6236 continue;
6238 $class = '';
6239 // hide/show link
6240 if (in_array($auth, $authsenabled)) {
6241 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6242 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6243 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6244 $enabled = true;
6245 $displayname = $name;
6247 else {
6248 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6249 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6250 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6251 $enabled = false;
6252 $displayname = $name;
6253 $class = 'dimmed_text';
6256 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6258 // up/down link (only if auth is enabled)
6259 $updown = '';
6260 if ($enabled) {
6261 if ($updowncount > 1) {
6262 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6263 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6265 else {
6266 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6268 if ($updowncount < $authcount) {
6269 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6270 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6272 else {
6273 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6275 ++ $updowncount;
6278 // settings link
6279 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6280 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6281 } else {
6282 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6285 // Uninstall link.
6286 $uninstall = '';
6287 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6288 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6291 $test = '';
6292 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6293 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6294 $test = html_writer::link($testurl, $txt->testsettings);
6297 // Add a row to the table.
6298 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6299 if ($class) {
6300 $row->attributes['class'] = $class;
6302 $table->data[] = $row;
6304 $return .= html_writer::table($table);
6305 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6306 $return .= $OUTPUT->box_end();
6307 return highlight($query, $return);
6313 * Special class for authentication administration.
6315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6317 class admin_setting_manageeditors extends admin_setting {
6319 * Calls parent::__construct with specific arguments
6321 public function __construct() {
6322 $this->nosave = true;
6323 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6327 * Always returns true, does nothing
6329 * @return true
6331 public function get_setting() {
6332 return true;
6336 * Always returns true, does nothing
6338 * @return true
6340 public function get_defaultsetting() {
6341 return true;
6345 * Always returns '', does not write anything
6347 * @return string Always returns ''
6349 public function write_setting($data) {
6350 // do not write any setting
6351 return '';
6355 * Checks if $query is one of the available editors
6357 * @param string $query The string to search for
6358 * @return bool Returns true if found, false if not
6360 public function is_related($query) {
6361 if (parent::is_related($query)) {
6362 return true;
6365 $editors_available = editors_get_available();
6366 foreach ($editors_available as $editor=>$editorstr) {
6367 if (strpos($editor, $query) !== false) {
6368 return true;
6370 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6371 return true;
6374 return false;
6378 * Builds the XHTML to display the control
6380 * @param string $data Unused
6381 * @param string $query
6382 * @return string
6384 public function output_html($data, $query='') {
6385 global $CFG, $OUTPUT;
6387 // display strings
6388 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6389 'up', 'down', 'none'));
6390 $struninstall = get_string('uninstallplugin', 'core_admin');
6392 $txt->updown = "$txt->up/$txt->down";
6394 $editors_available = editors_get_available();
6395 $active_editors = explode(',', $CFG->texteditors);
6397 $active_editors = array_reverse($active_editors);
6398 foreach ($active_editors as $key=>$editor) {
6399 if (empty($editors_available[$editor])) {
6400 unset($active_editors[$key]);
6401 } else {
6402 $name = $editors_available[$editor];
6403 unset($editors_available[$editor]);
6404 $editors_available[$editor] = $name;
6407 if (empty($active_editors)) {
6408 //$active_editors = array('textarea');
6410 $editors_available = array_reverse($editors_available, true);
6411 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6412 $return .= $OUTPUT->box_start('generalbox editorsui');
6414 $table = new html_table();
6415 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6416 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6417 $table->id = 'editormanagement';
6418 $table->attributes['class'] = 'admintable generaltable';
6419 $table->data = array();
6421 // iterate through auth plugins and add to the display table
6422 $updowncount = 1;
6423 $editorcount = count($active_editors);
6424 $url = "editors.php?sesskey=" . sesskey();
6425 foreach ($editors_available as $editor => $name) {
6426 // hide/show link
6427 $class = '';
6428 if (in_array($editor, $active_editors)) {
6429 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6430 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6431 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6432 $enabled = true;
6433 $displayname = $name;
6435 else {
6436 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6437 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6438 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6439 $enabled = false;
6440 $displayname = $name;
6441 $class = 'dimmed_text';
6444 // up/down link (only if auth is enabled)
6445 $updown = '';
6446 if ($enabled) {
6447 if ($updowncount > 1) {
6448 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6449 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6451 else {
6452 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6454 if ($updowncount < $editorcount) {
6455 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6456 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6458 else {
6459 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6461 ++ $updowncount;
6464 // settings link
6465 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6466 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6467 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6468 } else {
6469 $settings = '';
6472 $uninstall = '';
6473 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6474 $uninstall = html_writer::link($uninstallurl, $struninstall);
6477 // Add a row to the table.
6478 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6479 if ($class) {
6480 $row->attributes['class'] = $class;
6482 $table->data[] = $row;
6484 $return .= html_writer::table($table);
6485 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6486 $return .= $OUTPUT->box_end();
6487 return highlight($query, $return);
6493 * Special class for license administration.
6495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6497 class admin_setting_managelicenses extends admin_setting {
6499 * Calls parent::__construct with specific arguments
6501 public function __construct() {
6502 $this->nosave = true;
6503 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6507 * Always returns true, does nothing
6509 * @return true
6511 public function get_setting() {
6512 return true;
6516 * Always returns true, does nothing
6518 * @return true
6520 public function get_defaultsetting() {
6521 return true;
6525 * Always returns '', does not write anything
6527 * @return string Always returns ''
6529 public function write_setting($data) {
6530 // do not write any setting
6531 return '';
6535 * Builds the XHTML to display the control
6537 * @param string $data Unused
6538 * @param string $query
6539 * @return string
6541 public function output_html($data, $query='') {
6542 global $CFG, $OUTPUT;
6543 require_once($CFG->libdir . '/licenselib.php');
6544 $url = "licenses.php?sesskey=" . sesskey();
6546 // display strings
6547 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6548 $licenses = license_manager::get_licenses();
6550 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6552 $return .= $OUTPUT->box_start('generalbox editorsui');
6554 $table = new html_table();
6555 $table->head = array($txt->name, $txt->enable);
6556 $table->colclasses = array('leftalign', 'centeralign');
6557 $table->id = 'availablelicenses';
6558 $table->attributes['class'] = 'admintable generaltable';
6559 $table->data = array();
6561 foreach ($licenses as $value) {
6562 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6564 if ($value->enabled == 1) {
6565 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6566 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6567 } else {
6568 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6569 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6572 if ($value->shortname == $CFG->sitedefaultlicense) {
6573 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6574 $hideshow = '';
6577 $enabled = true;
6579 $table->data[] =array($displayname, $hideshow);
6581 $return .= html_writer::table($table);
6582 $return .= $OUTPUT->box_end();
6583 return highlight($query, $return);
6588 * Course formats manager. Allows to enable/disable formats and jump to settings
6590 class admin_setting_manageformats extends admin_setting {
6593 * Calls parent::__construct with specific arguments
6595 public function __construct() {
6596 $this->nosave = true;
6597 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6601 * Always returns true
6603 * @return true
6605 public function get_setting() {
6606 return true;
6610 * Always returns true
6612 * @return true
6614 public function get_defaultsetting() {
6615 return true;
6619 * Always returns '' and doesn't write anything
6621 * @param mixed $data string or array, must not be NULL
6622 * @return string Always returns ''
6624 public function write_setting($data) {
6625 // do not write any setting
6626 return '';
6630 * Search to find if Query is related to format plugin
6632 * @param string $query The string to search for
6633 * @return bool true for related false for not
6635 public function is_related($query) {
6636 if (parent::is_related($query)) {
6637 return true;
6639 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6640 foreach ($formats as $format) {
6641 if (strpos($format->component, $query) !== false ||
6642 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6643 return true;
6646 return false;
6650 * Return XHTML to display control
6652 * @param mixed $data Unused
6653 * @param string $query
6654 * @return string highlight
6656 public function output_html($data, $query='') {
6657 global $CFG, $OUTPUT;
6658 $return = '';
6659 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6660 $return .= $OUTPUT->box_start('generalbox formatsui');
6662 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6664 // display strings
6665 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6666 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6667 $txt->updown = "$txt->up/$txt->down";
6669 $table = new html_table();
6670 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6671 $table->align = array('left', 'center', 'center', 'center', 'center');
6672 $table->attributes['class'] = 'manageformattable generaltable admintable';
6673 $table->data = array();
6675 $cnt = 0;
6676 $defaultformat = get_config('moodlecourse', 'format');
6677 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6678 foreach ($formats as $format) {
6679 $url = new moodle_url('/admin/courseformats.php',
6680 array('sesskey' => sesskey(), 'format' => $format->name));
6681 $isdefault = '';
6682 $class = '';
6683 if ($format->is_enabled()) {
6684 $strformatname = $format->displayname;
6685 if ($defaultformat === $format->name) {
6686 $hideshow = $txt->default;
6687 } else {
6688 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6689 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6691 } else {
6692 $strformatname = $format->displayname;
6693 $class = 'dimmed_text';
6694 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6695 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6697 $updown = '';
6698 if ($cnt) {
6699 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6700 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6701 } else {
6702 $updown .= $spacer;
6704 if ($cnt < count($formats) - 1) {
6705 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6706 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6707 } else {
6708 $updown .= $spacer;
6710 $cnt++;
6711 $settings = '';
6712 if ($format->get_settings_url()) {
6713 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6715 $uninstall = '';
6716 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6717 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6719 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6720 if ($class) {
6721 $row->attributes['class'] = $class;
6723 $table->data[] = $row;
6725 $return .= html_writer::table($table);
6726 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6727 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6728 $return .= $OUTPUT->box_end();
6729 return highlight($query, $return);
6734 * Special class for filter administration.
6736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6738 class admin_page_managefilters extends admin_externalpage {
6740 * Calls parent::__construct with specific arguments
6742 public function __construct() {
6743 global $CFG;
6744 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6748 * Searches all installed filters for specified filter
6750 * @param string $query The filter(string) to search for
6751 * @param string $query
6753 public function search($query) {
6754 global $CFG;
6755 if ($result = parent::search($query)) {
6756 return $result;
6759 $found = false;
6760 $filternames = filter_get_all_installed();
6761 foreach ($filternames as $path => $strfiltername) {
6762 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6763 $found = true;
6764 break;
6766 if (strpos($path, $query) !== false) {
6767 $found = true;
6768 break;
6772 if ($found) {
6773 $result = new stdClass;
6774 $result->page = $this;
6775 $result->settings = array();
6776 return array($this->name => $result);
6777 } else {
6778 return array();
6785 * Initialise admin page - this function does require login and permission
6786 * checks specified in page definition.
6788 * This function must be called on each admin page before other code.
6790 * @global moodle_page $PAGE
6792 * @param string $section name of page
6793 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6794 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6795 * added to the turn blocks editing on/off form, so this page reloads correctly.
6796 * @param string $actualurl if the actual page being viewed is not the normal one for this
6797 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6798 * @param array $options Additional options that can be specified for page setup.
6799 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6801 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6802 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6804 $PAGE->set_context(null); // hack - set context to something, by default to system context
6806 $site = get_site();
6807 require_login();
6809 if (!empty($options['pagelayout'])) {
6810 // A specific page layout has been requested.
6811 $PAGE->set_pagelayout($options['pagelayout']);
6812 } else if ($section === 'upgradesettings') {
6813 $PAGE->set_pagelayout('maintenance');
6814 } else {
6815 $PAGE->set_pagelayout('admin');
6818 $adminroot = admin_get_root(false, false); // settings not required for external pages
6819 $extpage = $adminroot->locate($section, true);
6821 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6822 // The requested section isn't in the admin tree
6823 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6824 if (!has_capability('moodle/site:config', context_system::instance())) {
6825 // The requested section could depend on a different capability
6826 // but most likely the user has inadequate capabilities
6827 print_error('accessdenied', 'admin');
6828 } else {
6829 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6833 // this eliminates our need to authenticate on the actual pages
6834 if (!$extpage->check_access()) {
6835 print_error('accessdenied', 'admin');
6836 die;
6839 navigation_node::require_admin_tree();
6841 // $PAGE->set_extra_button($extrabutton); TODO
6843 if (!$actualurl) {
6844 $actualurl = $extpage->url;
6847 $PAGE->set_url($actualurl, $extraurlparams);
6848 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6849 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6852 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6853 // During initial install.
6854 $strinstallation = get_string('installation', 'install');
6855 $strsettings = get_string('settings');
6856 $PAGE->navbar->add($strsettings);
6857 $PAGE->set_title($strinstallation);
6858 $PAGE->set_heading($strinstallation);
6859 $PAGE->set_cacheable(false);
6860 return;
6863 // Locate the current item on the navigation and make it active when found.
6864 $path = $extpage->path;
6865 $node = $PAGE->settingsnav;
6866 while ($node && count($path) > 0) {
6867 $node = $node->get(array_pop($path));
6869 if ($node) {
6870 $node->make_active();
6873 // Normal case.
6874 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6875 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6876 $USER->editing = $adminediting;
6879 $visiblepathtosection = array_reverse($extpage->visiblepath);
6881 if ($PAGE->user_allowed_editing()) {
6882 if ($PAGE->user_is_editing()) {
6883 $caption = get_string('blockseditoff');
6884 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6885 } else {
6886 $caption = get_string('blocksediton');
6887 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6889 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6892 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6893 $PAGE->set_heading($SITE->fullname);
6895 // prevent caching in nav block
6896 $PAGE->navigation->clear_cache();
6900 * Returns the reference to admin tree root
6902 * @return object admin_root object
6904 function admin_get_root($reload=false, $requirefulltree=true) {
6905 global $CFG, $DB, $OUTPUT;
6907 static $ADMIN = NULL;
6909 if (is_null($ADMIN)) {
6910 // create the admin tree!
6911 $ADMIN = new admin_root($requirefulltree);
6914 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6915 $ADMIN->purge_children($requirefulltree);
6918 if (!$ADMIN->loaded) {
6919 // we process this file first to create categories first and in correct order
6920 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6922 // now we process all other files in admin/settings to build the admin tree
6923 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6924 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6925 continue;
6927 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6928 // plugins are loaded last - they may insert pages anywhere
6929 continue;
6931 require($file);
6933 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6935 $ADMIN->loaded = true;
6938 return $ADMIN;
6941 /// settings utility functions
6944 * This function applies default settings.
6946 * @param object $node, NULL means complete tree, null by default
6947 * @param bool $unconditional if true overrides all values with defaults, null buy default
6949 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6950 global $CFG;
6952 if (is_null($node)) {
6953 core_plugin_manager::reset_caches();
6954 $node = admin_get_root(true, true);
6957 if ($node instanceof admin_category) {
6958 $entries = array_keys($node->children);
6959 foreach ($entries as $entry) {
6960 admin_apply_default_settings($node->children[$entry], $unconditional);
6963 } else if ($node instanceof admin_settingpage) {
6964 foreach ($node->settings as $setting) {
6965 if (!$unconditional and !is_null($setting->get_setting())) {
6966 //do not override existing defaults
6967 continue;
6969 $defaultsetting = $setting->get_defaultsetting();
6970 if (is_null($defaultsetting)) {
6971 // no value yet - default maybe applied after admin user creation or in upgradesettings
6972 continue;
6974 $setting->write_setting($defaultsetting);
6975 $setting->write_setting_flags(null);
6978 // Just in case somebody modifies the list of active plugins directly.
6979 core_plugin_manager::reset_caches();
6983 * Store changed settings, this function updates the errors variable in $ADMIN
6985 * @param object $formdata from form
6986 * @return int number of changed settings
6988 function admin_write_settings($formdata) {
6989 global $CFG, $SITE, $DB;
6991 $olddbsessions = !empty($CFG->dbsessions);
6992 $formdata = (array)$formdata;
6994 $data = array();
6995 foreach ($formdata as $fullname=>$value) {
6996 if (strpos($fullname, 's_') !== 0) {
6997 continue; // not a config value
6999 $data[$fullname] = $value;
7002 $adminroot = admin_get_root();
7003 $settings = admin_find_write_settings($adminroot, $data);
7005 $count = 0;
7006 foreach ($settings as $fullname=>$setting) {
7007 /** @var $setting admin_setting */
7008 $original = $setting->get_setting();
7009 $error = $setting->write_setting($data[$fullname]);
7010 if ($error !== '') {
7011 $adminroot->errors[$fullname] = new stdClass();
7012 $adminroot->errors[$fullname]->data = $data[$fullname];
7013 $adminroot->errors[$fullname]->id = $setting->get_id();
7014 $adminroot->errors[$fullname]->error = $error;
7015 } else {
7016 $setting->write_setting_flags($data);
7018 if ($setting->post_write_settings($original)) {
7019 $count++;
7023 if ($olddbsessions != !empty($CFG->dbsessions)) {
7024 require_logout();
7027 // Now update $SITE - just update the fields, in case other people have a
7028 // a reference to it (e.g. $PAGE, $COURSE).
7029 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
7030 foreach (get_object_vars($newsite) as $field => $value) {
7031 $SITE->$field = $value;
7034 // now reload all settings - some of them might depend on the changed
7035 admin_get_root(true);
7036 return $count;
7040 * Internal recursive function - finds all settings from submitted form
7042 * @param object $node Instance of admin_category, or admin_settingpage
7043 * @param array $data
7044 * @return array
7046 function admin_find_write_settings($node, $data) {
7047 $return = array();
7049 if (empty($data)) {
7050 return $return;
7053 if ($node instanceof admin_category) {
7054 $entries = array_keys($node->children);
7055 foreach ($entries as $entry) {
7056 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
7059 } else if ($node instanceof admin_settingpage) {
7060 foreach ($node->settings as $setting) {
7061 $fullname = $setting->get_full_name();
7062 if (array_key_exists($fullname, $data)) {
7063 $return[$fullname] = $setting;
7069 return $return;
7073 * Internal function - prints the search results
7075 * @param string $query String to search for
7076 * @return string empty or XHTML
7078 function admin_search_settings_html($query) {
7079 global $CFG, $OUTPUT;
7081 if (core_text::strlen($query) < 2) {
7082 return '';
7084 $query = core_text::strtolower($query);
7086 $adminroot = admin_get_root();
7087 $findings = $adminroot->search($query);
7088 $return = '';
7089 $savebutton = false;
7091 foreach ($findings as $found) {
7092 $page = $found->page;
7093 $settings = $found->settings;
7094 if ($page->is_hidden()) {
7095 // hidden pages are not displayed in search results
7096 continue;
7098 if ($page instanceof admin_externalpage) {
7099 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
7100 } else if ($page instanceof admin_settingpage) {
7101 $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');
7102 } else {
7103 continue;
7105 if (!empty($settings)) {
7106 $return .= '<fieldset class="adminsettings">'."\n";
7107 foreach ($settings as $setting) {
7108 if (empty($setting->nosave)) {
7109 $savebutton = true;
7111 $return .= '<div class="clearer"><!-- --></div>'."\n";
7112 $fullname = $setting->get_full_name();
7113 if (array_key_exists($fullname, $adminroot->errors)) {
7114 $data = $adminroot->errors[$fullname]->data;
7115 } else {
7116 $data = $setting->get_setting();
7117 // do not use defaults if settings not available - upgradesettings handles the defaults!
7119 $return .= $setting->output_html($data, $query);
7121 $return .= '</fieldset>';
7125 if ($savebutton) {
7126 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
7129 return $return;
7133 * Internal function - returns arrays of html pages with uninitialised settings
7135 * @param object $node Instance of admin_category or admin_settingpage
7136 * @return array
7138 function admin_output_new_settings_by_page($node) {
7139 global $OUTPUT;
7140 $return = array();
7142 if ($node instanceof admin_category) {
7143 $entries = array_keys($node->children);
7144 foreach ($entries as $entry) {
7145 $return += admin_output_new_settings_by_page($node->children[$entry]);
7148 } else if ($node instanceof admin_settingpage) {
7149 $newsettings = array();
7150 foreach ($node->settings as $setting) {
7151 if (is_null($setting->get_setting())) {
7152 $newsettings[] = $setting;
7155 if (count($newsettings) > 0) {
7156 $adminroot = admin_get_root();
7157 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
7158 $page .= '<fieldset class="adminsettings">'."\n";
7159 foreach ($newsettings as $setting) {
7160 $fullname = $setting->get_full_name();
7161 if (array_key_exists($fullname, $adminroot->errors)) {
7162 $data = $adminroot->errors[$fullname]->data;
7163 } else {
7164 $data = $setting->get_setting();
7165 if (is_null($data)) {
7166 $data = $setting->get_defaultsetting();
7169 $page .= '<div class="clearer"><!-- --></div>'."\n";
7170 $page .= $setting->output_html($data);
7172 $page .= '</fieldset>';
7173 $return[$node->name] = $page;
7177 return $return;
7181 * Format admin settings
7183 * @param object $setting
7184 * @param string $title label element
7185 * @param string $form form fragment, html code - not highlighted automatically
7186 * @param string $description
7187 * @param mixed $label link label to id, true by default or string being the label to connect it to
7188 * @param string $warning warning text
7189 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
7190 * @param string $query search query to be highlighted
7191 * @return string XHTML
7193 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
7194 global $CFG;
7196 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
7197 $fullname = $setting->get_full_name();
7199 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
7200 if ($label === true) {
7201 $labelfor = 'for = "'.$setting->get_id().'"';
7202 } else if ($label === false) {
7203 $labelfor = '';
7204 } else {
7205 $labelfor = 'for="' . $label . '"';
7207 $form .= $setting->output_setting_flags();
7209 $override = '';
7210 if (empty($setting->plugin)) {
7211 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
7212 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7214 } else {
7215 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
7216 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7220 if ($warning !== '') {
7221 $warning = '<div class="form-warning">'.$warning.'</div>';
7224 $defaults = array();
7225 if (!is_null($defaultinfo)) {
7226 if ($defaultinfo === '') {
7227 $defaultinfo = get_string('emptysettingvalue', 'admin');
7229 $defaults[] = $defaultinfo;
7232 $setting->get_setting_flag_defaults($defaults);
7234 if (!empty($defaults)) {
7235 $defaultinfo = implode(', ', $defaults);
7236 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7237 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
7241 $adminroot = admin_get_root();
7242 $error = '';
7243 if (array_key_exists($fullname, $adminroot->errors)) {
7244 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
7247 $str = '
7248 <div class="form-item clearfix" id="admin-'.$setting->name.'">
7249 <div class="form-label">
7250 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
7251 <span class="form-shortname">'.highlightfast($query, $name).'</span>
7252 </div>
7253 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
7254 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
7255 </div>';
7257 return $str;
7261 * Based on find_new_settings{@link ()} in upgradesettings.php
7262 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7264 * @param object $node Instance of admin_category, or admin_settingpage
7265 * @return boolean true if any settings haven't been initialised, false if they all have
7267 function any_new_admin_settings($node) {
7269 if ($node instanceof admin_category) {
7270 $entries = array_keys($node->children);
7271 foreach ($entries as $entry) {
7272 if (any_new_admin_settings($node->children[$entry])) {
7273 return true;
7277 } else if ($node instanceof admin_settingpage) {
7278 foreach ($node->settings as $setting) {
7279 if ($setting->get_setting() === NULL) {
7280 return true;
7285 return false;
7289 * Moved from admin/replace.php so that we can use this in cron
7291 * @param string $search string to look for
7292 * @param string $replace string to replace
7293 * @return bool success or fail
7295 function db_replace($search, $replace) {
7296 global $DB, $CFG, $OUTPUT;
7298 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7299 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7300 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7301 'block_instances', '');
7303 // Turn off time limits, sometimes upgrades can be slow.
7304 core_php_time_limit::raise();
7306 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7307 return false;
7309 foreach ($tables as $table) {
7311 if (in_array($table, $skiptables)) { // Don't process these
7312 continue;
7315 if ($columns = $DB->get_columns($table)) {
7316 $DB->set_debug(true);
7317 foreach ($columns as $column) {
7318 $DB->replace_all_text($table, $column, $search, $replace);
7320 $DB->set_debug(false);
7324 // delete modinfo caches
7325 rebuild_course_cache(0, true);
7327 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7328 $blocks = core_component::get_plugin_list('block');
7329 foreach ($blocks as $blockname=>$fullblock) {
7330 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7331 continue;
7334 if (!is_readable($fullblock.'/lib.php')) {
7335 continue;
7338 $function = 'block_'.$blockname.'_global_db_replace';
7339 include_once($fullblock.'/lib.php');
7340 if (!function_exists($function)) {
7341 continue;
7344 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7345 $function($search, $replace);
7346 echo $OUTPUT->notification("...finished", 'notifysuccess');
7349 purge_all_caches();
7351 return true;
7355 * Manage repository settings
7357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7359 class admin_setting_managerepository extends admin_setting {
7360 /** @var string */
7361 private $baseurl;
7364 * calls parent::__construct with specific arguments
7366 public function __construct() {
7367 global $CFG;
7368 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7369 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7373 * Always returns true, does nothing
7375 * @return true
7377 public function get_setting() {
7378 return true;
7382 * Always returns true does nothing
7384 * @return true
7386 public function get_defaultsetting() {
7387 return true;
7391 * Always returns s_managerepository
7393 * @return string Always return 's_managerepository'
7395 public function get_full_name() {
7396 return 's_managerepository';
7400 * Always returns '' doesn't do anything
7402 public function write_setting($data) {
7403 $url = $this->baseurl . '&amp;new=' . $data;
7404 return '';
7405 // TODO
7406 // Should not use redirect and exit here
7407 // Find a better way to do this.
7408 // redirect($url);
7409 // exit;
7413 * Searches repository plugins for one that matches $query
7415 * @param string $query The string to search for
7416 * @return bool true if found, false if not
7418 public function is_related($query) {
7419 if (parent::is_related($query)) {
7420 return true;
7423 $repositories= core_component::get_plugin_list('repository');
7424 foreach ($repositories as $p => $dir) {
7425 if (strpos($p, $query) !== false) {
7426 return true;
7429 foreach (repository::get_types() as $instance) {
7430 $title = $instance->get_typename();
7431 if (strpos(core_text::strtolower($title), $query) !== false) {
7432 return true;
7435 return false;
7439 * Helper function that generates a moodle_url object
7440 * relevant to the repository
7443 function repository_action_url($repository) {
7444 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7448 * Builds XHTML to display the control
7450 * @param string $data Unused
7451 * @param string $query
7452 * @return string XHTML
7454 public function output_html($data, $query='') {
7455 global $CFG, $USER, $OUTPUT;
7457 // Get strings that are used
7458 $strshow = get_string('on', 'repository');
7459 $strhide = get_string('off', 'repository');
7460 $strdelete = get_string('disabled', 'repository');
7462 $actionchoicesforexisting = array(
7463 'show' => $strshow,
7464 'hide' => $strhide,
7465 'delete' => $strdelete
7468 $actionchoicesfornew = array(
7469 'newon' => $strshow,
7470 'newoff' => $strhide,
7471 'delete' => $strdelete
7474 $return = '';
7475 $return .= $OUTPUT->box_start('generalbox');
7477 // Set strings that are used multiple times
7478 $settingsstr = get_string('settings');
7479 $disablestr = get_string('disable');
7481 // Table to list plug-ins
7482 $table = new html_table();
7483 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7484 $table->align = array('left', 'center', 'center', 'center', 'center');
7485 $table->data = array();
7487 // Get list of used plug-ins
7488 $repositorytypes = repository::get_types();
7489 if (!empty($repositorytypes)) {
7490 // Array to store plugins being used
7491 $alreadyplugins = array();
7492 $totalrepositorytypes = count($repositorytypes);
7493 $updowncount = 1;
7494 foreach ($repositorytypes as $i) {
7495 $settings = '';
7496 $typename = $i->get_typename();
7497 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7498 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7499 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7501 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7502 // Calculate number of instances in order to display them for the Moodle administrator
7503 if (!empty($instanceoptionnames)) {
7504 $params = array();
7505 $params['context'] = array(context_system::instance());
7506 $params['onlyvisible'] = false;
7507 $params['type'] = $typename;
7508 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7509 // site instances
7510 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7511 $params['context'] = array();
7512 $instances = repository::static_function($typename, 'get_instances', $params);
7513 $courseinstances = array();
7514 $userinstances = array();
7516 foreach ($instances as $instance) {
7517 $repocontext = context::instance_by_id($instance->instance->contextid);
7518 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7519 $courseinstances[] = $instance;
7520 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7521 $userinstances[] = $instance;
7524 // course instances
7525 $instancenumber = count($courseinstances);
7526 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7528 // user private instances
7529 $instancenumber = count($userinstances);
7530 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7531 } else {
7532 $admininstancenumbertext = "";
7533 $courseinstancenumbertext = "";
7534 $userinstancenumbertext = "";
7537 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7539 $settings .= $OUTPUT->container_start('mdl-left');
7540 $settings .= '<br/>';
7541 $settings .= $admininstancenumbertext;
7542 $settings .= '<br/>';
7543 $settings .= $courseinstancenumbertext;
7544 $settings .= '<br/>';
7545 $settings .= $userinstancenumbertext;
7546 $settings .= $OUTPUT->container_end();
7548 // Get the current visibility
7549 if ($i->get_visible()) {
7550 $currentaction = 'show';
7551 } else {
7552 $currentaction = 'hide';
7555 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7557 // Display up/down link
7558 $updown = '';
7559 // Should be done with CSS instead.
7560 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7562 if ($updowncount > 1) {
7563 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7564 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7566 else {
7567 $updown .= $spacer;
7569 if ($updowncount < $totalrepositorytypes) {
7570 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7571 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7573 else {
7574 $updown .= $spacer;
7577 $updowncount++;
7579 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7581 if (!in_array($typename, $alreadyplugins)) {
7582 $alreadyplugins[] = $typename;
7587 // Get all the plugins that exist on disk
7588 $plugins = core_component::get_plugin_list('repository');
7589 if (!empty($plugins)) {
7590 foreach ($plugins as $plugin => $dir) {
7591 // Check that it has not already been listed
7592 if (!in_array($plugin, $alreadyplugins)) {
7593 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7594 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7599 $return .= html_writer::table($table);
7600 $return .= $OUTPUT->box_end();
7601 return highlight($query, $return);
7606 * Special checkbox for enable mobile web service
7607 * If enable then we store the service id of the mobile service into config table
7608 * If disable then we unstore the service id from the config table
7610 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7612 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7613 private $xmlrpcuse;
7614 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7615 private $restuse;
7618 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7620 * @return boolean
7622 private function is_protocol_cap_allowed() {
7623 global $DB, $CFG;
7625 // We keep xmlrpc enabled for backward compatibility.
7626 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7627 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7628 $params = array();
7629 $params['permission'] = CAP_ALLOW;
7630 $params['roleid'] = $CFG->defaultuserroleid;
7631 $params['capability'] = 'webservice/xmlrpc:use';
7632 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7635 // If the $this->restuse variable is not set, it needs to be set.
7636 if (empty($this->restuse) and $this->restuse!==false) {
7637 $params = array();
7638 $params['permission'] = CAP_ALLOW;
7639 $params['roleid'] = $CFG->defaultuserroleid;
7640 $params['capability'] = 'webservice/rest:use';
7641 $this->restuse = $DB->record_exists('role_capabilities', $params);
7644 return ($this->xmlrpcuse && $this->restuse);
7648 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7649 * @param type $status true to allow, false to not set
7651 private function set_protocol_cap($status) {
7652 global $CFG;
7653 if ($status and !$this->is_protocol_cap_allowed()) {
7654 //need to allow the cap
7655 $permission = CAP_ALLOW;
7656 $assign = true;
7657 } else if (!$status and $this->is_protocol_cap_allowed()){
7658 //need to disallow the cap
7659 $permission = CAP_INHERIT;
7660 $assign = true;
7662 if (!empty($assign)) {
7663 $systemcontext = context_system::instance();
7664 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7665 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7670 * Builds XHTML to display the control.
7671 * The main purpose of this overloading is to display a warning when https
7672 * is not supported by the server
7673 * @param string $data Unused
7674 * @param string $query
7675 * @return string XHTML
7677 public function output_html($data, $query='') {
7678 global $CFG, $OUTPUT;
7679 $html = parent::output_html($data, $query);
7681 if ((string)$data === $this->yes) {
7682 require_once($CFG->dirroot . "/lib/filelib.php");
7683 $curl = new curl();
7684 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7685 $curl->head($httpswwwroot . "/login/index.php");
7686 $info = $curl->get_info();
7687 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7688 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7692 return $html;
7696 * Retrieves the current setting using the objects name
7698 * @return string
7700 public function get_setting() {
7701 global $CFG;
7703 // First check if is not set.
7704 $result = $this->config_read($this->name);
7705 if (is_null($result)) {
7706 return null;
7709 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7710 // Or if web services aren't enabled this can't be,
7711 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7712 return 0;
7715 require_once($CFG->dirroot . '/webservice/lib.php');
7716 $webservicemanager = new webservice();
7717 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7718 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7719 return $result;
7720 } else {
7721 return 0;
7726 * Save the selected setting
7728 * @param string $data The selected site
7729 * @return string empty string or error message
7731 public function write_setting($data) {
7732 global $DB, $CFG;
7734 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7735 if (empty($CFG->defaultuserroleid)) {
7736 return '';
7739 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7741 require_once($CFG->dirroot . '/webservice/lib.php');
7742 $webservicemanager = new webservice();
7744 $updateprotocol = false;
7745 if ((string)$data === $this->yes) {
7746 //code run when enable mobile web service
7747 //enable web service systeme if necessary
7748 set_config('enablewebservices', true);
7750 //enable mobile service
7751 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7752 $mobileservice->enabled = 1;
7753 $webservicemanager->update_external_service($mobileservice);
7755 //enable xml-rpc server
7756 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7758 if (!in_array('xmlrpc', $activeprotocols)) {
7759 $activeprotocols[] = 'xmlrpc';
7760 $updateprotocol = true;
7763 if (!in_array('rest', $activeprotocols)) {
7764 $activeprotocols[] = 'rest';
7765 $updateprotocol = true;
7768 if ($updateprotocol) {
7769 set_config('webserviceprotocols', implode(',', $activeprotocols));
7772 //allow xml-rpc:use capability for authenticated user
7773 $this->set_protocol_cap(true);
7775 } else {
7776 //disable web service system if no other services are enabled
7777 $otherenabledservices = $DB->get_records_select('external_services',
7778 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7779 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7780 if (empty($otherenabledservices)) {
7781 set_config('enablewebservices', false);
7783 //also disable xml-rpc server
7784 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7785 $protocolkey = array_search('xmlrpc', $activeprotocols);
7786 if ($protocolkey !== false) {
7787 unset($activeprotocols[$protocolkey]);
7788 $updateprotocol = true;
7791 $protocolkey = array_search('rest', $activeprotocols);
7792 if ($protocolkey !== false) {
7793 unset($activeprotocols[$protocolkey]);
7794 $updateprotocol = true;
7797 if ($updateprotocol) {
7798 set_config('webserviceprotocols', implode(',', $activeprotocols));
7801 //disallow xml-rpc:use capability for authenticated user
7802 $this->set_protocol_cap(false);
7805 //disable the mobile service
7806 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7807 $mobileservice->enabled = 0;
7808 $webservicemanager->update_external_service($mobileservice);
7811 return (parent::write_setting($data));
7816 * Special class for management of external services
7818 * @author Petr Skoda (skodak)
7820 class admin_setting_manageexternalservices extends admin_setting {
7822 * Calls parent::__construct with specific arguments
7824 public function __construct() {
7825 $this->nosave = true;
7826 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7830 * Always returns true, does nothing
7832 * @return true
7834 public function get_setting() {
7835 return true;
7839 * Always returns true, does nothing
7841 * @return true
7843 public function get_defaultsetting() {
7844 return true;
7848 * Always returns '', does not write anything
7850 * @return string Always returns ''
7852 public function write_setting($data) {
7853 // do not write any setting
7854 return '';
7858 * Checks if $query is one of the available external services
7860 * @param string $query The string to search for
7861 * @return bool Returns true if found, false if not
7863 public function is_related($query) {
7864 global $DB;
7866 if (parent::is_related($query)) {
7867 return true;
7870 $services = $DB->get_records('external_services', array(), 'id, name');
7871 foreach ($services as $service) {
7872 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7873 return true;
7876 return false;
7880 * Builds the XHTML to display the control
7882 * @param string $data Unused
7883 * @param string $query
7884 * @return string
7886 public function output_html($data, $query='') {
7887 global $CFG, $OUTPUT, $DB;
7889 // display strings
7890 $stradministration = get_string('administration');
7891 $stredit = get_string('edit');
7892 $strservice = get_string('externalservice', 'webservice');
7893 $strdelete = get_string('delete');
7894 $strplugin = get_string('plugin', 'admin');
7895 $stradd = get_string('add');
7896 $strfunctions = get_string('functions', 'webservice');
7897 $strusers = get_string('users');
7898 $strserviceusers = get_string('serviceusers', 'webservice');
7900 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7901 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7902 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7904 // built in services
7905 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7906 $return = "";
7907 if (!empty($services)) {
7908 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7912 $table = new html_table();
7913 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7914 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7915 $table->id = 'builtinservices';
7916 $table->attributes['class'] = 'admintable externalservices generaltable';
7917 $table->data = array();
7919 // iterate through auth plugins and add to the display table
7920 foreach ($services as $service) {
7921 $name = $service->name;
7923 // hide/show link
7924 if ($service->enabled) {
7925 $displayname = "<span>$name</span>";
7926 } else {
7927 $displayname = "<span class=\"dimmed_text\">$name</span>";
7930 $plugin = $service->component;
7932 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7934 if ($service->restrictedusers) {
7935 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7936 } else {
7937 $users = get_string('allusers', 'webservice');
7940 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7942 // add a row to the table
7943 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7945 $return .= html_writer::table($table);
7948 // Custom services
7949 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7950 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7952 $table = new html_table();
7953 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7954 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7955 $table->id = 'customservices';
7956 $table->attributes['class'] = 'admintable externalservices generaltable';
7957 $table->data = array();
7959 // iterate through auth plugins and add to the display table
7960 foreach ($services as $service) {
7961 $name = $service->name;
7963 // hide/show link
7964 if ($service->enabled) {
7965 $displayname = "<span>$name</span>";
7966 } else {
7967 $displayname = "<span class=\"dimmed_text\">$name</span>";
7970 // delete link
7971 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7973 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7975 if ($service->restrictedusers) {
7976 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7977 } else {
7978 $users = get_string('allusers', 'webservice');
7981 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7983 // add a row to the table
7984 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7986 // add new custom service option
7987 $return .= html_writer::table($table);
7989 $return .= '<br />';
7990 // add a token to the table
7991 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7993 return highlight($query, $return);
7998 * Special class for overview of external services
8000 * @author Jerome Mouneyrac
8002 class admin_setting_webservicesoverview extends admin_setting {
8005 * Calls parent::__construct with specific arguments
8007 public function __construct() {
8008 $this->nosave = true;
8009 parent::__construct('webservicesoverviewui',
8010 get_string('webservicesoverview', 'webservice'), '', '');
8014 * Always returns true, does nothing
8016 * @return true
8018 public function get_setting() {
8019 return true;
8023 * Always returns true, does nothing
8025 * @return true
8027 public function get_defaultsetting() {
8028 return true;
8032 * Always returns '', does not write anything
8034 * @return string Always returns ''
8036 public function write_setting($data) {
8037 // do not write any setting
8038 return '';
8042 * Builds the XHTML to display the control
8044 * @param string $data Unused
8045 * @param string $query
8046 * @return string
8048 public function output_html($data, $query='') {
8049 global $CFG, $OUTPUT;
8051 $return = "";
8052 $brtag = html_writer::empty_tag('br');
8054 // Enable mobile web service
8055 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
8056 get_string('enablemobilewebservice', 'admin'),
8057 get_string('configenablemobilewebservice',
8058 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
8059 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
8060 $wsmobileparam = new stdClass();
8061 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
8062 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
8063 get_string('mobile', 'admin'));
8064 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
8065 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
8066 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
8067 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
8068 . $brtag . $brtag;
8070 /// One system controlling Moodle with Token
8071 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
8072 $table = new html_table();
8073 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8074 get_string('description'));
8075 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8076 $table->id = 'onesystemcontrol';
8077 $table->attributes['class'] = 'admintable wsoverview generaltable';
8078 $table->data = array();
8080 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
8081 . $brtag . $brtag;
8083 /// 1. Enable Web Services
8084 $row = array();
8085 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8086 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8087 array('href' => $url));
8088 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8089 if ($CFG->enablewebservices) {
8090 $status = get_string('yes');
8092 $row[1] = $status;
8093 $row[2] = get_string('enablewsdescription', 'webservice');
8094 $table->data[] = $row;
8096 /// 2. Enable protocols
8097 $row = array();
8098 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8099 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8100 array('href' => $url));
8101 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8102 //retrieve activated protocol
8103 $active_protocols = empty($CFG->webserviceprotocols) ?
8104 array() : explode(',', $CFG->webserviceprotocols);
8105 if (!empty($active_protocols)) {
8106 $status = "";
8107 foreach ($active_protocols as $protocol) {
8108 $status .= $protocol . $brtag;
8111 $row[1] = $status;
8112 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8113 $table->data[] = $row;
8115 /// 3. Create user account
8116 $row = array();
8117 $url = new moodle_url("/user/editadvanced.php?id=-1");
8118 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
8119 array('href' => $url));
8120 $row[1] = "";
8121 $row[2] = get_string('createuserdescription', 'webservice');
8122 $table->data[] = $row;
8124 /// 4. Add capability to users
8125 $row = array();
8126 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8127 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
8128 array('href' => $url));
8129 $row[1] = "";
8130 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
8131 $table->data[] = $row;
8133 /// 5. Select a web service
8134 $row = array();
8135 $url = new moodle_url("/admin/settings.php?section=externalservices");
8136 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8137 array('href' => $url));
8138 $row[1] = "";
8139 $row[2] = get_string('createservicedescription', 'webservice');
8140 $table->data[] = $row;
8142 /// 6. Add functions
8143 $row = array();
8144 $url = new moodle_url("/admin/settings.php?section=externalservices");
8145 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8146 array('href' => $url));
8147 $row[1] = "";
8148 $row[2] = get_string('addfunctionsdescription', 'webservice');
8149 $table->data[] = $row;
8151 /// 7. Add the specific user
8152 $row = array();
8153 $url = new moodle_url("/admin/settings.php?section=externalservices");
8154 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
8155 array('href' => $url));
8156 $row[1] = "";
8157 $row[2] = get_string('selectspecificuserdescription', 'webservice');
8158 $table->data[] = $row;
8160 /// 8. Create token for the specific user
8161 $row = array();
8162 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
8163 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
8164 array('href' => $url));
8165 $row[1] = "";
8166 $row[2] = get_string('createtokenforuserdescription', 'webservice');
8167 $table->data[] = $row;
8169 /// 9. Enable the documentation
8170 $row = array();
8171 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
8172 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
8173 array('href' => $url));
8174 $status = '<span class="warning">' . get_string('no') . '</span>';
8175 if ($CFG->enablewsdocumentation) {
8176 $status = get_string('yes');
8178 $row[1] = $status;
8179 $row[2] = get_string('enabledocumentationdescription', 'webservice');
8180 $table->data[] = $row;
8182 /// 10. Test the service
8183 $row = array();
8184 $url = new moodle_url("/admin/webservice/testclient.php");
8185 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8186 array('href' => $url));
8187 $row[1] = "";
8188 $row[2] = get_string('testwithtestclientdescription', 'webservice');
8189 $table->data[] = $row;
8191 $return .= html_writer::table($table);
8193 /// Users as clients with token
8194 $return .= $brtag . $brtag . $brtag;
8195 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
8196 $table = new html_table();
8197 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8198 get_string('description'));
8199 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8200 $table->id = 'userasclients';
8201 $table->attributes['class'] = 'admintable wsoverview generaltable';
8202 $table->data = array();
8204 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
8205 $brtag . $brtag;
8207 /// 1. Enable Web Services
8208 $row = array();
8209 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8210 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8211 array('href' => $url));
8212 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8213 if ($CFG->enablewebservices) {
8214 $status = get_string('yes');
8216 $row[1] = $status;
8217 $row[2] = get_string('enablewsdescription', 'webservice');
8218 $table->data[] = $row;
8220 /// 2. Enable protocols
8221 $row = array();
8222 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8223 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8224 array('href' => $url));
8225 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8226 //retrieve activated protocol
8227 $active_protocols = empty($CFG->webserviceprotocols) ?
8228 array() : explode(',', $CFG->webserviceprotocols);
8229 if (!empty($active_protocols)) {
8230 $status = "";
8231 foreach ($active_protocols as $protocol) {
8232 $status .= $protocol . $brtag;
8235 $row[1] = $status;
8236 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8237 $table->data[] = $row;
8240 /// 3. Select a web service
8241 $row = array();
8242 $url = new moodle_url("/admin/settings.php?section=externalservices");
8243 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8244 array('href' => $url));
8245 $row[1] = "";
8246 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8247 $table->data[] = $row;
8249 /// 4. Add functions
8250 $row = array();
8251 $url = new moodle_url("/admin/settings.php?section=externalservices");
8252 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8253 array('href' => $url));
8254 $row[1] = "";
8255 $row[2] = get_string('addfunctionsdescription', 'webservice');
8256 $table->data[] = $row;
8258 /// 5. Add capability to users
8259 $row = array();
8260 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8261 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8262 array('href' => $url));
8263 $row[1] = "";
8264 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8265 $table->data[] = $row;
8267 /// 6. Test the service
8268 $row = array();
8269 $url = new moodle_url("/admin/webservice/testclient.php");
8270 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8271 array('href' => $url));
8272 $row[1] = "";
8273 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8274 $table->data[] = $row;
8276 $return .= html_writer::table($table);
8278 return highlight($query, $return);
8285 * Special class for web service protocol administration.
8287 * @author Petr Skoda (skodak)
8289 class admin_setting_managewebserviceprotocols extends admin_setting {
8292 * Calls parent::__construct with specific arguments
8294 public function __construct() {
8295 $this->nosave = true;
8296 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8300 * Always returns true, does nothing
8302 * @return true
8304 public function get_setting() {
8305 return true;
8309 * Always returns true, does nothing
8311 * @return true
8313 public function get_defaultsetting() {
8314 return true;
8318 * Always returns '', does not write anything
8320 * @return string Always returns ''
8322 public function write_setting($data) {
8323 // do not write any setting
8324 return '';
8328 * Checks if $query is one of the available webservices
8330 * @param string $query The string to search for
8331 * @return bool Returns true if found, false if not
8333 public function is_related($query) {
8334 if (parent::is_related($query)) {
8335 return true;
8338 $protocols = core_component::get_plugin_list('webservice');
8339 foreach ($protocols as $protocol=>$location) {
8340 if (strpos($protocol, $query) !== false) {
8341 return true;
8343 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8344 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8345 return true;
8348 return false;
8352 * Builds the XHTML to display the control
8354 * @param string $data Unused
8355 * @param string $query
8356 * @return string
8358 public function output_html($data, $query='') {
8359 global $CFG, $OUTPUT;
8361 // display strings
8362 $stradministration = get_string('administration');
8363 $strsettings = get_string('settings');
8364 $stredit = get_string('edit');
8365 $strprotocol = get_string('protocol', 'webservice');
8366 $strenable = get_string('enable');
8367 $strdisable = get_string('disable');
8368 $strversion = get_string('version');
8370 $protocols_available = core_component::get_plugin_list('webservice');
8371 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8372 ksort($protocols_available);
8374 foreach ($active_protocols as $key=>$protocol) {
8375 if (empty($protocols_available[$protocol])) {
8376 unset($active_protocols[$key]);
8380 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8381 $return .= $OUTPUT->box_start('generalbox webservicesui');
8383 $table = new html_table();
8384 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8385 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8386 $table->id = 'webserviceprotocols';
8387 $table->attributes['class'] = 'admintable generaltable';
8388 $table->data = array();
8390 // iterate through auth plugins and add to the display table
8391 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8392 foreach ($protocols_available as $protocol => $location) {
8393 $name = get_string('pluginname', 'webservice_'.$protocol);
8395 $plugin = new stdClass();
8396 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8397 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8399 $version = isset($plugin->version) ? $plugin->version : '';
8401 // hide/show link
8402 if (in_array($protocol, $active_protocols)) {
8403 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8404 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8405 $displayname = "<span>$name</span>";
8406 } else {
8407 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8408 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8409 $displayname = "<span class=\"dimmed_text\">$name</span>";
8412 // settings link
8413 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8414 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8415 } else {
8416 $settings = '';
8419 // add a row to the table
8420 $table->data[] = array($displayname, $version, $hideshow, $settings);
8422 $return .= html_writer::table($table);
8423 $return .= get_string('configwebserviceplugins', 'webservice');
8424 $return .= $OUTPUT->box_end();
8426 return highlight($query, $return);
8432 * Special class for web service token administration.
8434 * @author Jerome Mouneyrac
8436 class admin_setting_managewebservicetokens extends admin_setting {
8439 * Calls parent::__construct with specific arguments
8441 public function __construct() {
8442 $this->nosave = true;
8443 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8447 * Always returns true, does nothing
8449 * @return true
8451 public function get_setting() {
8452 return true;
8456 * Always returns true, does nothing
8458 * @return true
8460 public function get_defaultsetting() {
8461 return true;
8465 * Always returns '', does not write anything
8467 * @return string Always returns ''
8469 public function write_setting($data) {
8470 // do not write any setting
8471 return '';
8475 * Builds the XHTML to display the control
8477 * @param string $data Unused
8478 * @param string $query
8479 * @return string
8481 public function output_html($data, $query='') {
8482 global $CFG, $OUTPUT, $DB, $USER;
8484 // display strings
8485 $stroperation = get_string('operation', 'webservice');
8486 $strtoken = get_string('token', 'webservice');
8487 $strservice = get_string('service', 'webservice');
8488 $struser = get_string('user');
8489 $strcontext = get_string('context', 'webservice');
8490 $strvaliduntil = get_string('validuntil', 'webservice');
8491 $striprestriction = get_string('iprestriction', 'webservice');
8493 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8495 $table = new html_table();
8496 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8497 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8498 $table->id = 'webservicetokens';
8499 $table->attributes['class'] = 'admintable generaltable';
8500 $table->data = array();
8502 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8504 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8506 //here retrieve token list (including linked users firstname/lastname and linked services name)
8507 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8508 FROM {external_tokens} t, {user} u, {external_services} s
8509 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8510 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8511 if (!empty($tokens)) {
8512 foreach ($tokens as $token) {
8513 //TODO: retrieve context
8515 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8516 $delete .= get_string('delete')."</a>";
8518 $validuntil = '';
8519 if (!empty($token->validuntil)) {
8520 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8523 $iprestriction = '';
8524 if (!empty($token->iprestriction)) {
8525 $iprestriction = $token->iprestriction;
8528 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8529 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8530 $useratag .= $token->firstname." ".$token->lastname;
8531 $useratag .= html_writer::end_tag('a');
8533 //check user missing capabilities
8534 require_once($CFG->dirroot . '/webservice/lib.php');
8535 $webservicemanager = new webservice();
8536 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8537 array(array('id' => $token->userid)), $token->serviceid);
8539 if (!is_siteadmin($token->userid) and
8540 array_key_exists($token->userid, $usermissingcaps)) {
8541 $missingcapabilities = implode(', ',
8542 $usermissingcaps[$token->userid]);
8543 if (!empty($missingcapabilities)) {
8544 $useratag .= html_writer::tag('div',
8545 get_string('usermissingcaps', 'webservice',
8546 $missingcapabilities)
8547 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8548 array('class' => 'missingcaps'));
8552 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8555 $return .= html_writer::table($table);
8556 } else {
8557 $return .= get_string('notoken', 'webservice');
8560 $return .= $OUTPUT->box_end();
8561 // add a token to the table
8562 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8563 $return .= get_string('add')."</a>";
8565 return highlight($query, $return);
8571 * Colour picker
8573 * @copyright 2010 Sam Hemelryk
8574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8576 class admin_setting_configcolourpicker extends admin_setting {
8579 * Information for previewing the colour
8581 * @var array|null
8583 protected $previewconfig = null;
8586 * Use default when empty.
8588 protected $usedefaultwhenempty = true;
8592 * @param string $name
8593 * @param string $visiblename
8594 * @param string $description
8595 * @param string $defaultsetting
8596 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8598 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8599 $usedefaultwhenempty = true) {
8600 $this->previewconfig = $previewconfig;
8601 $this->usedefaultwhenempty = $usedefaultwhenempty;
8602 parent::__construct($name, $visiblename, $description, $defaultsetting);
8606 * Return the setting
8608 * @return mixed returns config if successful else null
8610 public function get_setting() {
8611 return $this->config_read($this->name);
8615 * Saves the setting
8617 * @param string $data
8618 * @return bool
8620 public function write_setting($data) {
8621 $data = $this->validate($data);
8622 if ($data === false) {
8623 return get_string('validateerror', 'admin');
8625 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8629 * Validates the colour that was entered by the user
8631 * @param string $data
8632 * @return string|false
8634 protected function validate($data) {
8636 * List of valid HTML colour names
8638 * @var array
8640 $colornames = array(
8641 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8642 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8643 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8644 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8645 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8646 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8647 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8648 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8649 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8650 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8651 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8652 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8653 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8654 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8655 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8656 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8657 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8658 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8659 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8660 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8661 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8662 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8663 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8664 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8665 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8666 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8667 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8668 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8669 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8670 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8671 'whitesmoke', 'yellow', 'yellowgreen'
8674 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8675 if (strpos($data, '#')!==0) {
8676 $data = '#'.$data;
8678 return $data;
8679 } else if (in_array(strtolower($data), $colornames)) {
8680 return $data;
8681 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8682 return $data;
8683 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8684 return $data;
8685 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8686 return $data;
8687 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8688 return $data;
8689 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8690 return $data;
8691 } else if (empty($data)) {
8692 if ($this->usedefaultwhenempty){
8693 return $this->defaultsetting;
8694 } else {
8695 return '';
8697 } else {
8698 return false;
8703 * Generates the HTML for the setting
8705 * @global moodle_page $PAGE
8706 * @global core_renderer $OUTPUT
8707 * @param string $data
8708 * @param string $query
8710 public function output_html($data, $query = '') {
8711 global $PAGE, $OUTPUT;
8712 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8713 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8714 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8715 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8716 if (!empty($this->previewconfig)) {
8717 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8719 $content .= html_writer::end_tag('div');
8720 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8726 * Class used for uploading of one file into file storage,
8727 * the file name is stored in config table.
8729 * Please note you need to implement your own '_pluginfile' callback function,
8730 * this setting only stores the file, it does not deal with file serving.
8732 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8735 class admin_setting_configstoredfile extends admin_setting {
8736 /** @var array file area options - should be one file only */
8737 protected $options;
8738 /** @var string name of the file area */
8739 protected $filearea;
8740 /** @var int intemid */
8741 protected $itemid;
8742 /** @var string used for detection of changes */
8743 protected $oldhashes;
8746 * Create new stored file setting.
8748 * @param string $name low level setting name
8749 * @param string $visiblename human readable setting name
8750 * @param string $description description of setting
8751 * @param mixed $filearea file area for file storage
8752 * @param int $itemid itemid for file storage
8753 * @param array $options file area options
8755 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8756 parent::__construct($name, $visiblename, $description, '');
8757 $this->filearea = $filearea;
8758 $this->itemid = $itemid;
8759 $this->options = (array)$options;
8763 * Applies defaults and returns all options.
8764 * @return array
8766 protected function get_options() {
8767 global $CFG;
8769 require_once("$CFG->libdir/filelib.php");
8770 require_once("$CFG->dirroot/repository/lib.php");
8771 $defaults = array(
8772 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8773 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8774 'context' => context_system::instance());
8775 foreach($this->options as $k => $v) {
8776 $defaults[$k] = $v;
8779 return $defaults;
8782 public function get_setting() {
8783 return $this->config_read($this->name);
8786 public function write_setting($data) {
8787 global $USER;
8789 // Let's not deal with validation here, this is for admins only.
8790 $current = $this->get_setting();
8791 if (empty($data) && $current === null) {
8792 // This will be the case when applying default settings (installation).
8793 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8794 } else if (!is_number($data)) {
8795 // Draft item id is expected here!
8796 return get_string('errorsetting', 'admin');
8799 $options = $this->get_options();
8800 $fs = get_file_storage();
8801 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8803 $this->oldhashes = null;
8804 if ($current) {
8805 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8806 if ($file = $fs->get_file_by_hash($hash)) {
8807 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8809 unset($file);
8812 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8813 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8814 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8815 // with an error because the draft area does not exist, as he did not use it.
8816 $usercontext = context_user::instance($USER->id);
8817 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8818 return get_string('errorsetting', 'admin');
8822 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8823 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8825 $filepath = '';
8826 if ($files) {
8827 /** @var stored_file $file */
8828 $file = reset($files);
8829 $filepath = $file->get_filepath().$file->get_filename();
8832 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8835 public function post_write_settings($original) {
8836 $options = $this->get_options();
8837 $fs = get_file_storage();
8838 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8840 $current = $this->get_setting();
8841 $newhashes = null;
8842 if ($current) {
8843 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8844 if ($file = $fs->get_file_by_hash($hash)) {
8845 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8847 unset($file);
8850 if ($this->oldhashes === $newhashes) {
8851 $this->oldhashes = null;
8852 return false;
8854 $this->oldhashes = null;
8856 $callbackfunction = $this->updatedcallback;
8857 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8858 $callbackfunction($this->get_full_name());
8860 return true;
8863 public function output_html($data, $query = '') {
8864 global $PAGE, $CFG;
8866 $options = $this->get_options();
8867 $id = $this->get_id();
8868 $elname = $this->get_full_name();
8869 $draftitemid = file_get_submitted_draft_itemid($elname);
8870 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8871 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8873 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8874 require_once("$CFG->dirroot/lib/form/filemanager.php");
8876 $fmoptions = new stdClass();
8877 $fmoptions->mainfile = $options['mainfile'];
8878 $fmoptions->maxbytes = $options['maxbytes'];
8879 $fmoptions->maxfiles = $options['maxfiles'];
8880 $fmoptions->client_id = uniqid();
8881 $fmoptions->itemid = $draftitemid;
8882 $fmoptions->subdirs = $options['subdirs'];
8883 $fmoptions->target = $id;
8884 $fmoptions->accepted_types = $options['accepted_types'];
8885 $fmoptions->return_types = $options['return_types'];
8886 $fmoptions->context = $options['context'];
8887 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8889 $fm = new form_filemanager($fmoptions);
8890 $output = $PAGE->get_renderer('core', 'files');
8891 $html = $output->render($fm);
8893 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8894 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8896 return format_admin_setting($this, $this->visiblename,
8897 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8903 * Administration interface for user specified regular expressions for device detection.
8905 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8907 class admin_setting_devicedetectregex extends admin_setting {
8910 * Calls parent::__construct with specific args
8912 * @param string $name
8913 * @param string $visiblename
8914 * @param string $description
8915 * @param mixed $defaultsetting
8917 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8918 global $CFG;
8919 parent::__construct($name, $visiblename, $description, $defaultsetting);
8923 * Return the current setting(s)
8925 * @return array Current settings array
8927 public function get_setting() {
8928 global $CFG;
8930 $config = $this->config_read($this->name);
8931 if (is_null($config)) {
8932 return null;
8935 return $this->prepare_form_data($config);
8939 * Save selected settings
8941 * @param array $data Array of settings to save
8942 * @return bool
8944 public function write_setting($data) {
8945 if (empty($data)) {
8946 $data = array();
8949 if ($this->config_write($this->name, $this->process_form_data($data))) {
8950 return ''; // success
8951 } else {
8952 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8957 * Return XHTML field(s) for regexes
8959 * @param array $data Array of options to set in HTML
8960 * @return string XHTML string for the fields and wrapping div(s)
8962 public function output_html($data, $query='') {
8963 global $OUTPUT;
8965 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8966 $out .= html_writer::start_tag('thead');
8967 $out .= html_writer::start_tag('tr');
8968 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8969 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8970 $out .= html_writer::end_tag('tr');
8971 $out .= html_writer::end_tag('thead');
8972 $out .= html_writer::start_tag('tbody');
8974 if (empty($data)) {
8975 $looplimit = 1;
8976 } else {
8977 $looplimit = (count($data)/2)+1;
8980 for ($i=0; $i<$looplimit; $i++) {
8981 $out .= html_writer::start_tag('tr');
8983 $expressionname = 'expression'.$i;
8985 if (!empty($data[$expressionname])){
8986 $expression = $data[$expressionname];
8987 } else {
8988 $expression = '';
8991 $out .= html_writer::tag('td',
8992 html_writer::empty_tag('input',
8993 array(
8994 'type' => 'text',
8995 'class' => 'form-text',
8996 'name' => $this->get_full_name().'[expression'.$i.']',
8997 'value' => $expression,
8999 ), array('class' => 'c'.$i)
9002 $valuename = 'value'.$i;
9004 if (!empty($data[$valuename])){
9005 $value = $data[$valuename];
9006 } else {
9007 $value= '';
9010 $out .= html_writer::tag('td',
9011 html_writer::empty_tag('input',
9012 array(
9013 'type' => 'text',
9014 'class' => 'form-text',
9015 'name' => $this->get_full_name().'[value'.$i.']',
9016 'value' => $value,
9018 ), array('class' => 'c'.$i)
9021 $out .= html_writer::end_tag('tr');
9024 $out .= html_writer::end_tag('tbody');
9025 $out .= html_writer::end_tag('table');
9027 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
9031 * Converts the string of regexes
9033 * @see self::process_form_data()
9034 * @param $regexes string of regexes
9035 * @return array of form fields and their values
9037 protected function prepare_form_data($regexes) {
9039 $regexes = json_decode($regexes);
9041 $form = array();
9043 $i = 0;
9045 foreach ($regexes as $value => $regex) {
9046 $expressionname = 'expression'.$i;
9047 $valuename = 'value'.$i;
9049 $form[$expressionname] = $regex;
9050 $form[$valuename] = $value;
9051 $i++;
9054 return $form;
9058 * Converts the data from admin settings form into a string of regexes
9060 * @see self::prepare_form_data()
9061 * @param array $data array of admin form fields and values
9062 * @return false|string of regexes
9064 protected function process_form_data(array $form) {
9066 $count = count($form); // number of form field values
9068 if ($count % 2) {
9069 // we must get five fields per expression
9070 return false;
9073 $regexes = array();
9074 for ($i = 0; $i < $count / 2; $i++) {
9075 $expressionname = "expression".$i;
9076 $valuename = "value".$i;
9078 $expression = trim($form['expression'.$i]);
9079 $value = trim($form['value'.$i]);
9081 if (empty($expression)){
9082 continue;
9085 $regexes[$value] = $expression;
9088 $regexes = json_encode($regexes);
9090 return $regexes;
9095 * Multiselect for current modules
9097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9099 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
9100 private $excludesystem;
9103 * Calls parent::__construct - note array $choices is not required
9105 * @param string $name setting name
9106 * @param string $visiblename localised setting name
9107 * @param string $description setting description
9108 * @param array $defaultsetting a plain array of default module ids
9109 * @param bool $excludesystem If true, excludes modules with 'system' archetype
9111 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
9112 $excludesystem = true) {
9113 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
9114 $this->excludesystem = $excludesystem;
9118 * Loads an array of current module choices
9120 * @return bool always return true
9122 public function load_choices() {
9123 if (is_array($this->choices)) {
9124 return true;
9126 $this->choices = array();
9128 global $CFG, $DB;
9129 $records = $DB->get_records('modules', array('visible'=>1), 'name');
9130 foreach ($records as $record) {
9131 // Exclude modules if the code doesn't exist
9132 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
9133 // Also exclude system modules (if specified)
9134 if (!($this->excludesystem &&
9135 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
9136 MOD_ARCHETYPE_SYSTEM)) {
9137 $this->choices[$record->id] = $record->name;
9141 return true;
9146 * Admin setting to show if a php extension is enabled or not.
9148 * @copyright 2013 Damyon Wiese
9149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9151 class admin_setting_php_extension_enabled extends admin_setting {
9153 /** @var string The name of the extension to check for */
9154 private $extension;
9157 * Calls parent::__construct with specific arguments
9159 public function __construct($name, $visiblename, $description, $extension) {
9160 $this->extension = $extension;
9161 $this->nosave = true;
9162 parent::__construct($name, $visiblename, $description, '');
9166 * Always returns true, does nothing
9168 * @return true
9170 public function get_setting() {
9171 return true;
9175 * Always returns true, does nothing
9177 * @return true
9179 public function get_defaultsetting() {
9180 return true;
9184 * Always returns '', does not write anything
9186 * @return string Always returns ''
9188 public function write_setting($data) {
9189 // Do not write any setting.
9190 return '';
9194 * Outputs the html for this setting.
9195 * @return string Returns an XHTML string
9197 public function output_html($data, $query='') {
9198 global $OUTPUT;
9200 $o = '';
9201 if (!extension_loaded($this->extension)) {
9202 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
9204 $o .= format_admin_setting($this, $this->visiblename, $warning);
9206 return $o;
9211 * Server timezone setting.
9213 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9215 * @author Petr Skoda <petr.skoda@totaralms.com>
9217 class admin_setting_servertimezone extends admin_setting_configselect {
9219 * Constructor.
9221 public function __construct() {
9222 $default = core_date::get_default_php_timezone();
9223 if ($default === 'UTC') {
9224 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
9225 $default = 'Europe/London';
9228 parent::__construct('timezone',
9229 new lang_string('timezone', 'core_admin'),
9230 new lang_string('configtimezone', 'core_admin'), $default, null);
9234 * Lazy load timezone options.
9235 * @return bool true if loaded, false if error
9237 public function load_choices() {
9238 global $CFG;
9239 if (is_array($this->choices)) {
9240 return true;
9243 $current = isset($CFG->timezone) ? $CFG->timezone : null;
9244 $this->choices = core_date::get_list_of_timezones($current, false);
9245 if ($current == 99) {
9246 // Do not show 99 unless it is current value, we want to get rid of it over time.
9247 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
9248 core_date::get_default_php_timezone());
9251 return true;
9256 * Forced user timezone setting.
9258 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9260 * @author Petr Skoda <petr.skoda@totaralms.com>
9262 class admin_setting_forcetimezone extends admin_setting_configselect {
9264 * Constructor.
9266 public function __construct() {
9267 parent::__construct('forcetimezone',
9268 new lang_string('forcetimezone', 'core_admin'),
9269 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
9273 * Lazy load timezone options.
9274 * @return bool true if loaded, false if error
9276 public function load_choices() {
9277 global $CFG;
9278 if (is_array($this->choices)) {
9279 return true;
9282 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
9283 $this->choices = core_date::get_list_of_timezones($current, true);
9284 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
9286 return true;