Moodle release 2.9
[moodle.git] / lib / adminlib.php
blob485a7100e655353ae13ef73bd42d5ef4949253e2
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);
2187 * General text area without html editor.
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtextarea extends admin_setting_configtext {
2192 private $rows;
2193 private $cols;
2196 * @param string $name
2197 * @param string $visiblename
2198 * @param string $description
2199 * @param mixed $defaultsetting string or array
2200 * @param mixed $paramtype
2201 * @param string $cols The number of columns to make the editor
2202 * @param string $rows The number of rows to make the editor
2204 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2205 $this->rows = $rows;
2206 $this->cols = $cols;
2207 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2211 * Returns an XHTML string for the editor
2213 * @param string $data
2214 * @param string $query
2215 * @return string XHTML string for the editor
2217 public function output_html($data, $query='') {
2218 $default = $this->get_defaultsetting();
2220 $defaultinfo = $default;
2221 if (!is_null($default) and $default !== '') {
2222 $defaultinfo = "\n".$default;
2225 return format_admin_setting($this, $this->visiblename,
2226 '<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>',
2227 $this->description, true, '', $defaultinfo, $query);
2233 * General text area with html editor.
2235 class admin_setting_confightmleditor extends admin_setting_configtext {
2236 private $rows;
2237 private $cols;
2240 * @param string $name
2241 * @param string $visiblename
2242 * @param string $description
2243 * @param mixed $defaultsetting string or array
2244 * @param mixed $paramtype
2246 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2247 $this->rows = $rows;
2248 $this->cols = $cols;
2249 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2250 editors_head_setup();
2254 * Returns an XHTML string for the editor
2256 * @param string $data
2257 * @param string $query
2258 * @return string XHTML string for the editor
2260 public function output_html($data, $query='') {
2261 $default = $this->get_defaultsetting();
2263 $defaultinfo = $default;
2264 if (!is_null($default) and $default !== '') {
2265 $defaultinfo = "\n".$default;
2268 $editor = editors_get_preferred_editor(FORMAT_HTML);
2269 $editor->use_editor($this->get_id(), array('noclean'=>true));
2271 return format_admin_setting($this, $this->visiblename,
2272 '<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>',
2273 $this->description, true, '', $defaultinfo, $query);
2279 * Password field, allows unmasking of password
2281 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2283 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2285 * Constructor
2286 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2287 * @param string $visiblename localised
2288 * @param string $description long localised info
2289 * @param string $defaultsetting default password
2291 public function __construct($name, $visiblename, $description, $defaultsetting) {
2292 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2296 * Log config changes if necessary.
2297 * @param string $name
2298 * @param string $oldvalue
2299 * @param string $value
2301 protected function add_to_config_log($name, $oldvalue, $value) {
2302 if ($value !== '') {
2303 $value = '********';
2305 if ($oldvalue !== '' and $oldvalue !== null) {
2306 $oldvalue = '********';
2308 parent::add_to_config_log($name, $oldvalue, $value);
2312 * Returns XHTML for the field
2313 * Writes Javascript into the HTML below right before the last div
2315 * @todo Make javascript available through newer methods if possible
2316 * @param string $data Value for the field
2317 * @param string $query Passed as final argument for format_admin_setting
2318 * @return string XHTML field
2320 public function output_html($data, $query='') {
2321 $id = $this->get_id();
2322 $unmask = get_string('unmaskpassword', 'form');
2323 $unmaskjs = '<script type="text/javascript">
2324 //<![CDATA[
2325 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2327 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2329 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2331 var unmaskchb = document.createElement("input");
2332 unmaskchb.setAttribute("type", "checkbox");
2333 unmaskchb.setAttribute("id", "'.$id.'unmask");
2334 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2335 unmaskdiv.appendChild(unmaskchb);
2337 var unmasklbl = document.createElement("label");
2338 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2339 if (is_ie) {
2340 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2341 } else {
2342 unmasklbl.setAttribute("for", "'.$id.'unmask");
2344 unmaskdiv.appendChild(unmasklbl);
2346 if (is_ie) {
2347 // ugly hack to work around the famous onchange IE bug
2348 unmaskchb.onclick = function() {this.blur();};
2349 unmaskdiv.onclick = function() {this.blur();};
2351 //]]>
2352 </script>';
2353 return format_admin_setting($this, $this->visiblename,
2354 '<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>',
2355 $this->description, true, '', NULL, $query);
2360 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2361 * Note: Only advanced makes sense right now - locked does not.
2363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2365 class admin_setting_configempty extends admin_setting_configtext {
2368 * @param string $name
2369 * @param string $visiblename
2370 * @param string $description
2372 public function __construct($name, $visiblename, $description) {
2373 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2377 * Returns an XHTML string for the hidden field
2379 * @param string $data
2380 * @param string $query
2381 * @return string XHTML string for the editor
2383 public function output_html($data, $query='') {
2384 return format_admin_setting($this,
2385 $this->visiblename,
2386 '<div class="form-empty" >' .
2387 '<input type="hidden"' .
2388 ' id="'. $this->get_id() .'"' .
2389 ' name="'. $this->get_full_name() .'"' .
2390 ' value=""/></div>',
2391 $this->description,
2392 true,
2394 get_string('none'),
2395 $query);
2401 * Path to directory
2403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2405 class admin_setting_configfile extends admin_setting_configtext {
2407 * Constructor
2408 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2409 * @param string $visiblename localised
2410 * @param string $description long localised info
2411 * @param string $defaultdirectory default directory location
2413 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2414 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2418 * Returns XHTML for the field
2420 * Returns XHTML for the field and also checks whether the file
2421 * specified in $data exists using file_exists()
2423 * @param string $data File name and path to use in value attr
2424 * @param string $query
2425 * @return string XHTML field
2427 public function output_html($data, $query='') {
2428 global $CFG;
2429 $default = $this->get_defaultsetting();
2431 if ($data) {
2432 if (file_exists($data)) {
2433 $executable = '<span class="pathok">&#x2714;</span>';
2434 } else {
2435 $executable = '<span class="patherror">&#x2718;</span>';
2437 } else {
2438 $executable = '';
2440 $readonly = '';
2441 if (!empty($CFG->preventexecpath)) {
2442 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2443 $readonly = 'readonly="readonly"';
2446 return format_admin_setting($this, $this->visiblename,
2447 '<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>',
2448 $this->description, true, '', $default, $query);
2452 * Checks if execpatch has been disabled in config.php
2454 public function write_setting($data) {
2455 global $CFG;
2456 if (!empty($CFG->preventexecpath)) {
2457 if ($this->get_setting() === null) {
2458 // Use default during installation.
2459 $data = $this->get_defaultsetting();
2460 if ($data === null) {
2461 $data = '';
2463 } else {
2464 return '';
2467 return parent::write_setting($data);
2473 * Path to executable file
2475 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2477 class admin_setting_configexecutable extends admin_setting_configfile {
2480 * Returns an XHTML field
2482 * @param string $data This is the value for the field
2483 * @param string $query
2484 * @return string XHTML field
2486 public function output_html($data, $query='') {
2487 global $CFG;
2488 $default = $this->get_defaultsetting();
2490 if ($data) {
2491 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2492 $executable = '<span class="pathok">&#x2714;</span>';
2493 } else {
2494 $executable = '<span class="patherror">&#x2718;</span>';
2496 } else {
2497 $executable = '';
2499 $readonly = '';
2500 if (!empty($CFG->preventexecpath)) {
2501 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2502 $readonly = 'readonly="readonly"';
2505 return format_admin_setting($this, $this->visiblename,
2506 '<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>',
2507 $this->description, true, '', $default, $query);
2513 * Path to directory
2515 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2517 class admin_setting_configdirectory extends admin_setting_configfile {
2520 * Returns an XHTML field
2522 * @param string $data This is the value for the field
2523 * @param string $query
2524 * @return string XHTML
2526 public function output_html($data, $query='') {
2527 global $CFG;
2528 $default = $this->get_defaultsetting();
2530 if ($data) {
2531 if (file_exists($data) and is_dir($data)) {
2532 $executable = '<span class="pathok">&#x2714;</span>';
2533 } else {
2534 $executable = '<span class="patherror">&#x2718;</span>';
2536 } else {
2537 $executable = '';
2539 $readonly = '';
2540 if (!empty($CFG->preventexecpath)) {
2541 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2542 $readonly = 'readonly="readonly"';
2545 return format_admin_setting($this, $this->visiblename,
2546 '<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>',
2547 $this->description, true, '', $default, $query);
2553 * Checkbox
2555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2557 class admin_setting_configcheckbox extends admin_setting {
2558 /** @var string Value used when checked */
2559 public $yes;
2560 /** @var string Value used when not checked */
2561 public $no;
2564 * Constructor
2565 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2566 * @param string $visiblename localised
2567 * @param string $description long localised info
2568 * @param string $defaultsetting
2569 * @param string $yes value used when checked
2570 * @param string $no value used when not checked
2572 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2573 parent::__construct($name, $visiblename, $description, $defaultsetting);
2574 $this->yes = (string)$yes;
2575 $this->no = (string)$no;
2579 * Retrieves the current setting using the objects name
2581 * @return string
2583 public function get_setting() {
2584 return $this->config_read($this->name);
2588 * Sets the value for the setting
2590 * Sets the value for the setting to either the yes or no values
2591 * of the object by comparing $data to yes
2593 * @param mixed $data Gets converted to str for comparison against yes value
2594 * @return string empty string or error
2596 public function write_setting($data) {
2597 if ((string)$data === $this->yes) { // convert to strings before comparison
2598 $data = $this->yes;
2599 } else {
2600 $data = $this->no;
2602 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2606 * Returns an XHTML checkbox field
2608 * @param string $data If $data matches yes then checkbox is checked
2609 * @param string $query
2610 * @return string XHTML field
2612 public function output_html($data, $query='') {
2613 $default = $this->get_defaultsetting();
2615 if (!is_null($default)) {
2616 if ((string)$default === $this->yes) {
2617 $defaultinfo = get_string('checkboxyes', 'admin');
2618 } else {
2619 $defaultinfo = get_string('checkboxno', 'admin');
2621 } else {
2622 $defaultinfo = NULL;
2625 if ((string)$data === $this->yes) { // convert to strings before comparison
2626 $checked = 'checked="checked"';
2627 } else {
2628 $checked = '';
2631 return format_admin_setting($this, $this->visiblename,
2632 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2633 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2634 $this->description, true, '', $defaultinfo, $query);
2640 * Multiple checkboxes, each represents different value, stored in csv format
2642 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2644 class admin_setting_configmulticheckbox extends admin_setting {
2645 /** @var array Array of choices value=>label */
2646 public $choices;
2649 * Constructor: uses parent::__construct
2651 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2652 * @param string $visiblename localised
2653 * @param string $description long localised info
2654 * @param array $defaultsetting array of selected
2655 * @param array $choices array of $value=>$label for each checkbox
2657 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2658 $this->choices = $choices;
2659 parent::__construct($name, $visiblename, $description, $defaultsetting);
2663 * This public function may be used in ancestors for lazy loading of choices
2665 * @todo Check if this function is still required content commented out only returns true
2666 * @return bool true if loaded, false if error
2668 public function load_choices() {
2670 if (is_array($this->choices)) {
2671 return true;
2673 .... load choices here
2675 return true;
2679 * Is setting related to query text - used when searching
2681 * @param string $query
2682 * @return bool true on related, false on not or failure
2684 public function is_related($query) {
2685 if (!$this->load_choices() or empty($this->choices)) {
2686 return false;
2688 if (parent::is_related($query)) {
2689 return true;
2692 foreach ($this->choices as $desc) {
2693 if (strpos(core_text::strtolower($desc), $query) !== false) {
2694 return true;
2697 return false;
2701 * Returns the current setting if it is set
2703 * @return mixed null if null, else an array
2705 public function get_setting() {
2706 $result = $this->config_read($this->name);
2708 if (is_null($result)) {
2709 return NULL;
2711 if ($result === '') {
2712 return array();
2714 $enabled = explode(',', $result);
2715 $setting = array();
2716 foreach ($enabled as $option) {
2717 $setting[$option] = 1;
2719 return $setting;
2723 * Saves the setting(s) provided in $data
2725 * @param array $data An array of data, if not array returns empty str
2726 * @return mixed empty string on useless data or bool true=success, false=failed
2728 public function write_setting($data) {
2729 if (!is_array($data)) {
2730 return ''; // ignore it
2732 if (!$this->load_choices() or empty($this->choices)) {
2733 return '';
2735 unset($data['xxxxx']);
2736 $result = array();
2737 foreach ($data as $key => $value) {
2738 if ($value and array_key_exists($key, $this->choices)) {
2739 $result[] = $key;
2742 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2746 * Returns XHTML field(s) as required by choices
2748 * Relies on data being an array should data ever be another valid vartype with
2749 * acceptable value this may cause a warning/error
2750 * if (!is_array($data)) would fix the problem
2752 * @todo Add vartype handling to ensure $data is an array
2754 * @param array $data An array of checked values
2755 * @param string $query
2756 * @return string XHTML field
2758 public function output_html($data, $query='') {
2759 if (!$this->load_choices() or empty($this->choices)) {
2760 return '';
2762 $default = $this->get_defaultsetting();
2763 if (is_null($default)) {
2764 $default = array();
2766 if (is_null($data)) {
2767 $data = array();
2769 $options = array();
2770 $defaults = array();
2771 foreach ($this->choices as $key=>$description) {
2772 if (!empty($data[$key])) {
2773 $checked = 'checked="checked"';
2774 } else {
2775 $checked = '';
2777 if (!empty($default[$key])) {
2778 $defaults[] = $description;
2781 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2782 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2785 if (is_null($default)) {
2786 $defaultinfo = NULL;
2787 } else if (!empty($defaults)) {
2788 $defaultinfo = implode(', ', $defaults);
2789 } else {
2790 $defaultinfo = get_string('none');
2793 $return = '<div class="form-multicheckbox">';
2794 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2795 if ($options) {
2796 $return .= '<ul>';
2797 foreach ($options as $option) {
2798 $return .= '<li>'.$option.'</li>';
2800 $return .= '</ul>';
2802 $return .= '</div>';
2804 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2811 * Multiple checkboxes 2, value stored as string 00101011
2813 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2815 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2818 * Returns the setting if set
2820 * @return mixed null if not set, else an array of set settings
2822 public function get_setting() {
2823 $result = $this->config_read($this->name);
2824 if (is_null($result)) {
2825 return NULL;
2827 if (!$this->load_choices()) {
2828 return NULL;
2830 $result = str_pad($result, count($this->choices), '0');
2831 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2832 $setting = array();
2833 foreach ($this->choices as $key=>$unused) {
2834 $value = array_shift($result);
2835 if ($value) {
2836 $setting[$key] = 1;
2839 return $setting;
2843 * Save setting(s) provided in $data param
2845 * @param array $data An array of settings to save
2846 * @return mixed empty string for bad data or bool true=>success, false=>error
2848 public function write_setting($data) {
2849 if (!is_array($data)) {
2850 return ''; // ignore it
2852 if (!$this->load_choices() or empty($this->choices)) {
2853 return '';
2855 $result = '';
2856 foreach ($this->choices as $key=>$unused) {
2857 if (!empty($data[$key])) {
2858 $result .= '1';
2859 } else {
2860 $result .= '0';
2863 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2869 * Select one value from list
2871 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2873 class admin_setting_configselect extends admin_setting {
2874 /** @var array Array of choices value=>label */
2875 public $choices;
2878 * Constructor
2879 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2880 * @param string $visiblename localised
2881 * @param string $description long localised info
2882 * @param string|int $defaultsetting
2883 * @param array $choices array of $value=>$label for each selection
2885 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2886 $this->choices = $choices;
2887 parent::__construct($name, $visiblename, $description, $defaultsetting);
2891 * This function may be used in ancestors for lazy loading of choices
2893 * Override this method if loading of choices is expensive, such
2894 * as when it requires multiple db requests.
2896 * @return bool true if loaded, false if error
2898 public function load_choices() {
2900 if (is_array($this->choices)) {
2901 return true;
2903 .... load choices here
2905 return true;
2909 * Check if this is $query is related to a choice
2911 * @param string $query
2912 * @return bool true if related, false if not
2914 public function is_related($query) {
2915 if (parent::is_related($query)) {
2916 return true;
2918 if (!$this->load_choices()) {
2919 return false;
2921 foreach ($this->choices as $key=>$value) {
2922 if (strpos(core_text::strtolower($key), $query) !== false) {
2923 return true;
2925 if (strpos(core_text::strtolower($value), $query) !== false) {
2926 return true;
2929 return false;
2933 * Return the setting
2935 * @return mixed returns config if successful else null
2937 public function get_setting() {
2938 return $this->config_read($this->name);
2942 * Save a setting
2944 * @param string $data
2945 * @return string empty of error string
2947 public function write_setting($data) {
2948 if (!$this->load_choices() or empty($this->choices)) {
2949 return '';
2951 if (!array_key_exists($data, $this->choices)) {
2952 return ''; // ignore it
2955 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2959 * Returns XHTML select field
2961 * Ensure the options are loaded, and generate the XHTML for the select
2962 * element and any warning message. Separating this out from output_html
2963 * makes it easier to subclass this class.
2965 * @param string $data the option to show as selected.
2966 * @param string $current the currently selected option in the database, null if none.
2967 * @param string $default the default selected option.
2968 * @return array the HTML for the select element, and a warning message.
2970 public function output_select_html($data, $current, $default, $extraname = '') {
2971 if (!$this->load_choices() or empty($this->choices)) {
2972 return array('', '');
2975 $warning = '';
2976 if (is_null($current)) {
2977 // first run
2978 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2979 // no warning
2980 } else if (!array_key_exists($current, $this->choices)) {
2981 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2982 if (!is_null($default) and $data == $current) {
2983 $data = $default; // use default instead of first value when showing the form
2987 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2988 foreach ($this->choices as $key => $value) {
2989 // the string cast is needed because key may be integer - 0 is equal to most strings!
2990 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2992 $selecthtml .= '</select>';
2993 return array($selecthtml, $warning);
2997 * Returns XHTML select field and wrapping div(s)
2999 * @see output_select_html()
3001 * @param string $data the option to show as selected
3002 * @param string $query
3003 * @return string XHTML field and wrapping div
3005 public function output_html($data, $query='') {
3006 $default = $this->get_defaultsetting();
3007 $current = $this->get_setting();
3009 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3010 if (!$selecthtml) {
3011 return '';
3014 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3015 $defaultinfo = $this->choices[$default];
3016 } else {
3017 $defaultinfo = NULL;
3020 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3022 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3028 * Select multiple items from list
3030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3032 class admin_setting_configmultiselect extends admin_setting_configselect {
3034 * Constructor
3035 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3036 * @param string $visiblename localised
3037 * @param string $description long localised info
3038 * @param array $defaultsetting array of selected items
3039 * @param array $choices array of $value=>$label for each list item
3041 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3042 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3046 * Returns the select setting(s)
3048 * @return mixed null or array. Null if no settings else array of setting(s)
3050 public function get_setting() {
3051 $result = $this->config_read($this->name);
3052 if (is_null($result)) {
3053 return NULL;
3055 if ($result === '') {
3056 return array();
3058 return explode(',', $result);
3062 * Saves setting(s) provided through $data
3064 * Potential bug in the works should anyone call with this function
3065 * using a vartype that is not an array
3067 * @param array $data
3069 public function write_setting($data) {
3070 if (!is_array($data)) {
3071 return ''; //ignore it
3073 if (!$this->load_choices() or empty($this->choices)) {
3074 return '';
3077 unset($data['xxxxx']);
3079 $save = array();
3080 foreach ($data as $value) {
3081 if (!array_key_exists($value, $this->choices)) {
3082 continue; // ignore it
3084 $save[] = $value;
3087 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3091 * Is setting related to query text - used when searching
3093 * @param string $query
3094 * @return bool true if related, false if not
3096 public function is_related($query) {
3097 if (!$this->load_choices() or empty($this->choices)) {
3098 return false;
3100 if (parent::is_related($query)) {
3101 return true;
3104 foreach ($this->choices as $desc) {
3105 if (strpos(core_text::strtolower($desc), $query) !== false) {
3106 return true;
3109 return false;
3113 * Returns XHTML multi-select field
3115 * @todo Add vartype handling to ensure $data is an array
3116 * @param array $data Array of values to select by default
3117 * @param string $query
3118 * @return string XHTML multi-select field
3120 public function output_html($data, $query='') {
3121 if (!$this->load_choices() or empty($this->choices)) {
3122 return '';
3124 $choices = $this->choices;
3125 $default = $this->get_defaultsetting();
3126 if (is_null($default)) {
3127 $default = array();
3129 if (is_null($data)) {
3130 $data = array();
3133 $defaults = array();
3134 $size = min(10, count($this->choices));
3135 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3136 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3137 foreach ($this->choices as $key => $description) {
3138 if (in_array($key, $data)) {
3139 $selected = 'selected="selected"';
3140 } else {
3141 $selected = '';
3143 if (in_array($key, $default)) {
3144 $defaults[] = $description;
3147 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3150 if (is_null($default)) {
3151 $defaultinfo = NULL;
3152 } if (!empty($defaults)) {
3153 $defaultinfo = implode(', ', $defaults);
3154 } else {
3155 $defaultinfo = get_string('none');
3158 $return .= '</select></div>';
3159 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3164 * Time selector
3166 * This is a liiitle bit messy. we're using two selects, but we're returning
3167 * them as an array named after $name (so we only use $name2 internally for the setting)
3169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3171 class admin_setting_configtime extends admin_setting {
3172 /** @var string Used for setting second select (minutes) */
3173 public $name2;
3176 * Constructor
3177 * @param string $hoursname setting for hours
3178 * @param string $minutesname setting for hours
3179 * @param string $visiblename localised
3180 * @param string $description long localised info
3181 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3183 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3184 $this->name2 = $minutesname;
3185 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3189 * Get the selected time
3191 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3193 public function get_setting() {
3194 $result1 = $this->config_read($this->name);
3195 $result2 = $this->config_read($this->name2);
3196 if (is_null($result1) or is_null($result2)) {
3197 return NULL;
3200 return array('h' => $result1, 'm' => $result2);
3204 * Store the time (hours and minutes)
3206 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3207 * @return bool true if success, false if not
3209 public function write_setting($data) {
3210 if (!is_array($data)) {
3211 return '';
3214 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3215 return ($result ? '' : get_string('errorsetting', 'admin'));
3219 * Returns XHTML time select fields
3221 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3222 * @param string $query
3223 * @return string XHTML time select fields and wrapping div(s)
3225 public function output_html($data, $query='') {
3226 $default = $this->get_defaultsetting();
3228 if (is_array($default)) {
3229 $defaultinfo = $default['h'].':'.$default['m'];
3230 } else {
3231 $defaultinfo = NULL;
3234 $return = '<div class="form-time defaultsnext">';
3235 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3236 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3237 for ($i = 0; $i < 24; $i++) {
3238 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3240 $return .= '</select>:';
3241 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3242 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3243 for ($i = 0; $i < 60; $i += 5) {
3244 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3246 $return .= '</select>';
3247 $return .= '</div>';
3248 return format_admin_setting($this, $this->visiblename, $return, $this->description,
3249 $this->get_id() . 'h', '', $defaultinfo, $query);
3256 * Seconds duration setting.
3258 * @copyright 2012 Petr Skoda (http://skodak.org)
3259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3261 class admin_setting_configduration extends admin_setting {
3263 /** @var int default duration unit */
3264 protected $defaultunit;
3267 * Constructor
3268 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3269 * or 'myplugin/mysetting' for ones in config_plugins.
3270 * @param string $visiblename localised name
3271 * @param string $description localised long description
3272 * @param mixed $defaultsetting string or array depending on implementation
3273 * @param int $defaultunit - day, week, etc. (in seconds)
3275 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3276 if (is_number($defaultsetting)) {
3277 $defaultsetting = self::parse_seconds($defaultsetting);
3279 $units = self::get_units();
3280 if (isset($units[$defaultunit])) {
3281 $this->defaultunit = $defaultunit;
3282 } else {
3283 $this->defaultunit = 86400;
3285 parent::__construct($name, $visiblename, $description, $defaultsetting);
3289 * Returns selectable units.
3290 * @static
3291 * @return array
3293 protected static function get_units() {
3294 return array(
3295 604800 => get_string('weeks'),
3296 86400 => get_string('days'),
3297 3600 => get_string('hours'),
3298 60 => get_string('minutes'),
3299 1 => get_string('seconds'),
3304 * Converts seconds to some more user friendly string.
3305 * @static
3306 * @param int $seconds
3307 * @return string
3309 protected static function get_duration_text($seconds) {
3310 if (empty($seconds)) {
3311 return get_string('none');
3313 $data = self::parse_seconds($seconds);
3314 switch ($data['u']) {
3315 case (60*60*24*7):
3316 return get_string('numweeks', '', $data['v']);
3317 case (60*60*24):
3318 return get_string('numdays', '', $data['v']);
3319 case (60*60):
3320 return get_string('numhours', '', $data['v']);
3321 case (60):
3322 return get_string('numminutes', '', $data['v']);
3323 default:
3324 return get_string('numseconds', '', $data['v']*$data['u']);
3329 * Finds suitable units for given duration.
3330 * @static
3331 * @param int $seconds
3332 * @return array
3334 protected static function parse_seconds($seconds) {
3335 foreach (self::get_units() as $unit => $unused) {
3336 if ($seconds % $unit === 0) {
3337 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3340 return array('v'=>(int)$seconds, 'u'=>1);
3344 * Get the selected duration as array.
3346 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3348 public function get_setting() {
3349 $seconds = $this->config_read($this->name);
3350 if (is_null($seconds)) {
3351 return null;
3354 return self::parse_seconds($seconds);
3358 * Store the duration as seconds.
3360 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3361 * @return bool true if success, false if not
3363 public function write_setting($data) {
3364 if (!is_array($data)) {
3365 return '';
3368 $seconds = (int)($data['v']*$data['u']);
3369 if ($seconds < 0) {
3370 return get_string('errorsetting', 'admin');
3373 $result = $this->config_write($this->name, $seconds);
3374 return ($result ? '' : get_string('errorsetting', 'admin'));
3378 * Returns duration text+select fields.
3380 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3381 * @param string $query
3382 * @return string duration text+select fields and wrapping div(s)
3384 public function output_html($data, $query='') {
3385 $default = $this->get_defaultsetting();
3387 if (is_number($default)) {
3388 $defaultinfo = self::get_duration_text($default);
3389 } else if (is_array($default)) {
3390 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3391 } else {
3392 $defaultinfo = null;
3395 $units = self::get_units();
3397 $inputid = $this->get_id() . 'v';
3399 $return = '<div class="form-duration defaultsnext">';
3400 $return .= '<input type="text" size="5" id="' . $inputid . '" name="' . $this->get_full_name() .
3401 '[v]" value="' . s($data['v']) . '" />';
3402 $return .= '<label for="' . $this->get_id() . 'u" class="accesshide">' .
3403 get_string('durationunits', 'admin') . '</label>';
3404 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3405 foreach ($units as $val => $text) {
3406 $selected = '';
3407 if ($data['v'] == 0) {
3408 if ($val == $this->defaultunit) {
3409 $selected = ' selected="selected"';
3411 } else if ($val == $data['u']) {
3412 $selected = ' selected="selected"';
3414 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3416 $return .= '</select></div>';
3417 return format_admin_setting($this, $this->visiblename, $return, $this->description, $inputid, '', $defaultinfo, $query);
3423 * Seconds duration setting with an advanced checkbox, that controls a additional
3424 * $name.'_adv' setting.
3426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3427 * @copyright 2014 The Open University
3429 class admin_setting_configduration_with_advanced extends admin_setting_configduration {
3431 * Constructor
3432 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3433 * or 'myplugin/mysetting' for ones in config_plugins.
3434 * @param string $visiblename localised name
3435 * @param string $description localised long description
3436 * @param array $defaultsetting array of int value, and bool whether it is
3437 * is advanced by default.
3438 * @param int $defaultunit - day, week, etc. (in seconds)
3440 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3441 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $defaultunit);
3442 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
3448 * Used to validate a textarea used for ip addresses
3450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3451 * @copyright 2011 Petr Skoda (http://skodak.org)
3453 class admin_setting_configiplist extends admin_setting_configtextarea {
3456 * Validate the contents of the textarea as IP addresses
3458 * Used to validate a new line separated list of IP addresses collected from
3459 * a textarea control
3461 * @param string $data A list of IP Addresses separated by new lines
3462 * @return mixed bool true for success or string:error on failure
3464 public function validate($data) {
3465 if(!empty($data)) {
3466 $ips = explode("\n", $data);
3467 } else {
3468 return true;
3470 $result = true;
3471 foreach($ips as $ip) {
3472 $ip = trim($ip);
3473 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3474 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3475 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3476 $result = true;
3477 } else {
3478 $result = false;
3479 break;
3482 if($result) {
3483 return true;
3484 } else {
3485 return get_string('validateerror', 'admin');
3492 * An admin setting for selecting one or more users who have a capability
3493 * in the system context
3495 * An admin setting for selecting one or more users, who have a particular capability
3496 * in the system context. Warning, make sure the list will never be too long. There is
3497 * no paging or searching of this list.
3499 * To correctly get a list of users from this config setting, you need to call the
3500 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3502 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3504 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3505 /** @var string The capabilities name */
3506 protected $capability;
3507 /** @var int include admin users too */
3508 protected $includeadmins;
3511 * Constructor.
3513 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3514 * @param string $visiblename localised name
3515 * @param string $description localised long description
3516 * @param array $defaultsetting array of usernames
3517 * @param string $capability string capability name.
3518 * @param bool $includeadmins include administrators
3520 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3521 $this->capability = $capability;
3522 $this->includeadmins = $includeadmins;
3523 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3527 * Load all of the uses who have the capability into choice array
3529 * @return bool Always returns true
3531 function load_choices() {
3532 if (is_array($this->choices)) {
3533 return true;
3535 list($sort, $sortparams) = users_order_by_sql('u');
3536 if (!empty($sortparams)) {
3537 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3538 'This is unexpected, and a problem because there is no way to pass these ' .
3539 'parameters to get_users_by_capability. See MDL-34657.');
3541 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3542 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3543 $this->choices = array(
3544 '$@NONE@$' => get_string('nobody'),
3545 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3547 if ($this->includeadmins) {
3548 $admins = get_admins();
3549 foreach ($admins as $user) {
3550 $this->choices[$user->id] = fullname($user);
3553 if (is_array($users)) {
3554 foreach ($users as $user) {
3555 $this->choices[$user->id] = fullname($user);
3558 return true;
3562 * Returns the default setting for class
3564 * @return mixed Array, or string. Empty string if no default
3566 public function get_defaultsetting() {
3567 $this->load_choices();
3568 $defaultsetting = parent::get_defaultsetting();
3569 if (empty($defaultsetting)) {
3570 return array('$@NONE@$');
3571 } else if (array_key_exists($defaultsetting, $this->choices)) {
3572 return $defaultsetting;
3573 } else {
3574 return '';
3579 * Returns the current setting
3581 * @return mixed array or string
3583 public function get_setting() {
3584 $result = parent::get_setting();
3585 if ($result === null) {
3586 // this is necessary for settings upgrade
3587 return null;
3589 if (empty($result)) {
3590 $result = array('$@NONE@$');
3592 return $result;
3596 * Save the chosen setting provided as $data
3598 * @param array $data
3599 * @return mixed string or array
3601 public function write_setting($data) {
3602 // If all is selected, remove any explicit options.
3603 if (in_array('$@ALL@$', $data)) {
3604 $data = array('$@ALL@$');
3606 // None never needs to be written to the DB.
3607 if (in_array('$@NONE@$', $data)) {
3608 unset($data[array_search('$@NONE@$', $data)]);
3610 return parent::write_setting($data);
3616 * Special checkbox for calendar - resets SESSION vars.
3618 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3620 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3622 * Calls the parent::__construct with default values
3624 * name => calendar_adminseesall
3625 * visiblename => get_string('adminseesall', 'admin')
3626 * description => get_string('helpadminseesall', 'admin')
3627 * defaultsetting => 0
3629 public function __construct() {
3630 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3631 get_string('helpadminseesall', 'admin'), '0');
3635 * Stores the setting passed in $data
3637 * @param mixed gets converted to string for comparison
3638 * @return string empty string or error message
3640 public function write_setting($data) {
3641 global $SESSION;
3642 return parent::write_setting($data);
3647 * Special select for settings that are altered in setup.php and can not be altered on the fly
3649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3651 class admin_setting_special_selectsetup extends admin_setting_configselect {
3653 * Reads the setting directly from the database
3655 * @return mixed
3657 public function get_setting() {
3658 // read directly from db!
3659 return get_config(NULL, $this->name);
3663 * Save the setting passed in $data
3665 * @param string $data The setting to save
3666 * @return string empty or error message
3668 public function write_setting($data) {
3669 global $CFG;
3670 // do not change active CFG setting!
3671 $current = $CFG->{$this->name};
3672 $result = parent::write_setting($data);
3673 $CFG->{$this->name} = $current;
3674 return $result;
3680 * Special select for frontpage - stores data in course table
3682 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3684 class admin_setting_sitesetselect extends admin_setting_configselect {
3686 * Returns the site name for the selected site
3688 * @see get_site()
3689 * @return string The site name of the selected site
3691 public function get_setting() {
3692 $site = course_get_format(get_site())->get_course();
3693 return $site->{$this->name};
3697 * Updates the database and save the setting
3699 * @param string data
3700 * @return string empty or error message
3702 public function write_setting($data) {
3703 global $DB, $SITE, $COURSE;
3704 if (!in_array($data, array_keys($this->choices))) {
3705 return get_string('errorsetting', 'admin');
3707 $record = new stdClass();
3708 $record->id = SITEID;
3709 $temp = $this->name;
3710 $record->$temp = $data;
3711 $record->timemodified = time();
3713 course_get_format($SITE)->update_course_format_options($record);
3714 $DB->update_record('course', $record);
3716 // Reset caches.
3717 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3718 if ($SITE->id == $COURSE->id) {
3719 $COURSE = $SITE;
3721 format_base::reset_course_cache($SITE->id);
3723 return '';
3730 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3731 * block to hidden.
3733 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3735 class admin_setting_bloglevel extends admin_setting_configselect {
3737 * Updates the database and save the setting
3739 * @param string data
3740 * @return string empty or error message
3742 public function write_setting($data) {
3743 global $DB, $CFG;
3744 if ($data == 0) {
3745 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3746 foreach ($blogblocks as $block) {
3747 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3749 } else {
3750 // reenable all blocks only when switching from disabled blogs
3751 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3752 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3753 foreach ($blogblocks as $block) {
3754 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3758 return parent::write_setting($data);
3764 * Special select - lists on the frontpage - hacky
3766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3768 class admin_setting_courselist_frontpage extends admin_setting {
3769 /** @var array Array of choices value=>label */
3770 public $choices;
3773 * Construct override, requires one param
3775 * @param bool $loggedin Is the user logged in
3777 public function __construct($loggedin) {
3778 global $CFG;
3779 require_once($CFG->dirroot.'/course/lib.php');
3780 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3781 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3782 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3783 $defaults = array(FRONTPAGEALLCOURSELIST);
3784 parent::__construct($name, $visiblename, $description, $defaults);
3788 * Loads the choices available
3790 * @return bool always returns true
3792 public function load_choices() {
3793 if (is_array($this->choices)) {
3794 return true;
3796 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3797 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3798 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3799 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3800 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3801 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3802 'none' => get_string('none'));
3803 if ($this->name === 'frontpage') {
3804 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3806 return true;
3810 * Returns the selected settings
3812 * @param mixed array or setting or null
3814 public function get_setting() {
3815 $result = $this->config_read($this->name);
3816 if (is_null($result)) {
3817 return NULL;
3819 if ($result === '') {
3820 return array();
3822 return explode(',', $result);
3826 * Save the selected options
3828 * @param array $data
3829 * @return mixed empty string (data is not an array) or bool true=success false=failure
3831 public function write_setting($data) {
3832 if (!is_array($data)) {
3833 return '';
3835 $this->load_choices();
3836 $save = array();
3837 foreach($data as $datum) {
3838 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3839 continue;
3841 $save[$datum] = $datum; // no duplicates
3843 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3847 * Return XHTML select field and wrapping div
3849 * @todo Add vartype handling to make sure $data is an array
3850 * @param array $data Array of elements to select by default
3851 * @return string XHTML select field and wrapping div
3853 public function output_html($data, $query='') {
3854 $this->load_choices();
3855 $currentsetting = array();
3856 foreach ($data as $key) {
3857 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3858 $currentsetting[] = $key; // already selected first
3862 $return = '<div class="form-group">';
3863 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3864 if (!array_key_exists($i, $currentsetting)) {
3865 $currentsetting[$i] = 'none'; //none
3867 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3868 foreach ($this->choices as $key => $value) {
3869 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3871 $return .= '</select>';
3872 if ($i !== count($this->choices) - 2) {
3873 $return .= '<br />';
3876 $return .= '</div>';
3878 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3884 * Special checkbox for frontpage - stores data in course table
3886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3888 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3890 * Returns the current sites name
3892 * @return string
3894 public function get_setting() {
3895 $site = course_get_format(get_site())->get_course();
3896 return $site->{$this->name};
3900 * Save the selected setting
3902 * @param string $data The selected site
3903 * @return string empty string or error message
3905 public function write_setting($data) {
3906 global $DB, $SITE, $COURSE;
3907 $record = new stdClass();
3908 $record->id = $SITE->id;
3909 $record->{$this->name} = ($data == '1' ? 1 : 0);
3910 $record->timemodified = time();
3912 course_get_format($SITE)->update_course_format_options($record);
3913 $DB->update_record('course', $record);
3915 // Reset caches.
3916 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3917 if ($SITE->id == $COURSE->id) {
3918 $COURSE = $SITE;
3920 format_base::reset_course_cache($SITE->id);
3922 return '';
3927 * Special text for frontpage - stores data in course table.
3928 * Empty string means not set here. Manual setting is required.
3930 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3932 class admin_setting_sitesettext extends admin_setting_configtext {
3934 * Return the current setting
3936 * @return mixed string or null
3938 public function get_setting() {
3939 $site = course_get_format(get_site())->get_course();
3940 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3944 * Validate the selected data
3946 * @param string $data The selected value to validate
3947 * @return mixed true or message string
3949 public function validate($data) {
3950 $cleaned = clean_param($data, PARAM_TEXT);
3951 if ($cleaned === '') {
3952 return get_string('required');
3954 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3955 return true;
3956 } else {
3957 return get_string('validateerror', 'admin');
3962 * Save the selected setting
3964 * @param string $data The selected value
3965 * @return string empty or error message
3967 public function write_setting($data) {
3968 global $DB, $SITE, $COURSE;
3969 $data = trim($data);
3970 $validated = $this->validate($data);
3971 if ($validated !== true) {
3972 return $validated;
3975 $record = new stdClass();
3976 $record->id = $SITE->id;
3977 $record->{$this->name} = $data;
3978 $record->timemodified = time();
3980 course_get_format($SITE)->update_course_format_options($record);
3981 $DB->update_record('course', $record);
3983 // Reset caches.
3984 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3985 if ($SITE->id == $COURSE->id) {
3986 $COURSE = $SITE;
3988 format_base::reset_course_cache($SITE->id);
3990 return '';
3996 * Special text editor for site description.
3998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4000 class admin_setting_special_frontpagedesc extends admin_setting {
4002 * Calls parent::__construct with specific arguments
4004 public function __construct() {
4005 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
4006 editors_head_setup();
4010 * Return the current setting
4011 * @return string The current setting
4013 public function get_setting() {
4014 $site = course_get_format(get_site())->get_course();
4015 return $site->{$this->name};
4019 * Save the new setting
4021 * @param string $data The new value to save
4022 * @return string empty or error message
4024 public function write_setting($data) {
4025 global $DB, $SITE, $COURSE;
4026 $record = new stdClass();
4027 $record->id = $SITE->id;
4028 $record->{$this->name} = $data;
4029 $record->timemodified = time();
4031 course_get_format($SITE)->update_course_format_options($record);
4032 $DB->update_record('course', $record);
4034 // Reset caches.
4035 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4036 if ($SITE->id == $COURSE->id) {
4037 $COURSE = $SITE;
4039 format_base::reset_course_cache($SITE->id);
4041 return '';
4045 * Returns XHTML for the field plus wrapping div
4047 * @param string $data The current value
4048 * @param string $query
4049 * @return string The XHTML output
4051 public function output_html($data, $query='') {
4052 global $CFG;
4054 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4056 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4062 * Administration interface for emoticon_manager settings.
4064 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4066 class admin_setting_emoticons extends admin_setting {
4069 * Calls parent::__construct with specific args
4071 public function __construct() {
4072 global $CFG;
4074 $manager = get_emoticon_manager();
4075 $defaults = $this->prepare_form_data($manager->default_emoticons());
4076 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4080 * Return the current setting(s)
4082 * @return array Current settings array
4084 public function get_setting() {
4085 global $CFG;
4087 $manager = get_emoticon_manager();
4089 $config = $this->config_read($this->name);
4090 if (is_null($config)) {
4091 return null;
4094 $config = $manager->decode_stored_config($config);
4095 if (is_null($config)) {
4096 return null;
4099 return $this->prepare_form_data($config);
4103 * Save selected settings
4105 * @param array $data Array of settings to save
4106 * @return bool
4108 public function write_setting($data) {
4110 $manager = get_emoticon_manager();
4111 $emoticons = $this->process_form_data($data);
4113 if ($emoticons === false) {
4114 return false;
4117 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4118 return ''; // success
4119 } else {
4120 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4125 * Return XHTML field(s) for options
4127 * @param array $data Array of options to set in HTML
4128 * @return string XHTML string for the fields and wrapping div(s)
4130 public function output_html($data, $query='') {
4131 global $OUTPUT;
4133 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4134 $out .= html_writer::start_tag('thead');
4135 $out .= html_writer::start_tag('tr');
4136 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4137 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4138 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4139 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4140 $out .= html_writer::tag('th', '');
4141 $out .= html_writer::end_tag('tr');
4142 $out .= html_writer::end_tag('thead');
4143 $out .= html_writer::start_tag('tbody');
4144 $i = 0;
4145 foreach($data as $field => $value) {
4146 switch ($i) {
4147 case 0:
4148 $out .= html_writer::start_tag('tr');
4149 $current_text = $value;
4150 $current_filename = '';
4151 $current_imagecomponent = '';
4152 $current_altidentifier = '';
4153 $current_altcomponent = '';
4154 case 1:
4155 $current_filename = $value;
4156 case 2:
4157 $current_imagecomponent = $value;
4158 case 3:
4159 $current_altidentifier = $value;
4160 case 4:
4161 $current_altcomponent = $value;
4164 $out .= html_writer::tag('td',
4165 html_writer::empty_tag('input',
4166 array(
4167 'type' => 'text',
4168 'class' => 'form-text',
4169 'name' => $this->get_full_name().'['.$field.']',
4170 'value' => $value,
4172 ), array('class' => 'c'.$i)
4175 if ($i == 4) {
4176 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4177 $alt = get_string($current_altidentifier, $current_altcomponent);
4178 } else {
4179 $alt = $current_text;
4181 if ($current_filename) {
4182 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4183 } else {
4184 $out .= html_writer::tag('td', '');
4186 $out .= html_writer::end_tag('tr');
4187 $i = 0;
4188 } else {
4189 $i++;
4193 $out .= html_writer::end_tag('tbody');
4194 $out .= html_writer::end_tag('table');
4195 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4196 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4198 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4202 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4204 * @see self::process_form_data()
4205 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4206 * @return array of form fields and their values
4208 protected function prepare_form_data(array $emoticons) {
4210 $form = array();
4211 $i = 0;
4212 foreach ($emoticons as $emoticon) {
4213 $form['text'.$i] = $emoticon->text;
4214 $form['imagename'.$i] = $emoticon->imagename;
4215 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4216 $form['altidentifier'.$i] = $emoticon->altidentifier;
4217 $form['altcomponent'.$i] = $emoticon->altcomponent;
4218 $i++;
4220 // add one more blank field set for new object
4221 $form['text'.$i] = '';
4222 $form['imagename'.$i] = '';
4223 $form['imagecomponent'.$i] = '';
4224 $form['altidentifier'.$i] = '';
4225 $form['altcomponent'.$i] = '';
4227 return $form;
4231 * Converts the data from admin settings form into an array of emoticon objects
4233 * @see self::prepare_form_data()
4234 * @param array $data array of admin form fields and values
4235 * @return false|array of emoticon objects
4237 protected function process_form_data(array $form) {
4239 $count = count($form); // number of form field values
4241 if ($count % 5) {
4242 // we must get five fields per emoticon object
4243 return false;
4246 $emoticons = array();
4247 for ($i = 0; $i < $count / 5; $i++) {
4248 $emoticon = new stdClass();
4249 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4250 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4251 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4252 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4253 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4255 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4256 // prevent from breaking http://url.addresses by accident
4257 $emoticon->text = '';
4260 if (strlen($emoticon->text) < 2) {
4261 // do not allow single character emoticons
4262 $emoticon->text = '';
4265 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4266 // emoticon text must contain some non-alphanumeric character to prevent
4267 // breaking HTML tags
4268 $emoticon->text = '';
4271 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4272 $emoticons[] = $emoticon;
4275 return $emoticons;
4281 * Special setting for limiting of the list of available languages.
4283 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4285 class admin_setting_langlist extends admin_setting_configtext {
4287 * Calls parent::__construct with specific arguments
4289 public function __construct() {
4290 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4294 * Save the new setting
4296 * @param string $data The new setting
4297 * @return bool
4299 public function write_setting($data) {
4300 $return = parent::write_setting($data);
4301 get_string_manager()->reset_caches();
4302 return $return;
4308 * Selection of one of the recognised countries using the list
4309 * returned by {@link get_list_of_countries()}.
4311 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4313 class admin_settings_country_select extends admin_setting_configselect {
4314 protected $includeall;
4315 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4316 $this->includeall = $includeall;
4317 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4321 * Lazy-load the available choices for the select box
4323 public function load_choices() {
4324 global $CFG;
4325 if (is_array($this->choices)) {
4326 return true;
4328 $this->choices = array_merge(
4329 array('0' => get_string('choosedots')),
4330 get_string_manager()->get_list_of_countries($this->includeall));
4331 return true;
4337 * admin_setting_configselect for the default number of sections in a course,
4338 * simply so we can lazy-load the choices.
4340 * @copyright 2011 The Open University
4341 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4343 class admin_settings_num_course_sections extends admin_setting_configselect {
4344 public function __construct($name, $visiblename, $description, $defaultsetting) {
4345 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4348 /** Lazy-load the available choices for the select box */
4349 public function load_choices() {
4350 $max = get_config('moodlecourse', 'maxsections');
4351 if (!isset($max) || !is_numeric($max)) {
4352 $max = 52;
4354 for ($i = 0; $i <= $max; $i++) {
4355 $this->choices[$i] = "$i";
4357 return true;
4363 * Course category selection
4365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4367 class admin_settings_coursecat_select extends admin_setting_configselect {
4369 * Calls parent::__construct with specific arguments
4371 public function __construct($name, $visiblename, $description, $defaultsetting) {
4372 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4376 * Load the available choices for the select box
4378 * @return bool
4380 public function load_choices() {
4381 global $CFG;
4382 require_once($CFG->dirroot.'/course/lib.php');
4383 if (is_array($this->choices)) {
4384 return true;
4386 $this->choices = make_categories_options();
4387 return true;
4393 * Special control for selecting days to backup
4395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4397 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4399 * Calls parent::__construct with specific arguments
4401 public function __construct() {
4402 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4403 $this->plugin = 'backup';
4407 * Load the available choices for the select box
4409 * @return bool Always returns true
4411 public function load_choices() {
4412 if (is_array($this->choices)) {
4413 return true;
4415 $this->choices = array();
4416 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4417 foreach ($days as $day) {
4418 $this->choices[$day] = get_string($day, 'calendar');
4420 return true;
4425 * Special setting for backup auto destination.
4427 * @package core
4428 * @subpackage admin
4429 * @copyright 2014 Frédéric Massart - FMCorz.net
4430 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4432 class admin_setting_special_backup_auto_destination extends admin_setting_configdirectory {
4435 * Calls parent::__construct with specific arguments.
4437 public function __construct() {
4438 parent::__construct('backup/backup_auto_destination', new lang_string('saveto'), new lang_string('backupsavetohelp'), '');
4442 * Check if the directory must be set, depending on backup/backup_auto_storage.
4444 * Note: backup/backup_auto_storage must be specified BEFORE this setting otherwise
4445 * there will be conflicts if this validation happens before the other one.
4447 * @param string $data Form data.
4448 * @return string Empty when no errors.
4450 public function write_setting($data) {
4451 $storage = (int) get_config('backup', 'backup_auto_storage');
4452 if ($storage !== 0) {
4453 if (empty($data) || !file_exists($data) || !is_dir($data) || !is_writable($data) ) {
4454 // The directory must exist and be writable.
4455 return get_string('backuperrorinvaliddestination');
4458 return parent::write_setting($data);
4464 * Special debug setting
4466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4468 class admin_setting_special_debug extends admin_setting_configselect {
4470 * Calls parent::__construct with specific arguments
4472 public function __construct() {
4473 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4477 * Load the available choices for the select box
4479 * @return bool
4481 public function load_choices() {
4482 if (is_array($this->choices)) {
4483 return true;
4485 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4486 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4487 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4488 DEBUG_ALL => get_string('debugall', 'admin'),
4489 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4490 return true;
4496 * Special admin control
4498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4500 class admin_setting_special_calendar_weekend extends admin_setting {
4502 * Calls parent::__construct with specific arguments
4504 public function __construct() {
4505 $name = 'calendar_weekend';
4506 $visiblename = get_string('calendar_weekend', 'admin');
4507 $description = get_string('helpweekenddays', 'admin');
4508 $default = array ('0', '6'); // Saturdays and Sundays
4509 parent::__construct($name, $visiblename, $description, $default);
4513 * Gets the current settings as an array
4515 * @return mixed Null if none, else array of settings
4517 public function get_setting() {
4518 $result = $this->config_read($this->name);
4519 if (is_null($result)) {
4520 return NULL;
4522 if ($result === '') {
4523 return array();
4525 $settings = array();
4526 for ($i=0; $i<7; $i++) {
4527 if ($result & (1 << $i)) {
4528 $settings[] = $i;
4531 return $settings;
4535 * Save the new settings
4537 * @param array $data Array of new settings
4538 * @return bool
4540 public function write_setting($data) {
4541 if (!is_array($data)) {
4542 return '';
4544 unset($data['xxxxx']);
4545 $result = 0;
4546 foreach($data as $index) {
4547 $result |= 1 << $index;
4549 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4553 * Return XHTML to display the control
4555 * @param array $data array of selected days
4556 * @param string $query
4557 * @return string XHTML for display (field + wrapping div(s)
4559 public function output_html($data, $query='') {
4560 // The order matters very much because of the implied numeric keys
4561 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4562 $return = '<table><thead><tr>';
4563 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4564 foreach($days as $index => $day) {
4565 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4567 $return .= '</tr></thead><tbody><tr>';
4568 foreach($days as $index => $day) {
4569 $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>';
4571 $return .= '</tr></tbody></table>';
4573 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4580 * Admin setting that allows a user to pick a behaviour.
4582 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4584 class admin_setting_question_behaviour extends admin_setting_configselect {
4586 * @param string $name name of config variable
4587 * @param string $visiblename display name
4588 * @param string $description description
4589 * @param string $default default.
4591 public function __construct($name, $visiblename, $description, $default) {
4592 parent::__construct($name, $visiblename, $description, $default, NULL);
4596 * Load list of behaviours as choices
4597 * @return bool true => success, false => error.
4599 public function load_choices() {
4600 global $CFG;
4601 require_once($CFG->dirroot . '/question/engine/lib.php');
4602 $this->choices = question_engine::get_behaviour_options('');
4603 return true;
4609 * Admin setting that allows a user to pick appropriate roles for something.
4611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4613 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4614 /** @var array Array of capabilities which identify roles */
4615 private $types;
4618 * @param string $name Name of config variable
4619 * @param string $visiblename Display name
4620 * @param string $description Description
4621 * @param array $types Array of archetypes which identify
4622 * roles that will be enabled by default.
4624 public function __construct($name, $visiblename, $description, $types) {
4625 parent::__construct($name, $visiblename, $description, NULL, NULL);
4626 $this->types = $types;
4630 * Load roles as choices
4632 * @return bool true=>success, false=>error
4634 public function load_choices() {
4635 global $CFG, $DB;
4636 if (during_initial_install()) {
4637 return false;
4639 if (is_array($this->choices)) {
4640 return true;
4642 if ($roles = get_all_roles()) {
4643 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4644 return true;
4645 } else {
4646 return false;
4651 * Return the default setting for this control
4653 * @return array Array of default settings
4655 public function get_defaultsetting() {
4656 global $CFG;
4658 if (during_initial_install()) {
4659 return null;
4661 $result = array();
4662 foreach($this->types as $archetype) {
4663 if ($caproles = get_archetype_roles($archetype)) {
4664 foreach ($caproles as $caprole) {
4665 $result[$caprole->id] = 1;
4669 return $result;
4675 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4677 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4679 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4681 * Constructor
4682 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4683 * @param string $visiblename localised
4684 * @param string $description long localised info
4685 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4686 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4687 * @param int $size default field size
4689 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4690 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4691 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4697 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4699 * @copyright 2009 Petr Skoda (http://skodak.org)
4700 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4702 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4705 * Constructor
4706 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4707 * @param string $visiblename localised
4708 * @param string $description long localised info
4709 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4710 * @param string $yes value used when checked
4711 * @param string $no value used when not checked
4713 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4714 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4715 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4722 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4724 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4726 * @copyright 2010 Sam Hemelryk
4727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4729 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4731 * Constructor
4732 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4733 * @param string $visiblename localised
4734 * @param string $description long localised info
4735 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4736 * @param string $yes value used when checked
4737 * @param string $no value used when not checked
4739 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4740 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4741 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4748 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4752 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4754 * Calls parent::__construct with specific arguments
4756 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4757 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4758 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4765 * Graded roles in gradebook
4767 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4769 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4771 * Calls parent::__construct with specific arguments
4773 public function __construct() {
4774 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4775 get_string('configgradebookroles', 'admin'),
4776 array('student'));
4783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4785 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4787 * Saves the new settings passed in $data
4789 * @param string $data
4790 * @return mixed string or Array
4792 public function write_setting($data) {
4793 global $CFG, $DB;
4795 $oldvalue = $this->config_read($this->name);
4796 $return = parent::write_setting($data);
4797 $newvalue = $this->config_read($this->name);
4799 if ($oldvalue !== $newvalue) {
4800 // force full regrading
4801 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4804 return $return;
4810 * Which roles to show on course description page
4812 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4814 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4816 * Calls parent::__construct with specific arguments
4818 public function __construct() {
4819 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4820 get_string('coursecontact_desc', 'admin'),
4821 array('editingteacher'));
4828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4830 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4832 * Calls parent::__construct with specific arguments
4834 function admin_setting_special_gradelimiting() {
4835 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4836 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4840 * Force site regrading
4842 function regrade_all() {
4843 global $CFG;
4844 require_once("$CFG->libdir/gradelib.php");
4845 grade_force_site_regrading();
4849 * Saves the new settings
4851 * @param mixed $data
4852 * @return string empty string or error message
4854 function write_setting($data) {
4855 $previous = $this->get_setting();
4857 if ($previous === null) {
4858 if ($data) {
4859 $this->regrade_all();
4861 } else {
4862 if ($data != $previous) {
4863 $this->regrade_all();
4866 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4873 * Primary grade export plugin - has state tracking.
4875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4877 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4879 * Calls parent::__construct with specific arguments
4881 public function __construct() {
4882 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4883 get_string('configgradeexport', 'admin'), array(), NULL);
4887 * Load the available choices for the multicheckbox
4889 * @return bool always returns true
4891 public function load_choices() {
4892 if (is_array($this->choices)) {
4893 return true;
4895 $this->choices = array();
4897 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4898 foreach($plugins as $plugin => $unused) {
4899 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4902 return true;
4908 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4912 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4914 * Config gradepointmax constructor
4916 * @param string $name Overidden by "gradepointmax"
4917 * @param string $visiblename Overridden by "gradepointmax" language string.
4918 * @param string $description Overridden by "gradepointmax_help" language string.
4919 * @param string $defaultsetting Not used, overridden by 100.
4920 * @param mixed $paramtype Overridden by PARAM_INT.
4921 * @param int $size Overridden by 5.
4923 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4924 $name = 'gradepointdefault';
4925 $visiblename = get_string('gradepointdefault', 'grades');
4926 $description = get_string('gradepointdefault_help', 'grades');
4927 $defaultsetting = 100;
4928 $paramtype = PARAM_INT;
4929 $size = 5;
4930 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4934 * Validate data before storage
4935 * @param string $data The submitted data
4936 * @return bool|string true if ok, string if error found
4938 public function validate($data) {
4939 global $CFG;
4940 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4941 return true;
4942 } else {
4943 return get_string('gradepointdefault_validateerror', 'grades');
4950 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4952 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4954 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4957 * Config gradepointmax constructor
4959 * @param string $name Overidden by "gradepointmax"
4960 * @param string $visiblename Overridden by "gradepointmax" language string.
4961 * @param string $description Overridden by "gradepointmax_help" language string.
4962 * @param string $defaultsetting Not used, overridden by 100.
4963 * @param mixed $paramtype Overridden by PARAM_INT.
4964 * @param int $size Overridden by 5.
4966 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4967 $name = 'gradepointmax';
4968 $visiblename = get_string('gradepointmax', 'grades');
4969 $description = get_string('gradepointmax_help', 'grades');
4970 $defaultsetting = 100;
4971 $paramtype = PARAM_INT;
4972 $size = 5;
4973 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4977 * Save the selected setting
4979 * @param string $data The selected site
4980 * @return string empty string or error message
4982 public function write_setting($data) {
4983 if ($data === '') {
4984 $data = (int)$this->defaultsetting;
4985 } else {
4986 $data = $data;
4988 return parent::write_setting($data);
4992 * Validate data before storage
4993 * @param string $data The submitted data
4994 * @return bool|string true if ok, string if error found
4996 public function validate($data) {
4997 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
4998 return true;
4999 } else {
5000 return get_string('gradepointmax_validateerror', 'grades');
5005 * Return an XHTML string for the setting
5006 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5007 * @param string $query search query to be highlighted
5008 * @return string XHTML to display control
5010 public function output_html($data, $query = '') {
5011 $default = $this->get_defaultsetting();
5013 $attr = array(
5014 'type' => 'text',
5015 'size' => $this->size,
5016 'id' => $this->get_id(),
5017 'name' => $this->get_full_name(),
5018 'value' => s($data),
5019 'maxlength' => '5'
5021 $input = html_writer::empty_tag('input', $attr);
5023 $attr = array('class' => 'form-text defaultsnext');
5024 $div = html_writer::tag('div', $input, $attr);
5025 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
5031 * Grade category settings
5033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5035 class admin_setting_gradecat_combo extends admin_setting {
5036 /** @var array Array of choices */
5037 public $choices;
5040 * Sets choices and calls parent::__construct with passed arguments
5041 * @param string $name
5042 * @param string $visiblename
5043 * @param string $description
5044 * @param mixed $defaultsetting string or array depending on implementation
5045 * @param array $choices An array of choices for the control
5047 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5048 $this->choices = $choices;
5049 parent::__construct($name, $visiblename, $description, $defaultsetting);
5053 * Return the current setting(s) array
5055 * @return array Array of value=>xx, forced=>xx, adv=>xx
5057 public function get_setting() {
5058 global $CFG;
5060 $value = $this->config_read($this->name);
5061 $flag = $this->config_read($this->name.'_flag');
5063 if (is_null($value) or is_null($flag)) {
5064 return NULL;
5067 $flag = (int)$flag;
5068 $forced = (boolean)(1 & $flag); // first bit
5069 $adv = (boolean)(2 & $flag); // second bit
5071 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5075 * Save the new settings passed in $data
5077 * @todo Add vartype handling to ensure $data is array
5078 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5079 * @return string empty or error message
5081 public function write_setting($data) {
5082 global $CFG;
5084 $value = $data['value'];
5085 $forced = empty($data['forced']) ? 0 : 1;
5086 $adv = empty($data['adv']) ? 0 : 2;
5087 $flag = ($forced | $adv); //bitwise or
5089 if (!in_array($value, array_keys($this->choices))) {
5090 return 'Error setting ';
5093 $oldvalue = $this->config_read($this->name);
5094 $oldflag = (int)$this->config_read($this->name.'_flag');
5095 $oldforced = (1 & $oldflag); // first bit
5097 $result1 = $this->config_write($this->name, $value);
5098 $result2 = $this->config_write($this->name.'_flag', $flag);
5100 // force regrade if needed
5101 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5102 require_once($CFG->libdir.'/gradelib.php');
5103 grade_category::updated_forced_settings();
5106 if ($result1 and $result2) {
5107 return '';
5108 } else {
5109 return get_string('errorsetting', 'admin');
5114 * Return XHTML to display the field and wrapping div
5116 * @todo Add vartype handling to ensure $data is array
5117 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5118 * @param string $query
5119 * @return string XHTML to display control
5121 public function output_html($data, $query='') {
5122 $value = $data['value'];
5123 $forced = !empty($data['forced']);
5124 $adv = !empty($data['adv']);
5126 $default = $this->get_defaultsetting();
5127 if (!is_null($default)) {
5128 $defaultinfo = array();
5129 if (isset($this->choices[$default['value']])) {
5130 $defaultinfo[] = $this->choices[$default['value']];
5132 if (!empty($default['forced'])) {
5133 $defaultinfo[] = get_string('force');
5135 if (!empty($default['adv'])) {
5136 $defaultinfo[] = get_string('advanced');
5138 $defaultinfo = implode(', ', $defaultinfo);
5140 } else {
5141 $defaultinfo = NULL;
5145 $return = '<div class="form-group">';
5146 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5147 foreach ($this->choices as $key => $val) {
5148 // the string cast is needed because key may be integer - 0 is equal to most strings!
5149 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5151 $return .= '</select>';
5152 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5153 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5154 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5155 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5156 $return .= '</div>';
5158 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5164 * Selection of grade report in user profiles
5166 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5168 class admin_setting_grade_profilereport extends admin_setting_configselect {
5170 * Calls parent::__construct with specific arguments
5172 public function __construct() {
5173 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5177 * Loads an array of choices for the configselect control
5179 * @return bool always return true
5181 public function load_choices() {
5182 if (is_array($this->choices)) {
5183 return true;
5185 $this->choices = array();
5187 global $CFG;
5188 require_once($CFG->libdir.'/gradelib.php');
5190 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5191 if (file_exists($plugindir.'/lib.php')) {
5192 require_once($plugindir.'/lib.php');
5193 $functionname = 'grade_report_'.$plugin.'_profilereport';
5194 if (function_exists($functionname)) {
5195 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5199 return true;
5204 * Provides a selection of grade reports to be used for "grades".
5206 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
5207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5209 class admin_setting_my_grades_report extends admin_setting_configselect {
5212 * Calls parent::__construct with specific arguments.
5214 public function __construct() {
5215 parent::__construct('grade_mygrades_report', new lang_string('mygrades', 'grades'),
5216 new lang_string('mygrades_desc', 'grades'), 'overview', null);
5220 * Loads an array of choices for the configselect control.
5222 * @return bool always returns true.
5224 public function load_choices() {
5225 global $CFG; // Remove this line and behold the horror of behat test failures!
5226 $this->choices = array();
5227 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5228 if (file_exists($plugindir . '/lib.php')) {
5229 require_once($plugindir . '/lib.php');
5230 // Check to see if the class exists. Check the correct plugin convention first.
5231 if (class_exists('gradereport_' . $plugin)) {
5232 $classname = 'gradereport_' . $plugin;
5233 } else if (class_exists('grade_report_' . $plugin)) {
5234 // We are using the old plugin naming convention.
5235 $classname = 'grade_report_' . $plugin;
5236 } else {
5237 continue;
5239 if ($classname::supports_mygrades()) {
5240 $this->choices[$plugin] = get_string('pluginname', 'gradereport_' . $plugin);
5244 // Add an option to specify an external url.
5245 $this->choices['external'] = get_string('externalurl', 'grades');
5246 return true;
5251 * Special class for register auth selection
5253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5255 class admin_setting_special_registerauth extends admin_setting_configselect {
5257 * Calls parent::__construct with specific arguments
5259 public function __construct() {
5260 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5264 * Returns the default option
5266 * @return string empty or default option
5268 public function get_defaultsetting() {
5269 $this->load_choices();
5270 $defaultsetting = parent::get_defaultsetting();
5271 if (array_key_exists($defaultsetting, $this->choices)) {
5272 return $defaultsetting;
5273 } else {
5274 return '';
5279 * Loads the possible choices for the array
5281 * @return bool always returns true
5283 public function load_choices() {
5284 global $CFG;
5286 if (is_array($this->choices)) {
5287 return true;
5289 $this->choices = array();
5290 $this->choices[''] = get_string('disable');
5292 $authsenabled = get_enabled_auth_plugins(true);
5294 foreach ($authsenabled as $auth) {
5295 $authplugin = get_auth_plugin($auth);
5296 if (!$authplugin->can_signup()) {
5297 continue;
5299 // Get the auth title (from core or own auth lang files)
5300 $authtitle = $authplugin->get_title();
5301 $this->choices[$auth] = $authtitle;
5303 return true;
5309 * General plugins manager
5311 class admin_page_pluginsoverview extends admin_externalpage {
5314 * Sets basic information about the external page
5316 public function __construct() {
5317 global $CFG;
5318 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5319 "$CFG->wwwroot/$CFG->admin/plugins.php");
5324 * Module manage page
5326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5328 class admin_page_managemods extends admin_externalpage {
5330 * Calls parent::__construct with specific arguments
5332 public function __construct() {
5333 global $CFG;
5334 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5338 * Try to find the specified module
5340 * @param string $query The module to search for
5341 * @return array
5343 public function search($query) {
5344 global $CFG, $DB;
5345 if ($result = parent::search($query)) {
5346 return $result;
5349 $found = false;
5350 if ($modules = $DB->get_records('modules')) {
5351 foreach ($modules as $module) {
5352 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5353 continue;
5355 if (strpos($module->name, $query) !== false) {
5356 $found = true;
5357 break;
5359 $strmodulename = get_string('modulename', $module->name);
5360 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5361 $found = true;
5362 break;
5366 if ($found) {
5367 $result = new stdClass();
5368 $result->page = $this;
5369 $result->settings = array();
5370 return array($this->name => $result);
5371 } else {
5372 return array();
5379 * Special class for enrol plugins management.
5381 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5382 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5384 class admin_setting_manageenrols extends admin_setting {
5386 * Calls parent::__construct with specific arguments
5388 public function __construct() {
5389 $this->nosave = true;
5390 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5394 * Always returns true, does nothing
5396 * @return true
5398 public function get_setting() {
5399 return true;
5403 * Always returns true, does nothing
5405 * @return true
5407 public function get_defaultsetting() {
5408 return true;
5412 * Always returns '', does not write anything
5414 * @return string Always returns ''
5416 public function write_setting($data) {
5417 // do not write any setting
5418 return '';
5422 * Checks if $query is one of the available enrol plugins
5424 * @param string $query The string to search for
5425 * @return bool Returns true if found, false if not
5427 public function is_related($query) {
5428 if (parent::is_related($query)) {
5429 return true;
5432 $query = core_text::strtolower($query);
5433 $enrols = enrol_get_plugins(false);
5434 foreach ($enrols as $name=>$enrol) {
5435 $localised = get_string('pluginname', 'enrol_'.$name);
5436 if (strpos(core_text::strtolower($name), $query) !== false) {
5437 return true;
5439 if (strpos(core_text::strtolower($localised), $query) !== false) {
5440 return true;
5443 return false;
5447 * Builds the XHTML to display the control
5449 * @param string $data Unused
5450 * @param string $query
5451 * @return string
5453 public function output_html($data, $query='') {
5454 global $CFG, $OUTPUT, $DB, $PAGE;
5456 // Display strings.
5457 $strup = get_string('up');
5458 $strdown = get_string('down');
5459 $strsettings = get_string('settings');
5460 $strenable = get_string('enable');
5461 $strdisable = get_string('disable');
5462 $struninstall = get_string('uninstallplugin', 'core_admin');
5463 $strusage = get_string('enrolusage', 'enrol');
5464 $strversion = get_string('version');
5465 $strtest = get_string('testsettings', 'core_enrol');
5467 $pluginmanager = core_plugin_manager::instance();
5469 $enrols_available = enrol_get_plugins(false);
5470 $active_enrols = enrol_get_plugins(true);
5472 $allenrols = array();
5473 foreach ($active_enrols as $key=>$enrol) {
5474 $allenrols[$key] = true;
5476 foreach ($enrols_available as $key=>$enrol) {
5477 $allenrols[$key] = true;
5479 // Now find all borked plugins and at least allow then to uninstall.
5480 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5481 foreach ($condidates as $candidate) {
5482 if (empty($allenrols[$candidate])) {
5483 $allenrols[$candidate] = true;
5487 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5488 $return .= $OUTPUT->box_start('generalbox enrolsui');
5490 $table = new html_table();
5491 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5492 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5493 $table->id = 'courseenrolmentplugins';
5494 $table->attributes['class'] = 'admintable generaltable';
5495 $table->data = array();
5497 // Iterate through enrol plugins and add to the display table.
5498 $updowncount = 1;
5499 $enrolcount = count($active_enrols);
5500 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5501 $printed = array();
5502 foreach($allenrols as $enrol => $unused) {
5503 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5504 $version = get_config('enrol_'.$enrol, 'version');
5505 if ($version === false) {
5506 $version = '';
5509 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5510 $name = get_string('pluginname', 'enrol_'.$enrol);
5511 } else {
5512 $name = $enrol;
5514 // Usage.
5515 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5516 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5517 $usage = "$ci / $cp";
5519 // Hide/show links.
5520 $class = '';
5521 if (isset($active_enrols[$enrol])) {
5522 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5523 $hideshow = "<a href=\"$aurl\">";
5524 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5525 $enabled = true;
5526 $displayname = $name;
5527 } else if (isset($enrols_available[$enrol])) {
5528 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5529 $hideshow = "<a href=\"$aurl\">";
5530 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5531 $enabled = false;
5532 $displayname = $name;
5533 $class = 'dimmed_text';
5534 } else {
5535 $hideshow = '';
5536 $enabled = false;
5537 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5539 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5540 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5541 } else {
5542 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5545 // Up/down link (only if enrol is enabled).
5546 $updown = '';
5547 if ($enabled) {
5548 if ($updowncount > 1) {
5549 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5550 $updown .= "<a href=\"$aurl\">";
5551 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5552 } else {
5553 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5555 if ($updowncount < $enrolcount) {
5556 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5557 $updown .= "<a href=\"$aurl\">";
5558 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5559 } else {
5560 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5562 ++$updowncount;
5565 // Add settings link.
5566 if (!$version) {
5567 $settings = '';
5568 } else if ($surl = $plugininfo->get_settings_url()) {
5569 $settings = html_writer::link($surl, $strsettings);
5570 } else {
5571 $settings = '';
5574 // Add uninstall info.
5575 $uninstall = '';
5576 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5577 $uninstall = html_writer::link($uninstallurl, $struninstall);
5580 $test = '';
5581 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5582 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5583 $test = html_writer::link($testsettingsurl, $strtest);
5586 // Add a row to the table.
5587 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5588 if ($class) {
5589 $row->attributes['class'] = $class;
5591 $table->data[] = $row;
5593 $printed[$enrol] = true;
5596 $return .= html_writer::table($table);
5597 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5598 $return .= $OUTPUT->box_end();
5599 return highlight($query, $return);
5605 * Blocks manage page
5607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5609 class admin_page_manageblocks extends admin_externalpage {
5611 * Calls parent::__construct with specific arguments
5613 public function __construct() {
5614 global $CFG;
5615 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5619 * Search for a specific block
5621 * @param string $query The string to search for
5622 * @return array
5624 public function search($query) {
5625 global $CFG, $DB;
5626 if ($result = parent::search($query)) {
5627 return $result;
5630 $found = false;
5631 if ($blocks = $DB->get_records('block')) {
5632 foreach ($blocks as $block) {
5633 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5634 continue;
5636 if (strpos($block->name, $query) !== false) {
5637 $found = true;
5638 break;
5640 $strblockname = get_string('pluginname', 'block_'.$block->name);
5641 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5642 $found = true;
5643 break;
5647 if ($found) {
5648 $result = new stdClass();
5649 $result->page = $this;
5650 $result->settings = array();
5651 return array($this->name => $result);
5652 } else {
5653 return array();
5659 * Message outputs configuration
5661 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5663 class admin_page_managemessageoutputs extends admin_externalpage {
5665 * Calls parent::__construct with specific arguments
5667 public function __construct() {
5668 global $CFG;
5669 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5673 * Search for a specific message processor
5675 * @param string $query The string to search for
5676 * @return array
5678 public function search($query) {
5679 global $CFG, $DB;
5680 if ($result = parent::search($query)) {
5681 return $result;
5684 $found = false;
5685 if ($processors = get_message_processors()) {
5686 foreach ($processors as $processor) {
5687 if (!$processor->available) {
5688 continue;
5690 if (strpos($processor->name, $query) !== false) {
5691 $found = true;
5692 break;
5694 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5695 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5696 $found = true;
5697 break;
5701 if ($found) {
5702 $result = new stdClass();
5703 $result->page = $this;
5704 $result->settings = array();
5705 return array($this->name => $result);
5706 } else {
5707 return array();
5713 * Default message outputs configuration
5715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5717 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5719 * Calls parent::__construct with specific arguments
5721 public function __construct() {
5722 global $CFG;
5723 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5729 * Manage question behaviours page
5731 * @copyright 2011 The Open University
5732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5734 class admin_page_manageqbehaviours extends admin_externalpage {
5736 * Constructor
5738 public function __construct() {
5739 global $CFG;
5740 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5741 new moodle_url('/admin/qbehaviours.php'));
5745 * Search question behaviours for the specified string
5747 * @param string $query The string to search for in question behaviours
5748 * @return array
5750 public function search($query) {
5751 global $CFG;
5752 if ($result = parent::search($query)) {
5753 return $result;
5756 $found = false;
5757 require_once($CFG->dirroot . '/question/engine/lib.php');
5758 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5759 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5760 $query) !== false) {
5761 $found = true;
5762 break;
5765 if ($found) {
5766 $result = new stdClass();
5767 $result->page = $this;
5768 $result->settings = array();
5769 return array($this->name => $result);
5770 } else {
5771 return array();
5778 * Question type manage page
5780 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5782 class admin_page_manageqtypes extends admin_externalpage {
5784 * Calls parent::__construct with specific arguments
5786 public function __construct() {
5787 global $CFG;
5788 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5789 new moodle_url('/admin/qtypes.php'));
5793 * Search question types for the specified string
5795 * @param string $query The string to search for in question types
5796 * @return array
5798 public function search($query) {
5799 global $CFG;
5800 if ($result = parent::search($query)) {
5801 return $result;
5804 $found = false;
5805 require_once($CFG->dirroot . '/question/engine/bank.php');
5806 foreach (question_bank::get_all_qtypes() as $qtype) {
5807 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5808 $found = true;
5809 break;
5812 if ($found) {
5813 $result = new stdClass();
5814 $result->page = $this;
5815 $result->settings = array();
5816 return array($this->name => $result);
5817 } else {
5818 return array();
5824 class admin_page_manageportfolios extends admin_externalpage {
5826 * Calls parent::__construct with specific arguments
5828 public function __construct() {
5829 global $CFG;
5830 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5831 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5835 * Searches page for the specified string.
5836 * @param string $query The string to search for
5837 * @return bool True if it is found on this page
5839 public function search($query) {
5840 global $CFG;
5841 if ($result = parent::search($query)) {
5842 return $result;
5845 $found = false;
5846 $portfolios = core_component::get_plugin_list('portfolio');
5847 foreach ($portfolios as $p => $dir) {
5848 if (strpos($p, $query) !== false) {
5849 $found = true;
5850 break;
5853 if (!$found) {
5854 foreach (portfolio_instances(false, false) as $instance) {
5855 $title = $instance->get('name');
5856 if (strpos(core_text::strtolower($title), $query) !== false) {
5857 $found = true;
5858 break;
5863 if ($found) {
5864 $result = new stdClass();
5865 $result->page = $this;
5866 $result->settings = array();
5867 return array($this->name => $result);
5868 } else {
5869 return array();
5875 class admin_page_managerepositories extends admin_externalpage {
5877 * Calls parent::__construct with specific arguments
5879 public function __construct() {
5880 global $CFG;
5881 parent::__construct('managerepositories', get_string('manage',
5882 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5886 * Searches page for the specified string.
5887 * @param string $query The string to search for
5888 * @return bool True if it is found on this page
5890 public function search($query) {
5891 global $CFG;
5892 if ($result = parent::search($query)) {
5893 return $result;
5896 $found = false;
5897 $repositories= core_component::get_plugin_list('repository');
5898 foreach ($repositories as $p => $dir) {
5899 if (strpos($p, $query) !== false) {
5900 $found = true;
5901 break;
5904 if (!$found) {
5905 foreach (repository::get_types() as $instance) {
5906 $title = $instance->get_typename();
5907 if (strpos(core_text::strtolower($title), $query) !== false) {
5908 $found = true;
5909 break;
5914 if ($found) {
5915 $result = new stdClass();
5916 $result->page = $this;
5917 $result->settings = array();
5918 return array($this->name => $result);
5919 } else {
5920 return array();
5927 * Special class for authentication administration.
5929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5931 class admin_setting_manageauths extends admin_setting {
5933 * Calls parent::__construct with specific arguments
5935 public function __construct() {
5936 $this->nosave = true;
5937 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5941 * Always returns true
5943 * @return true
5945 public function get_setting() {
5946 return true;
5950 * Always returns true
5952 * @return true
5954 public function get_defaultsetting() {
5955 return true;
5959 * Always returns '' and doesn't write anything
5961 * @return string Always returns ''
5963 public function write_setting($data) {
5964 // do not write any setting
5965 return '';
5969 * Search to find if Query is related to auth plugin
5971 * @param string $query The string to search for
5972 * @return bool true for related false for not
5974 public function is_related($query) {
5975 if (parent::is_related($query)) {
5976 return true;
5979 $authsavailable = core_component::get_plugin_list('auth');
5980 foreach ($authsavailable as $auth => $dir) {
5981 if (strpos($auth, $query) !== false) {
5982 return true;
5984 $authplugin = get_auth_plugin($auth);
5985 $authtitle = $authplugin->get_title();
5986 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5987 return true;
5990 return false;
5994 * Return XHTML to display control
5996 * @param mixed $data Unused
5997 * @param string $query
5998 * @return string highlight
6000 public function output_html($data, $query='') {
6001 global $CFG, $OUTPUT, $DB;
6003 // display strings
6004 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
6005 'settings', 'edit', 'name', 'enable', 'disable',
6006 'up', 'down', 'none', 'users'));
6007 $txt->updown = "$txt->up/$txt->down";
6008 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6009 $txt->testsettings = get_string('testsettings', 'core_auth');
6011 $authsavailable = core_component::get_plugin_list('auth');
6012 get_enabled_auth_plugins(true); // fix the list of enabled auths
6013 if (empty($CFG->auth)) {
6014 $authsenabled = array();
6015 } else {
6016 $authsenabled = explode(',', $CFG->auth);
6019 // construct the display array, with enabled auth plugins at the top, in order
6020 $displayauths = array();
6021 $registrationauths = array();
6022 $registrationauths[''] = $txt->disable;
6023 $authplugins = array();
6024 foreach ($authsenabled as $auth) {
6025 $authplugin = get_auth_plugin($auth);
6026 $authplugins[$auth] = $authplugin;
6027 /// Get the auth title (from core or own auth lang files)
6028 $authtitle = $authplugin->get_title();
6029 /// Apply titles
6030 $displayauths[$auth] = $authtitle;
6031 if ($authplugin->can_signup()) {
6032 $registrationauths[$auth] = $authtitle;
6036 foreach ($authsavailable as $auth => $dir) {
6037 if (array_key_exists($auth, $displayauths)) {
6038 continue; //already in the list
6040 $authplugin = get_auth_plugin($auth);
6041 $authplugins[$auth] = $authplugin;
6042 /// Get the auth title (from core or own auth lang files)
6043 $authtitle = $authplugin->get_title();
6044 /// Apply titles
6045 $displayauths[$auth] = $authtitle;
6046 if ($authplugin->can_signup()) {
6047 $registrationauths[$auth] = $authtitle;
6051 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6052 $return .= $OUTPUT->box_start('generalbox authsui');
6054 $table = new html_table();
6055 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6056 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6057 $table->data = array();
6058 $table->attributes['class'] = 'admintable generaltable';
6059 $table->id = 'manageauthtable';
6061 //add always enabled plugins first
6062 $displayname = $displayauths['manual'];
6063 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6064 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6065 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6066 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6067 $displayname = $displayauths['nologin'];
6068 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6069 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6070 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6073 // iterate through auth plugins and add to the display table
6074 $updowncount = 1;
6075 $authcount = count($authsenabled);
6076 $url = "auth.php?sesskey=" . sesskey();
6077 foreach ($displayauths as $auth => $name) {
6078 if ($auth == 'manual' or $auth == 'nologin') {
6079 continue;
6081 $class = '';
6082 // hide/show link
6083 if (in_array($auth, $authsenabled)) {
6084 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6085 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6086 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6087 $enabled = true;
6088 $displayname = $name;
6090 else {
6091 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6092 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6093 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6094 $enabled = false;
6095 $displayname = $name;
6096 $class = 'dimmed_text';
6099 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6101 // up/down link (only if auth is enabled)
6102 $updown = '';
6103 if ($enabled) {
6104 if ($updowncount > 1) {
6105 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6106 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6108 else {
6109 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6111 if ($updowncount < $authcount) {
6112 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6113 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6115 else {
6116 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6118 ++ $updowncount;
6121 // settings link
6122 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6123 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6124 } else {
6125 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6128 // Uninstall link.
6129 $uninstall = '';
6130 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6131 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6134 $test = '';
6135 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6136 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6137 $test = html_writer::link($testurl, $txt->testsettings);
6140 // Add a row to the table.
6141 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6142 if ($class) {
6143 $row->attributes['class'] = $class;
6145 $table->data[] = $row;
6147 $return .= html_writer::table($table);
6148 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6149 $return .= $OUTPUT->box_end();
6150 return highlight($query, $return);
6156 * Special class for authentication administration.
6158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6160 class admin_setting_manageeditors extends admin_setting {
6162 * Calls parent::__construct with specific arguments
6164 public function __construct() {
6165 $this->nosave = true;
6166 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6170 * Always returns true, does nothing
6172 * @return true
6174 public function get_setting() {
6175 return true;
6179 * Always returns true, does nothing
6181 * @return true
6183 public function get_defaultsetting() {
6184 return true;
6188 * Always returns '', does not write anything
6190 * @return string Always returns ''
6192 public function write_setting($data) {
6193 // do not write any setting
6194 return '';
6198 * Checks if $query is one of the available editors
6200 * @param string $query The string to search for
6201 * @return bool Returns true if found, false if not
6203 public function is_related($query) {
6204 if (parent::is_related($query)) {
6205 return true;
6208 $editors_available = editors_get_available();
6209 foreach ($editors_available as $editor=>$editorstr) {
6210 if (strpos($editor, $query) !== false) {
6211 return true;
6213 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6214 return true;
6217 return false;
6221 * Builds the XHTML to display the control
6223 * @param string $data Unused
6224 * @param string $query
6225 * @return string
6227 public function output_html($data, $query='') {
6228 global $CFG, $OUTPUT;
6230 // display strings
6231 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6232 'up', 'down', 'none'));
6233 $struninstall = get_string('uninstallplugin', 'core_admin');
6235 $txt->updown = "$txt->up/$txt->down";
6237 $editors_available = editors_get_available();
6238 $active_editors = explode(',', $CFG->texteditors);
6240 $active_editors = array_reverse($active_editors);
6241 foreach ($active_editors as $key=>$editor) {
6242 if (empty($editors_available[$editor])) {
6243 unset($active_editors[$key]);
6244 } else {
6245 $name = $editors_available[$editor];
6246 unset($editors_available[$editor]);
6247 $editors_available[$editor] = $name;
6250 if (empty($active_editors)) {
6251 //$active_editors = array('textarea');
6253 $editors_available = array_reverse($editors_available, true);
6254 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6255 $return .= $OUTPUT->box_start('generalbox editorsui');
6257 $table = new html_table();
6258 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6259 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6260 $table->id = 'editormanagement';
6261 $table->attributes['class'] = 'admintable generaltable';
6262 $table->data = array();
6264 // iterate through auth plugins and add to the display table
6265 $updowncount = 1;
6266 $editorcount = count($active_editors);
6267 $url = "editors.php?sesskey=" . sesskey();
6268 foreach ($editors_available as $editor => $name) {
6269 // hide/show link
6270 $class = '';
6271 if (in_array($editor, $active_editors)) {
6272 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6273 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6274 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6275 $enabled = true;
6276 $displayname = $name;
6278 else {
6279 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6280 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6281 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6282 $enabled = false;
6283 $displayname = $name;
6284 $class = 'dimmed_text';
6287 // up/down link (only if auth is enabled)
6288 $updown = '';
6289 if ($enabled) {
6290 if ($updowncount > 1) {
6291 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6292 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6294 else {
6295 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6297 if ($updowncount < $editorcount) {
6298 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6299 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6301 else {
6302 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6304 ++ $updowncount;
6307 // settings link
6308 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6309 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6310 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6311 } else {
6312 $settings = '';
6315 $uninstall = '';
6316 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6317 $uninstall = html_writer::link($uninstallurl, $struninstall);
6320 // Add a row to the table.
6321 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6322 if ($class) {
6323 $row->attributes['class'] = $class;
6325 $table->data[] = $row;
6327 $return .= html_writer::table($table);
6328 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6329 $return .= $OUTPUT->box_end();
6330 return highlight($query, $return);
6336 * Special class for license administration.
6338 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6340 class admin_setting_managelicenses extends admin_setting {
6342 * Calls parent::__construct with specific arguments
6344 public function __construct() {
6345 $this->nosave = true;
6346 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6350 * Always returns true, does nothing
6352 * @return true
6354 public function get_setting() {
6355 return true;
6359 * Always returns true, does nothing
6361 * @return true
6363 public function get_defaultsetting() {
6364 return true;
6368 * Always returns '', does not write anything
6370 * @return string Always returns ''
6372 public function write_setting($data) {
6373 // do not write any setting
6374 return '';
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;
6386 require_once($CFG->libdir . '/licenselib.php');
6387 $url = "licenses.php?sesskey=" . sesskey();
6389 // display strings
6390 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6391 $licenses = license_manager::get_licenses();
6393 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6395 $return .= $OUTPUT->box_start('generalbox editorsui');
6397 $table = new html_table();
6398 $table->head = array($txt->name, $txt->enable);
6399 $table->colclasses = array('leftalign', 'centeralign');
6400 $table->id = 'availablelicenses';
6401 $table->attributes['class'] = 'admintable generaltable';
6402 $table->data = array();
6404 foreach ($licenses as $value) {
6405 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6407 if ($value->enabled == 1) {
6408 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6409 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6410 } else {
6411 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6412 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6415 if ($value->shortname == $CFG->sitedefaultlicense) {
6416 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6417 $hideshow = '';
6420 $enabled = true;
6422 $table->data[] =array($displayname, $hideshow);
6424 $return .= html_writer::table($table);
6425 $return .= $OUTPUT->box_end();
6426 return highlight($query, $return);
6431 * Course formats manager. Allows to enable/disable formats and jump to settings
6433 class admin_setting_manageformats extends admin_setting {
6436 * Calls parent::__construct with specific arguments
6438 public function __construct() {
6439 $this->nosave = true;
6440 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6444 * Always returns true
6446 * @return true
6448 public function get_setting() {
6449 return true;
6453 * Always returns true
6455 * @return true
6457 public function get_defaultsetting() {
6458 return true;
6462 * Always returns '' and doesn't write anything
6464 * @param mixed $data string or array, must not be NULL
6465 * @return string Always returns ''
6467 public function write_setting($data) {
6468 // do not write any setting
6469 return '';
6473 * Search to find if Query is related to format plugin
6475 * @param string $query The string to search for
6476 * @return bool true for related false for not
6478 public function is_related($query) {
6479 if (parent::is_related($query)) {
6480 return true;
6482 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6483 foreach ($formats as $format) {
6484 if (strpos($format->component, $query) !== false ||
6485 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6486 return true;
6489 return false;
6493 * Return XHTML to display control
6495 * @param mixed $data Unused
6496 * @param string $query
6497 * @return string highlight
6499 public function output_html($data, $query='') {
6500 global $CFG, $OUTPUT;
6501 $return = '';
6502 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6503 $return .= $OUTPUT->box_start('generalbox formatsui');
6505 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6507 // display strings
6508 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6509 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6510 $txt->updown = "$txt->up/$txt->down";
6512 $table = new html_table();
6513 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6514 $table->align = array('left', 'center', 'center', 'center', 'center');
6515 $table->attributes['class'] = 'manageformattable generaltable admintable';
6516 $table->data = array();
6518 $cnt = 0;
6519 $defaultformat = get_config('moodlecourse', 'format');
6520 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6521 foreach ($formats as $format) {
6522 $url = new moodle_url('/admin/courseformats.php',
6523 array('sesskey' => sesskey(), 'format' => $format->name));
6524 $isdefault = '';
6525 $class = '';
6526 if ($format->is_enabled()) {
6527 $strformatname = $format->displayname;
6528 if ($defaultformat === $format->name) {
6529 $hideshow = $txt->default;
6530 } else {
6531 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6532 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6534 } else {
6535 $strformatname = $format->displayname;
6536 $class = 'dimmed_text';
6537 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6538 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6540 $updown = '';
6541 if ($cnt) {
6542 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6543 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6544 } else {
6545 $updown .= $spacer;
6547 if ($cnt < count($formats) - 1) {
6548 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6549 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6550 } else {
6551 $updown .= $spacer;
6553 $cnt++;
6554 $settings = '';
6555 if ($format->get_settings_url()) {
6556 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6558 $uninstall = '';
6559 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6560 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6562 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6563 if ($class) {
6564 $row->attributes['class'] = $class;
6566 $table->data[] = $row;
6568 $return .= html_writer::table($table);
6569 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6570 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6571 $return .= $OUTPUT->box_end();
6572 return highlight($query, $return);
6577 * Special class for filter administration.
6579 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6581 class admin_page_managefilters extends admin_externalpage {
6583 * Calls parent::__construct with specific arguments
6585 public function __construct() {
6586 global $CFG;
6587 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6591 * Searches all installed filters for specified filter
6593 * @param string $query The filter(string) to search for
6594 * @param string $query
6596 public function search($query) {
6597 global $CFG;
6598 if ($result = parent::search($query)) {
6599 return $result;
6602 $found = false;
6603 $filternames = filter_get_all_installed();
6604 foreach ($filternames as $path => $strfiltername) {
6605 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6606 $found = true;
6607 break;
6609 if (strpos($path, $query) !== false) {
6610 $found = true;
6611 break;
6615 if ($found) {
6616 $result = new stdClass;
6617 $result->page = $this;
6618 $result->settings = array();
6619 return array($this->name => $result);
6620 } else {
6621 return array();
6628 * Initialise admin page - this function does require login and permission
6629 * checks specified in page definition.
6631 * This function must be called on each admin page before other code.
6633 * @global moodle_page $PAGE
6635 * @param string $section name of page
6636 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6637 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6638 * added to the turn blocks editing on/off form, so this page reloads correctly.
6639 * @param string $actualurl if the actual page being viewed is not the normal one for this
6640 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6641 * @param array $options Additional options that can be specified for page setup.
6642 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6644 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6645 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6647 $PAGE->set_context(null); // hack - set context to something, by default to system context
6649 $site = get_site();
6650 require_login();
6652 if (!empty($options['pagelayout'])) {
6653 // A specific page layout has been requested.
6654 $PAGE->set_pagelayout($options['pagelayout']);
6655 } else if ($section === 'upgradesettings') {
6656 $PAGE->set_pagelayout('maintenance');
6657 } else {
6658 $PAGE->set_pagelayout('admin');
6661 $adminroot = admin_get_root(false, false); // settings not required for external pages
6662 $extpage = $adminroot->locate($section, true);
6664 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6665 // The requested section isn't in the admin tree
6666 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6667 if (!has_capability('moodle/site:config', context_system::instance())) {
6668 // The requested section could depend on a different capability
6669 // but most likely the user has inadequate capabilities
6670 print_error('accessdenied', 'admin');
6671 } else {
6672 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6676 // this eliminates our need to authenticate on the actual pages
6677 if (!$extpage->check_access()) {
6678 print_error('accessdenied', 'admin');
6679 die;
6682 navigation_node::require_admin_tree();
6684 // $PAGE->set_extra_button($extrabutton); TODO
6686 if (!$actualurl) {
6687 $actualurl = $extpage->url;
6690 $PAGE->set_url($actualurl, $extraurlparams);
6691 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6692 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6695 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6696 // During initial install.
6697 $strinstallation = get_string('installation', 'install');
6698 $strsettings = get_string('settings');
6699 $PAGE->navbar->add($strsettings);
6700 $PAGE->set_title($strinstallation);
6701 $PAGE->set_heading($strinstallation);
6702 $PAGE->set_cacheable(false);
6703 return;
6706 // Locate the current item on the navigation and make it active when found.
6707 $path = $extpage->path;
6708 $node = $PAGE->settingsnav;
6709 while ($node && count($path) > 0) {
6710 $node = $node->get(array_pop($path));
6712 if ($node) {
6713 $node->make_active();
6716 // Normal case.
6717 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6718 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6719 $USER->editing = $adminediting;
6722 $visiblepathtosection = array_reverse($extpage->visiblepath);
6724 if ($PAGE->user_allowed_editing()) {
6725 if ($PAGE->user_is_editing()) {
6726 $caption = get_string('blockseditoff');
6727 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6728 } else {
6729 $caption = get_string('blocksediton');
6730 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6732 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6735 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6736 $PAGE->set_heading($SITE->fullname);
6738 // prevent caching in nav block
6739 $PAGE->navigation->clear_cache();
6743 * Returns the reference to admin tree root
6745 * @return object admin_root object
6747 function admin_get_root($reload=false, $requirefulltree=true) {
6748 global $CFG, $DB, $OUTPUT;
6750 static $ADMIN = NULL;
6752 if (is_null($ADMIN)) {
6753 // create the admin tree!
6754 $ADMIN = new admin_root($requirefulltree);
6757 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6758 $ADMIN->purge_children($requirefulltree);
6761 if (!$ADMIN->loaded) {
6762 // we process this file first to create categories first and in correct order
6763 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6765 // now we process all other files in admin/settings to build the admin tree
6766 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6767 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6768 continue;
6770 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6771 // plugins are loaded last - they may insert pages anywhere
6772 continue;
6774 require($file);
6776 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6778 $ADMIN->loaded = true;
6781 return $ADMIN;
6784 /// settings utility functions
6787 * This function applies default settings.
6789 * @param object $node, NULL means complete tree, null by default
6790 * @param bool $unconditional if true overrides all values with defaults, null buy default
6792 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6793 global $CFG;
6795 if (is_null($node)) {
6796 core_plugin_manager::reset_caches();
6797 $node = admin_get_root(true, true);
6800 if ($node instanceof admin_category) {
6801 $entries = array_keys($node->children);
6802 foreach ($entries as $entry) {
6803 admin_apply_default_settings($node->children[$entry], $unconditional);
6806 } else if ($node instanceof admin_settingpage) {
6807 foreach ($node->settings as $setting) {
6808 if (!$unconditional and !is_null($setting->get_setting())) {
6809 //do not override existing defaults
6810 continue;
6812 $defaultsetting = $setting->get_defaultsetting();
6813 if (is_null($defaultsetting)) {
6814 // no value yet - default maybe applied after admin user creation or in upgradesettings
6815 continue;
6817 $setting->write_setting($defaultsetting);
6818 $setting->write_setting_flags(null);
6821 // Just in case somebody modifies the list of active plugins directly.
6822 core_plugin_manager::reset_caches();
6826 * Store changed settings, this function updates the errors variable in $ADMIN
6828 * @param object $formdata from form
6829 * @return int number of changed settings
6831 function admin_write_settings($formdata) {
6832 global $CFG, $SITE, $DB;
6834 $olddbsessions = !empty($CFG->dbsessions);
6835 $formdata = (array)$formdata;
6837 $data = array();
6838 foreach ($formdata as $fullname=>$value) {
6839 if (strpos($fullname, 's_') !== 0) {
6840 continue; // not a config value
6842 $data[$fullname] = $value;
6845 $adminroot = admin_get_root();
6846 $settings = admin_find_write_settings($adminroot, $data);
6848 $count = 0;
6849 foreach ($settings as $fullname=>$setting) {
6850 /** @var $setting admin_setting */
6851 $original = $setting->get_setting();
6852 $error = $setting->write_setting($data[$fullname]);
6853 if ($error !== '') {
6854 $adminroot->errors[$fullname] = new stdClass();
6855 $adminroot->errors[$fullname]->data = $data[$fullname];
6856 $adminroot->errors[$fullname]->id = $setting->get_id();
6857 $adminroot->errors[$fullname]->error = $error;
6858 } else {
6859 $setting->write_setting_flags($data);
6861 if ($setting->post_write_settings($original)) {
6862 $count++;
6866 if ($olddbsessions != !empty($CFG->dbsessions)) {
6867 require_logout();
6870 // Now update $SITE - just update the fields, in case other people have a
6871 // a reference to it (e.g. $PAGE, $COURSE).
6872 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6873 foreach (get_object_vars($newsite) as $field => $value) {
6874 $SITE->$field = $value;
6877 // now reload all settings - some of them might depend on the changed
6878 admin_get_root(true);
6879 return $count;
6883 * Internal recursive function - finds all settings from submitted form
6885 * @param object $node Instance of admin_category, or admin_settingpage
6886 * @param array $data
6887 * @return array
6889 function admin_find_write_settings($node, $data) {
6890 $return = array();
6892 if (empty($data)) {
6893 return $return;
6896 if ($node instanceof admin_category) {
6897 $entries = array_keys($node->children);
6898 foreach ($entries as $entry) {
6899 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6902 } else if ($node instanceof admin_settingpage) {
6903 foreach ($node->settings as $setting) {
6904 $fullname = $setting->get_full_name();
6905 if (array_key_exists($fullname, $data)) {
6906 $return[$fullname] = $setting;
6912 return $return;
6916 * Internal function - prints the search results
6918 * @param string $query String to search for
6919 * @return string empty or XHTML
6921 function admin_search_settings_html($query) {
6922 global $CFG, $OUTPUT;
6924 if (core_text::strlen($query) < 2) {
6925 return '';
6927 $query = core_text::strtolower($query);
6929 $adminroot = admin_get_root();
6930 $findings = $adminroot->search($query);
6931 $return = '';
6932 $savebutton = false;
6934 foreach ($findings as $found) {
6935 $page = $found->page;
6936 $settings = $found->settings;
6937 if ($page->is_hidden()) {
6938 // hidden pages are not displayed in search results
6939 continue;
6941 if ($page instanceof admin_externalpage) {
6942 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6943 } else if ($page instanceof admin_settingpage) {
6944 $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');
6945 } else {
6946 continue;
6948 if (!empty($settings)) {
6949 $return .= '<fieldset class="adminsettings">'."\n";
6950 foreach ($settings as $setting) {
6951 if (empty($setting->nosave)) {
6952 $savebutton = true;
6954 $return .= '<div class="clearer"><!-- --></div>'."\n";
6955 $fullname = $setting->get_full_name();
6956 if (array_key_exists($fullname, $adminroot->errors)) {
6957 $data = $adminroot->errors[$fullname]->data;
6958 } else {
6959 $data = $setting->get_setting();
6960 // do not use defaults if settings not available - upgradesettings handles the defaults!
6962 $return .= $setting->output_html($data, $query);
6964 $return .= '</fieldset>';
6968 if ($savebutton) {
6969 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6972 return $return;
6976 * Internal function - returns arrays of html pages with uninitialised settings
6978 * @param object $node Instance of admin_category or admin_settingpage
6979 * @return array
6981 function admin_output_new_settings_by_page($node) {
6982 global $OUTPUT;
6983 $return = array();
6985 if ($node instanceof admin_category) {
6986 $entries = array_keys($node->children);
6987 foreach ($entries as $entry) {
6988 $return += admin_output_new_settings_by_page($node->children[$entry]);
6991 } else if ($node instanceof admin_settingpage) {
6992 $newsettings = array();
6993 foreach ($node->settings as $setting) {
6994 if (is_null($setting->get_setting())) {
6995 $newsettings[] = $setting;
6998 if (count($newsettings) > 0) {
6999 $adminroot = admin_get_root();
7000 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
7001 $page .= '<fieldset class="adminsettings">'."\n";
7002 foreach ($newsettings as $setting) {
7003 $fullname = $setting->get_full_name();
7004 if (array_key_exists($fullname, $adminroot->errors)) {
7005 $data = $adminroot->errors[$fullname]->data;
7006 } else {
7007 $data = $setting->get_setting();
7008 if (is_null($data)) {
7009 $data = $setting->get_defaultsetting();
7012 $page .= '<div class="clearer"><!-- --></div>'."\n";
7013 $page .= $setting->output_html($data);
7015 $page .= '</fieldset>';
7016 $return[$node->name] = $page;
7020 return $return;
7024 * Format admin settings
7026 * @param object $setting
7027 * @param string $title label element
7028 * @param string $form form fragment, html code - not highlighted automatically
7029 * @param string $description
7030 * @param mixed $label link label to id, true by default or string being the label to connect it to
7031 * @param string $warning warning text
7032 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
7033 * @param string $query search query to be highlighted
7034 * @return string XHTML
7036 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
7037 global $CFG;
7039 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
7040 $fullname = $setting->get_full_name();
7042 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
7043 if ($label === true) {
7044 $labelfor = 'for = "'.$setting->get_id().'"';
7045 } else if ($label === false) {
7046 $labelfor = '';
7047 } else {
7048 $labelfor = 'for="' . $label . '"';
7050 $form .= $setting->output_setting_flags();
7052 $override = '';
7053 if (empty($setting->plugin)) {
7054 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
7055 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7057 } else {
7058 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
7059 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7063 if ($warning !== '') {
7064 $warning = '<div class="form-warning">'.$warning.'</div>';
7067 $defaults = array();
7068 if (!is_null($defaultinfo)) {
7069 if ($defaultinfo === '') {
7070 $defaultinfo = get_string('emptysettingvalue', 'admin');
7072 $defaults[] = $defaultinfo;
7075 $setting->get_setting_flag_defaults($defaults);
7077 if (!empty($defaults)) {
7078 $defaultinfo = implode(', ', $defaults);
7079 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7080 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
7084 $adminroot = admin_get_root();
7085 $error = '';
7086 if (array_key_exists($fullname, $adminroot->errors)) {
7087 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
7090 $str = '
7091 <div class="form-item clearfix" id="admin-'.$setting->name.'">
7092 <div class="form-label">
7093 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
7094 <span class="form-shortname">'.highlightfast($query, $name).'</span>
7095 </div>
7096 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
7097 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
7098 </div>';
7100 return $str;
7104 * Based on find_new_settings{@link ()} in upgradesettings.php
7105 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7107 * @param object $node Instance of admin_category, or admin_settingpage
7108 * @return boolean true if any settings haven't been initialised, false if they all have
7110 function any_new_admin_settings($node) {
7112 if ($node instanceof admin_category) {
7113 $entries = array_keys($node->children);
7114 foreach ($entries as $entry) {
7115 if (any_new_admin_settings($node->children[$entry])) {
7116 return true;
7120 } else if ($node instanceof admin_settingpage) {
7121 foreach ($node->settings as $setting) {
7122 if ($setting->get_setting() === NULL) {
7123 return true;
7128 return false;
7132 * Moved from admin/replace.php so that we can use this in cron
7134 * @param string $search string to look for
7135 * @param string $replace string to replace
7136 * @return bool success or fail
7138 function db_replace($search, $replace) {
7139 global $DB, $CFG, $OUTPUT;
7141 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7142 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7143 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7144 'block_instances', '');
7146 // Turn off time limits, sometimes upgrades can be slow.
7147 core_php_time_limit::raise();
7149 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7150 return false;
7152 foreach ($tables as $table) {
7154 if (in_array($table, $skiptables)) { // Don't process these
7155 continue;
7158 if ($columns = $DB->get_columns($table)) {
7159 $DB->set_debug(true);
7160 foreach ($columns as $column) {
7161 $DB->replace_all_text($table, $column, $search, $replace);
7163 $DB->set_debug(false);
7167 // delete modinfo caches
7168 rebuild_course_cache(0, true);
7170 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7171 $blocks = core_component::get_plugin_list('block');
7172 foreach ($blocks as $blockname=>$fullblock) {
7173 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7174 continue;
7177 if (!is_readable($fullblock.'/lib.php')) {
7178 continue;
7181 $function = 'block_'.$blockname.'_global_db_replace';
7182 include_once($fullblock.'/lib.php');
7183 if (!function_exists($function)) {
7184 continue;
7187 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7188 $function($search, $replace);
7189 echo $OUTPUT->notification("...finished", 'notifysuccess');
7192 purge_all_caches();
7194 return true;
7198 * Manage repository settings
7200 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7202 class admin_setting_managerepository extends admin_setting {
7203 /** @var string */
7204 private $baseurl;
7207 * calls parent::__construct with specific arguments
7209 public function __construct() {
7210 global $CFG;
7211 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7212 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7216 * Always returns true, does nothing
7218 * @return true
7220 public function get_setting() {
7221 return true;
7225 * Always returns true does nothing
7227 * @return true
7229 public function get_defaultsetting() {
7230 return true;
7234 * Always returns s_managerepository
7236 * @return string Always return 's_managerepository'
7238 public function get_full_name() {
7239 return 's_managerepository';
7243 * Always returns '' doesn't do anything
7245 public function write_setting($data) {
7246 $url = $this->baseurl . '&amp;new=' . $data;
7247 return '';
7248 // TODO
7249 // Should not use redirect and exit here
7250 // Find a better way to do this.
7251 // redirect($url);
7252 // exit;
7256 * Searches repository plugins for one that matches $query
7258 * @param string $query The string to search for
7259 * @return bool true if found, false if not
7261 public function is_related($query) {
7262 if (parent::is_related($query)) {
7263 return true;
7266 $repositories= core_component::get_plugin_list('repository');
7267 foreach ($repositories as $p => $dir) {
7268 if (strpos($p, $query) !== false) {
7269 return true;
7272 foreach (repository::get_types() as $instance) {
7273 $title = $instance->get_typename();
7274 if (strpos(core_text::strtolower($title), $query) !== false) {
7275 return true;
7278 return false;
7282 * Helper function that generates a moodle_url object
7283 * relevant to the repository
7286 function repository_action_url($repository) {
7287 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7291 * Builds XHTML to display the control
7293 * @param string $data Unused
7294 * @param string $query
7295 * @return string XHTML
7297 public function output_html($data, $query='') {
7298 global $CFG, $USER, $OUTPUT;
7300 // Get strings that are used
7301 $strshow = get_string('on', 'repository');
7302 $strhide = get_string('off', 'repository');
7303 $strdelete = get_string('disabled', 'repository');
7305 $actionchoicesforexisting = array(
7306 'show' => $strshow,
7307 'hide' => $strhide,
7308 'delete' => $strdelete
7311 $actionchoicesfornew = array(
7312 'newon' => $strshow,
7313 'newoff' => $strhide,
7314 'delete' => $strdelete
7317 $return = '';
7318 $return .= $OUTPUT->box_start('generalbox');
7320 // Set strings that are used multiple times
7321 $settingsstr = get_string('settings');
7322 $disablestr = get_string('disable');
7324 // Table to list plug-ins
7325 $table = new html_table();
7326 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7327 $table->align = array('left', 'center', 'center', 'center', 'center');
7328 $table->data = array();
7330 // Get list of used plug-ins
7331 $repositorytypes = repository::get_types();
7332 if (!empty($repositorytypes)) {
7333 // Array to store plugins being used
7334 $alreadyplugins = array();
7335 $totalrepositorytypes = count($repositorytypes);
7336 $updowncount = 1;
7337 foreach ($repositorytypes as $i) {
7338 $settings = '';
7339 $typename = $i->get_typename();
7340 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7341 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7342 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7344 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7345 // Calculate number of instances in order to display them for the Moodle administrator
7346 if (!empty($instanceoptionnames)) {
7347 $params = array();
7348 $params['context'] = array(context_system::instance());
7349 $params['onlyvisible'] = false;
7350 $params['type'] = $typename;
7351 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7352 // site instances
7353 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7354 $params['context'] = array();
7355 $instances = repository::static_function($typename, 'get_instances', $params);
7356 $courseinstances = array();
7357 $userinstances = array();
7359 foreach ($instances as $instance) {
7360 $repocontext = context::instance_by_id($instance->instance->contextid);
7361 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7362 $courseinstances[] = $instance;
7363 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7364 $userinstances[] = $instance;
7367 // course instances
7368 $instancenumber = count($courseinstances);
7369 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7371 // user private instances
7372 $instancenumber = count($userinstances);
7373 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7374 } else {
7375 $admininstancenumbertext = "";
7376 $courseinstancenumbertext = "";
7377 $userinstancenumbertext = "";
7380 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7382 $settings .= $OUTPUT->container_start('mdl-left');
7383 $settings .= '<br/>';
7384 $settings .= $admininstancenumbertext;
7385 $settings .= '<br/>';
7386 $settings .= $courseinstancenumbertext;
7387 $settings .= '<br/>';
7388 $settings .= $userinstancenumbertext;
7389 $settings .= $OUTPUT->container_end();
7391 // Get the current visibility
7392 if ($i->get_visible()) {
7393 $currentaction = 'show';
7394 } else {
7395 $currentaction = 'hide';
7398 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7400 // Display up/down link
7401 $updown = '';
7402 // Should be done with CSS instead.
7403 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7405 if ($updowncount > 1) {
7406 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7407 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7409 else {
7410 $updown .= $spacer;
7412 if ($updowncount < $totalrepositorytypes) {
7413 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7414 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7416 else {
7417 $updown .= $spacer;
7420 $updowncount++;
7422 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7424 if (!in_array($typename, $alreadyplugins)) {
7425 $alreadyplugins[] = $typename;
7430 // Get all the plugins that exist on disk
7431 $plugins = core_component::get_plugin_list('repository');
7432 if (!empty($plugins)) {
7433 foreach ($plugins as $plugin => $dir) {
7434 // Check that it has not already been listed
7435 if (!in_array($plugin, $alreadyplugins)) {
7436 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7437 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7442 $return .= html_writer::table($table);
7443 $return .= $OUTPUT->box_end();
7444 return highlight($query, $return);
7449 * Special checkbox for enable mobile web service
7450 * If enable then we store the service id of the mobile service into config table
7451 * If disable then we unstore the service id from the config table
7453 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7455 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7456 private $xmlrpcuse;
7457 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7458 private $restuse;
7461 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7463 * @return boolean
7465 private function is_protocol_cap_allowed() {
7466 global $DB, $CFG;
7468 // We keep xmlrpc enabled for backward compatibility.
7469 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7470 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7471 $params = array();
7472 $params['permission'] = CAP_ALLOW;
7473 $params['roleid'] = $CFG->defaultuserroleid;
7474 $params['capability'] = 'webservice/xmlrpc:use';
7475 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7478 // If the $this->restuse variable is not set, it needs to be set.
7479 if (empty($this->restuse) and $this->restuse!==false) {
7480 $params = array();
7481 $params['permission'] = CAP_ALLOW;
7482 $params['roleid'] = $CFG->defaultuserroleid;
7483 $params['capability'] = 'webservice/rest:use';
7484 $this->restuse = $DB->record_exists('role_capabilities', $params);
7487 return ($this->xmlrpcuse && $this->restuse);
7491 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7492 * @param type $status true to allow, false to not set
7494 private function set_protocol_cap($status) {
7495 global $CFG;
7496 if ($status and !$this->is_protocol_cap_allowed()) {
7497 //need to allow the cap
7498 $permission = CAP_ALLOW;
7499 $assign = true;
7500 } else if (!$status and $this->is_protocol_cap_allowed()){
7501 //need to disallow the cap
7502 $permission = CAP_INHERIT;
7503 $assign = true;
7505 if (!empty($assign)) {
7506 $systemcontext = context_system::instance();
7507 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7508 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7513 * Builds XHTML to display the control.
7514 * The main purpose of this overloading is to display a warning when https
7515 * is not supported by the server
7516 * @param string $data Unused
7517 * @param string $query
7518 * @return string XHTML
7520 public function output_html($data, $query='') {
7521 global $CFG, $OUTPUT;
7522 $html = parent::output_html($data, $query);
7524 if ((string)$data === $this->yes) {
7525 require_once($CFG->dirroot . "/lib/filelib.php");
7526 $curl = new curl();
7527 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7528 $curl->head($httpswwwroot . "/login/index.php");
7529 $info = $curl->get_info();
7530 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7531 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7535 return $html;
7539 * Retrieves the current setting using the objects name
7541 * @return string
7543 public function get_setting() {
7544 global $CFG;
7546 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7547 // Or if web services aren't enabled this can't be,
7548 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7549 return 0;
7552 require_once($CFG->dirroot . '/webservice/lib.php');
7553 $webservicemanager = new webservice();
7554 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7555 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7556 return $this->config_read($this->name); //same as returning 1
7557 } else {
7558 return 0;
7563 * Save the selected setting
7565 * @param string $data The selected site
7566 * @return string empty string or error message
7568 public function write_setting($data) {
7569 global $DB, $CFG;
7571 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7572 if (empty($CFG->defaultuserroleid)) {
7573 return '';
7576 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7578 require_once($CFG->dirroot . '/webservice/lib.php');
7579 $webservicemanager = new webservice();
7581 $updateprotocol = false;
7582 if ((string)$data === $this->yes) {
7583 //code run when enable mobile web service
7584 //enable web service systeme if necessary
7585 set_config('enablewebservices', true);
7587 //enable mobile service
7588 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7589 $mobileservice->enabled = 1;
7590 $webservicemanager->update_external_service($mobileservice);
7592 //enable xml-rpc server
7593 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7595 if (!in_array('xmlrpc', $activeprotocols)) {
7596 $activeprotocols[] = 'xmlrpc';
7597 $updateprotocol = true;
7600 if (!in_array('rest', $activeprotocols)) {
7601 $activeprotocols[] = 'rest';
7602 $updateprotocol = true;
7605 if ($updateprotocol) {
7606 set_config('webserviceprotocols', implode(',', $activeprotocols));
7609 //allow xml-rpc:use capability for authenticated user
7610 $this->set_protocol_cap(true);
7612 } else {
7613 //disable web service system if no other services are enabled
7614 $otherenabledservices = $DB->get_records_select('external_services',
7615 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7616 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7617 if (empty($otherenabledservices)) {
7618 set_config('enablewebservices', false);
7620 //also disable xml-rpc server
7621 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7622 $protocolkey = array_search('xmlrpc', $activeprotocols);
7623 if ($protocolkey !== false) {
7624 unset($activeprotocols[$protocolkey]);
7625 $updateprotocol = true;
7628 $protocolkey = array_search('rest', $activeprotocols);
7629 if ($protocolkey !== false) {
7630 unset($activeprotocols[$protocolkey]);
7631 $updateprotocol = true;
7634 if ($updateprotocol) {
7635 set_config('webserviceprotocols', implode(',', $activeprotocols));
7638 //disallow xml-rpc:use capability for authenticated user
7639 $this->set_protocol_cap(false);
7642 //disable the mobile service
7643 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7644 $mobileservice->enabled = 0;
7645 $webservicemanager->update_external_service($mobileservice);
7648 return (parent::write_setting($data));
7653 * Special class for management of external services
7655 * @author Petr Skoda (skodak)
7657 class admin_setting_manageexternalservices extends admin_setting {
7659 * Calls parent::__construct with specific arguments
7661 public function __construct() {
7662 $this->nosave = true;
7663 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7667 * Always returns true, does nothing
7669 * @return true
7671 public function get_setting() {
7672 return true;
7676 * Always returns true, does nothing
7678 * @return true
7680 public function get_defaultsetting() {
7681 return true;
7685 * Always returns '', does not write anything
7687 * @return string Always returns ''
7689 public function write_setting($data) {
7690 // do not write any setting
7691 return '';
7695 * Checks if $query is one of the available external services
7697 * @param string $query The string to search for
7698 * @return bool Returns true if found, false if not
7700 public function is_related($query) {
7701 global $DB;
7703 if (parent::is_related($query)) {
7704 return true;
7707 $services = $DB->get_records('external_services', array(), 'id, name');
7708 foreach ($services as $service) {
7709 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7710 return true;
7713 return false;
7717 * Builds the XHTML to display the control
7719 * @param string $data Unused
7720 * @param string $query
7721 * @return string
7723 public function output_html($data, $query='') {
7724 global $CFG, $OUTPUT, $DB;
7726 // display strings
7727 $stradministration = get_string('administration');
7728 $stredit = get_string('edit');
7729 $strservice = get_string('externalservice', 'webservice');
7730 $strdelete = get_string('delete');
7731 $strplugin = get_string('plugin', 'admin');
7732 $stradd = get_string('add');
7733 $strfunctions = get_string('functions', 'webservice');
7734 $strusers = get_string('users');
7735 $strserviceusers = get_string('serviceusers', 'webservice');
7737 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7738 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7739 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7741 // built in services
7742 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7743 $return = "";
7744 if (!empty($services)) {
7745 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7749 $table = new html_table();
7750 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7751 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7752 $table->id = 'builtinservices';
7753 $table->attributes['class'] = 'admintable externalservices generaltable';
7754 $table->data = array();
7756 // iterate through auth plugins and add to the display table
7757 foreach ($services as $service) {
7758 $name = $service->name;
7760 // hide/show link
7761 if ($service->enabled) {
7762 $displayname = "<span>$name</span>";
7763 } else {
7764 $displayname = "<span class=\"dimmed_text\">$name</span>";
7767 $plugin = $service->component;
7769 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7771 if ($service->restrictedusers) {
7772 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7773 } else {
7774 $users = get_string('allusers', 'webservice');
7777 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7779 // add a row to the table
7780 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7782 $return .= html_writer::table($table);
7785 // Custom services
7786 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7787 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7789 $table = new html_table();
7790 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7791 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7792 $table->id = 'customservices';
7793 $table->attributes['class'] = 'admintable externalservices generaltable';
7794 $table->data = array();
7796 // iterate through auth plugins and add to the display table
7797 foreach ($services as $service) {
7798 $name = $service->name;
7800 // hide/show link
7801 if ($service->enabled) {
7802 $displayname = "<span>$name</span>";
7803 } else {
7804 $displayname = "<span class=\"dimmed_text\">$name</span>";
7807 // delete link
7808 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7810 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7812 if ($service->restrictedusers) {
7813 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7814 } else {
7815 $users = get_string('allusers', 'webservice');
7818 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7820 // add a row to the table
7821 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7823 // add new custom service option
7824 $return .= html_writer::table($table);
7826 $return .= '<br />';
7827 // add a token to the table
7828 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7830 return highlight($query, $return);
7835 * Special class for overview of external services
7837 * @author Jerome Mouneyrac
7839 class admin_setting_webservicesoverview extends admin_setting {
7842 * Calls parent::__construct with specific arguments
7844 public function __construct() {
7845 $this->nosave = true;
7846 parent::__construct('webservicesoverviewui',
7847 get_string('webservicesoverview', 'webservice'), '', '');
7851 * Always returns true, does nothing
7853 * @return true
7855 public function get_setting() {
7856 return true;
7860 * Always returns true, does nothing
7862 * @return true
7864 public function get_defaultsetting() {
7865 return true;
7869 * Always returns '', does not write anything
7871 * @return string Always returns ''
7873 public function write_setting($data) {
7874 // do not write any setting
7875 return '';
7879 * Builds the XHTML to display the control
7881 * @param string $data Unused
7882 * @param string $query
7883 * @return string
7885 public function output_html($data, $query='') {
7886 global $CFG, $OUTPUT;
7888 $return = "";
7889 $brtag = html_writer::empty_tag('br');
7891 // Enable mobile web service
7892 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7893 get_string('enablemobilewebservice', 'admin'),
7894 get_string('configenablemobilewebservice',
7895 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7896 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
7897 $wsmobileparam = new stdClass();
7898 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7899 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7900 get_string('mobile', 'admin'));
7901 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7902 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7903 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7904 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7905 . $brtag . $brtag;
7907 /// One system controlling Moodle with Token
7908 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7909 $table = new html_table();
7910 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7911 get_string('description'));
7912 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7913 $table->id = 'onesystemcontrol';
7914 $table->attributes['class'] = 'admintable wsoverview generaltable';
7915 $table->data = array();
7917 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7918 . $brtag . $brtag;
7920 /// 1. Enable Web Services
7921 $row = array();
7922 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7923 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7924 array('href' => $url));
7925 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7926 if ($CFG->enablewebservices) {
7927 $status = get_string('yes');
7929 $row[1] = $status;
7930 $row[2] = get_string('enablewsdescription', 'webservice');
7931 $table->data[] = $row;
7933 /// 2. Enable protocols
7934 $row = array();
7935 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7936 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7937 array('href' => $url));
7938 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7939 //retrieve activated protocol
7940 $active_protocols = empty($CFG->webserviceprotocols) ?
7941 array() : explode(',', $CFG->webserviceprotocols);
7942 if (!empty($active_protocols)) {
7943 $status = "";
7944 foreach ($active_protocols as $protocol) {
7945 $status .= $protocol . $brtag;
7948 $row[1] = $status;
7949 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7950 $table->data[] = $row;
7952 /// 3. Create user account
7953 $row = array();
7954 $url = new moodle_url("/user/editadvanced.php?id=-1");
7955 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7956 array('href' => $url));
7957 $row[1] = "";
7958 $row[2] = get_string('createuserdescription', 'webservice');
7959 $table->data[] = $row;
7961 /// 4. Add capability to users
7962 $row = array();
7963 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7964 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7965 array('href' => $url));
7966 $row[1] = "";
7967 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7968 $table->data[] = $row;
7970 /// 5. Select a web service
7971 $row = array();
7972 $url = new moodle_url("/admin/settings.php?section=externalservices");
7973 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7974 array('href' => $url));
7975 $row[1] = "";
7976 $row[2] = get_string('createservicedescription', 'webservice');
7977 $table->data[] = $row;
7979 /// 6. Add functions
7980 $row = array();
7981 $url = new moodle_url("/admin/settings.php?section=externalservices");
7982 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7983 array('href' => $url));
7984 $row[1] = "";
7985 $row[2] = get_string('addfunctionsdescription', 'webservice');
7986 $table->data[] = $row;
7988 /// 7. Add the specific user
7989 $row = array();
7990 $url = new moodle_url("/admin/settings.php?section=externalservices");
7991 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7992 array('href' => $url));
7993 $row[1] = "";
7994 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7995 $table->data[] = $row;
7997 /// 8. Create token for the specific user
7998 $row = array();
7999 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
8000 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
8001 array('href' => $url));
8002 $row[1] = "";
8003 $row[2] = get_string('createtokenforuserdescription', 'webservice');
8004 $table->data[] = $row;
8006 /// 9. Enable the documentation
8007 $row = array();
8008 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
8009 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
8010 array('href' => $url));
8011 $status = '<span class="warning">' . get_string('no') . '</span>';
8012 if ($CFG->enablewsdocumentation) {
8013 $status = get_string('yes');
8015 $row[1] = $status;
8016 $row[2] = get_string('enabledocumentationdescription', 'webservice');
8017 $table->data[] = $row;
8019 /// 10. Test the service
8020 $row = array();
8021 $url = new moodle_url("/admin/webservice/testclient.php");
8022 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8023 array('href' => $url));
8024 $row[1] = "";
8025 $row[2] = get_string('testwithtestclientdescription', 'webservice');
8026 $table->data[] = $row;
8028 $return .= html_writer::table($table);
8030 /// Users as clients with token
8031 $return .= $brtag . $brtag . $brtag;
8032 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
8033 $table = new html_table();
8034 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8035 get_string('description'));
8036 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8037 $table->id = 'userasclients';
8038 $table->attributes['class'] = 'admintable wsoverview generaltable';
8039 $table->data = array();
8041 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
8042 $brtag . $brtag;
8044 /// 1. Enable Web Services
8045 $row = array();
8046 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8047 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8048 array('href' => $url));
8049 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8050 if ($CFG->enablewebservices) {
8051 $status = get_string('yes');
8053 $row[1] = $status;
8054 $row[2] = get_string('enablewsdescription', 'webservice');
8055 $table->data[] = $row;
8057 /// 2. Enable protocols
8058 $row = array();
8059 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8060 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8061 array('href' => $url));
8062 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8063 //retrieve activated protocol
8064 $active_protocols = empty($CFG->webserviceprotocols) ?
8065 array() : explode(',', $CFG->webserviceprotocols);
8066 if (!empty($active_protocols)) {
8067 $status = "";
8068 foreach ($active_protocols as $protocol) {
8069 $status .= $protocol . $brtag;
8072 $row[1] = $status;
8073 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8074 $table->data[] = $row;
8077 /// 3. Select a web service
8078 $row = array();
8079 $url = new moodle_url("/admin/settings.php?section=externalservices");
8080 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8081 array('href' => $url));
8082 $row[1] = "";
8083 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8084 $table->data[] = $row;
8086 /// 4. Add functions
8087 $row = array();
8088 $url = new moodle_url("/admin/settings.php?section=externalservices");
8089 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8090 array('href' => $url));
8091 $row[1] = "";
8092 $row[2] = get_string('addfunctionsdescription', 'webservice');
8093 $table->data[] = $row;
8095 /// 5. Add capability to users
8096 $row = array();
8097 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8098 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8099 array('href' => $url));
8100 $row[1] = "";
8101 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8102 $table->data[] = $row;
8104 /// 6. Test the service
8105 $row = array();
8106 $url = new moodle_url("/admin/webservice/testclient.php");
8107 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8108 array('href' => $url));
8109 $row[1] = "";
8110 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8111 $table->data[] = $row;
8113 $return .= html_writer::table($table);
8115 return highlight($query, $return);
8122 * Special class for web service protocol administration.
8124 * @author Petr Skoda (skodak)
8126 class admin_setting_managewebserviceprotocols extends admin_setting {
8129 * Calls parent::__construct with specific arguments
8131 public function __construct() {
8132 $this->nosave = true;
8133 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8137 * Always returns true, does nothing
8139 * @return true
8141 public function get_setting() {
8142 return true;
8146 * Always returns true, does nothing
8148 * @return true
8150 public function get_defaultsetting() {
8151 return true;
8155 * Always returns '', does not write anything
8157 * @return string Always returns ''
8159 public function write_setting($data) {
8160 // do not write any setting
8161 return '';
8165 * Checks if $query is one of the available webservices
8167 * @param string $query The string to search for
8168 * @return bool Returns true if found, false if not
8170 public function is_related($query) {
8171 if (parent::is_related($query)) {
8172 return true;
8175 $protocols = core_component::get_plugin_list('webservice');
8176 foreach ($protocols as $protocol=>$location) {
8177 if (strpos($protocol, $query) !== false) {
8178 return true;
8180 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8181 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8182 return true;
8185 return false;
8189 * Builds the XHTML to display the control
8191 * @param string $data Unused
8192 * @param string $query
8193 * @return string
8195 public function output_html($data, $query='') {
8196 global $CFG, $OUTPUT;
8198 // display strings
8199 $stradministration = get_string('administration');
8200 $strsettings = get_string('settings');
8201 $stredit = get_string('edit');
8202 $strprotocol = get_string('protocol', 'webservice');
8203 $strenable = get_string('enable');
8204 $strdisable = get_string('disable');
8205 $strversion = get_string('version');
8207 $protocols_available = core_component::get_plugin_list('webservice');
8208 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8209 ksort($protocols_available);
8211 foreach ($active_protocols as $key=>$protocol) {
8212 if (empty($protocols_available[$protocol])) {
8213 unset($active_protocols[$key]);
8217 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8218 $return .= $OUTPUT->box_start('generalbox webservicesui');
8220 $table = new html_table();
8221 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8222 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8223 $table->id = 'webserviceprotocols';
8224 $table->attributes['class'] = 'admintable generaltable';
8225 $table->data = array();
8227 // iterate through auth plugins and add to the display table
8228 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8229 foreach ($protocols_available as $protocol => $location) {
8230 $name = get_string('pluginname', 'webservice_'.$protocol);
8232 $plugin = new stdClass();
8233 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8234 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8236 $version = isset($plugin->version) ? $plugin->version : '';
8238 // hide/show link
8239 if (in_array($protocol, $active_protocols)) {
8240 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8241 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8242 $displayname = "<span>$name</span>";
8243 } else {
8244 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8245 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8246 $displayname = "<span class=\"dimmed_text\">$name</span>";
8249 // settings link
8250 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8251 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8252 } else {
8253 $settings = '';
8256 // add a row to the table
8257 $table->data[] = array($displayname, $version, $hideshow, $settings);
8259 $return .= html_writer::table($table);
8260 $return .= get_string('configwebserviceplugins', 'webservice');
8261 $return .= $OUTPUT->box_end();
8263 return highlight($query, $return);
8269 * Special class for web service token administration.
8271 * @author Jerome Mouneyrac
8273 class admin_setting_managewebservicetokens extends admin_setting {
8276 * Calls parent::__construct with specific arguments
8278 public function __construct() {
8279 $this->nosave = true;
8280 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8284 * Always returns true, does nothing
8286 * @return true
8288 public function get_setting() {
8289 return true;
8293 * Always returns true, does nothing
8295 * @return true
8297 public function get_defaultsetting() {
8298 return true;
8302 * Always returns '', does not write anything
8304 * @return string Always returns ''
8306 public function write_setting($data) {
8307 // do not write any setting
8308 return '';
8312 * Builds the XHTML to display the control
8314 * @param string $data Unused
8315 * @param string $query
8316 * @return string
8318 public function output_html($data, $query='') {
8319 global $CFG, $OUTPUT, $DB, $USER;
8321 // display strings
8322 $stroperation = get_string('operation', 'webservice');
8323 $strtoken = get_string('token', 'webservice');
8324 $strservice = get_string('service', 'webservice');
8325 $struser = get_string('user');
8326 $strcontext = get_string('context', 'webservice');
8327 $strvaliduntil = get_string('validuntil', 'webservice');
8328 $striprestriction = get_string('iprestriction', 'webservice');
8330 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8332 $table = new html_table();
8333 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8334 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8335 $table->id = 'webservicetokens';
8336 $table->attributes['class'] = 'admintable generaltable';
8337 $table->data = array();
8339 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8341 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8343 //here retrieve token list (including linked users firstname/lastname and linked services name)
8344 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8345 FROM {external_tokens} t, {user} u, {external_services} s
8346 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8347 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8348 if (!empty($tokens)) {
8349 foreach ($tokens as $token) {
8350 //TODO: retrieve context
8352 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8353 $delete .= get_string('delete')."</a>";
8355 $validuntil = '';
8356 if (!empty($token->validuntil)) {
8357 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8360 $iprestriction = '';
8361 if (!empty($token->iprestriction)) {
8362 $iprestriction = $token->iprestriction;
8365 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8366 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8367 $useratag .= $token->firstname." ".$token->lastname;
8368 $useratag .= html_writer::end_tag('a');
8370 //check user missing capabilities
8371 require_once($CFG->dirroot . '/webservice/lib.php');
8372 $webservicemanager = new webservice();
8373 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8374 array(array('id' => $token->userid)), $token->serviceid);
8376 if (!is_siteadmin($token->userid) and
8377 array_key_exists($token->userid, $usermissingcaps)) {
8378 $missingcapabilities = implode(', ',
8379 $usermissingcaps[$token->userid]);
8380 if (!empty($missingcapabilities)) {
8381 $useratag .= html_writer::tag('div',
8382 get_string('usermissingcaps', 'webservice',
8383 $missingcapabilities)
8384 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8385 array('class' => 'missingcaps'));
8389 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8392 $return .= html_writer::table($table);
8393 } else {
8394 $return .= get_string('notoken', 'webservice');
8397 $return .= $OUTPUT->box_end();
8398 // add a token to the table
8399 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8400 $return .= get_string('add')."</a>";
8402 return highlight($query, $return);
8408 * Colour picker
8410 * @copyright 2010 Sam Hemelryk
8411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8413 class admin_setting_configcolourpicker extends admin_setting {
8416 * Information for previewing the colour
8418 * @var array|null
8420 protected $previewconfig = null;
8423 * Use default when empty.
8425 protected $usedefaultwhenempty = true;
8429 * @param string $name
8430 * @param string $visiblename
8431 * @param string $description
8432 * @param string $defaultsetting
8433 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8435 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8436 $usedefaultwhenempty = true) {
8437 $this->previewconfig = $previewconfig;
8438 $this->usedefaultwhenempty = $usedefaultwhenempty;
8439 parent::__construct($name, $visiblename, $description, $defaultsetting);
8443 * Return the setting
8445 * @return mixed returns config if successful else null
8447 public function get_setting() {
8448 return $this->config_read($this->name);
8452 * Saves the setting
8454 * @param string $data
8455 * @return bool
8457 public function write_setting($data) {
8458 $data = $this->validate($data);
8459 if ($data === false) {
8460 return get_string('validateerror', 'admin');
8462 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8466 * Validates the colour that was entered by the user
8468 * @param string $data
8469 * @return string|false
8471 protected function validate($data) {
8473 * List of valid HTML colour names
8475 * @var array
8477 $colornames = array(
8478 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8479 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8480 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8481 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8482 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8483 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8484 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8485 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8486 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8487 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8488 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8489 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8490 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8491 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8492 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8493 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8494 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8495 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8496 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8497 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8498 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8499 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8500 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8501 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8502 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8503 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8504 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8505 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8506 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8507 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8508 'whitesmoke', 'yellow', 'yellowgreen'
8511 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8512 if (strpos($data, '#')!==0) {
8513 $data = '#'.$data;
8515 return $data;
8516 } else if (in_array(strtolower($data), $colornames)) {
8517 return $data;
8518 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8519 return $data;
8520 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8521 return $data;
8522 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8523 return $data;
8524 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8525 return $data;
8526 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8527 return $data;
8528 } else if (empty($data)) {
8529 if ($this->usedefaultwhenempty){
8530 return $this->defaultsetting;
8531 } else {
8532 return '';
8534 } else {
8535 return false;
8540 * Generates the HTML for the setting
8542 * @global moodle_page $PAGE
8543 * @global core_renderer $OUTPUT
8544 * @param string $data
8545 * @param string $query
8547 public function output_html($data, $query = '') {
8548 global $PAGE, $OUTPUT;
8549 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8550 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8551 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8552 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8553 if (!empty($this->previewconfig)) {
8554 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8556 $content .= html_writer::end_tag('div');
8557 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8563 * Class used for uploading of one file into file storage,
8564 * the file name is stored in config table.
8566 * Please note you need to implement your own '_pluginfile' callback function,
8567 * this setting only stores the file, it does not deal with file serving.
8569 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8572 class admin_setting_configstoredfile extends admin_setting {
8573 /** @var array file area options - should be one file only */
8574 protected $options;
8575 /** @var string name of the file area */
8576 protected $filearea;
8577 /** @var int intemid */
8578 protected $itemid;
8579 /** @var string used for detection of changes */
8580 protected $oldhashes;
8583 * Create new stored file setting.
8585 * @param string $name low level setting name
8586 * @param string $visiblename human readable setting name
8587 * @param string $description description of setting
8588 * @param mixed $filearea file area for file storage
8589 * @param int $itemid itemid for file storage
8590 * @param array $options file area options
8592 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8593 parent::__construct($name, $visiblename, $description, '');
8594 $this->filearea = $filearea;
8595 $this->itemid = $itemid;
8596 $this->options = (array)$options;
8600 * Applies defaults and returns all options.
8601 * @return array
8603 protected function get_options() {
8604 global $CFG;
8606 require_once("$CFG->libdir/filelib.php");
8607 require_once("$CFG->dirroot/repository/lib.php");
8608 $defaults = array(
8609 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8610 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8611 'context' => context_system::instance());
8612 foreach($this->options as $k => $v) {
8613 $defaults[$k] = $v;
8616 return $defaults;
8619 public function get_setting() {
8620 return $this->config_read($this->name);
8623 public function write_setting($data) {
8624 global $USER;
8626 // Let's not deal with validation here, this is for admins only.
8627 $current = $this->get_setting();
8628 if (empty($data) && $current === null) {
8629 // This will be the case when applying default settings (installation).
8630 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8631 } else if (!is_number($data)) {
8632 // Draft item id is expected here!
8633 return get_string('errorsetting', 'admin');
8636 $options = $this->get_options();
8637 $fs = get_file_storage();
8638 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8640 $this->oldhashes = null;
8641 if ($current) {
8642 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8643 if ($file = $fs->get_file_by_hash($hash)) {
8644 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8646 unset($file);
8649 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8650 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8651 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8652 // with an error because the draft area does not exist, as he did not use it.
8653 $usercontext = context_user::instance($USER->id);
8654 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8655 return get_string('errorsetting', 'admin');
8659 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8660 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8662 $filepath = '';
8663 if ($files) {
8664 /** @var stored_file $file */
8665 $file = reset($files);
8666 $filepath = $file->get_filepath().$file->get_filename();
8669 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8672 public function post_write_settings($original) {
8673 $options = $this->get_options();
8674 $fs = get_file_storage();
8675 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8677 $current = $this->get_setting();
8678 $newhashes = null;
8679 if ($current) {
8680 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8681 if ($file = $fs->get_file_by_hash($hash)) {
8682 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8684 unset($file);
8687 if ($this->oldhashes === $newhashes) {
8688 $this->oldhashes = null;
8689 return false;
8691 $this->oldhashes = null;
8693 $callbackfunction = $this->updatedcallback;
8694 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8695 $callbackfunction($this->get_full_name());
8697 return true;
8700 public function output_html($data, $query = '') {
8701 global $PAGE, $CFG;
8703 $options = $this->get_options();
8704 $id = $this->get_id();
8705 $elname = $this->get_full_name();
8706 $draftitemid = file_get_submitted_draft_itemid($elname);
8707 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8708 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8710 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8711 require_once("$CFG->dirroot/lib/form/filemanager.php");
8713 $fmoptions = new stdClass();
8714 $fmoptions->mainfile = $options['mainfile'];
8715 $fmoptions->maxbytes = $options['maxbytes'];
8716 $fmoptions->maxfiles = $options['maxfiles'];
8717 $fmoptions->client_id = uniqid();
8718 $fmoptions->itemid = $draftitemid;
8719 $fmoptions->subdirs = $options['subdirs'];
8720 $fmoptions->target = $id;
8721 $fmoptions->accepted_types = $options['accepted_types'];
8722 $fmoptions->return_types = $options['return_types'];
8723 $fmoptions->context = $options['context'];
8724 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8726 $fm = new form_filemanager($fmoptions);
8727 $output = $PAGE->get_renderer('core', 'files');
8728 $html = $output->render($fm);
8730 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8731 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8733 return format_admin_setting($this, $this->visiblename,
8734 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8740 * Administration interface for user specified regular expressions for device detection.
8742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8744 class admin_setting_devicedetectregex extends admin_setting {
8747 * Calls parent::__construct with specific args
8749 * @param string $name
8750 * @param string $visiblename
8751 * @param string $description
8752 * @param mixed $defaultsetting
8754 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8755 global $CFG;
8756 parent::__construct($name, $visiblename, $description, $defaultsetting);
8760 * Return the current setting(s)
8762 * @return array Current settings array
8764 public function get_setting() {
8765 global $CFG;
8767 $config = $this->config_read($this->name);
8768 if (is_null($config)) {
8769 return null;
8772 return $this->prepare_form_data($config);
8776 * Save selected settings
8778 * @param array $data Array of settings to save
8779 * @return bool
8781 public function write_setting($data) {
8782 if (empty($data)) {
8783 $data = array();
8786 if ($this->config_write($this->name, $this->process_form_data($data))) {
8787 return ''; // success
8788 } else {
8789 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8794 * Return XHTML field(s) for regexes
8796 * @param array $data Array of options to set in HTML
8797 * @return string XHTML string for the fields and wrapping div(s)
8799 public function output_html($data, $query='') {
8800 global $OUTPUT;
8802 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8803 $out .= html_writer::start_tag('thead');
8804 $out .= html_writer::start_tag('tr');
8805 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8806 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8807 $out .= html_writer::end_tag('tr');
8808 $out .= html_writer::end_tag('thead');
8809 $out .= html_writer::start_tag('tbody');
8811 if (empty($data)) {
8812 $looplimit = 1;
8813 } else {
8814 $looplimit = (count($data)/2)+1;
8817 for ($i=0; $i<$looplimit; $i++) {
8818 $out .= html_writer::start_tag('tr');
8820 $expressionname = 'expression'.$i;
8822 if (!empty($data[$expressionname])){
8823 $expression = $data[$expressionname];
8824 } else {
8825 $expression = '';
8828 $out .= html_writer::tag('td',
8829 html_writer::empty_tag('input',
8830 array(
8831 'type' => 'text',
8832 'class' => 'form-text',
8833 'name' => $this->get_full_name().'[expression'.$i.']',
8834 'value' => $expression,
8836 ), array('class' => 'c'.$i)
8839 $valuename = 'value'.$i;
8841 if (!empty($data[$valuename])){
8842 $value = $data[$valuename];
8843 } else {
8844 $value= '';
8847 $out .= html_writer::tag('td',
8848 html_writer::empty_tag('input',
8849 array(
8850 'type' => 'text',
8851 'class' => 'form-text',
8852 'name' => $this->get_full_name().'[value'.$i.']',
8853 'value' => $value,
8855 ), array('class' => 'c'.$i)
8858 $out .= html_writer::end_tag('tr');
8861 $out .= html_writer::end_tag('tbody');
8862 $out .= html_writer::end_tag('table');
8864 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8868 * Converts the string of regexes
8870 * @see self::process_form_data()
8871 * @param $regexes string of regexes
8872 * @return array of form fields and their values
8874 protected function prepare_form_data($regexes) {
8876 $regexes = json_decode($regexes);
8878 $form = array();
8880 $i = 0;
8882 foreach ($regexes as $value => $regex) {
8883 $expressionname = 'expression'.$i;
8884 $valuename = 'value'.$i;
8886 $form[$expressionname] = $regex;
8887 $form[$valuename] = $value;
8888 $i++;
8891 return $form;
8895 * Converts the data from admin settings form into a string of regexes
8897 * @see self::prepare_form_data()
8898 * @param array $data array of admin form fields and values
8899 * @return false|string of regexes
8901 protected function process_form_data(array $form) {
8903 $count = count($form); // number of form field values
8905 if ($count % 2) {
8906 // we must get five fields per expression
8907 return false;
8910 $regexes = array();
8911 for ($i = 0; $i < $count / 2; $i++) {
8912 $expressionname = "expression".$i;
8913 $valuename = "value".$i;
8915 $expression = trim($form['expression'.$i]);
8916 $value = trim($form['value'.$i]);
8918 if (empty($expression)){
8919 continue;
8922 $regexes[$value] = $expression;
8925 $regexes = json_encode($regexes);
8927 return $regexes;
8932 * Multiselect for current modules
8934 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8936 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8937 private $excludesystem;
8940 * Calls parent::__construct - note array $choices is not required
8942 * @param string $name setting name
8943 * @param string $visiblename localised setting name
8944 * @param string $description setting description
8945 * @param array $defaultsetting a plain array of default module ids
8946 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8948 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8949 $excludesystem = true) {
8950 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8951 $this->excludesystem = $excludesystem;
8955 * Loads an array of current module choices
8957 * @return bool always return true
8959 public function load_choices() {
8960 if (is_array($this->choices)) {
8961 return true;
8963 $this->choices = array();
8965 global $CFG, $DB;
8966 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8967 foreach ($records as $record) {
8968 // Exclude modules if the code doesn't exist
8969 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8970 // Also exclude system modules (if specified)
8971 if (!($this->excludesystem &&
8972 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8973 MOD_ARCHETYPE_SYSTEM)) {
8974 $this->choices[$record->id] = $record->name;
8978 return true;
8983 * Admin setting to show if a php extension is enabled or not.
8985 * @copyright 2013 Damyon Wiese
8986 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8988 class admin_setting_php_extension_enabled extends admin_setting {
8990 /** @var string The name of the extension to check for */
8991 private $extension;
8994 * Calls parent::__construct with specific arguments
8996 public function __construct($name, $visiblename, $description, $extension) {
8997 $this->extension = $extension;
8998 $this->nosave = true;
8999 parent::__construct($name, $visiblename, $description, '');
9003 * Always returns true, does nothing
9005 * @return true
9007 public function get_setting() {
9008 return true;
9012 * Always returns true, does nothing
9014 * @return true
9016 public function get_defaultsetting() {
9017 return true;
9021 * Always returns '', does not write anything
9023 * @return string Always returns ''
9025 public function write_setting($data) {
9026 // Do not write any setting.
9027 return '';
9031 * Outputs the html for this setting.
9032 * @return string Returns an XHTML string
9034 public function output_html($data, $query='') {
9035 global $OUTPUT;
9037 $o = '';
9038 if (!extension_loaded($this->extension)) {
9039 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
9041 $o .= format_admin_setting($this, $this->visiblename, $warning);
9043 return $o;
9048 * Server timezone setting.
9050 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9051 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9052 * @author Petr Skoda <petr.skoda@totaralms.com>
9054 class admin_setting_servertimezone extends admin_setting_configselect {
9056 * Constructor.
9058 public function __construct() {
9059 $default = core_date::get_default_php_timezone();
9060 if ($default === 'UTC') {
9061 // Nobody really wants UTC, so instead default selection to the country that is confused by the UTC the most.
9062 $default = 'Europe/London';
9065 parent::__construct('timezone',
9066 new lang_string('timezone', 'core_admin'),
9067 new lang_string('configtimezone', 'core_admin'), $default, null);
9071 * Lazy load timezone options.
9072 * @return bool true if loaded, false if error
9074 public function load_choices() {
9075 global $CFG;
9076 if (is_array($this->choices)) {
9077 return true;
9080 $current = isset($CFG->timezone) ? $CFG->timezone : null;
9081 $this->choices = core_date::get_list_of_timezones($current, false);
9082 if ($current == 99) {
9083 // Do not show 99 unless it is current value, we want to get rid of it over time.
9084 $this->choices['99'] = new lang_string('timezonephpdefault', 'core_admin',
9085 core_date::get_default_php_timezone());
9088 return true;
9093 * Forced user timezone setting.
9095 * @copyright 2015 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
9096 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9097 * @author Petr Skoda <petr.skoda@totaralms.com>
9099 class admin_setting_forcetimezone extends admin_setting_configselect {
9101 * Constructor.
9103 public function __construct() {
9104 parent::__construct('forcetimezone',
9105 new lang_string('forcetimezone', 'core_admin'),
9106 new lang_string('helpforcetimezone', 'core_admin'), '99', null);
9110 * Lazy load timezone options.
9111 * @return bool true if loaded, false if error
9113 public function load_choices() {
9114 global $CFG;
9115 if (is_array($this->choices)) {
9116 return true;
9119 $current = isset($CFG->forcetimezone) ? $CFG->forcetimezone : null;
9120 $this->choices = core_date::get_list_of_timezones($current, true);
9121 $this->choices['99'] = new lang_string('timezonenotforced', 'core_admin');
9123 return true;