MDL-52808 calendar: Do not return events for hidden activities
[moodle.git] / lib / adminlib.php
blob1b77210d739c6500c351273d7c353ab461e4940f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * NOTE: do not call directly, use new /admin/plugins.php?uninstall=component instead!
120 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
121 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
122 * @uses global $OUTPUT to produce notices and other messages
123 * @return void
125 function uninstall_plugin($type, $name) {
126 global $CFG, $DB, $OUTPUT;
128 // This may take a long time.
129 core_php_time_limit::raise();
131 // Recursively uninstall all subplugins first.
132 $subplugintypes = core_component::get_plugin_types_with_subplugins();
133 if (isset($subplugintypes[$type])) {
134 $base = core_component::get_plugin_directory($type, $name);
135 if (file_exists("$base/db/subplugins.php")) {
136 $subplugins = array();
137 include("$base/db/subplugins.php");
138 foreach ($subplugins as $subplugintype=>$dir) {
139 $instances = core_component::get_plugin_list($subplugintype);
140 foreach ($instances as $subpluginname => $notusedpluginpath) {
141 uninstall_plugin($subplugintype, $subpluginname);
148 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
150 if ($type === 'mod') {
151 $pluginname = $name; // eg. 'forum'
152 if (get_string_manager()->string_exists('modulename', $component)) {
153 $strpluginname = get_string('modulename', $component);
154 } else {
155 $strpluginname = $component;
158 } else {
159 $pluginname = $component;
160 if (get_string_manager()->string_exists('pluginname', $component)) {
161 $strpluginname = get_string('pluginname', $component);
162 } else {
163 $strpluginname = $component;
167 echo $OUTPUT->heading($pluginname);
169 // Delete all tag instances associated with this plugin.
170 require_once($CFG->dirroot . '/tag/lib.php');
171 tag_delete_instances($component);
173 // Custom plugin uninstall.
174 $plugindirectory = core_component::get_plugin_directory($type, $name);
175 $uninstalllib = $plugindirectory . '/db/uninstall.php';
176 if (file_exists($uninstalllib)) {
177 require_once($uninstalllib);
178 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
179 if (function_exists($uninstallfunction)) {
180 // Do not verify result, let plugin complain if necessary.
181 $uninstallfunction();
185 // Specific plugin type cleanup.
186 $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
187 if ($plugininfo) {
188 $plugininfo->uninstall_cleanup();
189 core_plugin_manager::reset_caches();
191 $plugininfo = null;
193 // perform clean-up task common for all the plugin/subplugin types
195 //delete the web service functions and pre-built services
196 require_once($CFG->dirroot.'/lib/externallib.php');
197 external_delete_descriptions($component);
199 // delete calendar events
200 $DB->delete_records('event', array('modulename' => $pluginname));
202 // Delete scheduled tasks.
203 $DB->delete_records('task_scheduled', array('component' => $pluginname));
205 // Delete Inbound Message datakeys.
206 $DB->delete_records_select('messageinbound_datakeys',
207 'handler IN (SELECT id FROM {messageinbound_handlers} WHERE component = ?)', array($pluginname));
209 // Delete Inbound Message handlers.
210 $DB->delete_records('messageinbound_handlers', array('component' => $pluginname));
212 // delete all the logs
213 $DB->delete_records('log', array('module' => $pluginname));
215 // delete log_display information
216 $DB->delete_records('log_display', array('component' => $component));
218 // delete the module configuration records
219 unset_all_config_for_plugin($component);
220 if ($type === 'mod') {
221 unset_all_config_for_plugin($pluginname);
224 // delete message provider
225 message_provider_uninstall($component);
227 // delete the plugin tables
228 $xmldbfilepath = $plugindirectory . '/db/install.xml';
229 drop_plugin_tables($component, $xmldbfilepath, false);
230 if ($type === 'mod' or $type === 'block') {
231 // non-frankenstyle table prefixes
232 drop_plugin_tables($name, $xmldbfilepath, false);
235 // delete the capabilities that were defined by this module
236 capabilities_cleanup($component);
238 // remove event handlers and dequeue pending events
239 events_uninstall($component);
241 // Delete all remaining files in the filepool owned by the component.
242 $fs = get_file_storage();
243 $fs->delete_component_files($component);
245 // Finally purge all caches.
246 purge_all_caches();
248 // Invalidate the hash used for upgrade detections.
249 set_config('allversionshash', '');
251 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
255 * Returns the version of installed component
257 * @param string $component component name
258 * @param string $source either 'disk' or 'installed' - where to get the version information from
259 * @return string|bool version number or false if the component is not found
261 function get_component_version($component, $source='installed') {
262 global $CFG, $DB;
264 list($type, $name) = core_component::normalize_component($component);
266 // moodle core or a core subsystem
267 if ($type === 'core') {
268 if ($source === 'installed') {
269 if (empty($CFG->version)) {
270 return false;
271 } else {
272 return $CFG->version;
274 } else {
275 if (!is_readable($CFG->dirroot.'/version.php')) {
276 return false;
277 } else {
278 $version = null; //initialize variable for IDEs
279 include($CFG->dirroot.'/version.php');
280 return $version;
285 // activity module
286 if ($type === 'mod') {
287 if ($source === 'installed') {
288 if ($CFG->version < 2013092001.02) {
289 return $DB->get_field('modules', 'version', array('name'=>$name));
290 } else {
291 return get_config('mod_'.$name, 'version');
294 } else {
295 $mods = core_component::get_plugin_list('mod');
296 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
297 return false;
298 } else {
299 $plugin = new stdClass();
300 $plugin->version = null;
301 $module = $plugin;
302 include($mods[$name].'/version.php');
303 return $plugin->version;
308 // block
309 if ($type === 'block') {
310 if ($source === 'installed') {
311 if ($CFG->version < 2013092001.02) {
312 return $DB->get_field('block', 'version', array('name'=>$name));
313 } else {
314 return get_config('block_'.$name, 'version');
316 } else {
317 $blocks = core_component::get_plugin_list('block');
318 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
319 return false;
320 } else {
321 $plugin = new stdclass();
322 include($blocks[$name].'/version.php');
323 return $plugin->version;
328 // all other plugin types
329 if ($source === 'installed') {
330 return get_config($type.'_'.$name, 'version');
331 } else {
332 $plugins = core_component::get_plugin_list($type);
333 if (empty($plugins[$name])) {
334 return false;
335 } else {
336 $plugin = new stdclass();
337 include($plugins[$name].'/version.php');
338 return $plugin->version;
344 * Delete all plugin tables
346 * @param string $name Name of plugin, used as table prefix
347 * @param string $file Path to install.xml file
348 * @param bool $feedback defaults to true
349 * @return bool Always returns true
351 function drop_plugin_tables($name, $file, $feedback=true) {
352 global $CFG, $DB;
354 // first try normal delete
355 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
356 return true;
359 // then try to find all tables that start with name and are not in any xml file
360 $used_tables = get_used_table_names();
362 $tables = $DB->get_tables();
364 /// Iterate over, fixing id fields as necessary
365 foreach ($tables as $table) {
366 if (in_array($table, $used_tables)) {
367 continue;
370 if (strpos($table, $name) !== 0) {
371 continue;
374 // found orphan table --> delete it
375 if ($DB->get_manager()->table_exists($table)) {
376 $xmldb_table = new xmldb_table($table);
377 $DB->get_manager()->drop_table($xmldb_table);
381 return true;
385 * Returns names of all known tables == tables that moodle knows about.
387 * @return array Array of lowercase table names
389 function get_used_table_names() {
390 $table_names = array();
391 $dbdirs = get_db_directories();
393 foreach ($dbdirs as $dbdir) {
394 $file = $dbdir.'/install.xml';
396 $xmldb_file = new xmldb_file($file);
398 if (!$xmldb_file->fileExists()) {
399 continue;
402 $loaded = $xmldb_file->loadXMLStructure();
403 $structure = $xmldb_file->getStructure();
405 if ($loaded and $tables = $structure->getTables()) {
406 foreach($tables as $table) {
407 $table_names[] = strtolower($table->getName());
412 return $table_names;
416 * Returns list of all directories where we expect install.xml files
417 * @return array Array of paths
419 function get_db_directories() {
420 global $CFG;
422 $dbdirs = array();
424 /// First, the main one (lib/db)
425 $dbdirs[] = $CFG->libdir.'/db';
427 /// Then, all the ones defined by core_component::get_plugin_types()
428 $plugintypes = core_component::get_plugin_types();
429 foreach ($plugintypes as $plugintype => $pluginbasedir) {
430 if ($plugins = core_component::get_plugin_list($plugintype)) {
431 foreach ($plugins as $plugin => $plugindir) {
432 $dbdirs[] = $plugindir.'/db';
437 return $dbdirs;
441 * Try to obtain or release the cron lock.
442 * @param string $name name of lock
443 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
444 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
445 * @return bool true if lock obtained
447 function set_cron_lock($name, $until, $ignorecurrent=false) {
448 global $DB;
449 if (empty($name)) {
450 debugging("Tried to get a cron lock for a null fieldname");
451 return false;
454 // remove lock by force == remove from config table
455 if (is_null($until)) {
456 set_config($name, null);
457 return true;
460 if (!$ignorecurrent) {
461 // read value from db - other processes might have changed it
462 $value = $DB->get_field('config', 'value', array('name'=>$name));
464 if ($value and $value > time()) {
465 //lock active
466 return false;
470 set_config($name, $until);
471 return true;
475 * Test if and critical warnings are present
476 * @return bool
478 function admin_critical_warnings_present() {
479 global $SESSION;
481 if (!has_capability('moodle/site:config', context_system::instance())) {
482 return 0;
485 if (!isset($SESSION->admin_critical_warning)) {
486 $SESSION->admin_critical_warning = 0;
487 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
488 $SESSION->admin_critical_warning = 1;
492 return $SESSION->admin_critical_warning;
496 * Detects if float supports at least 10 decimal digits
498 * Detects if float supports at least 10 decimal digits
499 * and also if float-->string conversion works as expected.
501 * @return bool true if problem found
503 function is_float_problem() {
504 $num1 = 2009010200.01;
505 $num2 = 2009010200.02;
507 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
511 * Try to verify that dataroot is not accessible from web.
513 * Try to verify that dataroot is not accessible from web.
514 * It is not 100% correct but might help to reduce number of vulnerable sites.
515 * Protection from httpd.conf and .htaccess is not detected properly.
517 * @uses INSECURE_DATAROOT_WARNING
518 * @uses INSECURE_DATAROOT_ERROR
519 * @param bool $fetchtest try to test public access by fetching file, default false
520 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
522 function is_dataroot_insecure($fetchtest=false) {
523 global $CFG;
525 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
527 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
528 $rp = strrev(trim($rp, '/'));
529 $rp = explode('/', $rp);
530 foreach($rp as $r) {
531 if (strpos($siteroot, '/'.$r.'/') === 0) {
532 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
533 } else {
534 break; // probably alias root
538 $siteroot = strrev($siteroot);
539 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
541 if (strpos($dataroot, $siteroot) !== 0) {
542 return false;
545 if (!$fetchtest) {
546 return INSECURE_DATAROOT_WARNING;
549 // now try all methods to fetch a test file using http protocol
551 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
552 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
553 $httpdocroot = $matches[1];
554 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
555 make_upload_directory('diag');
556 $testfile = $CFG->dataroot.'/diag/public.txt';
557 if (!file_exists($testfile)) {
558 file_put_contents($testfile, 'test file, do not delete');
559 @chmod($testfile, $CFG->filepermissions);
561 $teststr = trim(file_get_contents($testfile));
562 if (empty($teststr)) {
563 // hmm, strange
564 return INSECURE_DATAROOT_WARNING;
567 $testurl = $datarooturl.'/diag/public.txt';
568 if (extension_loaded('curl') and
569 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
570 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
571 ($ch = @curl_init($testurl)) !== false) {
572 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
573 curl_setopt($ch, CURLOPT_HEADER, false);
574 $data = curl_exec($ch);
575 if (!curl_errno($ch)) {
576 $data = trim($data);
577 if ($data === $teststr) {
578 curl_close($ch);
579 return INSECURE_DATAROOT_ERROR;
582 curl_close($ch);
585 if ($data = @file_get_contents($testurl)) {
586 $data = trim($data);
587 if ($data === $teststr) {
588 return INSECURE_DATAROOT_ERROR;
592 preg_match('|https?://([^/]+)|i', $testurl, $matches);
593 $sitename = $matches[1];
594 $error = 0;
595 if ($fp = @fsockopen($sitename, 80, $error)) {
596 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
597 $localurl = $matches[1];
598 $out = "GET $localurl HTTP/1.1\r\n";
599 $out .= "Host: $sitename\r\n";
600 $out .= "Connection: Close\r\n\r\n";
601 fwrite($fp, $out);
602 $data = '';
603 $incoming = false;
604 while (!feof($fp)) {
605 if ($incoming) {
606 $data .= fgets($fp, 1024);
607 } else if (@fgets($fp, 1024) === "\r\n") {
608 $incoming = true;
611 fclose($fp);
612 $data = trim($data);
613 if ($data === $teststr) {
614 return INSECURE_DATAROOT_ERROR;
618 return INSECURE_DATAROOT_WARNING;
622 * Enables CLI maintenance mode by creating new dataroot/climaintenance.html file.
624 function enable_cli_maintenance_mode() {
625 global $CFG;
627 if (file_exists("$CFG->dataroot/climaintenance.html")) {
628 unlink("$CFG->dataroot/climaintenance.html");
631 if (isset($CFG->maintenance_message) and !html_is_blank($CFG->maintenance_message)) {
632 $data = $CFG->maintenance_message;
633 $data = bootstrap_renderer::early_error_content($data, null, null, null);
634 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
636 } else if (file_exists("$CFG->dataroot/climaintenance.template.html")) {
637 $data = file_get_contents("$CFG->dataroot/climaintenance.template.html");
639 } else {
640 $data = get_string('sitemaintenance', 'admin');
641 $data = bootstrap_renderer::early_error_content($data, null, null, null);
642 $data = bootstrap_renderer::plain_page(get_string('sitemaintenance', 'admin'), $data);
645 file_put_contents("$CFG->dataroot/climaintenance.html", $data);
646 chmod("$CFG->dataroot/climaintenance.html", $CFG->filepermissions);
649 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
653 * Interface for anything appearing in the admin tree
655 * The interface that is implemented by anything that appears in the admin tree
656 * block. It forces inheriting classes to define a method for checking user permissions
657 * and methods for finding something in the admin tree.
659 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
661 interface part_of_admin_tree {
664 * Finds a named part_of_admin_tree.
666 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
667 * and not parentable_part_of_admin_tree, then this function should only check if
668 * $this->name matches $name. If it does, it should return a reference to $this,
669 * otherwise, it should return a reference to NULL.
671 * If a class inherits parentable_part_of_admin_tree, this method should be called
672 * recursively on all child objects (assuming, of course, the parent object's name
673 * doesn't match the search criterion).
675 * @param string $name The internal name of the part_of_admin_tree we're searching for.
676 * @return mixed An object reference or a NULL reference.
678 public function locate($name);
681 * Removes named part_of_admin_tree.
683 * @param string $name The internal name of the part_of_admin_tree we want to remove.
684 * @return bool success.
686 public function prune($name);
689 * Search using query
690 * @param string $query
691 * @return mixed array-object structure of found settings and pages
693 public function search($query);
696 * Verifies current user's access to this part_of_admin_tree.
698 * Used to check if the current user has access to this part of the admin tree or
699 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
700 * then this method is usually just a call to has_capability() in the site context.
702 * If a class inherits parentable_part_of_admin_tree, this method should return the
703 * logical OR of the return of check_access() on all child objects.
705 * @return bool True if the user has access, false if she doesn't.
707 public function check_access();
710 * Mostly useful for removing of some parts of the tree in admin tree block.
712 * @return True is hidden from normal list view
714 public function is_hidden();
717 * Show we display Save button at the page bottom?
718 * @return bool
720 public function show_save();
725 * Interface implemented by any part_of_admin_tree that has children.
727 * The interface implemented by any part_of_admin_tree that can be a parent
728 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
729 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
730 * include an add method for adding other part_of_admin_tree objects as children.
732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
734 interface parentable_part_of_admin_tree extends part_of_admin_tree {
737 * Adds a part_of_admin_tree object to the admin tree.
739 * Used to add a part_of_admin_tree object to this object or a child of this
740 * object. $something should only be added if $destinationname matches
741 * $this->name. If it doesn't, add should be called on child objects that are
742 * also parentable_part_of_admin_tree's.
744 * $something should be appended as the last child in the $destinationname. If the
745 * $beforesibling is specified, $something should be prepended to it. If the given
746 * sibling is not found, $something should be appended to the end of $destinationname
747 * and a developer debugging message should be displayed.
749 * @param string $destinationname The internal name of the new parent for $something.
750 * @param part_of_admin_tree $something The object to be added.
751 * @return bool True on success, false on failure.
753 public function add($destinationname, $something, $beforesibling = null);
759 * The object used to represent folders (a.k.a. categories) in the admin tree block.
761 * Each admin_category object contains a number of part_of_admin_tree objects.
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 class admin_category implements parentable_part_of_admin_tree {
767 /** @var part_of_admin_tree[] An array of part_of_admin_tree objects that are this object's children */
768 protected $children;
769 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
770 public $name;
771 /** @var string The displayed name for this category. Usually obtained through get_string() */
772 public $visiblename;
773 /** @var bool Should this category be hidden in admin tree block? */
774 public $hidden;
775 /** @var mixed Either a string or an array or strings */
776 public $path;
777 /** @var mixed Either a string or an array or strings */
778 public $visiblepath;
780 /** @var array fast lookup category cache, all categories of one tree point to one cache */
781 protected $category_cache;
783 /** @var bool If set to true children will be sorted when calling {@link admin_category::get_children()} */
784 protected $sort = false;
785 /** @var bool If set to true children will be sorted in ascending order. */
786 protected $sortasc = true;
787 /** @var bool If set to true sub categories and pages will be split and then sorted.. */
788 protected $sortsplit = true;
789 /** @var bool $sorted True if the children have been sorted and don't need resorting */
790 protected $sorted = false;
793 * Constructor for an empty admin category
795 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
796 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
797 * @param bool $hidden hide category in admin tree block, defaults to false
799 public function __construct($name, $visiblename, $hidden=false) {
800 $this->children = array();
801 $this->name = $name;
802 $this->visiblename = $visiblename;
803 $this->hidden = $hidden;
807 * Returns a reference to the part_of_admin_tree object with internal name $name.
809 * @param string $name The internal name of the object we want.
810 * @param bool $findpath initialize path and visiblepath arrays
811 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
812 * defaults to false
814 public function locate($name, $findpath=false) {
815 if (!isset($this->category_cache[$this->name])) {
816 // somebody much have purged the cache
817 $this->category_cache[$this->name] = $this;
820 if ($this->name == $name) {
821 if ($findpath) {
822 $this->visiblepath[] = $this->visiblename;
823 $this->path[] = $this->name;
825 return $this;
828 // quick category lookup
829 if (!$findpath and isset($this->category_cache[$name])) {
830 return $this->category_cache[$name];
833 $return = NULL;
834 foreach($this->children as $childid=>$unused) {
835 if ($return = $this->children[$childid]->locate($name, $findpath)) {
836 break;
840 if (!is_null($return) and $findpath) {
841 $return->visiblepath[] = $this->visiblename;
842 $return->path[] = $this->name;
845 return $return;
849 * Search using query
851 * @param string query
852 * @return mixed array-object structure of found settings and pages
854 public function search($query) {
855 $result = array();
856 foreach ($this->get_children() as $child) {
857 $subsearch = $child->search($query);
858 if (!is_array($subsearch)) {
859 debugging('Incorrect search result from '.$child->name);
860 continue;
862 $result = array_merge($result, $subsearch);
864 return $result;
868 * Removes part_of_admin_tree object with internal name $name.
870 * @param string $name The internal name of the object we want to remove.
871 * @return bool success
873 public function prune($name) {
875 if ($this->name == $name) {
876 return false; //can not remove itself
879 foreach($this->children as $precedence => $child) {
880 if ($child->name == $name) {
881 // clear cache and delete self
882 while($this->category_cache) {
883 // delete the cache, but keep the original array address
884 array_pop($this->category_cache);
886 unset($this->children[$precedence]);
887 return true;
888 } else if ($this->children[$precedence]->prune($name)) {
889 return true;
892 return false;
896 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
898 * By default the new part of the tree is appended as the last child of the parent. You
899 * can specify a sibling node that the new part should be prepended to. If the given
900 * sibling is not found, the part is appended to the end (as it would be by default) and
901 * a developer debugging message is displayed.
903 * @throws coding_exception if the $beforesibling is empty string or is not string at all.
904 * @param string $destinationame The internal name of the immediate parent that we want for $something.
905 * @param mixed $something A part_of_admin_tree or setting instance to be added.
906 * @param string $beforesibling The name of the parent's child the $something should be prepended to.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something, $beforesibling = null) {
910 global $CFG;
912 $parent = $this->locate($parentname);
913 if (is_null($parent)) {
914 debugging('parent does not exist!');
915 return false;
918 if ($something instanceof part_of_admin_tree) {
919 if (!($parent instanceof parentable_part_of_admin_tree)) {
920 debugging('error - parts of tree can be inserted only into parentable parts');
921 return false;
923 if ($CFG->debugdeveloper && !is_null($this->locate($something->name))) {
924 // The name of the node is already used, simply warn the developer that this should not happen.
925 // It is intentional to check for the debug level before performing the check.
926 debugging('Duplicate admin page name: ' . $something->name, DEBUG_DEVELOPER);
928 if (is_null($beforesibling)) {
929 // Append $something as the parent's last child.
930 $parent->children[] = $something;
931 } else {
932 if (!is_string($beforesibling) or trim($beforesibling) === '') {
933 throw new coding_exception('Unexpected value of the beforesibling parameter');
935 // Try to find the position of the sibling.
936 $siblingposition = null;
937 foreach ($parent->children as $childposition => $child) {
938 if ($child->name === $beforesibling) {
939 $siblingposition = $childposition;
940 break;
943 if (is_null($siblingposition)) {
944 debugging('Sibling '.$beforesibling.' not found', DEBUG_DEVELOPER);
945 $parent->children[] = $something;
946 } else {
947 $parent->children = array_merge(
948 array_slice($parent->children, 0, $siblingposition),
949 array($something),
950 array_slice($parent->children, $siblingposition)
954 if ($something instanceof admin_category) {
955 if (isset($this->category_cache[$something->name])) {
956 debugging('Duplicate admin category name: '.$something->name);
957 } else {
958 $this->category_cache[$something->name] = $something;
959 $something->category_cache =& $this->category_cache;
960 foreach ($something->children as $child) {
961 // just in case somebody already added subcategories
962 if ($child instanceof admin_category) {
963 if (isset($this->category_cache[$child->name])) {
964 debugging('Duplicate admin category name: '.$child->name);
965 } else {
966 $this->category_cache[$child->name] = $child;
967 $child->category_cache =& $this->category_cache;
973 return true;
975 } else {
976 debugging('error - can not add this element');
977 return false;
983 * Checks if the user has access to anything in this category.
985 * @return bool True if the user has access to at least one child in this category, false otherwise.
987 public function check_access() {
988 foreach ($this->children as $child) {
989 if ($child->check_access()) {
990 return true;
993 return false;
997 * Is this category hidden in admin tree block?
999 * @return bool True if hidden
1001 public function is_hidden() {
1002 return $this->hidden;
1006 * Show we display Save button at the page bottom?
1007 * @return bool
1009 public function show_save() {
1010 foreach ($this->children as $child) {
1011 if ($child->show_save()) {
1012 return true;
1015 return false;
1019 * Sets sorting on this category.
1021 * Please note this function doesn't actually do the sorting.
1022 * It can be called anytime.
1023 * Sorting occurs when the user calls get_children.
1024 * Code using the children array directly won't see the sorted results.
1026 * @param bool $sort If set to true children will be sorted, if false they won't be.
1027 * @param bool $asc If true sorting will be ascending, otherwise descending.
1028 * @param bool $split If true we sort pages and sub categories separately.
1030 public function set_sorting($sort, $asc = true, $split = true) {
1031 $this->sort = (bool)$sort;
1032 $this->sortasc = (bool)$asc;
1033 $this->sortsplit = (bool)$split;
1037 * Returns the children associated with this category.
1039 * @return part_of_admin_tree[]
1041 public function get_children() {
1042 // If we should sort and it hasn't already been sorted.
1043 if ($this->sort && !$this->sorted) {
1044 if ($this->sortsplit) {
1045 $categories = array();
1046 $pages = array();
1047 foreach ($this->children as $child) {
1048 if ($child instanceof admin_category) {
1049 $categories[] = $child;
1050 } else {
1051 $pages[] = $child;
1054 core_collator::asort_objects_by_property($categories, 'visiblename');
1055 core_collator::asort_objects_by_property($pages, 'visiblename');
1056 if (!$this->sortasc) {
1057 $categories = array_reverse($categories);
1058 $pages = array_reverse($pages);
1060 $this->children = array_merge($pages, $categories);
1061 } else {
1062 core_collator::asort_objects_by_property($this->children, 'visiblename');
1063 if (!$this->sortasc) {
1064 $this->children = array_reverse($this->children);
1067 $this->sorted = true;
1069 return $this->children;
1073 * Magically gets a property from this object.
1075 * @param $property
1076 * @return part_of_admin_tree[]
1077 * @throws coding_exception
1079 public function __get($property) {
1080 if ($property === 'children') {
1081 return $this->get_children();
1083 throw new coding_exception('Invalid property requested.');
1087 * Magically sets a property against this object.
1089 * @param string $property
1090 * @param mixed $value
1091 * @throws coding_exception
1093 public function __set($property, $value) {
1094 if ($property === 'children') {
1095 $this->sorted = false;
1096 $this->children = $value;
1097 } else {
1098 throw new coding_exception('Invalid property requested.');
1103 * Checks if an inaccessible property is set.
1105 * @param string $property
1106 * @return bool
1107 * @throws coding_exception
1109 public function __isset($property) {
1110 if ($property === 'children') {
1111 return isset($this->children);
1113 throw new coding_exception('Invalid property requested.');
1119 * Root of admin settings tree, does not have any parent.
1121 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1123 class admin_root extends admin_category {
1124 /** @var array List of errors */
1125 public $errors;
1126 /** @var string search query */
1127 public $search;
1128 /** @var bool full tree flag - true means all settings required, false only pages required */
1129 public $fulltree;
1130 /** @var bool flag indicating loaded tree */
1131 public $loaded;
1132 /** @var mixed site custom defaults overriding defaults in settings files*/
1133 public $custom_defaults;
1136 * @param bool $fulltree true means all settings required,
1137 * false only pages required
1139 public function __construct($fulltree) {
1140 global $CFG;
1142 parent::__construct('root', get_string('administration'), false);
1143 $this->errors = array();
1144 $this->search = '';
1145 $this->fulltree = $fulltree;
1146 $this->loaded = false;
1148 $this->category_cache = array();
1150 // load custom defaults if found
1151 $this->custom_defaults = null;
1152 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1153 if (is_readable($defaultsfile)) {
1154 $defaults = array();
1155 include($defaultsfile);
1156 if (is_array($defaults) and count($defaults)) {
1157 $this->custom_defaults = $defaults;
1163 * Empties children array, and sets loaded to false
1165 * @param bool $requirefulltree
1167 public function purge_children($requirefulltree) {
1168 $this->children = array();
1169 $this->fulltree = ($requirefulltree || $this->fulltree);
1170 $this->loaded = false;
1171 //break circular dependencies - this helps PHP 5.2
1172 while($this->category_cache) {
1173 array_pop($this->category_cache);
1175 $this->category_cache = array();
1181 * Links external PHP pages into the admin tree.
1183 * See detailed usage example at the top of this document (adminlib.php)
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1187 class admin_externalpage implements part_of_admin_tree {
1189 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1190 public $name;
1192 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1193 public $visiblename;
1195 /** @var string The external URL that we should link to when someone requests this external page. */
1196 public $url;
1198 /** @var string The role capability/permission a user must have to access this external page. */
1199 public $req_capability;
1201 /** @var object The context in which capability/permission should be checked, default is site context. */
1202 public $context;
1204 /** @var bool hidden in admin tree block. */
1205 public $hidden;
1207 /** @var mixed either string or array of string */
1208 public $path;
1210 /** @var array list of visible names of page parents */
1211 public $visiblepath;
1214 * Constructor for adding an external page into the admin tree.
1216 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1217 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1218 * @param string $url The external URL that we should link to when someone requests this external page.
1219 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1220 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1221 * @param stdClass $context The context the page relates to. Not sure what happens
1222 * if you specify something other than system or front page. Defaults to system.
1224 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1225 $this->name = $name;
1226 $this->visiblename = $visiblename;
1227 $this->url = $url;
1228 if (is_array($req_capability)) {
1229 $this->req_capability = $req_capability;
1230 } else {
1231 $this->req_capability = array($req_capability);
1233 $this->hidden = $hidden;
1234 $this->context = $context;
1238 * Returns a reference to the part_of_admin_tree object with internal name $name.
1240 * @param string $name The internal name of the object we want.
1241 * @param bool $findpath defaults to false
1242 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1244 public function locate($name, $findpath=false) {
1245 if ($this->name == $name) {
1246 if ($findpath) {
1247 $this->visiblepath = array($this->visiblename);
1248 $this->path = array($this->name);
1250 return $this;
1251 } else {
1252 $return = NULL;
1253 return $return;
1258 * This function always returns false, required function by interface
1260 * @param string $name
1261 * @return false
1263 public function prune($name) {
1264 return false;
1268 * Search using query
1270 * @param string $query
1271 * @return mixed array-object structure of found settings and pages
1273 public function search($query) {
1274 $found = false;
1275 if (strpos(strtolower($this->name), $query) !== false) {
1276 $found = true;
1277 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1278 $found = true;
1280 if ($found) {
1281 $result = new stdClass();
1282 $result->page = $this;
1283 $result->settings = array();
1284 return array($this->name => $result);
1285 } else {
1286 return array();
1291 * Determines if the current user has access to this external page based on $this->req_capability.
1293 * @return bool True if user has access, false otherwise.
1295 public function check_access() {
1296 global $CFG;
1297 $context = empty($this->context) ? context_system::instance() : $this->context;
1298 foreach($this->req_capability as $cap) {
1299 if (has_capability($cap, $context)) {
1300 return true;
1303 return false;
1307 * Is this external page hidden in admin tree block?
1309 * @return bool True if hidden
1311 public function is_hidden() {
1312 return $this->hidden;
1316 * Show we display Save button at the page bottom?
1317 * @return bool
1319 public function show_save() {
1320 return false;
1326 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1330 class admin_settingpage implements part_of_admin_tree {
1332 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1333 public $name;
1335 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1336 public $visiblename;
1338 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1339 public $settings;
1341 /** @var string The role capability/permission a user must have to access this external page. */
1342 public $req_capability;
1344 /** @var object The context in which capability/permission should be checked, default is site context. */
1345 public $context;
1347 /** @var bool hidden in admin tree block. */
1348 public $hidden;
1350 /** @var mixed string of paths or array of strings of paths */
1351 public $path;
1353 /** @var array list of visible names of page parents */
1354 public $visiblepath;
1357 * see admin_settingpage for details of this function
1359 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1360 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1361 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1362 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1363 * @param stdClass $context The context the page relates to. Not sure what happens
1364 * if you specify something other than system or front page. Defaults to system.
1366 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1367 $this->settings = new stdClass();
1368 $this->name = $name;
1369 $this->visiblename = $visiblename;
1370 if (is_array($req_capability)) {
1371 $this->req_capability = $req_capability;
1372 } else {
1373 $this->req_capability = array($req_capability);
1375 $this->hidden = $hidden;
1376 $this->context = $context;
1380 * see admin_category
1382 * @param string $name
1383 * @param bool $findpath
1384 * @return mixed Object (this) if name == this->name, else returns null
1386 public function locate($name, $findpath=false) {
1387 if ($this->name == $name) {
1388 if ($findpath) {
1389 $this->visiblepath = array($this->visiblename);
1390 $this->path = array($this->name);
1392 return $this;
1393 } else {
1394 $return = NULL;
1395 return $return;
1400 * Search string in settings page.
1402 * @param string $query
1403 * @return array
1405 public function search($query) {
1406 $found = array();
1408 foreach ($this->settings as $setting) {
1409 if ($setting->is_related($query)) {
1410 $found[] = $setting;
1414 if ($found) {
1415 $result = new stdClass();
1416 $result->page = $this;
1417 $result->settings = $found;
1418 return array($this->name => $result);
1421 $found = false;
1422 if (strpos(strtolower($this->name), $query) !== false) {
1423 $found = true;
1424 } else if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1425 $found = true;
1427 if ($found) {
1428 $result = new stdClass();
1429 $result->page = $this;
1430 $result->settings = array();
1431 return array($this->name => $result);
1432 } else {
1433 return array();
1438 * This function always returns false, required by interface
1440 * @param string $name
1441 * @return bool Always false
1443 public function prune($name) {
1444 return false;
1448 * adds an admin_setting to this admin_settingpage
1450 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1451 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1453 * @param object $setting is the admin_setting object you want to add
1454 * @return bool true if successful, false if not
1456 public function add($setting) {
1457 if (!($setting instanceof admin_setting)) {
1458 debugging('error - not a setting instance');
1459 return false;
1462 $this->settings->{$setting->name} = $setting;
1463 return true;
1467 * see admin_externalpage
1469 * @return bool Returns true for yes false for no
1471 public function check_access() {
1472 global $CFG;
1473 $context = empty($this->context) ? context_system::instance() : $this->context;
1474 foreach($this->req_capability as $cap) {
1475 if (has_capability($cap, $context)) {
1476 return true;
1479 return false;
1483 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1484 * @return string Returns an XHTML string
1486 public function output_html() {
1487 $adminroot = admin_get_root();
1488 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1489 foreach($this->settings as $setting) {
1490 $fullname = $setting->get_full_name();
1491 if (array_key_exists($fullname, $adminroot->errors)) {
1492 $data = $adminroot->errors[$fullname]->data;
1493 } else {
1494 $data = $setting->get_setting();
1495 // do not use defaults if settings not available - upgrade settings handles the defaults!
1497 $return .= $setting->output_html($data);
1499 $return .= '</fieldset>';
1500 return $return;
1504 * Is this settings page hidden in admin tree block?
1506 * @return bool True if hidden
1508 public function is_hidden() {
1509 return $this->hidden;
1513 * Show we display Save button at the page bottom?
1514 * @return bool
1516 public function show_save() {
1517 foreach($this->settings as $setting) {
1518 if (empty($setting->nosave)) {
1519 return true;
1522 return false;
1528 * Admin settings class. Only exists on setting pages.
1529 * Read & write happens at this level; no authentication.
1531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1533 abstract class admin_setting {
1534 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1535 public $name;
1536 /** @var string localised name */
1537 public $visiblename;
1538 /** @var string localised long description in Markdown format */
1539 public $description;
1540 /** @var mixed Can be string or array of string */
1541 public $defaultsetting;
1542 /** @var string */
1543 public $updatedcallback;
1544 /** @var mixed can be String or Null. Null means main config table */
1545 public $plugin; // null means main config table
1546 /** @var bool true indicates this setting does not actually save anything, just information */
1547 public $nosave = false;
1548 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1549 public $affectsmodinfo = false;
1550 /** @var array of admin_setting_flag - These are extra checkboxes attached to a setting. */
1551 private $flags = array();
1554 * Constructor
1555 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1556 * or 'myplugin/mysetting' for ones in config_plugins.
1557 * @param string $visiblename localised name
1558 * @param string $description localised long description
1559 * @param mixed $defaultsetting string or array depending on implementation
1561 public function __construct($name, $visiblename, $description, $defaultsetting) {
1562 $this->parse_setting_name($name);
1563 $this->visiblename = $visiblename;
1564 $this->description = $description;
1565 $this->defaultsetting = $defaultsetting;
1569 * Generic function to add a flag to this admin setting.
1571 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1572 * @param bool $default - The default for the flag
1573 * @param string $shortname - The shortname for this flag. Used as a suffix for the setting name.
1574 * @param string $displayname - The display name for this flag. Used as a label next to the checkbox.
1576 protected function set_flag_options($enabled, $default, $shortname, $displayname) {
1577 if (empty($this->flags[$shortname])) {
1578 $this->flags[$shortname] = new admin_setting_flag($enabled, $default, $shortname, $displayname);
1579 } else {
1580 $this->flags[$shortname]->set_options($enabled, $default);
1585 * Set the enabled options flag on this admin setting.
1587 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1588 * @param bool $default - The default for the flag
1590 public function set_enabled_flag_options($enabled, $default) {
1591 $this->set_flag_options($enabled, $default, 'enabled', new lang_string('enabled', 'core_admin'));
1595 * Set the advanced options flag on this admin setting.
1597 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1598 * @param bool $default - The default for the flag
1600 public function set_advanced_flag_options($enabled, $default) {
1601 $this->set_flag_options($enabled, $default, 'adv', new lang_string('advanced'));
1606 * Set the locked options flag on this admin setting.
1608 * @param bool $enabled - One of self::OPTION_ENABLED or self::OPTION_DISABLED
1609 * @param bool $default - The default for the flag
1611 public function set_locked_flag_options($enabled, $default) {
1612 $this->set_flag_options($enabled, $default, 'locked', new lang_string('locked', 'core_admin'));
1616 * Get the currently saved value for a setting flag
1618 * @param admin_setting_flag $flag - One of the admin_setting_flag for this admin_setting.
1619 * @return bool
1621 public function get_setting_flag_value(admin_setting_flag $flag) {
1622 $value = $this->config_read($this->name . '_' . $flag->get_shortname());
1623 if (!isset($value)) {
1624 $value = $flag->get_default();
1627 return !empty($value);
1631 * Get the list of defaults for the flags on this setting.
1633 * @param array of strings describing the defaults for this setting. This is appended to by this function.
1635 public function get_setting_flag_defaults(& $defaults) {
1636 foreach ($this->flags as $flag) {
1637 if ($flag->is_enabled() && $flag->get_default()) {
1638 $defaults[] = $flag->get_displayname();
1644 * Output the input fields for the advanced and locked flags on this setting.
1646 * @param bool $adv - The current value of the advanced flag.
1647 * @param bool $locked - The current value of the locked flag.
1648 * @return string $output - The html for the flags.
1650 public function output_setting_flags() {
1651 $output = '';
1653 foreach ($this->flags as $flag) {
1654 if ($flag->is_enabled()) {
1655 $output .= $flag->output_setting_flag($this);
1659 if (!empty($output)) {
1660 return html_writer::tag('span', $output, array('class' => 'adminsettingsflags'));
1662 return $output;
1666 * Write the values of the flags for this admin setting.
1668 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1669 * @return bool - true if successful.
1671 public function write_setting_flags($data) {
1672 $result = true;
1673 foreach ($this->flags as $flag) {
1674 $result = $result && $flag->write_setting_flag($this, $data);
1676 return $result;
1680 * Set up $this->name and potentially $this->plugin
1682 * Set up $this->name and possibly $this->plugin based on whether $name looks
1683 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1684 * on the names, that is, output a developer debug warning if the name
1685 * contains anything other than [a-zA-Z0-9_]+.
1687 * @param string $name the setting name passed in to the constructor.
1689 private function parse_setting_name($name) {
1690 $bits = explode('/', $name);
1691 if (count($bits) > 2) {
1692 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1694 $this->name = array_pop($bits);
1695 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1696 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1698 if (!empty($bits)) {
1699 $this->plugin = array_pop($bits);
1700 if ($this->plugin === 'moodle') {
1701 $this->plugin = null;
1702 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1703 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1709 * Returns the fullname prefixed by the plugin
1710 * @return string
1712 public function get_full_name() {
1713 return 's_'.$this->plugin.'_'.$this->name;
1717 * Returns the ID string based on plugin and name
1718 * @return string
1720 public function get_id() {
1721 return 'id_s_'.$this->plugin.'_'.$this->name;
1725 * @param bool $affectsmodinfo If true, changes to this setting will
1726 * cause the course cache to be rebuilt
1728 public function set_affects_modinfo($affectsmodinfo) {
1729 $this->affectsmodinfo = $affectsmodinfo;
1733 * Returns the config if possible
1735 * @return mixed returns config if successful else null
1737 public function config_read($name) {
1738 global $CFG;
1739 if (!empty($this->plugin)) {
1740 $value = get_config($this->plugin, $name);
1741 return $value === false ? NULL : $value;
1743 } else {
1744 if (isset($CFG->$name)) {
1745 return $CFG->$name;
1746 } else {
1747 return NULL;
1753 * Used to set a config pair and log change
1755 * @param string $name
1756 * @param mixed $value Gets converted to string if not null
1757 * @return bool Write setting to config table
1759 public function config_write($name, $value) {
1760 global $DB, $USER, $CFG;
1762 if ($this->nosave) {
1763 return true;
1766 // make sure it is a real change
1767 $oldvalue = get_config($this->plugin, $name);
1768 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1769 $value = is_null($value) ? null : (string)$value;
1771 if ($oldvalue === $value) {
1772 return true;
1775 // store change
1776 set_config($name, $value, $this->plugin);
1778 // Some admin settings affect course modinfo
1779 if ($this->affectsmodinfo) {
1780 // Clear course cache for all courses
1781 rebuild_course_cache(0, true);
1784 $this->add_to_config_log($name, $oldvalue, $value);
1786 return true; // BC only
1790 * Log config changes if necessary.
1791 * @param string $name
1792 * @param string $oldvalue
1793 * @param string $value
1795 protected function add_to_config_log($name, $oldvalue, $value) {
1796 add_to_config_log($name, $oldvalue, $value, $this->plugin);
1800 * Returns current value of this setting
1801 * @return mixed array or string depending on instance, NULL means not set yet
1803 public abstract function get_setting();
1806 * Returns default setting if exists
1807 * @return mixed array or string depending on instance; NULL means no default, user must supply
1809 public function get_defaultsetting() {
1810 $adminroot = admin_get_root(false, false);
1811 if (!empty($adminroot->custom_defaults)) {
1812 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1813 if (isset($adminroot->custom_defaults[$plugin])) {
1814 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1815 return $adminroot->custom_defaults[$plugin][$this->name];
1819 return $this->defaultsetting;
1823 * Store new setting
1825 * @param mixed $data string or array, must not be NULL
1826 * @return string empty string if ok, string error message otherwise
1828 public abstract function write_setting($data);
1831 * Return part of form with setting
1832 * This function should always be overwritten
1834 * @param mixed $data array or string depending on setting
1835 * @param string $query
1836 * @return string
1838 public function output_html($data, $query='') {
1839 // should be overridden
1840 return;
1844 * Function called if setting updated - cleanup, cache reset, etc.
1845 * @param string $functionname Sets the function name
1846 * @return void
1848 public function set_updatedcallback($functionname) {
1849 $this->updatedcallback = $functionname;
1853 * Execute postupdatecallback if necessary.
1854 * @param mixed $original original value before write_setting()
1855 * @return bool true if changed, false if not.
1857 public function post_write_settings($original) {
1858 // Comparison must work for arrays too.
1859 if (serialize($original) === serialize($this->get_setting())) {
1860 return false;
1863 $callbackfunction = $this->updatedcallback;
1864 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
1865 $callbackfunction($this->get_full_name());
1867 return true;
1871 * Is setting related to query text - used when searching
1872 * @param string $query
1873 * @return bool
1875 public function is_related($query) {
1876 if (strpos(strtolower($this->name), $query) !== false) {
1877 return true;
1879 if (strpos(core_text::strtolower($this->visiblename), $query) !== false) {
1880 return true;
1882 if (strpos(core_text::strtolower($this->description), $query) !== false) {
1883 return true;
1885 $current = $this->get_setting();
1886 if (!is_null($current)) {
1887 if (is_string($current)) {
1888 if (strpos(core_text::strtolower($current), $query) !== false) {
1889 return true;
1893 $default = $this->get_defaultsetting();
1894 if (!is_null($default)) {
1895 if (is_string($default)) {
1896 if (strpos(core_text::strtolower($default), $query) !== false) {
1897 return true;
1901 return false;
1906 * An additional option that can be applied to an admin setting.
1907 * The currently supported options are 'ADVANCED' and 'LOCKED'.
1909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1911 class admin_setting_flag {
1912 /** @var bool Flag to indicate if this option can be toggled for this setting */
1913 private $enabled = false;
1914 /** @var bool Flag to indicate if this option defaults to true or false */
1915 private $default = false;
1916 /** @var string Short string used to create setting name - e.g. 'adv' */
1917 private $shortname = '';
1918 /** @var string String used as the label for this flag */
1919 private $displayname = '';
1920 /** @const Checkbox for this flag is displayed in admin page */
1921 const ENABLED = true;
1922 /** @const Checkbox for this flag is not displayed in admin page */
1923 const DISABLED = false;
1926 * Constructor
1928 * @param bool $enabled Can this option can be toggled.
1929 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1930 * @param bool $default The default checked state for this setting option.
1931 * @param string $shortname The shortname of this flag. Currently supported flags are 'locked' and 'adv'
1932 * @param string $displayname The displayname of this flag. Used as a label for the flag.
1934 public function __construct($enabled, $default, $shortname, $displayname) {
1935 $this->shortname = $shortname;
1936 $this->displayname = $displayname;
1937 $this->set_options($enabled, $default);
1941 * Update the values of this setting options class
1943 * @param bool $enabled Can this option can be toggled.
1944 * Should be one of admin_setting_flag::ENABLED or admin_setting_flag::DISABLED.
1945 * @param bool $default The default checked state for this setting option.
1947 public function set_options($enabled, $default) {
1948 $this->enabled = $enabled;
1949 $this->default = $default;
1953 * Should this option appear in the interface and be toggleable?
1955 * @return bool Is it enabled?
1957 public function is_enabled() {
1958 return $this->enabled;
1962 * Should this option be checked by default?
1964 * @return bool Is it on by default?
1966 public function get_default() {
1967 return $this->default;
1971 * Return the short name for this flag. e.g. 'adv' or 'locked'
1973 * @return string
1975 public function get_shortname() {
1976 return $this->shortname;
1980 * Return the display name for this flag. e.g. 'Advanced' or 'Locked'
1982 * @return string
1984 public function get_displayname() {
1985 return $this->displayname;
1989 * Save the submitted data for this flag - or set it to the default if $data is null.
1991 * @param admin_setting $setting - The admin setting for this flag
1992 * @param array $data - The data submitted from the form or null to set the default value for new installs.
1993 * @return bool
1995 public function write_setting_flag(admin_setting $setting, $data) {
1996 $result = true;
1997 if ($this->is_enabled()) {
1998 if (!isset($data)) {
1999 $value = $this->get_default();
2000 } else {
2001 $value = !empty($data[$setting->get_full_name() . '_' . $this->get_shortname()]);
2003 $result = $setting->config_write($setting->name . '_' . $this->get_shortname(), $value);
2006 return $result;
2011 * Output the checkbox for this setting flag. Should only be called if the flag is enabled.
2013 * @param admin_setting $setting - The admin setting for this flag
2014 * @return string - The html for the checkbox.
2016 public function output_setting_flag(admin_setting $setting) {
2017 $value = $setting->get_setting_flag_value($this);
2018 $output = ' <input type="checkbox" class="form-checkbox" ' .
2019 ' id="' . $setting->get_id() . '_' . $this->get_shortname() . '" ' .
2020 ' name="' . $setting->get_full_name() . '_' . $this->get_shortname() . '" ' .
2021 ' value="1" ' . ($value ? 'checked="checked"' : '') . ' />' .
2022 ' <label for="' . $setting->get_id() . '_' . $this->get_shortname() . '">' .
2023 $this->get_displayname() .
2024 ' </label> ';
2025 return $output;
2031 * No setting - just heading and text.
2033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2035 class admin_setting_heading extends admin_setting {
2038 * not a setting, just text
2039 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2040 * @param string $heading heading
2041 * @param string $information text in box
2043 public function __construct($name, $heading, $information) {
2044 $this->nosave = true;
2045 parent::__construct($name, $heading, $information, '');
2049 * Always returns true
2050 * @return bool Always returns true
2052 public function get_setting() {
2053 return true;
2057 * Always returns true
2058 * @return bool Always returns true
2060 public function get_defaultsetting() {
2061 return true;
2065 * Never write settings
2066 * @return string Always returns an empty string
2068 public function write_setting($data) {
2069 // do not write any setting
2070 return '';
2074 * Returns an HTML string
2075 * @return string Returns an HTML string
2077 public function output_html($data, $query='') {
2078 global $OUTPUT;
2079 $return = '';
2080 if ($this->visiblename != '') {
2081 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
2083 if ($this->description != '') {
2084 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
2086 return $return;
2092 * The most flexibly setting, user is typing text
2094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2096 class admin_setting_configtext extends admin_setting {
2098 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
2099 public $paramtype;
2100 /** @var int default field size */
2101 public $size;
2104 * Config text constructor
2106 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2107 * @param string $visiblename localised
2108 * @param string $description long localised info
2109 * @param string $defaultsetting
2110 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2111 * @param int $size default field size
2113 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
2114 $this->paramtype = $paramtype;
2115 if (!is_null($size)) {
2116 $this->size = $size;
2117 } else {
2118 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
2120 parent::__construct($name, $visiblename, $description, $defaultsetting);
2124 * Return the setting
2126 * @return mixed returns config if successful else null
2128 public function get_setting() {
2129 return $this->config_read($this->name);
2132 public function write_setting($data) {
2133 if ($this->paramtype === PARAM_INT and $data === '') {
2134 // do not complain if '' used instead of 0
2135 $data = 0;
2137 // $data is a string
2138 $validated = $this->validate($data);
2139 if ($validated !== true) {
2140 return $validated;
2142 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2146 * Validate data before storage
2147 * @param string data
2148 * @return mixed true if ok string if error found
2150 public function validate($data) {
2151 // allow paramtype to be a custom regex if it is the form of /pattern/
2152 if (preg_match('#^/.*/$#', $this->paramtype)) {
2153 if (preg_match($this->paramtype, $data)) {
2154 return true;
2155 } else {
2156 return get_string('validateerror', 'admin');
2159 } else if ($this->paramtype === PARAM_RAW) {
2160 return true;
2162 } else {
2163 $cleaned = clean_param($data, $this->paramtype);
2164 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
2165 return true;
2166 } else {
2167 return get_string('validateerror', 'admin');
2173 * Return an XHTML string for the setting
2174 * @return string Returns an XHTML string
2176 public function output_html($data, $query='') {
2177 $default = $this->get_defaultsetting();
2179 return format_admin_setting($this, $this->visiblename,
2180 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
2181 $this->description, true, '', $default, $query);
2186 * Text input with a maximum length constraint.
2188 * @copyright 2015 onwards Ankit Agarwal
2189 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2191 class admin_setting_configtext_with_maxlength extends admin_setting_configtext {
2193 /** @var int maximum number of chars allowed. */
2194 protected $maxlength;
2197 * Config text constructor
2199 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2200 * or 'myplugin/mysetting' for ones in config_plugins.
2201 * @param string $visiblename localised
2202 * @param string $description long localised info
2203 * @param string $defaultsetting
2204 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
2205 * @param int $size default field size
2206 * @param mixed $maxlength int maxlength allowed, 0 for infinite.
2208 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW,
2209 $size=null, $maxlength = 0) {
2210 $this->maxlength = $maxlength;
2211 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
2215 * Validate data before storage
2217 * @param string $data data
2218 * @return mixed true if ok string if error found
2220 public function validate($data) {
2221 $parentvalidation = parent::validate($data);
2222 if ($parentvalidation === true) {
2223 if ($this->maxlength > 0) {
2224 // Max length check.
2225 $length = core_text::strlen($data);
2226 if ($length > $this->maxlength) {
2227 return get_string('maximumchars', 'moodle', $this->maxlength);
2229 return true;
2230 } else {
2231 return true; // No max length check needed.
2233 } else {
2234 return $parentvalidation;
2240 * General text area without html editor.
2242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2244 class admin_setting_configtextarea extends admin_setting_configtext {
2245 private $rows;
2246 private $cols;
2249 * @param string $name
2250 * @param string $visiblename
2251 * @param string $description
2252 * @param mixed $defaultsetting string or array
2253 * @param mixed $paramtype
2254 * @param string $cols The number of columns to make the editor
2255 * @param string $rows The number of rows to make the editor
2257 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2258 $this->rows = $rows;
2259 $this->cols = $cols;
2260 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2264 * Returns an XHTML string for the editor
2266 * @param string $data
2267 * @param string $query
2268 * @return string XHTML string for the editor
2270 public function output_html($data, $query='') {
2271 $default = $this->get_defaultsetting();
2273 $defaultinfo = $default;
2274 if (!is_null($default) and $default !== '') {
2275 $defaultinfo = "\n".$default;
2278 return format_admin_setting($this, $this->visiblename,
2279 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2280 $this->description, true, '', $defaultinfo, $query);
2286 * General text area with html editor.
2288 class admin_setting_confightmleditor extends admin_setting_configtext {
2289 private $rows;
2290 private $cols;
2293 * @param string $name
2294 * @param string $visiblename
2295 * @param string $description
2296 * @param mixed $defaultsetting string or array
2297 * @param mixed $paramtype
2299 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
2300 $this->rows = $rows;
2301 $this->cols = $cols;
2302 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
2303 editors_head_setup();
2307 * Returns an XHTML string for the editor
2309 * @param string $data
2310 * @param string $query
2311 * @return string XHTML string for the editor
2313 public function output_html($data, $query='') {
2314 $default = $this->get_defaultsetting();
2316 $defaultinfo = $default;
2317 if (!is_null($default) and $default !== '') {
2318 $defaultinfo = "\n".$default;
2321 $editor = editors_get_preferred_editor(FORMAT_HTML);
2322 $editor->set_text($data);
2323 $editor->use_editor($this->get_id(), array('noclean'=>true));
2325 return format_admin_setting($this, $this->visiblename,
2326 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>',
2327 $this->description, true, '', $defaultinfo, $query);
2333 * Password field, allows unmasking of password
2335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2337 class admin_setting_configpasswordunmask extends admin_setting_configtext {
2339 * Constructor
2340 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2341 * @param string $visiblename localised
2342 * @param string $description long localised info
2343 * @param string $defaultsetting default password
2345 public function __construct($name, $visiblename, $description, $defaultsetting) {
2346 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
2350 * Log config changes if necessary.
2351 * @param string $name
2352 * @param string $oldvalue
2353 * @param string $value
2355 protected function add_to_config_log($name, $oldvalue, $value) {
2356 if ($value !== '') {
2357 $value = '********';
2359 if ($oldvalue !== '' and $oldvalue !== null) {
2360 $oldvalue = '********';
2362 parent::add_to_config_log($name, $oldvalue, $value);
2366 * Returns XHTML for the field
2367 * Writes Javascript into the HTML below right before the last div
2369 * @todo Make javascript available through newer methods if possible
2370 * @param string $data Value for the field
2371 * @param string $query Passed as final argument for format_admin_setting
2372 * @return string XHTML field
2374 public function output_html($data, $query='') {
2375 $id = $this->get_id();
2376 $unmask = get_string('unmaskpassword', 'form');
2377 $unmaskjs = '<script type="text/javascript">
2378 //<![CDATA[
2379 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
2381 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
2383 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
2385 var unmaskchb = document.createElement("input");
2386 unmaskchb.setAttribute("type", "checkbox");
2387 unmaskchb.setAttribute("id", "'.$id.'unmask");
2388 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
2389 unmaskdiv.appendChild(unmaskchb);
2391 var unmasklbl = document.createElement("label");
2392 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
2393 if (is_ie) {
2394 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
2395 } else {
2396 unmasklbl.setAttribute("for", "'.$id.'unmask");
2398 unmaskdiv.appendChild(unmasklbl);
2400 if (is_ie) {
2401 // ugly hack to work around the famous onchange IE bug
2402 unmaskchb.onclick = function() {this.blur();};
2403 unmaskdiv.onclick = function() {this.blur();};
2405 //]]>
2406 </script>';
2407 return format_admin_setting($this, $this->visiblename,
2408 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
2409 $this->description, true, '', NULL, $query);
2414 * Empty setting used to allow flags (advanced) on settings that can have no sensible default.
2415 * Note: Only advanced makes sense right now - locked does not.
2417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2419 class admin_setting_configempty extends admin_setting_configtext {
2422 * @param string $name
2423 * @param string $visiblename
2424 * @param string $description
2426 public function __construct($name, $visiblename, $description) {
2427 parent::__construct($name, $visiblename, $description, '', PARAM_RAW);
2431 * Returns an XHTML string for the hidden field
2433 * @param string $data
2434 * @param string $query
2435 * @return string XHTML string for the editor
2437 public function output_html($data, $query='') {
2438 return format_admin_setting($this,
2439 $this->visiblename,
2440 '<div class="form-empty" >' .
2441 '<input type="hidden"' .
2442 ' id="'. $this->get_id() .'"' .
2443 ' name="'. $this->get_full_name() .'"' .
2444 ' value=""/></div>',
2445 $this->description,
2446 true,
2448 get_string('none'),
2449 $query);
2455 * Path to directory
2457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2459 class admin_setting_configfile extends admin_setting_configtext {
2461 * Constructor
2462 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2463 * @param string $visiblename localised
2464 * @param string $description long localised info
2465 * @param string $defaultdirectory default directory location
2467 public function __construct($name, $visiblename, $description, $defaultdirectory) {
2468 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
2472 * Returns XHTML for the field
2474 * Returns XHTML for the field and also checks whether the file
2475 * specified in $data exists using file_exists()
2477 * @param string $data File name and path to use in value attr
2478 * @param string $query
2479 * @return string XHTML field
2481 public function output_html($data, $query='') {
2482 global $CFG;
2483 $default = $this->get_defaultsetting();
2485 if ($data) {
2486 if (file_exists($data)) {
2487 $executable = '<span class="pathok">&#x2714;</span>';
2488 } else {
2489 $executable = '<span class="patherror">&#x2718;</span>';
2491 } else {
2492 $executable = '';
2494 $readonly = '';
2495 if (!empty($CFG->preventexecpath)) {
2496 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2497 $readonly = 'readonly="readonly"';
2500 return format_admin_setting($this, $this->visiblename,
2501 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2502 $this->description, true, '', $default, $query);
2506 * Checks if execpatch has been disabled in config.php
2508 public function write_setting($data) {
2509 global $CFG;
2510 if (!empty($CFG->preventexecpath)) {
2511 if ($this->get_setting() === null) {
2512 // Use default during installation.
2513 $data = $this->get_defaultsetting();
2514 if ($data === null) {
2515 $data = '';
2517 } else {
2518 return '';
2521 return parent::write_setting($data);
2527 * Path to executable file
2529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 class admin_setting_configexecutable extends admin_setting_configfile {
2534 * Returns an XHTML field
2536 * @param string $data This is the value for the field
2537 * @param string $query
2538 * @return string XHTML field
2540 public function output_html($data, $query='') {
2541 global $CFG;
2542 $default = $this->get_defaultsetting();
2544 if ($data) {
2545 if (file_exists($data) and !is_dir($data) and is_executable($data)) {
2546 $executable = '<span class="pathok">&#x2714;</span>';
2547 } else {
2548 $executable = '<span class="patherror">&#x2718;</span>';
2550 } else {
2551 $executable = '';
2553 $readonly = '';
2554 if (!empty($CFG->preventexecpath)) {
2555 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2556 $readonly = 'readonly="readonly"';
2559 return format_admin_setting($this, $this->visiblename,
2560 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2561 $this->description, true, '', $default, $query);
2567 * Path to directory
2569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2571 class admin_setting_configdirectory extends admin_setting_configfile {
2574 * Returns an XHTML field
2576 * @param string $data This is the value for the field
2577 * @param string $query
2578 * @return string XHTML
2580 public function output_html($data, $query='') {
2581 global $CFG;
2582 $default = $this->get_defaultsetting();
2584 if ($data) {
2585 if (file_exists($data) and is_dir($data)) {
2586 $executable = '<span class="pathok">&#x2714;</span>';
2587 } else {
2588 $executable = '<span class="patherror">&#x2718;</span>';
2590 } else {
2591 $executable = '';
2593 $readonly = '';
2594 if (!empty($CFG->preventexecpath)) {
2595 $this->visiblename .= '<div class="form-overridden">'.get_string('execpathnotallowed', 'admin').'</div>';
2596 $readonly = 'readonly="readonly"';
2599 return format_admin_setting($this, $this->visiblename,
2600 '<div class="form-file defaultsnext"><input '.$readonly.' type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2601 $this->description, true, '', $default, $query);
2607 * Checkbox
2609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2611 class admin_setting_configcheckbox extends admin_setting {
2612 /** @var string Value used when checked */
2613 public $yes;
2614 /** @var string Value used when not checked */
2615 public $no;
2618 * Constructor
2619 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2620 * @param string $visiblename localised
2621 * @param string $description long localised info
2622 * @param string $defaultsetting
2623 * @param string $yes value used when checked
2624 * @param string $no value used when not checked
2626 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2627 parent::__construct($name, $visiblename, $description, $defaultsetting);
2628 $this->yes = (string)$yes;
2629 $this->no = (string)$no;
2633 * Retrieves the current setting using the objects name
2635 * @return string
2637 public function get_setting() {
2638 return $this->config_read($this->name);
2642 * Sets the value for the setting
2644 * Sets the value for the setting to either the yes or no values
2645 * of the object by comparing $data to yes
2647 * @param mixed $data Gets converted to str for comparison against yes value
2648 * @return string empty string or error
2650 public function write_setting($data) {
2651 if ((string)$data === $this->yes) { // convert to strings before comparison
2652 $data = $this->yes;
2653 } else {
2654 $data = $this->no;
2656 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2660 * Returns an XHTML checkbox field
2662 * @param string $data If $data matches yes then checkbox is checked
2663 * @param string $query
2664 * @return string XHTML field
2666 public function output_html($data, $query='') {
2667 $default = $this->get_defaultsetting();
2669 if (!is_null($default)) {
2670 if ((string)$default === $this->yes) {
2671 $defaultinfo = get_string('checkboxyes', 'admin');
2672 } else {
2673 $defaultinfo = get_string('checkboxno', 'admin');
2675 } else {
2676 $defaultinfo = NULL;
2679 if ((string)$data === $this->yes) { // convert to strings before comparison
2680 $checked = 'checked="checked"';
2681 } else {
2682 $checked = '';
2685 return format_admin_setting($this, $this->visiblename,
2686 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2687 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2688 $this->description, true, '', $defaultinfo, $query);
2694 * Multiple checkboxes, each represents different value, stored in csv format
2696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2698 class admin_setting_configmulticheckbox extends admin_setting {
2699 /** @var array Array of choices value=>label */
2700 public $choices;
2703 * Constructor: uses parent::__construct
2705 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2706 * @param string $visiblename localised
2707 * @param string $description long localised info
2708 * @param array $defaultsetting array of selected
2709 * @param array $choices array of $value=>$label for each checkbox
2711 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2712 $this->choices = $choices;
2713 parent::__construct($name, $visiblename, $description, $defaultsetting);
2717 * This public function may be used in ancestors for lazy loading of choices
2719 * @todo Check if this function is still required content commented out only returns true
2720 * @return bool true if loaded, false if error
2722 public function load_choices() {
2724 if (is_array($this->choices)) {
2725 return true;
2727 .... load choices here
2729 return true;
2733 * Is setting related to query text - used when searching
2735 * @param string $query
2736 * @return bool true on related, false on not or failure
2738 public function is_related($query) {
2739 if (!$this->load_choices() or empty($this->choices)) {
2740 return false;
2742 if (parent::is_related($query)) {
2743 return true;
2746 foreach ($this->choices as $desc) {
2747 if (strpos(core_text::strtolower($desc), $query) !== false) {
2748 return true;
2751 return false;
2755 * Returns the current setting if it is set
2757 * @return mixed null if null, else an array
2759 public function get_setting() {
2760 $result = $this->config_read($this->name);
2762 if (is_null($result)) {
2763 return NULL;
2765 if ($result === '') {
2766 return array();
2768 $enabled = explode(',', $result);
2769 $setting = array();
2770 foreach ($enabled as $option) {
2771 $setting[$option] = 1;
2773 return $setting;
2777 * Saves the setting(s) provided in $data
2779 * @param array $data An array of data, if not array returns empty str
2780 * @return mixed empty string on useless data or bool true=success, false=failed
2782 public function write_setting($data) {
2783 if (!is_array($data)) {
2784 return ''; // ignore it
2786 if (!$this->load_choices() or empty($this->choices)) {
2787 return '';
2789 unset($data['xxxxx']);
2790 $result = array();
2791 foreach ($data as $key => $value) {
2792 if ($value and array_key_exists($key, $this->choices)) {
2793 $result[] = $key;
2796 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2800 * Returns XHTML field(s) as required by choices
2802 * Relies on data being an array should data ever be another valid vartype with
2803 * acceptable value this may cause a warning/error
2804 * if (!is_array($data)) would fix the problem
2806 * @todo Add vartype handling to ensure $data is an array
2808 * @param array $data An array of checked values
2809 * @param string $query
2810 * @return string XHTML field
2812 public function output_html($data, $query='') {
2813 if (!$this->load_choices() or empty($this->choices)) {
2814 return '';
2816 $default = $this->get_defaultsetting();
2817 if (is_null($default)) {
2818 $default = array();
2820 if (is_null($data)) {
2821 $data = array();
2823 $options = array();
2824 $defaults = array();
2825 foreach ($this->choices as $key=>$description) {
2826 if (!empty($data[$key])) {
2827 $checked = 'checked="checked"';
2828 } else {
2829 $checked = '';
2831 if (!empty($default[$key])) {
2832 $defaults[] = $description;
2835 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2836 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2839 if (is_null($default)) {
2840 $defaultinfo = NULL;
2841 } else if (!empty($defaults)) {
2842 $defaultinfo = implode(', ', $defaults);
2843 } else {
2844 $defaultinfo = get_string('none');
2847 $return = '<div class="form-multicheckbox">';
2848 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2849 if ($options) {
2850 $return .= '<ul>';
2851 foreach ($options as $option) {
2852 $return .= '<li>'.$option.'</li>';
2854 $return .= '</ul>';
2856 $return .= '</div>';
2858 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2865 * Multiple checkboxes 2, value stored as string 00101011
2867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2869 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2872 * Returns the setting if set
2874 * @return mixed null if not set, else an array of set settings
2876 public function get_setting() {
2877 $result = $this->config_read($this->name);
2878 if (is_null($result)) {
2879 return NULL;
2881 if (!$this->load_choices()) {
2882 return NULL;
2884 $result = str_pad($result, count($this->choices), '0');
2885 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2886 $setting = array();
2887 foreach ($this->choices as $key=>$unused) {
2888 $value = array_shift($result);
2889 if ($value) {
2890 $setting[$key] = 1;
2893 return $setting;
2897 * Save setting(s) provided in $data param
2899 * @param array $data An array of settings to save
2900 * @return mixed empty string for bad data or bool true=>success, false=>error
2902 public function write_setting($data) {
2903 if (!is_array($data)) {
2904 return ''; // ignore it
2906 if (!$this->load_choices() or empty($this->choices)) {
2907 return '';
2909 $result = '';
2910 foreach ($this->choices as $key=>$unused) {
2911 if (!empty($data[$key])) {
2912 $result .= '1';
2913 } else {
2914 $result .= '0';
2917 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2923 * Select one value from list
2925 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2927 class admin_setting_configselect extends admin_setting {
2928 /** @var array Array of choices value=>label */
2929 public $choices;
2932 * Constructor
2933 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2934 * @param string $visiblename localised
2935 * @param string $description long localised info
2936 * @param string|int $defaultsetting
2937 * @param array $choices array of $value=>$label for each selection
2939 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2940 $this->choices = $choices;
2941 parent::__construct($name, $visiblename, $description, $defaultsetting);
2945 * This function may be used in ancestors for lazy loading of choices
2947 * Override this method if loading of choices is expensive, such
2948 * as when it requires multiple db requests.
2950 * @return bool true if loaded, false if error
2952 public function load_choices() {
2954 if (is_array($this->choices)) {
2955 return true;
2957 .... load choices here
2959 return true;
2963 * Check if this is $query is related to a choice
2965 * @param string $query
2966 * @return bool true if related, false if not
2968 public function is_related($query) {
2969 if (parent::is_related($query)) {
2970 return true;
2972 if (!$this->load_choices()) {
2973 return false;
2975 foreach ($this->choices as $key=>$value) {
2976 if (strpos(core_text::strtolower($key), $query) !== false) {
2977 return true;
2979 if (strpos(core_text::strtolower($value), $query) !== false) {
2980 return true;
2983 return false;
2987 * Return the setting
2989 * @return mixed returns config if successful else null
2991 public function get_setting() {
2992 return $this->config_read($this->name);
2996 * Save a setting
2998 * @param string $data
2999 * @return string empty of error string
3001 public function write_setting($data) {
3002 if (!$this->load_choices() or empty($this->choices)) {
3003 return '';
3005 if (!array_key_exists($data, $this->choices)) {
3006 return ''; // ignore it
3009 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
3013 * Returns XHTML select field
3015 * Ensure the options are loaded, and generate the XHTML for the select
3016 * element and any warning message. Separating this out from output_html
3017 * makes it easier to subclass this class.
3019 * @param string $data the option to show as selected.
3020 * @param string $current the currently selected option in the database, null if none.
3021 * @param string $default the default selected option.
3022 * @return array the HTML for the select element, and a warning message.
3024 public function output_select_html($data, $current, $default, $extraname = '') {
3025 if (!$this->load_choices() or empty($this->choices)) {
3026 return array('', '');
3029 $warning = '';
3030 if (is_null($current)) {
3031 // first run
3032 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
3033 // no warning
3034 } else if (!array_key_exists($current, $this->choices)) {
3035 $warning = get_string('warningcurrentsetting', 'admin', s($current));
3036 if (!is_null($default) and $data == $current) {
3037 $data = $default; // use default instead of first value when showing the form
3041 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
3042 foreach ($this->choices as $key => $value) {
3043 // the string cast is needed because key may be integer - 0 is equal to most strings!
3044 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
3046 $selecthtml .= '</select>';
3047 return array($selecthtml, $warning);
3051 * Returns XHTML select field and wrapping div(s)
3053 * @see output_select_html()
3055 * @param string $data the option to show as selected
3056 * @param string $query
3057 * @return string XHTML field and wrapping div
3059 public function output_html($data, $query='') {
3060 $default = $this->get_defaultsetting();
3061 $current = $this->get_setting();
3063 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
3064 if (!$selecthtml) {
3065 return '';
3068 if (!is_null($default) and array_key_exists($default, $this->choices)) {
3069 $defaultinfo = $this->choices[$default];
3070 } else {
3071 $defaultinfo = NULL;
3074 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
3076 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
3082 * Select multiple items from list
3084 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3086 class admin_setting_configmultiselect extends admin_setting_configselect {
3088 * Constructor
3089 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3090 * @param string $visiblename localised
3091 * @param string $description long localised info
3092 * @param array $defaultsetting array of selected items
3093 * @param array $choices array of $value=>$label for each list item
3095 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
3096 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
3100 * Returns the select setting(s)
3102 * @return mixed null or array. Null if no settings else array of setting(s)
3104 public function get_setting() {
3105 $result = $this->config_read($this->name);
3106 if (is_null($result)) {
3107 return NULL;
3109 if ($result === '') {
3110 return array();
3112 return explode(',', $result);
3116 * Saves setting(s) provided through $data
3118 * Potential bug in the works should anyone call with this function
3119 * using a vartype that is not an array
3121 * @param array $data
3123 public function write_setting($data) {
3124 if (!is_array($data)) {
3125 return ''; //ignore it
3127 if (!$this->load_choices() or empty($this->choices)) {
3128 return '';
3131 unset($data['xxxxx']);
3133 $save = array();
3134 foreach ($data as $value) {
3135 if (!array_key_exists($value, $this->choices)) {
3136 continue; // ignore it
3138 $save[] = $value;
3141 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3145 * Is setting related to query text - used when searching
3147 * @param string $query
3148 * @return bool true if related, false if not
3150 public function is_related($query) {
3151 if (!$this->load_choices() or empty($this->choices)) {
3152 return false;
3154 if (parent::is_related($query)) {
3155 return true;
3158 foreach ($this->choices as $desc) {
3159 if (strpos(core_text::strtolower($desc), $query) !== false) {
3160 return true;
3163 return false;
3167 * Returns XHTML multi-select field
3169 * @todo Add vartype handling to ensure $data is an array
3170 * @param array $data Array of values to select by default
3171 * @param string $query
3172 * @return string XHTML multi-select field
3174 public function output_html($data, $query='') {
3175 if (!$this->load_choices() or empty($this->choices)) {
3176 return '';
3178 $choices = $this->choices;
3179 $default = $this->get_defaultsetting();
3180 if (is_null($default)) {
3181 $default = array();
3183 if (is_null($data)) {
3184 $data = array();
3187 $defaults = array();
3188 $size = min(10, count($this->choices));
3189 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3190 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
3191 foreach ($this->choices as $key => $description) {
3192 if (in_array($key, $data)) {
3193 $selected = 'selected="selected"';
3194 } else {
3195 $selected = '';
3197 if (in_array($key, $default)) {
3198 $defaults[] = $description;
3201 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
3204 if (is_null($default)) {
3205 $defaultinfo = NULL;
3206 } if (!empty($defaults)) {
3207 $defaultinfo = implode(', ', $defaults);
3208 } else {
3209 $defaultinfo = get_string('none');
3212 $return .= '</select></div>';
3213 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
3218 * Time selector
3220 * This is a liiitle bit messy. we're using two selects, but we're returning
3221 * them as an array named after $name (so we only use $name2 internally for the setting)
3223 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3225 class admin_setting_configtime extends admin_setting {
3226 /** @var string Used for setting second select (minutes) */
3227 public $name2;
3230 * Constructor
3231 * @param string $hoursname setting for hours
3232 * @param string $minutesname setting for hours
3233 * @param string $visiblename localised
3234 * @param string $description long localised info
3235 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
3237 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
3238 $this->name2 = $minutesname;
3239 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
3243 * Get the selected time
3245 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
3247 public function get_setting() {
3248 $result1 = $this->config_read($this->name);
3249 $result2 = $this->config_read($this->name2);
3250 if (is_null($result1) or is_null($result2)) {
3251 return NULL;
3254 return array('h' => $result1, 'm' => $result2);
3258 * Store the time (hours and minutes)
3260 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3261 * @return bool true if success, false if not
3263 public function write_setting($data) {
3264 if (!is_array($data)) {
3265 return '';
3268 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
3269 return ($result ? '' : get_string('errorsetting', 'admin'));
3273 * Returns XHTML time select fields
3275 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3276 * @param string $query
3277 * @return string XHTML time select fields and wrapping div(s)
3279 public function output_html($data, $query='') {
3280 $default = $this->get_defaultsetting();
3282 if (is_array($default)) {
3283 $defaultinfo = $default['h'].':'.$default['m'];
3284 } else {
3285 $defaultinfo = NULL;
3288 $return = '<div class="form-time defaultsnext">';
3289 $return .= '<label class="accesshide" for="' . $this->get_id() . 'h">' . get_string('hours') . '</label>';
3290 $return .= '<select id="' . $this->get_id() . 'h" name="' . $this->get_full_name() . '[h]">';
3291 for ($i = 0; $i < 24; $i++) {
3292 $return .= '<option value="' . $i . '"' . ($i == $data['h'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3294 $return .= '</select>:';
3295 $return .= '<label class="accesshide" for="' . $this->get_id() . 'm">' . get_string('minutes') . '</label>';
3296 $return .= '<select id="' . $this->get_id() . 'm" name="' . $this->get_full_name() . '[m]">';
3297 for ($i = 0; $i < 60; $i += 5) {
3298 $return .= '<option value="' . $i . '"' . ($i == $data['m'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
3300 $return .= '</select>';
3301 $return .= '</div>';
3302 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3309 * Seconds duration setting.
3311 * @copyright 2012 Petr Skoda (http://skodak.org)
3312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3314 class admin_setting_configduration extends admin_setting {
3316 /** @var int default duration unit */
3317 protected $defaultunit;
3320 * Constructor
3321 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
3322 * or 'myplugin/mysetting' for ones in config_plugins.
3323 * @param string $visiblename localised name
3324 * @param string $description localised long description
3325 * @param mixed $defaultsetting string or array depending on implementation
3326 * @param int $defaultunit - day, week, etc. (in seconds)
3328 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
3329 if (is_number($defaultsetting)) {
3330 $defaultsetting = self::parse_seconds($defaultsetting);
3332 $units = self::get_units();
3333 if (isset($units[$defaultunit])) {
3334 $this->defaultunit = $defaultunit;
3335 } else {
3336 $this->defaultunit = 86400;
3338 parent::__construct($name, $visiblename, $description, $defaultsetting);
3342 * Returns selectable units.
3343 * @static
3344 * @return array
3346 protected static function get_units() {
3347 return array(
3348 604800 => get_string('weeks'),
3349 86400 => get_string('days'),
3350 3600 => get_string('hours'),
3351 60 => get_string('minutes'),
3352 1 => get_string('seconds'),
3357 * Converts seconds to some more user friendly string.
3358 * @static
3359 * @param int $seconds
3360 * @return string
3362 protected static function get_duration_text($seconds) {
3363 if (empty($seconds)) {
3364 return get_string('none');
3366 $data = self::parse_seconds($seconds);
3367 switch ($data['u']) {
3368 case (60*60*24*7):
3369 return get_string('numweeks', '', $data['v']);
3370 case (60*60*24):
3371 return get_string('numdays', '', $data['v']);
3372 case (60*60):
3373 return get_string('numhours', '', $data['v']);
3374 case (60):
3375 return get_string('numminutes', '', $data['v']);
3376 default:
3377 return get_string('numseconds', '', $data['v']*$data['u']);
3382 * Finds suitable units for given duration.
3383 * @static
3384 * @param int $seconds
3385 * @return array
3387 protected static function parse_seconds($seconds) {
3388 foreach (self::get_units() as $unit => $unused) {
3389 if ($seconds % $unit === 0) {
3390 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
3393 return array('v'=>(int)$seconds, 'u'=>1);
3397 * Get the selected duration as array.
3399 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
3401 public function get_setting() {
3402 $seconds = $this->config_read($this->name);
3403 if (is_null($seconds)) {
3404 return null;
3407 return self::parse_seconds($seconds);
3411 * Store the duration as seconds.
3413 * @param array $data Must be form 'h'=>xx, 'm'=>xx
3414 * @return bool true if success, false if not
3416 public function write_setting($data) {
3417 if (!is_array($data)) {
3418 return '';
3421 $seconds = (int)($data['v']*$data['u']);
3422 if ($seconds < 0) {
3423 return get_string('errorsetting', 'admin');
3426 $result = $this->config_write($this->name, $seconds);
3427 return ($result ? '' : get_string('errorsetting', 'admin'));
3431 * Returns duration text+select fields.
3433 * @param array $data Must be form 'v'=>xx, 'u'=>xx
3434 * @param string $query
3435 * @return string duration text+select fields and wrapping div(s)
3437 public function output_html($data, $query='') {
3438 $default = $this->get_defaultsetting();
3440 if (is_number($default)) {
3441 $defaultinfo = self::get_duration_text($default);
3442 } else if (is_array($default)) {
3443 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
3444 } else {
3445 $defaultinfo = null;
3448 $units = self::get_units();
3450 $return = '<div class="form-duration defaultsnext">';
3451 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
3452 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
3453 foreach ($units as $val => $text) {
3454 $selected = '';
3455 if ($data['v'] == 0) {
3456 if ($val == $this->defaultunit) {
3457 $selected = ' selected="selected"';
3459 } else if ($val == $data['u']) {
3460 $selected = ' selected="selected"';
3462 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
3464 $return .= '</select></div>';
3465 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
3471 * Used to validate a textarea used for ip addresses
3473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3475 class admin_setting_configiplist extends admin_setting_configtextarea {
3478 * Validate the contents of the textarea as IP addresses
3480 * Used to validate a new line separated list of IP addresses collected from
3481 * a textarea control
3483 * @param string $data A list of IP Addresses separated by new lines
3484 * @return mixed bool true for success or string:error on failure
3486 public function validate($data) {
3487 if(!empty($data)) {
3488 $ips = explode("\n", $data);
3489 } else {
3490 return true;
3492 $result = true;
3493 foreach($ips as $ip) {
3494 $ip = trim($ip);
3495 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
3496 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
3497 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
3498 $result = true;
3499 } else {
3500 $result = false;
3501 break;
3504 if($result) {
3505 return true;
3506 } else {
3507 return get_string('validateerror', 'admin');
3514 * An admin setting for selecting one or more users who have a capability
3515 * in the system context
3517 * An admin setting for selecting one or more users, who have a particular capability
3518 * in the system context. Warning, make sure the list will never be too long. There is
3519 * no paging or searching of this list.
3521 * To correctly get a list of users from this config setting, you need to call the
3522 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3524 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3526 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3527 /** @var string The capabilities name */
3528 protected $capability;
3529 /** @var int include admin users too */
3530 protected $includeadmins;
3533 * Constructor.
3535 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3536 * @param string $visiblename localised name
3537 * @param string $description localised long description
3538 * @param array $defaultsetting array of usernames
3539 * @param string $capability string capability name.
3540 * @param bool $includeadmins include administrators
3542 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3543 $this->capability = $capability;
3544 $this->includeadmins = $includeadmins;
3545 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3549 * Load all of the uses who have the capability into choice array
3551 * @return bool Always returns true
3553 function load_choices() {
3554 if (is_array($this->choices)) {
3555 return true;
3557 list($sort, $sortparams) = users_order_by_sql('u');
3558 if (!empty($sortparams)) {
3559 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3560 'This is unexpected, and a problem because there is no way to pass these ' .
3561 'parameters to get_users_by_capability. See MDL-34657.');
3563 $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
3564 $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
3565 $this->choices = array(
3566 '$@NONE@$' => get_string('nobody'),
3567 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3569 if ($this->includeadmins) {
3570 $admins = get_admins();
3571 foreach ($admins as $user) {
3572 $this->choices[$user->id] = fullname($user);
3575 if (is_array($users)) {
3576 foreach ($users as $user) {
3577 $this->choices[$user->id] = fullname($user);
3580 return true;
3584 * Returns the default setting for class
3586 * @return mixed Array, or string. Empty string if no default
3588 public function get_defaultsetting() {
3589 $this->load_choices();
3590 $defaultsetting = parent::get_defaultsetting();
3591 if (empty($defaultsetting)) {
3592 return array('$@NONE@$');
3593 } else if (array_key_exists($defaultsetting, $this->choices)) {
3594 return $defaultsetting;
3595 } else {
3596 return '';
3601 * Returns the current setting
3603 * @return mixed array or string
3605 public function get_setting() {
3606 $result = parent::get_setting();
3607 if ($result === null) {
3608 // this is necessary for settings upgrade
3609 return null;
3611 if (empty($result)) {
3612 $result = array('$@NONE@$');
3614 return $result;
3618 * Save the chosen setting provided as $data
3620 * @param array $data
3621 * @return mixed string or array
3623 public function write_setting($data) {
3624 // If all is selected, remove any explicit options.
3625 if (in_array('$@ALL@$', $data)) {
3626 $data = array('$@ALL@$');
3628 // None never needs to be written to the DB.
3629 if (in_array('$@NONE@$', $data)) {
3630 unset($data[array_search('$@NONE@$', $data)]);
3632 return parent::write_setting($data);
3638 * Special checkbox for calendar - resets SESSION vars.
3640 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3642 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3644 * Calls the parent::__construct with default values
3646 * name => calendar_adminseesall
3647 * visiblename => get_string('adminseesall', 'admin')
3648 * description => get_string('helpadminseesall', 'admin')
3649 * defaultsetting => 0
3651 public function __construct() {
3652 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3653 get_string('helpadminseesall', 'admin'), '0');
3657 * Stores the setting passed in $data
3659 * @param mixed gets converted to string for comparison
3660 * @return string empty string or error message
3662 public function write_setting($data) {
3663 global $SESSION;
3664 return parent::write_setting($data);
3669 * Special select for settings that are altered in setup.php and can not be altered on the fly
3671 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3673 class admin_setting_special_selectsetup extends admin_setting_configselect {
3675 * Reads the setting directly from the database
3677 * @return mixed
3679 public function get_setting() {
3680 // read directly from db!
3681 return get_config(NULL, $this->name);
3685 * Save the setting passed in $data
3687 * @param string $data The setting to save
3688 * @return string empty or error message
3690 public function write_setting($data) {
3691 global $CFG;
3692 // do not change active CFG setting!
3693 $current = $CFG->{$this->name};
3694 $result = parent::write_setting($data);
3695 $CFG->{$this->name} = $current;
3696 return $result;
3702 * Special select for frontpage - stores data in course table
3704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3706 class admin_setting_sitesetselect extends admin_setting_configselect {
3708 * Returns the site name for the selected site
3710 * @see get_site()
3711 * @return string The site name of the selected site
3713 public function get_setting() {
3714 $site = course_get_format(get_site())->get_course();
3715 return $site->{$this->name};
3719 * Updates the database and save the setting
3721 * @param string data
3722 * @return string empty or error message
3724 public function write_setting($data) {
3725 global $DB, $SITE, $COURSE;
3726 if (!in_array($data, array_keys($this->choices))) {
3727 return get_string('errorsetting', 'admin');
3729 $record = new stdClass();
3730 $record->id = SITEID;
3731 $temp = $this->name;
3732 $record->$temp = $data;
3733 $record->timemodified = time();
3735 course_get_format($SITE)->update_course_format_options($record);
3736 $DB->update_record('course', $record);
3738 // Reset caches.
3739 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3740 if ($SITE->id == $COURSE->id) {
3741 $COURSE = $SITE;
3743 format_base::reset_course_cache($SITE->id);
3745 return '';
3752 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3753 * block to hidden.
3755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3757 class admin_setting_bloglevel extends admin_setting_configselect {
3759 * Updates the database and save the setting
3761 * @param string data
3762 * @return string empty or error message
3764 public function write_setting($data) {
3765 global $DB, $CFG;
3766 if ($data == 0) {
3767 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3768 foreach ($blogblocks as $block) {
3769 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3771 } else {
3772 // reenable all blocks only when switching from disabled blogs
3773 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3774 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3775 foreach ($blogblocks as $block) {
3776 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3780 return parent::write_setting($data);
3786 * Special select - lists on the frontpage - hacky
3788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3790 class admin_setting_courselist_frontpage extends admin_setting {
3791 /** @var array Array of choices value=>label */
3792 public $choices;
3795 * Construct override, requires one param
3797 * @param bool $loggedin Is the user logged in
3799 public function __construct($loggedin) {
3800 global $CFG;
3801 require_once($CFG->dirroot.'/course/lib.php');
3802 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3803 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3804 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3805 $defaults = array(FRONTPAGEALLCOURSELIST);
3806 parent::__construct($name, $visiblename, $description, $defaults);
3810 * Loads the choices available
3812 * @return bool always returns true
3814 public function load_choices() {
3815 if (is_array($this->choices)) {
3816 return true;
3818 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3819 FRONTPAGEALLCOURSELIST => get_string('frontpagecourselist'),
3820 FRONTPAGEENROLLEDCOURSELIST => get_string('frontpageenrolledcourselist'),
3821 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3822 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3823 FRONTPAGECOURSESEARCH => get_string('frontpagecoursesearch'),
3824 'none' => get_string('none'));
3825 if ($this->name === 'frontpage') {
3826 unset($this->choices[FRONTPAGEENROLLEDCOURSELIST]);
3828 return true;
3832 * Returns the selected settings
3834 * @param mixed array or setting or null
3836 public function get_setting() {
3837 $result = $this->config_read($this->name);
3838 if (is_null($result)) {
3839 return NULL;
3841 if ($result === '') {
3842 return array();
3844 return explode(',', $result);
3848 * Save the selected options
3850 * @param array $data
3851 * @return mixed empty string (data is not an array) or bool true=success false=failure
3853 public function write_setting($data) {
3854 if (!is_array($data)) {
3855 return '';
3857 $this->load_choices();
3858 $save = array();
3859 foreach($data as $datum) {
3860 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3861 continue;
3863 $save[$datum] = $datum; // no duplicates
3865 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3869 * Return XHTML select field and wrapping div
3871 * @todo Add vartype handling to make sure $data is an array
3872 * @param array $data Array of elements to select by default
3873 * @return string XHTML select field and wrapping div
3875 public function output_html($data, $query='') {
3876 $this->load_choices();
3877 $currentsetting = array();
3878 foreach ($data as $key) {
3879 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3880 $currentsetting[] = $key; // already selected first
3884 $return = '<div class="form-group">';
3885 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3886 if (!array_key_exists($i, $currentsetting)) {
3887 $currentsetting[$i] = 'none'; //none
3889 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3890 foreach ($this->choices as $key => $value) {
3891 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3893 $return .= '</select>';
3894 if ($i !== count($this->choices) - 2) {
3895 $return .= '<br />';
3898 $return .= '</div>';
3900 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3906 * Special checkbox for frontpage - stores data in course table
3908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3910 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3912 * Returns the current sites name
3914 * @return string
3916 public function get_setting() {
3917 $site = course_get_format(get_site())->get_course();
3918 return $site->{$this->name};
3922 * Save the selected setting
3924 * @param string $data The selected site
3925 * @return string empty string or error message
3927 public function write_setting($data) {
3928 global $DB, $SITE, $COURSE;
3929 $record = new stdClass();
3930 $record->id = $SITE->id;
3931 $record->{$this->name} = ($data == '1' ? 1 : 0);
3932 $record->timemodified = time();
3934 course_get_format($SITE)->update_course_format_options($record);
3935 $DB->update_record('course', $record);
3937 // Reset caches.
3938 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
3939 if ($SITE->id == $COURSE->id) {
3940 $COURSE = $SITE;
3942 format_base::reset_course_cache($SITE->id);
3944 return '';
3949 * Special text for frontpage - stores data in course table.
3950 * Empty string means not set here. Manual setting is required.
3952 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3954 class admin_setting_sitesettext extends admin_setting_configtext {
3956 * Return the current setting
3958 * @return mixed string or null
3960 public function get_setting() {
3961 $site = course_get_format(get_site())->get_course();
3962 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3966 * Validate the selected data
3968 * @param string $data The selected value to validate
3969 * @return mixed true or message string
3971 public function validate($data) {
3972 global $DB, $SITE;
3973 $cleaned = clean_param($data, PARAM_TEXT);
3974 if ($cleaned === '') {
3975 return get_string('required');
3977 if ($this->name ==='shortname' &&
3978 $DB->record_exists_sql('SELECT id from {course} WHERE shortname = ? AND id <> ?', array($data, $SITE->id))) {
3979 return get_string('shortnametaken', 'error', $data);
3981 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3982 return true;
3983 } else {
3984 return get_string('validateerror', 'admin');
3989 * Save the selected setting
3991 * @param string $data The selected value
3992 * @return string empty or error message
3994 public function write_setting($data) {
3995 global $DB, $SITE, $COURSE;
3996 $data = trim($data);
3997 $validated = $this->validate($data);
3998 if ($validated !== true) {
3999 return $validated;
4002 $record = new stdClass();
4003 $record->id = $SITE->id;
4004 $record->{$this->name} = $data;
4005 $record->timemodified = time();
4007 course_get_format($SITE)->update_course_format_options($record);
4008 $DB->update_record('course', $record);
4010 // Reset caches.
4011 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4012 if ($SITE->id == $COURSE->id) {
4013 $COURSE = $SITE;
4015 format_base::reset_course_cache($SITE->id);
4017 return '';
4023 * Special text editor for site description.
4025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4027 class admin_setting_special_frontpagedesc extends admin_setting {
4029 * Calls parent::__construct with specific arguments
4031 public function __construct() {
4032 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
4033 editors_head_setup();
4037 * Return the current setting
4038 * @return string The current setting
4040 public function get_setting() {
4041 $site = course_get_format(get_site())->get_course();
4042 return $site->{$this->name};
4046 * Save the new setting
4048 * @param string $data The new value to save
4049 * @return string empty or error message
4051 public function write_setting($data) {
4052 global $DB, $SITE, $COURSE;
4053 $record = new stdClass();
4054 $record->id = $SITE->id;
4055 $record->{$this->name} = $data;
4056 $record->timemodified = time();
4058 course_get_format($SITE)->update_course_format_options($record);
4059 $DB->update_record('course', $record);
4061 // Reset caches.
4062 $SITE = $DB->get_record('course', array('id'=>$SITE->id), '*', MUST_EXIST);
4063 if ($SITE->id == $COURSE->id) {
4064 $COURSE = $SITE;
4066 format_base::reset_course_cache($SITE->id);
4068 return '';
4072 * Returns XHTML for the field plus wrapping div
4074 * @param string $data The current value
4075 * @param string $query
4076 * @return string The XHTML output
4078 public function output_html($data, $query='') {
4079 global $CFG;
4081 $return = '<div class="form-htmlarea">'.print_textarea(true, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
4083 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4089 * Administration interface for emoticon_manager settings.
4091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4093 class admin_setting_emoticons extends admin_setting {
4096 * Calls parent::__construct with specific args
4098 public function __construct() {
4099 global $CFG;
4101 $manager = get_emoticon_manager();
4102 $defaults = $this->prepare_form_data($manager->default_emoticons());
4103 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
4107 * Return the current setting(s)
4109 * @return array Current settings array
4111 public function get_setting() {
4112 global $CFG;
4114 $manager = get_emoticon_manager();
4116 $config = $this->config_read($this->name);
4117 if (is_null($config)) {
4118 return null;
4121 $config = $manager->decode_stored_config($config);
4122 if (is_null($config)) {
4123 return null;
4126 return $this->prepare_form_data($config);
4130 * Save selected settings
4132 * @param array $data Array of settings to save
4133 * @return bool
4135 public function write_setting($data) {
4137 $manager = get_emoticon_manager();
4138 $emoticons = $this->process_form_data($data);
4140 if ($emoticons === false) {
4141 return false;
4144 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
4145 return ''; // success
4146 } else {
4147 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
4152 * Return XHTML field(s) for options
4154 * @param array $data Array of options to set in HTML
4155 * @return string XHTML string for the fields and wrapping div(s)
4157 public function output_html($data, $query='') {
4158 global $OUTPUT;
4160 $out = html_writer::start_tag('table', array('id' => 'emoticonsetting', 'class' => 'admintable generaltable'));
4161 $out .= html_writer::start_tag('thead');
4162 $out .= html_writer::start_tag('tr');
4163 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
4164 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
4165 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
4166 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
4167 $out .= html_writer::tag('th', '');
4168 $out .= html_writer::end_tag('tr');
4169 $out .= html_writer::end_tag('thead');
4170 $out .= html_writer::start_tag('tbody');
4171 $i = 0;
4172 foreach($data as $field => $value) {
4173 switch ($i) {
4174 case 0:
4175 $out .= html_writer::start_tag('tr');
4176 $current_text = $value;
4177 $current_filename = '';
4178 $current_imagecomponent = '';
4179 $current_altidentifier = '';
4180 $current_altcomponent = '';
4181 case 1:
4182 $current_filename = $value;
4183 case 2:
4184 $current_imagecomponent = $value;
4185 case 3:
4186 $current_altidentifier = $value;
4187 case 4:
4188 $current_altcomponent = $value;
4191 $out .= html_writer::tag('td',
4192 html_writer::empty_tag('input',
4193 array(
4194 'type' => 'text',
4195 'class' => 'form-text',
4196 'name' => $this->get_full_name().'['.$field.']',
4197 'value' => $value,
4199 ), array('class' => 'c'.$i)
4202 if ($i == 4) {
4203 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
4204 $alt = get_string($current_altidentifier, $current_altcomponent);
4205 } else {
4206 $alt = $current_text;
4208 if ($current_filename) {
4209 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
4210 } else {
4211 $out .= html_writer::tag('td', '');
4213 $out .= html_writer::end_tag('tr');
4214 $i = 0;
4215 } else {
4216 $i++;
4220 $out .= html_writer::end_tag('tbody');
4221 $out .= html_writer::end_tag('table');
4222 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
4223 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
4225 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
4229 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
4231 * @see self::process_form_data()
4232 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
4233 * @return array of form fields and their values
4235 protected function prepare_form_data(array $emoticons) {
4237 $form = array();
4238 $i = 0;
4239 foreach ($emoticons as $emoticon) {
4240 $form['text'.$i] = $emoticon->text;
4241 $form['imagename'.$i] = $emoticon->imagename;
4242 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
4243 $form['altidentifier'.$i] = $emoticon->altidentifier;
4244 $form['altcomponent'.$i] = $emoticon->altcomponent;
4245 $i++;
4247 // add one more blank field set for new object
4248 $form['text'.$i] = '';
4249 $form['imagename'.$i] = '';
4250 $form['imagecomponent'.$i] = '';
4251 $form['altidentifier'.$i] = '';
4252 $form['altcomponent'.$i] = '';
4254 return $form;
4258 * Converts the data from admin settings form into an array of emoticon objects
4260 * @see self::prepare_form_data()
4261 * @param array $data array of admin form fields and values
4262 * @return false|array of emoticon objects
4264 protected function process_form_data(array $form) {
4266 $count = count($form); // number of form field values
4268 if ($count % 5) {
4269 // we must get five fields per emoticon object
4270 return false;
4273 $emoticons = array();
4274 for ($i = 0; $i < $count / 5; $i++) {
4275 $emoticon = new stdClass();
4276 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
4277 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
4278 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
4279 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
4280 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
4282 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
4283 // prevent from breaking http://url.addresses by accident
4284 $emoticon->text = '';
4287 if (strlen($emoticon->text) < 2) {
4288 // do not allow single character emoticons
4289 $emoticon->text = '';
4292 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
4293 // emoticon text must contain some non-alphanumeric character to prevent
4294 // breaking HTML tags
4295 $emoticon->text = '';
4298 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
4299 $emoticons[] = $emoticon;
4302 return $emoticons;
4308 * Special setting for limiting of the list of available languages.
4310 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4312 class admin_setting_langlist extends admin_setting_configtext {
4314 * Calls parent::__construct with specific arguments
4316 public function __construct() {
4317 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
4321 * Save the new setting
4323 * @param string $data The new setting
4324 * @return bool
4326 public function write_setting($data) {
4327 $return = parent::write_setting($data);
4328 get_string_manager()->reset_caches();
4329 return $return;
4335 * Selection of one of the recognised countries using the list
4336 * returned by {@link get_list_of_countries()}.
4338 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4340 class admin_settings_country_select extends admin_setting_configselect {
4341 protected $includeall;
4342 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
4343 $this->includeall = $includeall;
4344 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4348 * Lazy-load the available choices for the select box
4350 public function load_choices() {
4351 global $CFG;
4352 if (is_array($this->choices)) {
4353 return true;
4355 $this->choices = array_merge(
4356 array('0' => get_string('choosedots')),
4357 get_string_manager()->get_list_of_countries($this->includeall));
4358 return true;
4364 * admin_setting_configselect for the default number of sections in a course,
4365 * simply so we can lazy-load the choices.
4367 * @copyright 2011 The Open University
4368 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4370 class admin_settings_num_course_sections extends admin_setting_configselect {
4371 public function __construct($name, $visiblename, $description, $defaultsetting) {
4372 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
4375 /** Lazy-load the available choices for the select box */
4376 public function load_choices() {
4377 $max = get_config('moodlecourse', 'maxsections');
4378 if (!isset($max) || !is_numeric($max)) {
4379 $max = 52;
4381 for ($i = 0; $i <= $max; $i++) {
4382 $this->choices[$i] = "$i";
4384 return true;
4390 * Course category selection
4392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4394 class admin_settings_coursecat_select extends admin_setting_configselect {
4396 * Calls parent::__construct with specific arguments
4398 public function __construct($name, $visiblename, $description, $defaultsetting) {
4399 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
4403 * Load the available choices for the select box
4405 * @return bool
4407 public function load_choices() {
4408 global $CFG;
4409 require_once($CFG->dirroot.'/course/lib.php');
4410 if (is_array($this->choices)) {
4411 return true;
4413 $this->choices = make_categories_options();
4414 return true;
4420 * Special control for selecting days to backup
4422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4424 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
4426 * Calls parent::__construct with specific arguments
4428 public function __construct() {
4429 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
4430 $this->plugin = 'backup';
4434 * Load the available choices for the select box
4436 * @return bool Always returns true
4438 public function load_choices() {
4439 if (is_array($this->choices)) {
4440 return true;
4442 $this->choices = array();
4443 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4444 foreach ($days as $day) {
4445 $this->choices[$day] = get_string($day, 'calendar');
4447 return true;
4453 * Special debug setting
4455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4457 class admin_setting_special_debug extends admin_setting_configselect {
4459 * Calls parent::__construct with specific arguments
4461 public function __construct() {
4462 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
4466 * Load the available choices for the select box
4468 * @return bool
4470 public function load_choices() {
4471 if (is_array($this->choices)) {
4472 return true;
4474 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
4475 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
4476 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
4477 DEBUG_ALL => get_string('debugall', 'admin'),
4478 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
4479 return true;
4485 * Special admin control
4487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4489 class admin_setting_special_calendar_weekend extends admin_setting {
4491 * Calls parent::__construct with specific arguments
4493 public function __construct() {
4494 $name = 'calendar_weekend';
4495 $visiblename = get_string('calendar_weekend', 'admin');
4496 $description = get_string('helpweekenddays', 'admin');
4497 $default = array ('0', '6'); // Saturdays and Sundays
4498 parent::__construct($name, $visiblename, $description, $default);
4502 * Gets the current settings as an array
4504 * @return mixed Null if none, else array of settings
4506 public function get_setting() {
4507 $result = $this->config_read($this->name);
4508 if (is_null($result)) {
4509 return NULL;
4511 if ($result === '') {
4512 return array();
4514 $settings = array();
4515 for ($i=0; $i<7; $i++) {
4516 if ($result & (1 << $i)) {
4517 $settings[] = $i;
4520 return $settings;
4524 * Save the new settings
4526 * @param array $data Array of new settings
4527 * @return bool
4529 public function write_setting($data) {
4530 if (!is_array($data)) {
4531 return '';
4533 unset($data['xxxxx']);
4534 $result = 0;
4535 foreach($data as $index) {
4536 $result |= 1 << $index;
4538 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
4542 * Return XHTML to display the control
4544 * @param array $data array of selected days
4545 * @param string $query
4546 * @return string XHTML for display (field + wrapping div(s)
4548 public function output_html($data, $query='') {
4549 // The order matters very much because of the implied numeric keys
4550 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
4551 $return = '<table><thead><tr>';
4552 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
4553 foreach($days as $index => $day) {
4554 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4556 $return .= '</tr></thead><tbody><tr>';
4557 foreach($days as $index => $day) {
4558 $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>';
4560 $return .= '</tr></tbody></table>';
4562 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4569 * Admin setting that allows a user to pick a behaviour.
4571 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4573 class admin_setting_question_behaviour extends admin_setting_configselect {
4575 * @param string $name name of config variable
4576 * @param string $visiblename display name
4577 * @param string $description description
4578 * @param string $default default.
4580 public function __construct($name, $visiblename, $description, $default) {
4581 parent::__construct($name, $visiblename, $description, $default, NULL);
4585 * Load list of behaviours as choices
4586 * @return bool true => success, false => error.
4588 public function load_choices() {
4589 global $CFG;
4590 require_once($CFG->dirroot . '/question/engine/lib.php');
4591 $this->choices = question_engine::get_behaviour_options('');
4592 return true;
4598 * Admin setting that allows a user to pick appropriate roles for something.
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4602 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4603 /** @var array Array of capabilities which identify roles */
4604 private $types;
4607 * @param string $name Name of config variable
4608 * @param string $visiblename Display name
4609 * @param string $description Description
4610 * @param array $types Array of archetypes which identify
4611 * roles that will be enabled by default.
4613 public function __construct($name, $visiblename, $description, $types) {
4614 parent::__construct($name, $visiblename, $description, NULL, NULL);
4615 $this->types = $types;
4619 * Load roles as choices
4621 * @return bool true=>success, false=>error
4623 public function load_choices() {
4624 global $CFG, $DB;
4625 if (during_initial_install()) {
4626 return false;
4628 if (is_array($this->choices)) {
4629 return true;
4631 if ($roles = get_all_roles()) {
4632 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4633 return true;
4634 } else {
4635 return false;
4640 * Return the default setting for this control
4642 * @return array Array of default settings
4644 public function get_defaultsetting() {
4645 global $CFG;
4647 if (during_initial_install()) {
4648 return null;
4650 $result = array();
4651 foreach($this->types as $archetype) {
4652 if ($caproles = get_archetype_roles($archetype)) {
4653 foreach ($caproles as $caprole) {
4654 $result[$caprole->id] = 1;
4658 return $result;
4664 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4666 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4668 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4670 * Constructor
4671 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4672 * @param string $visiblename localised
4673 * @param string $description long localised info
4674 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4675 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4676 * @param int $size default field size
4678 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4679 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $paramtype, $size);
4680 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4686 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4688 * @copyright 2009 Petr Skoda (http://skodak.org)
4689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4691 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4694 * Constructor
4695 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4696 * @param string $visiblename localised
4697 * @param string $description long localised info
4698 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4699 * @param string $yes value used when checked
4700 * @param string $no value used when not checked
4702 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4703 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4704 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4711 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4713 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4715 * @copyright 2010 Sam Hemelryk
4716 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4718 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4720 * Constructor
4721 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4722 * @param string $visiblename localised
4723 * @param string $description long localised info
4724 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4725 * @param string $yes value used when checked
4726 * @param string $no value used when not checked
4728 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4729 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $yes, $no);
4730 $this->set_locked_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['locked']));
4737 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4741 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4743 * Calls parent::__construct with specific arguments
4745 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4746 parent::__construct($name, $visiblename, $description, $defaultsetting['value'], $choices);
4747 $this->set_advanced_flag_options(admin_setting_flag::ENABLED, !empty($defaultsetting['adv']));
4754 * Graded roles in gradebook
4756 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4758 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4760 * Calls parent::__construct with specific arguments
4762 public function __construct() {
4763 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4764 get_string('configgradebookroles', 'admin'),
4765 array('student'));
4772 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4774 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4776 * Saves the new settings passed in $data
4778 * @param string $data
4779 * @return mixed string or Array
4781 public function write_setting($data) {
4782 global $CFG, $DB;
4784 $oldvalue = $this->config_read($this->name);
4785 $return = parent::write_setting($data);
4786 $newvalue = $this->config_read($this->name);
4788 if ($oldvalue !== $newvalue) {
4789 // force full regrading
4790 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4793 return $return;
4799 * Which roles to show on course description page
4801 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4803 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4805 * Calls parent::__construct with specific arguments
4807 public function __construct() {
4808 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4809 get_string('coursecontact_desc', 'admin'),
4810 array('editingteacher'));
4811 $this->set_updatedcallback(create_function('',
4812 "cache::make('core', 'coursecontacts')->purge();"));
4819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4821 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4823 * Calls parent::__construct with specific arguments
4825 function admin_setting_special_gradelimiting() {
4826 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4827 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4831 * Force site regrading
4833 function regrade_all() {
4834 global $CFG;
4835 require_once("$CFG->libdir/gradelib.php");
4836 grade_force_site_regrading();
4840 * Saves the new settings
4842 * @param mixed $data
4843 * @return string empty string or error message
4845 function write_setting($data) {
4846 $previous = $this->get_setting();
4848 if ($previous === null) {
4849 if ($data) {
4850 $this->regrade_all();
4852 } else {
4853 if ($data != $previous) {
4854 $this->regrade_all();
4857 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4863 * Special setting for $CFG->grade_minmaxtouse.
4865 * @package core
4866 * @copyright 2015 Frédéric Massart - FMCorz.net
4867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4869 class admin_setting_special_grademinmaxtouse extends admin_setting_configselect {
4872 * Constructor.
4874 public function __construct() {
4875 parent::__construct('grade_minmaxtouse', new lang_string('minmaxtouse', 'grades'),
4876 new lang_string('minmaxtouse_desc', 'grades'), GRADE_MIN_MAX_FROM_GRADE_ITEM,
4877 array(
4878 GRADE_MIN_MAX_FROM_GRADE_ITEM => get_string('gradeitemminmax', 'grades'),
4879 GRADE_MIN_MAX_FROM_GRADE_GRADE => get_string('gradegrademinmax', 'grades')
4885 * Saves the new setting.
4887 * @param mixed $data
4888 * @return string empty string or error message
4890 function write_setting($data) {
4891 global $CFG;
4893 $previous = $this->get_setting();
4894 $result = parent::write_setting($data);
4896 // If saved and the value has changed.
4897 if (empty($result) && $previous != $data) {
4898 require_once($CFG->libdir . '/gradelib.php');
4899 grade_force_site_regrading();
4902 return $result;
4909 * Primary grade export plugin - has state tracking.
4911 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4913 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4915 * Calls parent::__construct with specific arguments
4917 public function __construct() {
4918 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4919 get_string('configgradeexport', 'admin'), array(), NULL);
4923 * Load the available choices for the multicheckbox
4925 * @return bool always returns true
4927 public function load_choices() {
4928 if (is_array($this->choices)) {
4929 return true;
4931 $this->choices = array();
4933 if ($plugins = core_component::get_plugin_list('gradeexport')) {
4934 foreach($plugins as $plugin => $unused) {
4935 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4938 return true;
4944 * A setting for setting the default grade point value. Must be an integer between 1 and $CFG->gradepointmax.
4946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4948 class admin_setting_special_gradepointdefault extends admin_setting_configtext {
4950 * Config gradepointmax constructor
4952 * @param string $name Overidden by "gradepointmax"
4953 * @param string $visiblename Overridden by "gradepointmax" language string.
4954 * @param string $description Overridden by "gradepointmax_help" language string.
4955 * @param string $defaultsetting Not used, overridden by 100.
4956 * @param mixed $paramtype Overridden by PARAM_INT.
4957 * @param int $size Overridden by 5.
4959 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
4960 $name = 'gradepointdefault';
4961 $visiblename = get_string('gradepointdefault', 'grades');
4962 $description = get_string('gradepointdefault_help', 'grades');
4963 $defaultsetting = 100;
4964 $paramtype = PARAM_INT;
4965 $size = 5;
4966 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4970 * Validate data before storage
4971 * @param string $data The submitted data
4972 * @return bool|string true if ok, string if error found
4974 public function validate($data) {
4975 global $CFG;
4976 if (((string)(int)$data === (string)$data && $data > 0 && $data <= $CFG->gradepointmax)) {
4977 return true;
4978 } else {
4979 return get_string('gradepointdefault_validateerror', 'grades');
4986 * A setting for setting the maximum grade value. Must be an integer between 1 and 10000.
4988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4990 class admin_setting_special_gradepointmax extends admin_setting_configtext {
4993 * Config gradepointmax constructor
4995 * @param string $name Overidden by "gradepointmax"
4996 * @param string $visiblename Overridden by "gradepointmax" language string.
4997 * @param string $description Overridden by "gradepointmax_help" language string.
4998 * @param string $defaultsetting Not used, overridden by 100.
4999 * @param mixed $paramtype Overridden by PARAM_INT.
5000 * @param int $size Overridden by 5.
5002 public function __construct($name = '', $visiblename = '', $description = '', $defaultsetting = '', $paramtype = PARAM_INT, $size = 5) {
5003 $name = 'gradepointmax';
5004 $visiblename = get_string('gradepointmax', 'grades');
5005 $description = get_string('gradepointmax_help', 'grades');
5006 $defaultsetting = 100;
5007 $paramtype = PARAM_INT;
5008 $size = 5;
5009 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
5013 * Save the selected setting
5015 * @param string $data The selected site
5016 * @return string empty string or error message
5018 public function write_setting($data) {
5019 if ($data === '') {
5020 $data = (int)$this->defaultsetting;
5021 } else {
5022 $data = $data;
5024 return parent::write_setting($data);
5028 * Validate data before storage
5029 * @param string $data The submitted data
5030 * @return bool|string true if ok, string if error found
5032 public function validate($data) {
5033 if (((string)(int)$data === (string)$data && $data > 0 && $data <= 10000)) {
5034 return true;
5035 } else {
5036 return get_string('gradepointmax_validateerror', 'grades');
5041 * Return an XHTML string for the setting
5042 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5043 * @param string $query search query to be highlighted
5044 * @return string XHTML to display control
5046 public function output_html($data, $query = '') {
5047 $default = $this->get_defaultsetting();
5049 $attr = array(
5050 'type' => 'text',
5051 'size' => $this->size,
5052 'id' => $this->get_id(),
5053 'name' => $this->get_full_name(),
5054 'value' => s($data),
5055 'maxlength' => '5'
5057 $input = html_writer::empty_tag('input', $attr);
5059 $attr = array('class' => 'form-text defaultsnext');
5060 $div = html_writer::tag('div', $input, $attr);
5061 return format_admin_setting($this, $this->visiblename, $div, $this->description, true, '', $default, $query);
5067 * Grade category settings
5069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5071 class admin_setting_gradecat_combo extends admin_setting {
5072 /** @var array Array of choices */
5073 public $choices;
5076 * Sets choices and calls parent::__construct with passed arguments
5077 * @param string $name
5078 * @param string $visiblename
5079 * @param string $description
5080 * @param mixed $defaultsetting string or array depending on implementation
5081 * @param array $choices An array of choices for the control
5083 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
5084 $this->choices = $choices;
5085 parent::__construct($name, $visiblename, $description, $defaultsetting);
5089 * Return the current setting(s) array
5091 * @return array Array of value=>xx, forced=>xx, adv=>xx
5093 public function get_setting() {
5094 global $CFG;
5096 $value = $this->config_read($this->name);
5097 $flag = $this->config_read($this->name.'_flag');
5099 if (is_null($value) or is_null($flag)) {
5100 return NULL;
5103 $flag = (int)$flag;
5104 $forced = (boolean)(1 & $flag); // first bit
5105 $adv = (boolean)(2 & $flag); // second bit
5107 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
5111 * Save the new settings passed in $data
5113 * @todo Add vartype handling to ensure $data is array
5114 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5115 * @return string empty or error message
5117 public function write_setting($data) {
5118 global $CFG;
5120 $value = $data['value'];
5121 $forced = empty($data['forced']) ? 0 : 1;
5122 $adv = empty($data['adv']) ? 0 : 2;
5123 $flag = ($forced | $adv); //bitwise or
5125 if (!in_array($value, array_keys($this->choices))) {
5126 return 'Error setting ';
5129 $oldvalue = $this->config_read($this->name);
5130 $oldflag = (int)$this->config_read($this->name.'_flag');
5131 $oldforced = (1 & $oldflag); // first bit
5133 $result1 = $this->config_write($this->name, $value);
5134 $result2 = $this->config_write($this->name.'_flag', $flag);
5136 // force regrade if needed
5137 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
5138 require_once($CFG->libdir.'/gradelib.php');
5139 grade_category::updated_forced_settings();
5142 if ($result1 and $result2) {
5143 return '';
5144 } else {
5145 return get_string('errorsetting', 'admin');
5150 * Return XHTML to display the field and wrapping div
5152 * @todo Add vartype handling to ensure $data is array
5153 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
5154 * @param string $query
5155 * @return string XHTML to display control
5157 public function output_html($data, $query='') {
5158 $value = $data['value'];
5159 $forced = !empty($data['forced']);
5160 $adv = !empty($data['adv']);
5162 $default = $this->get_defaultsetting();
5163 if (!is_null($default)) {
5164 $defaultinfo = array();
5165 if (isset($this->choices[$default['value']])) {
5166 $defaultinfo[] = $this->choices[$default['value']];
5168 if (!empty($default['forced'])) {
5169 $defaultinfo[] = get_string('force');
5171 if (!empty($default['adv'])) {
5172 $defaultinfo[] = get_string('advanced');
5174 $defaultinfo = implode(', ', $defaultinfo);
5176 } else {
5177 $defaultinfo = NULL;
5181 $return = '<div class="form-group">';
5182 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
5183 foreach ($this->choices as $key => $val) {
5184 // the string cast is needed because key may be integer - 0 is equal to most strings!
5185 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
5187 $return .= '</select>';
5188 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
5189 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
5190 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
5191 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
5192 $return .= '</div>';
5194 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
5200 * Selection of grade report in user profiles
5202 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5204 class admin_setting_grade_profilereport extends admin_setting_configselect {
5206 * Calls parent::__construct with specific arguments
5208 public function __construct() {
5209 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
5213 * Loads an array of choices for the configselect control
5215 * @return bool always return true
5217 public function load_choices() {
5218 if (is_array($this->choices)) {
5219 return true;
5221 $this->choices = array();
5223 global $CFG;
5224 require_once($CFG->libdir.'/gradelib.php');
5226 foreach (core_component::get_plugin_list('gradereport') as $plugin => $plugindir) {
5227 if (file_exists($plugindir.'/lib.php')) {
5228 require_once($plugindir.'/lib.php');
5229 $functionname = 'grade_report_'.$plugin.'_profilereport';
5230 if (function_exists($functionname)) {
5231 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
5235 return true;
5241 * Special class for register auth selection
5243 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5245 class admin_setting_special_registerauth extends admin_setting_configselect {
5247 * Calls parent::__construct with specific arguments
5249 public function __construct() {
5250 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
5254 * Returns the default option
5256 * @return string empty or default option
5258 public function get_defaultsetting() {
5259 $this->load_choices();
5260 $defaultsetting = parent::get_defaultsetting();
5261 if (array_key_exists($defaultsetting, $this->choices)) {
5262 return $defaultsetting;
5263 } else {
5264 return '';
5269 * Loads the possible choices for the array
5271 * @return bool always returns true
5273 public function load_choices() {
5274 global $CFG;
5276 if (is_array($this->choices)) {
5277 return true;
5279 $this->choices = array();
5280 $this->choices[''] = get_string('disable');
5282 $authsenabled = get_enabled_auth_plugins(true);
5284 foreach ($authsenabled as $auth) {
5285 $authplugin = get_auth_plugin($auth);
5286 if (!$authplugin->can_signup()) {
5287 continue;
5289 // Get the auth title (from core or own auth lang files)
5290 $authtitle = $authplugin->get_title();
5291 $this->choices[$auth] = $authtitle;
5293 return true;
5299 * General plugins manager
5301 class admin_page_pluginsoverview extends admin_externalpage {
5304 * Sets basic information about the external page
5306 public function __construct() {
5307 global $CFG;
5308 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
5309 "$CFG->wwwroot/$CFG->admin/plugins.php");
5314 * Module manage page
5316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5318 class admin_page_managemods extends admin_externalpage {
5320 * Calls parent::__construct with specific arguments
5322 public function __construct() {
5323 global $CFG;
5324 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
5328 * Try to find the specified module
5330 * @param string $query The module to search for
5331 * @return array
5333 public function search($query) {
5334 global $CFG, $DB;
5335 if ($result = parent::search($query)) {
5336 return $result;
5339 $found = false;
5340 if ($modules = $DB->get_records('modules')) {
5341 foreach ($modules as $module) {
5342 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
5343 continue;
5345 if (strpos($module->name, $query) !== false) {
5346 $found = true;
5347 break;
5349 $strmodulename = get_string('modulename', $module->name);
5350 if (strpos(core_text::strtolower($strmodulename), $query) !== false) {
5351 $found = true;
5352 break;
5356 if ($found) {
5357 $result = new stdClass();
5358 $result->page = $this;
5359 $result->settings = array();
5360 return array($this->name => $result);
5361 } else {
5362 return array();
5369 * Special class for enrol plugins management.
5371 * @copyright 2010 Petr Skoda {@link http://skodak.org}
5372 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5374 class admin_setting_manageenrols extends admin_setting {
5376 * Calls parent::__construct with specific arguments
5378 public function __construct() {
5379 $this->nosave = true;
5380 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
5384 * Always returns true, does nothing
5386 * @return true
5388 public function get_setting() {
5389 return true;
5393 * Always returns true, does nothing
5395 * @return true
5397 public function get_defaultsetting() {
5398 return true;
5402 * Always returns '', does not write anything
5404 * @return string Always returns ''
5406 public function write_setting($data) {
5407 // do not write any setting
5408 return '';
5412 * Checks if $query is one of the available enrol plugins
5414 * @param string $query The string to search for
5415 * @return bool Returns true if found, false if not
5417 public function is_related($query) {
5418 if (parent::is_related($query)) {
5419 return true;
5422 $query = core_text::strtolower($query);
5423 $enrols = enrol_get_plugins(false);
5424 foreach ($enrols as $name=>$enrol) {
5425 $localised = get_string('pluginname', 'enrol_'.$name);
5426 if (strpos(core_text::strtolower($name), $query) !== false) {
5427 return true;
5429 if (strpos(core_text::strtolower($localised), $query) !== false) {
5430 return true;
5433 return false;
5437 * Builds the XHTML to display the control
5439 * @param string $data Unused
5440 * @param string $query
5441 * @return string
5443 public function output_html($data, $query='') {
5444 global $CFG, $OUTPUT, $DB, $PAGE;
5446 // Display strings.
5447 $strup = get_string('up');
5448 $strdown = get_string('down');
5449 $strsettings = get_string('settings');
5450 $strenable = get_string('enable');
5451 $strdisable = get_string('disable');
5452 $struninstall = get_string('uninstallplugin', 'core_admin');
5453 $strusage = get_string('enrolusage', 'enrol');
5454 $strversion = get_string('version');
5455 $strtest = get_string('testsettings', 'core_enrol');
5457 $pluginmanager = core_plugin_manager::instance();
5459 $enrols_available = enrol_get_plugins(false);
5460 $active_enrols = enrol_get_plugins(true);
5462 $allenrols = array();
5463 foreach ($active_enrols as $key=>$enrol) {
5464 $allenrols[$key] = true;
5466 foreach ($enrols_available as $key=>$enrol) {
5467 $allenrols[$key] = true;
5469 // Now find all borked plugins and at least allow then to uninstall.
5470 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5471 foreach ($condidates as $candidate) {
5472 if (empty($allenrols[$candidate])) {
5473 $allenrols[$candidate] = true;
5477 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5478 $return .= $OUTPUT->box_start('generalbox enrolsui');
5480 $table = new html_table();
5481 $table->head = array(get_string('name'), $strusage, $strversion, $strenable, $strup.'/'.$strdown, $strsettings, $strtest, $struninstall);
5482 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
5483 $table->id = 'courseenrolmentplugins';
5484 $table->attributes['class'] = 'admintable generaltable';
5485 $table->data = array();
5487 // Iterate through enrol plugins and add to the display table.
5488 $updowncount = 1;
5489 $enrolcount = count($active_enrols);
5490 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5491 $printed = array();
5492 foreach($allenrols as $enrol => $unused) {
5493 $plugininfo = $pluginmanager->get_plugin_info('enrol_'.$enrol);
5494 $version = get_config('enrol_'.$enrol, 'version');
5495 if ($version === false) {
5496 $version = '';
5499 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5500 $name = get_string('pluginname', 'enrol_'.$enrol);
5501 } else {
5502 $name = $enrol;
5504 // Usage.
5505 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5506 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5507 $usage = "$ci / $cp";
5509 // Hide/show links.
5510 $class = '';
5511 if (isset($active_enrols[$enrol])) {
5512 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5513 $hideshow = "<a href=\"$aurl\">";
5514 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5515 $enabled = true;
5516 $displayname = $name;
5517 } else if (isset($enrols_available[$enrol])) {
5518 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5519 $hideshow = "<a href=\"$aurl\">";
5520 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5521 $enabled = false;
5522 $displayname = $name;
5523 $class = 'dimmed_text';
5524 } else {
5525 $hideshow = '';
5526 $enabled = false;
5527 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5529 if ($PAGE->theme->resolve_image_location('icon', 'enrol_' . $name, false)) {
5530 $icon = $OUTPUT->pix_icon('icon', '', 'enrol_' . $name, array('class' => 'icon pluginicon'));
5531 } else {
5532 $icon = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'icon pluginicon noicon'));
5535 // Up/down link (only if enrol is enabled).
5536 $updown = '';
5537 if ($enabled) {
5538 if ($updowncount > 1) {
5539 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5540 $updown .= "<a href=\"$aurl\">";
5541 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5542 } else {
5543 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5545 if ($updowncount < $enrolcount) {
5546 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5547 $updown .= "<a href=\"$aurl\">";
5548 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5549 } else {
5550 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5552 ++$updowncount;
5555 // Add settings link.
5556 if (!$version) {
5557 $settings = '';
5558 } else if ($surl = $plugininfo->get_settings_url()) {
5559 $settings = html_writer::link($surl, $strsettings);
5560 } else {
5561 $settings = '';
5564 // Add uninstall info.
5565 $uninstall = '';
5566 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('enrol_'.$enrol, 'manage')) {
5567 $uninstall = html_writer::link($uninstallurl, $struninstall);
5570 $test = '';
5571 if (!empty($enrols_available[$enrol]) and method_exists($enrols_available[$enrol], 'test_settings')) {
5572 $testsettingsurl = new moodle_url('/enrol/test_settings.php', array('enrol'=>$enrol, 'sesskey'=>sesskey()));
5573 $test = html_writer::link($testsettingsurl, $strtest);
5576 // Add a row to the table.
5577 $row = new html_table_row(array($icon.$displayname, $usage, $version, $hideshow, $updown, $settings, $test, $uninstall));
5578 if ($class) {
5579 $row->attributes['class'] = $class;
5581 $table->data[] = $row;
5583 $printed[$enrol] = true;
5586 $return .= html_writer::table($table);
5587 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5588 $return .= $OUTPUT->box_end();
5589 return highlight($query, $return);
5595 * Blocks manage page
5597 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5599 class admin_page_manageblocks extends admin_externalpage {
5601 * Calls parent::__construct with specific arguments
5603 public function __construct() {
5604 global $CFG;
5605 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5609 * Search for a specific block
5611 * @param string $query The string to search for
5612 * @return array
5614 public function search($query) {
5615 global $CFG, $DB;
5616 if ($result = parent::search($query)) {
5617 return $result;
5620 $found = false;
5621 if ($blocks = $DB->get_records('block')) {
5622 foreach ($blocks as $block) {
5623 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5624 continue;
5626 if (strpos($block->name, $query) !== false) {
5627 $found = true;
5628 break;
5630 $strblockname = get_string('pluginname', 'block_'.$block->name);
5631 if (strpos(core_text::strtolower($strblockname), $query) !== false) {
5632 $found = true;
5633 break;
5637 if ($found) {
5638 $result = new stdClass();
5639 $result->page = $this;
5640 $result->settings = array();
5641 return array($this->name => $result);
5642 } else {
5643 return array();
5649 * Message outputs configuration
5651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5653 class admin_page_managemessageoutputs extends admin_externalpage {
5655 * Calls parent::__construct with specific arguments
5657 public function __construct() {
5658 global $CFG;
5659 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5663 * Search for a specific message processor
5665 * @param string $query The string to search for
5666 * @return array
5668 public function search($query) {
5669 global $CFG, $DB;
5670 if ($result = parent::search($query)) {
5671 return $result;
5674 $found = false;
5675 if ($processors = get_message_processors()) {
5676 foreach ($processors as $processor) {
5677 if (!$processor->available) {
5678 continue;
5680 if (strpos($processor->name, $query) !== false) {
5681 $found = true;
5682 break;
5684 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5685 if (strpos(core_text::strtolower($strprocessorname), $query) !== false) {
5686 $found = true;
5687 break;
5691 if ($found) {
5692 $result = new stdClass();
5693 $result->page = $this;
5694 $result->settings = array();
5695 return array($this->name => $result);
5696 } else {
5697 return array();
5703 * Default message outputs configuration
5705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5707 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5709 * Calls parent::__construct with specific arguments
5711 public function __construct() {
5712 global $CFG;
5713 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5719 * Manage question behaviours page
5721 * @copyright 2011 The Open University
5722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5724 class admin_page_manageqbehaviours extends admin_externalpage {
5726 * Constructor
5728 public function __construct() {
5729 global $CFG;
5730 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5731 new moodle_url('/admin/qbehaviours.php'));
5735 * Search question behaviours for the specified string
5737 * @param string $query The string to search for in question behaviours
5738 * @return array
5740 public function search($query) {
5741 global $CFG;
5742 if ($result = parent::search($query)) {
5743 return $result;
5746 $found = false;
5747 require_once($CFG->dirroot . '/question/engine/lib.php');
5748 foreach (core_component::get_plugin_list('qbehaviour') as $behaviour => $notused) {
5749 if (strpos(core_text::strtolower(question_engine::get_behaviour_name($behaviour)),
5750 $query) !== false) {
5751 $found = true;
5752 break;
5755 if ($found) {
5756 $result = new stdClass();
5757 $result->page = $this;
5758 $result->settings = array();
5759 return array($this->name => $result);
5760 } else {
5761 return array();
5768 * Question type manage page
5770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5772 class admin_page_manageqtypes extends admin_externalpage {
5774 * Calls parent::__construct with specific arguments
5776 public function __construct() {
5777 global $CFG;
5778 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5779 new moodle_url('/admin/qtypes.php'));
5783 * Search question types for the specified string
5785 * @param string $query The string to search for in question types
5786 * @return array
5788 public function search($query) {
5789 global $CFG;
5790 if ($result = parent::search($query)) {
5791 return $result;
5794 $found = false;
5795 require_once($CFG->dirroot . '/question/engine/bank.php');
5796 foreach (question_bank::get_all_qtypes() as $qtype) {
5797 if (strpos(core_text::strtolower($qtype->local_name()), $query) !== false) {
5798 $found = true;
5799 break;
5802 if ($found) {
5803 $result = new stdClass();
5804 $result->page = $this;
5805 $result->settings = array();
5806 return array($this->name => $result);
5807 } else {
5808 return array();
5814 class admin_page_manageportfolios extends admin_externalpage {
5816 * Calls parent::__construct with specific arguments
5818 public function __construct() {
5819 global $CFG;
5820 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5821 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5825 * Searches page for the specified string.
5826 * @param string $query The string to search for
5827 * @return bool True if it is found on this page
5829 public function search($query) {
5830 global $CFG;
5831 if ($result = parent::search($query)) {
5832 return $result;
5835 $found = false;
5836 $portfolios = core_component::get_plugin_list('portfolio');
5837 foreach ($portfolios as $p => $dir) {
5838 if (strpos($p, $query) !== false) {
5839 $found = true;
5840 break;
5843 if (!$found) {
5844 foreach (portfolio_instances(false, false) as $instance) {
5845 $title = $instance->get('name');
5846 if (strpos(core_text::strtolower($title), $query) !== false) {
5847 $found = true;
5848 break;
5853 if ($found) {
5854 $result = new stdClass();
5855 $result->page = $this;
5856 $result->settings = array();
5857 return array($this->name => $result);
5858 } else {
5859 return array();
5865 class admin_page_managerepositories extends admin_externalpage {
5867 * Calls parent::__construct with specific arguments
5869 public function __construct() {
5870 global $CFG;
5871 parent::__construct('managerepositories', get_string('manage',
5872 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5876 * Searches page for the specified string.
5877 * @param string $query The string to search for
5878 * @return bool True if it is found on this page
5880 public function search($query) {
5881 global $CFG;
5882 if ($result = parent::search($query)) {
5883 return $result;
5886 $found = false;
5887 $repositories= core_component::get_plugin_list('repository');
5888 foreach ($repositories as $p => $dir) {
5889 if (strpos($p, $query) !== false) {
5890 $found = true;
5891 break;
5894 if (!$found) {
5895 foreach (repository::get_types() as $instance) {
5896 $title = $instance->get_typename();
5897 if (strpos(core_text::strtolower($title), $query) !== false) {
5898 $found = true;
5899 break;
5904 if ($found) {
5905 $result = new stdClass();
5906 $result->page = $this;
5907 $result->settings = array();
5908 return array($this->name => $result);
5909 } else {
5910 return array();
5917 * Special class for authentication administration.
5919 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5921 class admin_setting_manageauths extends admin_setting {
5923 * Calls parent::__construct with specific arguments
5925 public function __construct() {
5926 $this->nosave = true;
5927 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5931 * Always returns true
5933 * @return true
5935 public function get_setting() {
5936 return true;
5940 * Always returns true
5942 * @return true
5944 public function get_defaultsetting() {
5945 return true;
5949 * Always returns '' and doesn't write anything
5951 * @return string Always returns ''
5953 public function write_setting($data) {
5954 // do not write any setting
5955 return '';
5959 * Search to find if Query is related to auth plugin
5961 * @param string $query The string to search for
5962 * @return bool true for related false for not
5964 public function is_related($query) {
5965 if (parent::is_related($query)) {
5966 return true;
5969 $authsavailable = core_component::get_plugin_list('auth');
5970 foreach ($authsavailable as $auth => $dir) {
5971 if (strpos($auth, $query) !== false) {
5972 return true;
5974 $authplugin = get_auth_plugin($auth);
5975 $authtitle = $authplugin->get_title();
5976 if (strpos(core_text::strtolower($authtitle), $query) !== false) {
5977 return true;
5980 return false;
5984 * Return XHTML to display control
5986 * @param mixed $data Unused
5987 * @param string $query
5988 * @return string highlight
5990 public function output_html($data, $query='') {
5991 global $CFG, $OUTPUT, $DB;
5993 // display strings
5994 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5995 'settings', 'edit', 'name', 'enable', 'disable',
5996 'up', 'down', 'none', 'users'));
5997 $txt->updown = "$txt->up/$txt->down";
5998 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
5999 $txt->testsettings = get_string('testsettings', 'core_auth');
6001 $authsavailable = core_component::get_plugin_list('auth');
6002 get_enabled_auth_plugins(true); // fix the list of enabled auths
6003 if (empty($CFG->auth)) {
6004 $authsenabled = array();
6005 } else {
6006 $authsenabled = explode(',', $CFG->auth);
6009 // construct the display array, with enabled auth plugins at the top, in order
6010 $displayauths = array();
6011 $registrationauths = array();
6012 $registrationauths[''] = $txt->disable;
6013 $authplugins = array();
6014 foreach ($authsenabled as $auth) {
6015 $authplugin = get_auth_plugin($auth);
6016 $authplugins[$auth] = $authplugin;
6017 /// Get the auth title (from core or own auth lang files)
6018 $authtitle = $authplugin->get_title();
6019 /// Apply titles
6020 $displayauths[$auth] = $authtitle;
6021 if ($authplugin->can_signup()) {
6022 $registrationauths[$auth] = $authtitle;
6026 foreach ($authsavailable as $auth => $dir) {
6027 if (array_key_exists($auth, $displayauths)) {
6028 continue; //already in the list
6030 $authplugin = get_auth_plugin($auth);
6031 $authplugins[$auth] = $authplugin;
6032 /// Get the auth title (from core or own auth lang files)
6033 $authtitle = $authplugin->get_title();
6034 /// Apply titles
6035 $displayauths[$auth] = $authtitle;
6036 if ($authplugin->can_signup()) {
6037 $registrationauths[$auth] = $authtitle;
6041 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
6042 $return .= $OUTPUT->box_start('generalbox authsui');
6044 $table = new html_table();
6045 $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall);
6046 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6047 $table->data = array();
6048 $table->attributes['class'] = 'admintable generaltable';
6049 $table->id = 'manageauthtable';
6051 //add always enabled plugins first
6052 $displayname = $displayauths['manual'];
6053 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
6054 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
6055 $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0));
6056 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6057 $displayname = $displayauths['nologin'];
6058 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
6059 $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0));
6060 $table->data[] = array($displayname, $usercount, '', '', $settings, '', '');
6063 // iterate through auth plugins and add to the display table
6064 $updowncount = 1;
6065 $authcount = count($authsenabled);
6066 $url = "auth.php?sesskey=" . sesskey();
6067 foreach ($displayauths as $auth => $name) {
6068 if ($auth == 'manual' or $auth == 'nologin') {
6069 continue;
6071 $class = '';
6072 // hide/show link
6073 if (in_array($auth, $authsenabled)) {
6074 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
6075 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6076 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
6077 $enabled = true;
6078 $displayname = $name;
6080 else {
6081 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
6082 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6083 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
6084 $enabled = false;
6085 $displayname = $name;
6086 $class = 'dimmed_text';
6089 $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0));
6091 // up/down link (only if auth is enabled)
6092 $updown = '';
6093 if ($enabled) {
6094 if ($updowncount > 1) {
6095 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
6096 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6098 else {
6099 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6101 if ($updowncount < $authcount) {
6102 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
6103 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6105 else {
6106 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6108 ++ $updowncount;
6111 // settings link
6112 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
6113 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
6114 } else {
6115 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
6118 // Uninstall link.
6119 $uninstall = '';
6120 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) {
6121 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6124 $test = '';
6125 if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) {
6126 $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey()));
6127 $test = html_writer::link($testurl, $txt->testsettings);
6130 // Add a row to the table.
6131 $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall));
6132 if ($class) {
6133 $row->attributes['class'] = $class;
6135 $table->data[] = $row;
6137 $return .= html_writer::table($table);
6138 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
6139 $return .= $OUTPUT->box_end();
6140 return highlight($query, $return);
6146 * Special class for authentication administration.
6148 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6150 class admin_setting_manageeditors extends admin_setting {
6152 * Calls parent::__construct with specific arguments
6154 public function __construct() {
6155 $this->nosave = true;
6156 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
6160 * Always returns true, does nothing
6162 * @return true
6164 public function get_setting() {
6165 return true;
6169 * Always returns true, does nothing
6171 * @return true
6173 public function get_defaultsetting() {
6174 return true;
6178 * Always returns '', does not write anything
6180 * @return string Always returns ''
6182 public function write_setting($data) {
6183 // do not write any setting
6184 return '';
6188 * Checks if $query is one of the available editors
6190 * @param string $query The string to search for
6191 * @return bool Returns true if found, false if not
6193 public function is_related($query) {
6194 if (parent::is_related($query)) {
6195 return true;
6198 $editors_available = editors_get_available();
6199 foreach ($editors_available as $editor=>$editorstr) {
6200 if (strpos($editor, $query) !== false) {
6201 return true;
6203 if (strpos(core_text::strtolower($editorstr), $query) !== false) {
6204 return true;
6207 return false;
6211 * Builds the XHTML to display the control
6213 * @param string $data Unused
6214 * @param string $query
6215 * @return string
6217 public function output_html($data, $query='') {
6218 global $CFG, $OUTPUT;
6220 // display strings
6221 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
6222 'up', 'down', 'none'));
6223 $struninstall = get_string('uninstallplugin', 'core_admin');
6225 $txt->updown = "$txt->up/$txt->down";
6227 $editors_available = editors_get_available();
6228 $active_editors = explode(',', $CFG->texteditors);
6230 $active_editors = array_reverse($active_editors);
6231 foreach ($active_editors as $key=>$editor) {
6232 if (empty($editors_available[$editor])) {
6233 unset($active_editors[$key]);
6234 } else {
6235 $name = $editors_available[$editor];
6236 unset($editors_available[$editor]);
6237 $editors_available[$editor] = $name;
6240 if (empty($active_editors)) {
6241 //$active_editors = array('textarea');
6243 $editors_available = array_reverse($editors_available, true);
6244 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
6245 $return .= $OUTPUT->box_start('generalbox editorsui');
6247 $table = new html_table();
6248 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
6249 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
6250 $table->id = 'editormanagement';
6251 $table->attributes['class'] = 'admintable generaltable';
6252 $table->data = array();
6254 // iterate through auth plugins and add to the display table
6255 $updowncount = 1;
6256 $editorcount = count($active_editors);
6257 $url = "editors.php?sesskey=" . sesskey();
6258 foreach ($editors_available as $editor => $name) {
6259 // hide/show link
6260 $class = '';
6261 if (in_array($editor, $active_editors)) {
6262 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
6263 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
6264 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
6265 $enabled = true;
6266 $displayname = $name;
6268 else {
6269 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
6270 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
6271 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
6272 $enabled = false;
6273 $displayname = $name;
6274 $class = 'dimmed_text';
6277 // up/down link (only if auth is enabled)
6278 $updown = '';
6279 if ($enabled) {
6280 if ($updowncount > 1) {
6281 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
6282 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6284 else {
6285 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
6287 if ($updowncount < $editorcount) {
6288 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
6289 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6291 else {
6292 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
6294 ++ $updowncount;
6297 // settings link
6298 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
6299 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
6300 $settings = "<a href='$eurl'>{$txt->settings}</a>";
6301 } else {
6302 $settings = '';
6305 $uninstall = '';
6306 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('editor_'.$editor, 'manage')) {
6307 $uninstall = html_writer::link($uninstallurl, $struninstall);
6310 // Add a row to the table.
6311 $row = new html_table_row(array($displayname, $hideshow, $updown, $settings, $uninstall));
6312 if ($class) {
6313 $row->attributes['class'] = $class;
6315 $table->data[] = $row;
6317 $return .= html_writer::table($table);
6318 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
6319 $return .= $OUTPUT->box_end();
6320 return highlight($query, $return);
6326 * Special class for license administration.
6328 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6330 class admin_setting_managelicenses extends admin_setting {
6332 * Calls parent::__construct with specific arguments
6334 public function __construct() {
6335 $this->nosave = true;
6336 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
6340 * Always returns true, does nothing
6342 * @return true
6344 public function get_setting() {
6345 return true;
6349 * Always returns true, does nothing
6351 * @return true
6353 public function get_defaultsetting() {
6354 return true;
6358 * Always returns '', does not write anything
6360 * @return string Always returns ''
6362 public function write_setting($data) {
6363 // do not write any setting
6364 return '';
6368 * Builds the XHTML to display the control
6370 * @param string $data Unused
6371 * @param string $query
6372 * @return string
6374 public function output_html($data, $query='') {
6375 global $CFG, $OUTPUT;
6376 require_once($CFG->libdir . '/licenselib.php');
6377 $url = "licenses.php?sesskey=" . sesskey();
6379 // display strings
6380 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
6381 $licenses = license_manager::get_licenses();
6383 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
6385 $return .= $OUTPUT->box_start('generalbox editorsui');
6387 $table = new html_table();
6388 $table->head = array($txt->name, $txt->enable);
6389 $table->colclasses = array('leftalign', 'centeralign');
6390 $table->id = 'availablelicenses';
6391 $table->attributes['class'] = 'admintable generaltable';
6392 $table->data = array();
6394 foreach ($licenses as $value) {
6395 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
6397 if ($value->enabled == 1) {
6398 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
6399 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
6400 } else {
6401 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
6402 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
6405 if ($value->shortname == $CFG->sitedefaultlicense) {
6406 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
6407 $hideshow = '';
6410 $enabled = true;
6412 $table->data[] =array($displayname, $hideshow);
6414 $return .= html_writer::table($table);
6415 $return .= $OUTPUT->box_end();
6416 return highlight($query, $return);
6421 * Course formats manager. Allows to enable/disable formats and jump to settings
6423 class admin_setting_manageformats extends admin_setting {
6426 * Calls parent::__construct with specific arguments
6428 public function __construct() {
6429 $this->nosave = true;
6430 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
6434 * Always returns true
6436 * @return true
6438 public function get_setting() {
6439 return true;
6443 * Always returns true
6445 * @return true
6447 public function get_defaultsetting() {
6448 return true;
6452 * Always returns '' and doesn't write anything
6454 * @param mixed $data string or array, must not be NULL
6455 * @return string Always returns ''
6457 public function write_setting($data) {
6458 // do not write any setting
6459 return '';
6463 * Search to find if Query is related to format plugin
6465 * @param string $query The string to search for
6466 * @return bool true for related false for not
6468 public function is_related($query) {
6469 if (parent::is_related($query)) {
6470 return true;
6472 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6473 foreach ($formats as $format) {
6474 if (strpos($format->component, $query) !== false ||
6475 strpos(core_text::strtolower($format->displayname), $query) !== false) {
6476 return true;
6479 return false;
6483 * Return XHTML to display control
6485 * @param mixed $data Unused
6486 * @param string $query
6487 * @return string highlight
6489 public function output_html($data, $query='') {
6490 global $CFG, $OUTPUT;
6491 $return = '';
6492 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
6493 $return .= $OUTPUT->box_start('generalbox formatsui');
6495 $formats = core_plugin_manager::instance()->get_plugins_of_type('format');
6497 // display strings
6498 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default'));
6499 $txt->uninstall = get_string('uninstallplugin', 'core_admin');
6500 $txt->updown = "$txt->up/$txt->down";
6502 $table = new html_table();
6503 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->uninstall, $txt->settings);
6504 $table->align = array('left', 'center', 'center', 'center', 'center');
6505 $table->attributes['class'] = 'manageformattable generaltable admintable';
6506 $table->data = array();
6508 $cnt = 0;
6509 $defaultformat = get_config('moodlecourse', 'format');
6510 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6511 foreach ($formats as $format) {
6512 $url = new moodle_url('/admin/courseformats.php',
6513 array('sesskey' => sesskey(), 'format' => $format->name));
6514 $isdefault = '';
6515 $class = '';
6516 if ($format->is_enabled()) {
6517 $strformatname = $format->displayname;
6518 if ($defaultformat === $format->name) {
6519 $hideshow = $txt->default;
6520 } else {
6521 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6522 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6524 } else {
6525 $strformatname = $format->displayname;
6526 $class = 'dimmed_text';
6527 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6528 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6530 $updown = '';
6531 if ($cnt) {
6532 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6533 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6534 } else {
6535 $updown .= $spacer;
6537 if ($cnt < count($formats) - 1) {
6538 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6539 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6540 } else {
6541 $updown .= $spacer;
6543 $cnt++;
6544 $settings = '';
6545 if ($format->get_settings_url()) {
6546 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6548 $uninstall = '';
6549 if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('format_'.$format->name, 'manage')) {
6550 $uninstall = html_writer::link($uninstallurl, $txt->uninstall);
6552 $row = new html_table_row(array($strformatname, $hideshow, $updown, $uninstall, $settings));
6553 if ($class) {
6554 $row->attributes['class'] = $class;
6556 $table->data[] = $row;
6558 $return .= html_writer::table($table);
6559 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6560 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6561 $return .= $OUTPUT->box_end();
6562 return highlight($query, $return);
6567 * Special class for filter administration.
6569 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6571 class admin_page_managefilters extends admin_externalpage {
6573 * Calls parent::__construct with specific arguments
6575 public function __construct() {
6576 global $CFG;
6577 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6581 * Searches all installed filters for specified filter
6583 * @param string $query The filter(string) to search for
6584 * @param string $query
6586 public function search($query) {
6587 global $CFG;
6588 if ($result = parent::search($query)) {
6589 return $result;
6592 $found = false;
6593 $filternames = filter_get_all_installed();
6594 foreach ($filternames as $path => $strfiltername) {
6595 if (strpos(core_text::strtolower($strfiltername), $query) !== false) {
6596 $found = true;
6597 break;
6599 if (strpos($path, $query) !== false) {
6600 $found = true;
6601 break;
6605 if ($found) {
6606 $result = new stdClass;
6607 $result->page = $this;
6608 $result->settings = array();
6609 return array($this->name => $result);
6610 } else {
6611 return array();
6618 * Initialise admin page - this function does require login and permission
6619 * checks specified in page definition.
6621 * This function must be called on each admin page before other code.
6623 * @global moodle_page $PAGE
6625 * @param string $section name of page
6626 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6627 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6628 * added to the turn blocks editing on/off form, so this page reloads correctly.
6629 * @param string $actualurl if the actual page being viewed is not the normal one for this
6630 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6631 * @param array $options Additional options that can be specified for page setup.
6632 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6634 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6635 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6637 $PAGE->set_context(null); // hack - set context to something, by default to system context
6639 $site = get_site();
6640 require_login();
6642 if (!empty($options['pagelayout'])) {
6643 // A specific page layout has been requested.
6644 $PAGE->set_pagelayout($options['pagelayout']);
6645 } else if ($section === 'upgradesettings') {
6646 $PAGE->set_pagelayout('maintenance');
6647 } else {
6648 $PAGE->set_pagelayout('admin');
6651 $adminroot = admin_get_root(false, false); // settings not required for external pages
6652 $extpage = $adminroot->locate($section, true);
6654 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6655 // The requested section isn't in the admin tree
6656 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6657 if (!has_capability('moodle/site:config', context_system::instance())) {
6658 // The requested section could depend on a different capability
6659 // but most likely the user has inadequate capabilities
6660 print_error('accessdenied', 'admin');
6661 } else {
6662 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6666 // this eliminates our need to authenticate on the actual pages
6667 if (!$extpage->check_access()) {
6668 print_error('accessdenied', 'admin');
6669 die;
6672 navigation_node::require_admin_tree();
6674 // $PAGE->set_extra_button($extrabutton); TODO
6676 if (!$actualurl) {
6677 $actualurl = $extpage->url;
6680 $PAGE->set_url($actualurl, $extraurlparams);
6681 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6682 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6685 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6686 // During initial install.
6687 $strinstallation = get_string('installation', 'install');
6688 $strsettings = get_string('settings');
6689 $PAGE->navbar->add($strsettings);
6690 $PAGE->set_title($strinstallation);
6691 $PAGE->set_heading($strinstallation);
6692 $PAGE->set_cacheable(false);
6693 return;
6696 // Locate the current item on the navigation and make it active when found.
6697 $path = $extpage->path;
6698 $node = $PAGE->settingsnav;
6699 while ($node && count($path) > 0) {
6700 $node = $node->get(array_pop($path));
6702 if ($node) {
6703 $node->make_active();
6706 // Normal case.
6707 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6708 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6709 $USER->editing = $adminediting;
6712 $visiblepathtosection = array_reverse($extpage->visiblepath);
6714 if ($PAGE->user_allowed_editing()) {
6715 if ($PAGE->user_is_editing()) {
6716 $caption = get_string('blockseditoff');
6717 $url = new moodle_url($PAGE->url, array('adminedit'=>'0', 'sesskey'=>sesskey()));
6718 } else {
6719 $caption = get_string('blocksediton');
6720 $url = new moodle_url($PAGE->url, array('adminedit'=>'1', 'sesskey'=>sesskey()));
6722 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6725 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6726 $PAGE->set_heading($SITE->fullname);
6728 // prevent caching in nav block
6729 $PAGE->navigation->clear_cache();
6733 * Returns the reference to admin tree root
6735 * @return object admin_root object
6737 function admin_get_root($reload=false, $requirefulltree=true) {
6738 global $CFG, $DB, $OUTPUT;
6740 static $ADMIN = NULL;
6742 if (is_null($ADMIN)) {
6743 // create the admin tree!
6744 $ADMIN = new admin_root($requirefulltree);
6747 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6748 $ADMIN->purge_children($requirefulltree);
6751 if (!$ADMIN->loaded) {
6752 // we process this file first to create categories first and in correct order
6753 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6755 // now we process all other files in admin/settings to build the admin tree
6756 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6757 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6758 continue;
6760 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6761 // plugins are loaded last - they may insert pages anywhere
6762 continue;
6764 require($file);
6766 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6768 $ADMIN->loaded = true;
6771 return $ADMIN;
6774 /// settings utility functions
6777 * This function applies default settings.
6779 * @param object $node, NULL means complete tree, null by default
6780 * @param bool $unconditional if true overrides all values with defaults, null buy default
6782 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6783 global $CFG;
6785 if (is_null($node)) {
6786 core_plugin_manager::reset_caches();
6787 $node = admin_get_root(true, true);
6790 if ($node instanceof admin_category) {
6791 $entries = array_keys($node->children);
6792 foreach ($entries as $entry) {
6793 admin_apply_default_settings($node->children[$entry], $unconditional);
6796 } else if ($node instanceof admin_settingpage) {
6797 foreach ($node->settings as $setting) {
6798 if (!$unconditional and !is_null($setting->get_setting())) {
6799 //do not override existing defaults
6800 continue;
6802 $defaultsetting = $setting->get_defaultsetting();
6803 if (is_null($defaultsetting)) {
6804 // no value yet - default maybe applied after admin user creation or in upgradesettings
6805 continue;
6807 $setting->write_setting($defaultsetting);
6808 $setting->write_setting_flags(null);
6811 // Just in case somebody modifies the list of active plugins directly.
6812 core_plugin_manager::reset_caches();
6816 * Store changed settings, this function updates the errors variable in $ADMIN
6818 * @param object $formdata from form
6819 * @return int number of changed settings
6821 function admin_write_settings($formdata) {
6822 global $CFG, $SITE, $DB;
6824 $olddbsessions = !empty($CFG->dbsessions);
6825 $formdata = (array)$formdata;
6827 $data = array();
6828 foreach ($formdata as $fullname=>$value) {
6829 if (strpos($fullname, 's_') !== 0) {
6830 continue; // not a config value
6832 $data[$fullname] = $value;
6835 $adminroot = admin_get_root();
6836 $settings = admin_find_write_settings($adminroot, $data);
6838 $count = 0;
6839 foreach ($settings as $fullname=>$setting) {
6840 /** @var $setting admin_setting */
6841 $original = $setting->get_setting();
6842 $error = $setting->write_setting($data[$fullname]);
6843 if ($error !== '') {
6844 $adminroot->errors[$fullname] = new stdClass();
6845 $adminroot->errors[$fullname]->data = $data[$fullname];
6846 $adminroot->errors[$fullname]->id = $setting->get_id();
6847 $adminroot->errors[$fullname]->error = $error;
6848 } else {
6849 $setting->write_setting_flags($data);
6851 if ($setting->post_write_settings($original)) {
6852 $count++;
6856 if ($olddbsessions != !empty($CFG->dbsessions)) {
6857 require_logout();
6860 // Now update $SITE - just update the fields, in case other people have a
6861 // a reference to it (e.g. $PAGE, $COURSE).
6862 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6863 foreach (get_object_vars($newsite) as $field => $value) {
6864 $SITE->$field = $value;
6867 // now reload all settings - some of them might depend on the changed
6868 admin_get_root(true);
6869 return $count;
6873 * Internal recursive function - finds all settings from submitted form
6875 * @param object $node Instance of admin_category, or admin_settingpage
6876 * @param array $data
6877 * @return array
6879 function admin_find_write_settings($node, $data) {
6880 $return = array();
6882 if (empty($data)) {
6883 return $return;
6886 if ($node instanceof admin_category) {
6887 $entries = array_keys($node->children);
6888 foreach ($entries as $entry) {
6889 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6892 } else if ($node instanceof admin_settingpage) {
6893 foreach ($node->settings as $setting) {
6894 $fullname = $setting->get_full_name();
6895 if (array_key_exists($fullname, $data)) {
6896 $return[$fullname] = $setting;
6902 return $return;
6906 * Internal function - prints the search results
6908 * @param string $query String to search for
6909 * @return string empty or XHTML
6911 function admin_search_settings_html($query) {
6912 global $CFG, $OUTPUT;
6914 if (core_text::strlen($query) < 2) {
6915 return '';
6917 $query = core_text::strtolower($query);
6919 $adminroot = admin_get_root();
6920 $findings = $adminroot->search($query);
6921 $return = '';
6922 $savebutton = false;
6924 foreach ($findings as $found) {
6925 $page = $found->page;
6926 $settings = $found->settings;
6927 if ($page->is_hidden()) {
6928 // hidden pages are not displayed in search results
6929 continue;
6931 if ($page instanceof admin_externalpage) {
6932 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6933 } else if ($page instanceof admin_settingpage) {
6934 $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');
6935 } else {
6936 continue;
6938 if (!empty($settings)) {
6939 $return .= '<fieldset class="adminsettings">'."\n";
6940 foreach ($settings as $setting) {
6941 if (empty($setting->nosave)) {
6942 $savebutton = true;
6944 $return .= '<div class="clearer"><!-- --></div>'."\n";
6945 $fullname = $setting->get_full_name();
6946 if (array_key_exists($fullname, $adminroot->errors)) {
6947 $data = $adminroot->errors[$fullname]->data;
6948 } else {
6949 $data = $setting->get_setting();
6950 // do not use defaults if settings not available - upgradesettings handles the defaults!
6952 $return .= $setting->output_html($data, $query);
6954 $return .= '</fieldset>';
6958 if ($savebutton) {
6959 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6962 return $return;
6966 * Internal function - returns arrays of html pages with uninitialised settings
6968 * @param object $node Instance of admin_category or admin_settingpage
6969 * @return array
6971 function admin_output_new_settings_by_page($node) {
6972 global $OUTPUT;
6973 $return = array();
6975 if ($node instanceof admin_category) {
6976 $entries = array_keys($node->children);
6977 foreach ($entries as $entry) {
6978 $return += admin_output_new_settings_by_page($node->children[$entry]);
6981 } else if ($node instanceof admin_settingpage) {
6982 $newsettings = array();
6983 foreach ($node->settings as $setting) {
6984 if (is_null($setting->get_setting())) {
6985 $newsettings[] = $setting;
6988 if (count($newsettings) > 0) {
6989 $adminroot = admin_get_root();
6990 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6991 $page .= '<fieldset class="adminsettings">'."\n";
6992 foreach ($newsettings as $setting) {
6993 $fullname = $setting->get_full_name();
6994 if (array_key_exists($fullname, $adminroot->errors)) {
6995 $data = $adminroot->errors[$fullname]->data;
6996 } else {
6997 $data = $setting->get_setting();
6998 if (is_null($data)) {
6999 $data = $setting->get_defaultsetting();
7002 $page .= '<div class="clearer"><!-- --></div>'."\n";
7003 $page .= $setting->output_html($data);
7005 $page .= '</fieldset>';
7006 $return[$node->name] = $page;
7010 return $return;
7014 * Format admin settings
7016 * @param object $setting
7017 * @param string $title label element
7018 * @param string $form form fragment, html code - not highlighted automatically
7019 * @param string $description
7020 * @param bool $label link label to id, true by default
7021 * @param string $warning warning text
7022 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
7023 * @param string $query search query to be highlighted
7024 * @return string XHTML
7026 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
7027 global $CFG;
7029 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
7030 $fullname = $setting->get_full_name();
7032 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
7033 if ($label) {
7034 $labelfor = 'for = "'.$setting->get_id().'"';
7035 } else {
7036 $labelfor = '';
7038 $form .= $setting->output_setting_flags();
7040 $override = '';
7041 if (empty($setting->plugin)) {
7042 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
7043 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7045 } else {
7046 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
7047 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
7051 if ($warning !== '') {
7052 $warning = '<div class="form-warning">'.$warning.'</div>';
7055 $defaults = array();
7056 if (!is_null($defaultinfo)) {
7057 if ($defaultinfo === '') {
7058 $defaultinfo = get_string('emptysettingvalue', 'admin');
7060 $defaults[] = $defaultinfo;
7063 $setting->get_setting_flag_defaults($defaults);
7065 if (!empty($defaults)) {
7066 $defaultinfo = implode(', ', $defaults);
7067 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
7068 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
7072 $adminroot = admin_get_root();
7073 $error = '';
7074 if (array_key_exists($fullname, $adminroot->errors)) {
7075 $error = '<div><span class="error">' . $adminroot->errors[$fullname]->error . '</span></div>';
7078 $str = '
7079 <div class="form-item clearfix" id="admin-'.$setting->name.'">
7080 <div class="form-label">
7081 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
7082 <span class="form-shortname">'.highlightfast($query, $name).'</span>
7083 </div>
7084 <div class="form-setting">'.$error.$form.$defaultinfo.'</div>
7085 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
7086 </div>';
7088 return $str;
7092 * Based on find_new_settings{@link ()} in upgradesettings.php
7093 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
7095 * @param object $node Instance of admin_category, or admin_settingpage
7096 * @return boolean true if any settings haven't been initialised, false if they all have
7098 function any_new_admin_settings($node) {
7100 if ($node instanceof admin_category) {
7101 $entries = array_keys($node->children);
7102 foreach ($entries as $entry) {
7103 if (any_new_admin_settings($node->children[$entry])) {
7104 return true;
7108 } else if ($node instanceof admin_settingpage) {
7109 foreach ($node->settings as $setting) {
7110 if ($setting->get_setting() === NULL) {
7111 return true;
7116 return false;
7120 * Moved from admin/replace.php so that we can use this in cron
7122 * @param string $search string to look for
7123 * @param string $replace string to replace
7124 * @return bool success or fail
7126 function db_replace($search, $replace) {
7127 global $DB, $CFG, $OUTPUT;
7129 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
7130 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log', 'log',
7131 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
7132 'block_instances', '');
7134 // Turn off time limits, sometimes upgrades can be slow.
7135 core_php_time_limit::raise();
7137 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
7138 return false;
7140 foreach ($tables as $table) {
7142 if (in_array($table, $skiptables)) { // Don't process these
7143 continue;
7146 if ($columns = $DB->get_columns($table)) {
7147 $DB->set_debug(true);
7148 foreach ($columns as $column) {
7149 $DB->replace_all_text($table, $column, $search, $replace);
7151 $DB->set_debug(false);
7155 // delete modinfo caches
7156 rebuild_course_cache(0, true);
7158 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
7159 $blocks = core_component::get_plugin_list('block');
7160 foreach ($blocks as $blockname=>$fullblock) {
7161 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
7162 continue;
7165 if (!is_readable($fullblock.'/lib.php')) {
7166 continue;
7169 $function = 'block_'.$blockname.'_global_db_replace';
7170 include_once($fullblock.'/lib.php');
7171 if (!function_exists($function)) {
7172 continue;
7175 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
7176 $function($search, $replace);
7177 echo $OUTPUT->notification("...finished", 'notifysuccess');
7180 purge_all_caches();
7182 return true;
7186 * Manage repository settings
7188 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7190 class admin_setting_managerepository extends admin_setting {
7191 /** @var string */
7192 private $baseurl;
7195 * calls parent::__construct with specific arguments
7197 public function __construct() {
7198 global $CFG;
7199 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
7200 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
7204 * Always returns true, does nothing
7206 * @return true
7208 public function get_setting() {
7209 return true;
7213 * Always returns true does nothing
7215 * @return true
7217 public function get_defaultsetting() {
7218 return true;
7222 * Always returns s_managerepository
7224 * @return string Always return 's_managerepository'
7226 public function get_full_name() {
7227 return 's_managerepository';
7231 * Always returns '' doesn't do anything
7233 public function write_setting($data) {
7234 $url = $this->baseurl . '&amp;new=' . $data;
7235 return '';
7236 // TODO
7237 // Should not use redirect and exit here
7238 // Find a better way to do this.
7239 // redirect($url);
7240 // exit;
7244 * Searches repository plugins for one that matches $query
7246 * @param string $query The string to search for
7247 * @return bool true if found, false if not
7249 public function is_related($query) {
7250 if (parent::is_related($query)) {
7251 return true;
7254 $repositories= core_component::get_plugin_list('repository');
7255 foreach ($repositories as $p => $dir) {
7256 if (strpos($p, $query) !== false) {
7257 return true;
7260 foreach (repository::get_types() as $instance) {
7261 $title = $instance->get_typename();
7262 if (strpos(core_text::strtolower($title), $query) !== false) {
7263 return true;
7266 return false;
7270 * Helper function that generates a moodle_url object
7271 * relevant to the repository
7274 function repository_action_url($repository) {
7275 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
7279 * Builds XHTML to display the control
7281 * @param string $data Unused
7282 * @param string $query
7283 * @return string XHTML
7285 public function output_html($data, $query='') {
7286 global $CFG, $USER, $OUTPUT;
7288 // Get strings that are used
7289 $strshow = get_string('on', 'repository');
7290 $strhide = get_string('off', 'repository');
7291 $strdelete = get_string('disabled', 'repository');
7293 $actionchoicesforexisting = array(
7294 'show' => $strshow,
7295 'hide' => $strhide,
7296 'delete' => $strdelete
7299 $actionchoicesfornew = array(
7300 'newon' => $strshow,
7301 'newoff' => $strhide,
7302 'delete' => $strdelete
7305 $return = '';
7306 $return .= $OUTPUT->box_start('generalbox');
7308 // Set strings that are used multiple times
7309 $settingsstr = get_string('settings');
7310 $disablestr = get_string('disable');
7312 // Table to list plug-ins
7313 $table = new html_table();
7314 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
7315 $table->align = array('left', 'center', 'center', 'center', 'center');
7316 $table->data = array();
7318 // Get list of used plug-ins
7319 $repositorytypes = repository::get_types();
7320 if (!empty($repositorytypes)) {
7321 // Array to store plugins being used
7322 $alreadyplugins = array();
7323 $totalrepositorytypes = count($repositorytypes);
7324 $updowncount = 1;
7325 foreach ($repositorytypes as $i) {
7326 $settings = '';
7327 $typename = $i->get_typename();
7328 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
7329 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
7330 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
7332 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
7333 // Calculate number of instances in order to display them for the Moodle administrator
7334 if (!empty($instanceoptionnames)) {
7335 $params = array();
7336 $params['context'] = array(context_system::instance());
7337 $params['onlyvisible'] = false;
7338 $params['type'] = $typename;
7339 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
7340 // site instances
7341 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
7342 $params['context'] = array();
7343 $instances = repository::static_function($typename, 'get_instances', $params);
7344 $courseinstances = array();
7345 $userinstances = array();
7347 foreach ($instances as $instance) {
7348 $repocontext = context::instance_by_id($instance->instance->contextid);
7349 if ($repocontext->contextlevel == CONTEXT_COURSE) {
7350 $courseinstances[] = $instance;
7351 } else if ($repocontext->contextlevel == CONTEXT_USER) {
7352 $userinstances[] = $instance;
7355 // course instances
7356 $instancenumber = count($courseinstances);
7357 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
7359 // user private instances
7360 $instancenumber = count($userinstances);
7361 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
7362 } else {
7363 $admininstancenumbertext = "";
7364 $courseinstancenumbertext = "";
7365 $userinstancenumbertext = "";
7368 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
7370 $settings .= $OUTPUT->container_start('mdl-left');
7371 $settings .= '<br/>';
7372 $settings .= $admininstancenumbertext;
7373 $settings .= '<br/>';
7374 $settings .= $courseinstancenumbertext;
7375 $settings .= '<br/>';
7376 $settings .= $userinstancenumbertext;
7377 $settings .= $OUTPUT->container_end();
7379 // Get the current visibility
7380 if ($i->get_visible()) {
7381 $currentaction = 'show';
7382 } else {
7383 $currentaction = 'hide';
7386 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
7388 // Display up/down link
7389 $updown = '';
7390 // Should be done with CSS instead.
7391 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
7393 if ($updowncount > 1) {
7394 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
7395 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
7397 else {
7398 $updown .= $spacer;
7400 if ($updowncount < $totalrepositorytypes) {
7401 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
7402 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
7404 else {
7405 $updown .= $spacer;
7408 $updowncount++;
7410 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
7412 if (!in_array($typename, $alreadyplugins)) {
7413 $alreadyplugins[] = $typename;
7418 // Get all the plugins that exist on disk
7419 $plugins = core_component::get_plugin_list('repository');
7420 if (!empty($plugins)) {
7421 foreach ($plugins as $plugin => $dir) {
7422 // Check that it has not already been listed
7423 if (!in_array($plugin, $alreadyplugins)) {
7424 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
7425 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
7430 $return .= html_writer::table($table);
7431 $return .= $OUTPUT->box_end();
7432 return highlight($query, $return);
7437 * Special checkbox for enable mobile web service
7438 * If enable then we store the service id of the mobile service into config table
7439 * If disable then we unstore the service id from the config table
7441 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
7443 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
7444 private $xmlrpcuse;
7445 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
7446 private $restuse;
7449 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
7451 * @return boolean
7453 private function is_protocol_cap_allowed() {
7454 global $DB, $CFG;
7456 // We keep xmlrpc enabled for backward compatibility.
7457 // If the $this->xmlrpcuse variable is not set, it needs to be set.
7458 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
7459 $params = array();
7460 $params['permission'] = CAP_ALLOW;
7461 $params['roleid'] = $CFG->defaultuserroleid;
7462 $params['capability'] = 'webservice/xmlrpc:use';
7463 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
7466 // If the $this->restuse variable is not set, it needs to be set.
7467 if (empty($this->restuse) and $this->restuse!==false) {
7468 $params = array();
7469 $params['permission'] = CAP_ALLOW;
7470 $params['roleid'] = $CFG->defaultuserroleid;
7471 $params['capability'] = 'webservice/rest:use';
7472 $this->restuse = $DB->record_exists('role_capabilities', $params);
7475 return ($this->xmlrpcuse && $this->restuse);
7479 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
7480 * @param type $status true to allow, false to not set
7482 private function set_protocol_cap($status) {
7483 global $CFG;
7484 if ($status and !$this->is_protocol_cap_allowed()) {
7485 //need to allow the cap
7486 $permission = CAP_ALLOW;
7487 $assign = true;
7488 } else if (!$status and $this->is_protocol_cap_allowed()){
7489 //need to disallow the cap
7490 $permission = CAP_INHERIT;
7491 $assign = true;
7493 if (!empty($assign)) {
7494 $systemcontext = context_system::instance();
7495 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7496 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
7501 * Builds XHTML to display the control.
7502 * The main purpose of this overloading is to display a warning when https
7503 * is not supported by the server
7504 * @param string $data Unused
7505 * @param string $query
7506 * @return string XHTML
7508 public function output_html($data, $query='') {
7509 global $CFG, $OUTPUT;
7510 $html = parent::output_html($data, $query);
7512 if ((string)$data === $this->yes) {
7513 require_once($CFG->dirroot . "/lib/filelib.php");
7514 $curl = new curl();
7515 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7516 $curl->head($httpswwwroot . "/login/index.php");
7517 $info = $curl->get_info();
7518 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7519 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7523 return $html;
7527 * Retrieves the current setting using the objects name
7529 * @return string
7531 public function get_setting() {
7532 global $CFG;
7534 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7535 // Or if web services aren't enabled this can't be,
7536 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7537 return 0;
7540 require_once($CFG->dirroot . '/webservice/lib.php');
7541 $webservicemanager = new webservice();
7542 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7543 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7544 return $this->config_read($this->name); //same as returning 1
7545 } else {
7546 return 0;
7551 * Save the selected setting
7553 * @param string $data The selected site
7554 * @return string empty string or error message
7556 public function write_setting($data) {
7557 global $DB, $CFG;
7559 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7560 if (empty($CFG->defaultuserroleid)) {
7561 return '';
7564 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7566 require_once($CFG->dirroot . '/webservice/lib.php');
7567 $webservicemanager = new webservice();
7569 $updateprotocol = false;
7570 if ((string)$data === $this->yes) {
7571 //code run when enable mobile web service
7572 //enable web service systeme if necessary
7573 set_config('enablewebservices', true);
7575 //enable mobile service
7576 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7577 $mobileservice->enabled = 1;
7578 $webservicemanager->update_external_service($mobileservice);
7580 //enable xml-rpc server
7581 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7583 if (!in_array('xmlrpc', $activeprotocols)) {
7584 $activeprotocols[] = 'xmlrpc';
7585 $updateprotocol = true;
7588 if (!in_array('rest', $activeprotocols)) {
7589 $activeprotocols[] = 'rest';
7590 $updateprotocol = true;
7593 if ($updateprotocol) {
7594 set_config('webserviceprotocols', implode(',', $activeprotocols));
7597 //allow xml-rpc:use capability for authenticated user
7598 $this->set_protocol_cap(true);
7600 } else {
7601 //disable web service system if no other services are enabled
7602 $otherenabledservices = $DB->get_records_select('external_services',
7603 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7604 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7605 if (empty($otherenabledservices)) {
7606 set_config('enablewebservices', false);
7608 //also disable xml-rpc server
7609 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7610 $protocolkey = array_search('xmlrpc', $activeprotocols);
7611 if ($protocolkey !== false) {
7612 unset($activeprotocols[$protocolkey]);
7613 $updateprotocol = true;
7616 $protocolkey = array_search('rest', $activeprotocols);
7617 if ($protocolkey !== false) {
7618 unset($activeprotocols[$protocolkey]);
7619 $updateprotocol = true;
7622 if ($updateprotocol) {
7623 set_config('webserviceprotocols', implode(',', $activeprotocols));
7626 //disallow xml-rpc:use capability for authenticated user
7627 $this->set_protocol_cap(false);
7630 //disable the mobile service
7631 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7632 $mobileservice->enabled = 0;
7633 $webservicemanager->update_external_service($mobileservice);
7636 return (parent::write_setting($data));
7641 * Special class for management of external services
7643 * @author Petr Skoda (skodak)
7645 class admin_setting_manageexternalservices extends admin_setting {
7647 * Calls parent::__construct with specific arguments
7649 public function __construct() {
7650 $this->nosave = true;
7651 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7655 * Always returns true, does nothing
7657 * @return true
7659 public function get_setting() {
7660 return true;
7664 * Always returns true, does nothing
7666 * @return true
7668 public function get_defaultsetting() {
7669 return true;
7673 * Always returns '', does not write anything
7675 * @return string Always returns ''
7677 public function write_setting($data) {
7678 // do not write any setting
7679 return '';
7683 * Checks if $query is one of the available external services
7685 * @param string $query The string to search for
7686 * @return bool Returns true if found, false if not
7688 public function is_related($query) {
7689 global $DB;
7691 if (parent::is_related($query)) {
7692 return true;
7695 $services = $DB->get_records('external_services', array(), 'id, name');
7696 foreach ($services as $service) {
7697 if (strpos(core_text::strtolower($service->name), $query) !== false) {
7698 return true;
7701 return false;
7705 * Builds the XHTML to display the control
7707 * @param string $data Unused
7708 * @param string $query
7709 * @return string
7711 public function output_html($data, $query='') {
7712 global $CFG, $OUTPUT, $DB;
7714 // display strings
7715 $stradministration = get_string('administration');
7716 $stredit = get_string('edit');
7717 $strservice = get_string('externalservice', 'webservice');
7718 $strdelete = get_string('delete');
7719 $strplugin = get_string('plugin', 'admin');
7720 $stradd = get_string('add');
7721 $strfunctions = get_string('functions', 'webservice');
7722 $strusers = get_string('users');
7723 $strserviceusers = get_string('serviceusers', 'webservice');
7725 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7726 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7727 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7729 // built in services
7730 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7731 $return = "";
7732 if (!empty($services)) {
7733 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7737 $table = new html_table();
7738 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7739 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7740 $table->id = 'builtinservices';
7741 $table->attributes['class'] = 'admintable externalservices generaltable';
7742 $table->data = array();
7744 // iterate through auth plugins and add to the display table
7745 foreach ($services as $service) {
7746 $name = $service->name;
7748 // hide/show link
7749 if ($service->enabled) {
7750 $displayname = "<span>$name</span>";
7751 } else {
7752 $displayname = "<span class=\"dimmed_text\">$name</span>";
7755 $plugin = $service->component;
7757 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7759 if ($service->restrictedusers) {
7760 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7761 } else {
7762 $users = get_string('allusers', 'webservice');
7765 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7767 // add a row to the table
7768 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7770 $return .= html_writer::table($table);
7773 // Custom services
7774 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7775 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7777 $table = new html_table();
7778 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7779 $table->colclasses = array('leftalign service', 'leftalign plugin', 'centeralign functions', 'centeralign users', 'centeralign ');
7780 $table->id = 'customservices';
7781 $table->attributes['class'] = 'admintable externalservices generaltable';
7782 $table->data = array();
7784 // iterate through auth plugins and add to the display table
7785 foreach ($services as $service) {
7786 $name = $service->name;
7788 // hide/show link
7789 if ($service->enabled) {
7790 $displayname = "<span>$name</span>";
7791 } else {
7792 $displayname = "<span class=\"dimmed_text\">$name</span>";
7795 // delete link
7796 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7798 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7800 if ($service->restrictedusers) {
7801 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7802 } else {
7803 $users = get_string('allusers', 'webservice');
7806 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7808 // add a row to the table
7809 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7811 // add new custom service option
7812 $return .= html_writer::table($table);
7814 $return .= '<br />';
7815 // add a token to the table
7816 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7818 return highlight($query, $return);
7823 * Special class for overview of external services
7825 * @author Jerome Mouneyrac
7827 class admin_setting_webservicesoverview extends admin_setting {
7830 * Calls parent::__construct with specific arguments
7832 public function __construct() {
7833 $this->nosave = true;
7834 parent::__construct('webservicesoverviewui',
7835 get_string('webservicesoverview', 'webservice'), '', '');
7839 * Always returns true, does nothing
7841 * @return true
7843 public function get_setting() {
7844 return true;
7848 * Always returns true, does nothing
7850 * @return true
7852 public function get_defaultsetting() {
7853 return true;
7857 * Always returns '', does not write anything
7859 * @return string Always returns ''
7861 public function write_setting($data) {
7862 // do not write any setting
7863 return '';
7867 * Builds the XHTML to display the control
7869 * @param string $data Unused
7870 * @param string $query
7871 * @return string
7873 public function output_html($data, $query='') {
7874 global $CFG, $OUTPUT;
7876 $return = "";
7877 $brtag = html_writer::empty_tag('br');
7879 // Enable mobile web service
7880 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7881 get_string('enablemobilewebservice', 'admin'),
7882 get_string('configenablemobilewebservice',
7883 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7884 $manageserviceurl = new moodle_url("/admin/settings.php?section=mobile");
7885 $wsmobileparam = new stdClass();
7886 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7887 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7888 get_string('mobile', 'admin'));
7889 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7890 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7891 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7892 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7893 . $brtag . $brtag;
7895 /// One system controlling Moodle with Token
7896 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7897 $table = new html_table();
7898 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7899 get_string('description'));
7900 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
7901 $table->id = 'onesystemcontrol';
7902 $table->attributes['class'] = 'admintable wsoverview generaltable';
7903 $table->data = array();
7905 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7906 . $brtag . $brtag;
7908 /// 1. Enable Web Services
7909 $row = array();
7910 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7911 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7912 array('href' => $url));
7913 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7914 if ($CFG->enablewebservices) {
7915 $status = get_string('yes');
7917 $row[1] = $status;
7918 $row[2] = get_string('enablewsdescription', 'webservice');
7919 $table->data[] = $row;
7921 /// 2. Enable protocols
7922 $row = array();
7923 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7924 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7925 array('href' => $url));
7926 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7927 //retrieve activated protocol
7928 $active_protocols = empty($CFG->webserviceprotocols) ?
7929 array() : explode(',', $CFG->webserviceprotocols);
7930 if (!empty($active_protocols)) {
7931 $status = "";
7932 foreach ($active_protocols as $protocol) {
7933 $status .= $protocol . $brtag;
7936 $row[1] = $status;
7937 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7938 $table->data[] = $row;
7940 /// 3. Create user account
7941 $row = array();
7942 $url = new moodle_url("/user/editadvanced.php?id=-1");
7943 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7944 array('href' => $url));
7945 $row[1] = "";
7946 $row[2] = get_string('createuserdescription', 'webservice');
7947 $table->data[] = $row;
7949 /// 4. Add capability to users
7950 $row = array();
7951 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7952 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7953 array('href' => $url));
7954 $row[1] = "";
7955 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7956 $table->data[] = $row;
7958 /// 5. Select a web service
7959 $row = array();
7960 $url = new moodle_url("/admin/settings.php?section=externalservices");
7961 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7962 array('href' => $url));
7963 $row[1] = "";
7964 $row[2] = get_string('createservicedescription', 'webservice');
7965 $table->data[] = $row;
7967 /// 6. Add functions
7968 $row = array();
7969 $url = new moodle_url("/admin/settings.php?section=externalservices");
7970 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7971 array('href' => $url));
7972 $row[1] = "";
7973 $row[2] = get_string('addfunctionsdescription', 'webservice');
7974 $table->data[] = $row;
7976 /// 7. Add the specific user
7977 $row = array();
7978 $url = new moodle_url("/admin/settings.php?section=externalservices");
7979 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7980 array('href' => $url));
7981 $row[1] = "";
7982 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7983 $table->data[] = $row;
7985 /// 8. Create token for the specific user
7986 $row = array();
7987 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7988 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7989 array('href' => $url));
7990 $row[1] = "";
7991 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7992 $table->data[] = $row;
7994 /// 9. Enable the documentation
7995 $row = array();
7996 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7997 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7998 array('href' => $url));
7999 $status = '<span class="warning">' . get_string('no') . '</span>';
8000 if ($CFG->enablewsdocumentation) {
8001 $status = get_string('yes');
8003 $row[1] = $status;
8004 $row[2] = get_string('enabledocumentationdescription', 'webservice');
8005 $table->data[] = $row;
8007 /// 10. Test the service
8008 $row = array();
8009 $url = new moodle_url("/admin/webservice/testclient.php");
8010 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8011 array('href' => $url));
8012 $row[1] = "";
8013 $row[2] = get_string('testwithtestclientdescription', 'webservice');
8014 $table->data[] = $row;
8016 $return .= html_writer::table($table);
8018 /// Users as clients with token
8019 $return .= $brtag . $brtag . $brtag;
8020 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
8021 $table = new html_table();
8022 $table->head = array(get_string('step', 'webservice'), get_string('status'),
8023 get_string('description'));
8024 $table->colclasses = array('leftalign step', 'leftalign status', 'leftalign description');
8025 $table->id = 'userasclients';
8026 $table->attributes['class'] = 'admintable wsoverview generaltable';
8027 $table->data = array();
8029 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
8030 $brtag . $brtag;
8032 /// 1. Enable Web Services
8033 $row = array();
8034 $url = new moodle_url("/admin/search.php?query=enablewebservices");
8035 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
8036 array('href' => $url));
8037 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
8038 if ($CFG->enablewebservices) {
8039 $status = get_string('yes');
8041 $row[1] = $status;
8042 $row[2] = get_string('enablewsdescription', 'webservice');
8043 $table->data[] = $row;
8045 /// 2. Enable protocols
8046 $row = array();
8047 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
8048 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
8049 array('href' => $url));
8050 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
8051 //retrieve activated protocol
8052 $active_protocols = empty($CFG->webserviceprotocols) ?
8053 array() : explode(',', $CFG->webserviceprotocols);
8054 if (!empty($active_protocols)) {
8055 $status = "";
8056 foreach ($active_protocols as $protocol) {
8057 $status .= $protocol . $brtag;
8060 $row[1] = $status;
8061 $row[2] = get_string('enableprotocolsdescription', 'webservice');
8062 $table->data[] = $row;
8065 /// 3. Select a web service
8066 $row = array();
8067 $url = new moodle_url("/admin/settings.php?section=externalservices");
8068 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
8069 array('href' => $url));
8070 $row[1] = "";
8071 $row[2] = get_string('createserviceforusersdescription', 'webservice');
8072 $table->data[] = $row;
8074 /// 4. Add functions
8075 $row = array();
8076 $url = new moodle_url("/admin/settings.php?section=externalservices");
8077 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
8078 array('href' => $url));
8079 $row[1] = "";
8080 $row[2] = get_string('addfunctionsdescription', 'webservice');
8081 $table->data[] = $row;
8083 /// 5. Add capability to users
8084 $row = array();
8085 $url = new moodle_url("/admin/roles/check.php?contextid=1");
8086 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
8087 array('href' => $url));
8088 $row[1] = "";
8089 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
8090 $table->data[] = $row;
8092 /// 6. Test the service
8093 $row = array();
8094 $url = new moodle_url("/admin/webservice/testclient.php");
8095 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
8096 array('href' => $url));
8097 $row[1] = "";
8098 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
8099 $table->data[] = $row;
8101 $return .= html_writer::table($table);
8103 return highlight($query, $return);
8110 * Special class for web service protocol administration.
8112 * @author Petr Skoda (skodak)
8114 class admin_setting_managewebserviceprotocols extends admin_setting {
8117 * Calls parent::__construct with specific arguments
8119 public function __construct() {
8120 $this->nosave = true;
8121 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
8125 * Always returns true, does nothing
8127 * @return true
8129 public function get_setting() {
8130 return true;
8134 * Always returns true, does nothing
8136 * @return true
8138 public function get_defaultsetting() {
8139 return true;
8143 * Always returns '', does not write anything
8145 * @return string Always returns ''
8147 public function write_setting($data) {
8148 // do not write any setting
8149 return '';
8153 * Checks if $query is one of the available webservices
8155 * @param string $query The string to search for
8156 * @return bool Returns true if found, false if not
8158 public function is_related($query) {
8159 if (parent::is_related($query)) {
8160 return true;
8163 $protocols = core_component::get_plugin_list('webservice');
8164 foreach ($protocols as $protocol=>$location) {
8165 if (strpos($protocol, $query) !== false) {
8166 return true;
8168 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
8169 if (strpos(core_text::strtolower($protocolstr), $query) !== false) {
8170 return true;
8173 return false;
8177 * Builds the XHTML to display the control
8179 * @param string $data Unused
8180 * @param string $query
8181 * @return string
8183 public function output_html($data, $query='') {
8184 global $CFG, $OUTPUT;
8186 // display strings
8187 $stradministration = get_string('administration');
8188 $strsettings = get_string('settings');
8189 $stredit = get_string('edit');
8190 $strprotocol = get_string('protocol', 'webservice');
8191 $strenable = get_string('enable');
8192 $strdisable = get_string('disable');
8193 $strversion = get_string('version');
8195 $protocols_available = core_component::get_plugin_list('webservice');
8196 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
8197 ksort($protocols_available);
8199 foreach ($active_protocols as $key=>$protocol) {
8200 if (empty($protocols_available[$protocol])) {
8201 unset($active_protocols[$key]);
8205 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
8206 $return .= $OUTPUT->box_start('generalbox webservicesui');
8208 $table = new html_table();
8209 $table->head = array($strprotocol, $strversion, $strenable, $strsettings);
8210 $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign');
8211 $table->id = 'webserviceprotocols';
8212 $table->attributes['class'] = 'admintable generaltable';
8213 $table->data = array();
8215 // iterate through auth plugins and add to the display table
8216 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
8217 foreach ($protocols_available as $protocol => $location) {
8218 $name = get_string('pluginname', 'webservice_'.$protocol);
8220 $plugin = new stdClass();
8221 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
8222 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
8224 $version = isset($plugin->version) ? $plugin->version : '';
8226 // hide/show link
8227 if (in_array($protocol, $active_protocols)) {
8228 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
8229 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
8230 $displayname = "<span>$name</span>";
8231 } else {
8232 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
8233 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
8234 $displayname = "<span class=\"dimmed_text\">$name</span>";
8237 // settings link
8238 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
8239 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
8240 } else {
8241 $settings = '';
8244 // add a row to the table
8245 $table->data[] = array($displayname, $version, $hideshow, $settings);
8247 $return .= html_writer::table($table);
8248 $return .= get_string('configwebserviceplugins', 'webservice');
8249 $return .= $OUTPUT->box_end();
8251 return highlight($query, $return);
8257 * Special class for web service token administration.
8259 * @author Jerome Mouneyrac
8261 class admin_setting_managewebservicetokens extends admin_setting {
8264 * Calls parent::__construct with specific arguments
8266 public function __construct() {
8267 $this->nosave = true;
8268 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
8272 * Always returns true, does nothing
8274 * @return true
8276 public function get_setting() {
8277 return true;
8281 * Always returns true, does nothing
8283 * @return true
8285 public function get_defaultsetting() {
8286 return true;
8290 * Always returns '', does not write anything
8292 * @return string Always returns ''
8294 public function write_setting($data) {
8295 // do not write any setting
8296 return '';
8300 * Builds the XHTML to display the control
8302 * @param string $data Unused
8303 * @param string $query
8304 * @return string
8306 public function output_html($data, $query='') {
8307 global $CFG, $OUTPUT, $DB, $USER;
8309 // display strings
8310 $stroperation = get_string('operation', 'webservice');
8311 $strtoken = get_string('token', 'webservice');
8312 $strservice = get_string('service', 'webservice');
8313 $struser = get_string('user');
8314 $strcontext = get_string('context', 'webservice');
8315 $strvaliduntil = get_string('validuntil', 'webservice');
8316 $striprestriction = get_string('iprestriction', 'webservice');
8318 $return = $OUTPUT->box_start('generalbox webservicestokenui');
8320 $table = new html_table();
8321 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
8322 $table->colclasses = array('leftalign', 'leftalign', 'leftalign', 'centeralign', 'centeralign', 'centeralign');
8323 $table->id = 'webservicetokens';
8324 $table->attributes['class'] = 'admintable generaltable';
8325 $table->data = array();
8327 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
8329 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
8331 //here retrieve token list (including linked users firstname/lastname and linked services name)
8332 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
8333 FROM {external_tokens} t, {user} u, {external_services} s
8334 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
8335 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
8336 if (!empty($tokens)) {
8337 foreach ($tokens as $token) {
8338 //TODO: retrieve context
8340 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
8341 $delete .= get_string('delete')."</a>";
8343 $validuntil = '';
8344 if (!empty($token->validuntil)) {
8345 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
8348 $iprestriction = '';
8349 if (!empty($token->iprestriction)) {
8350 $iprestriction = $token->iprestriction;
8353 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
8354 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
8355 $useratag .= $token->firstname." ".$token->lastname;
8356 $useratag .= html_writer::end_tag('a');
8358 //check user missing capabilities
8359 require_once($CFG->dirroot . '/webservice/lib.php');
8360 $webservicemanager = new webservice();
8361 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
8362 array(array('id' => $token->userid)), $token->serviceid);
8364 if (!is_siteadmin($token->userid) and
8365 array_key_exists($token->userid, $usermissingcaps)) {
8366 $missingcapabilities = implode(', ',
8367 $usermissingcaps[$token->userid]);
8368 if (!empty($missingcapabilities)) {
8369 $useratag .= html_writer::tag('div',
8370 get_string('usermissingcaps', 'webservice',
8371 $missingcapabilities)
8372 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
8373 array('class' => 'missingcaps'));
8377 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
8380 $return .= html_writer::table($table);
8381 } else {
8382 $return .= get_string('notoken', 'webservice');
8385 $return .= $OUTPUT->box_end();
8386 // add a token to the table
8387 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
8388 $return .= get_string('add')."</a>";
8390 return highlight($query, $return);
8396 * Colour picker
8398 * @copyright 2010 Sam Hemelryk
8399 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8401 class admin_setting_configcolourpicker extends admin_setting {
8404 * Information for previewing the colour
8406 * @var array|null
8408 protected $previewconfig = null;
8411 * Use default when empty.
8413 protected $usedefaultwhenempty = true;
8417 * @param string $name
8418 * @param string $visiblename
8419 * @param string $description
8420 * @param string $defaultsetting
8421 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
8423 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig = null,
8424 $usedefaultwhenempty = true) {
8425 $this->previewconfig = $previewconfig;
8426 $this->usedefaultwhenempty = $usedefaultwhenempty;
8427 parent::__construct($name, $visiblename, $description, $defaultsetting);
8431 * Return the setting
8433 * @return mixed returns config if successful else null
8435 public function get_setting() {
8436 return $this->config_read($this->name);
8440 * Saves the setting
8442 * @param string $data
8443 * @return bool
8445 public function write_setting($data) {
8446 $data = $this->validate($data);
8447 if ($data === false) {
8448 return get_string('validateerror', 'admin');
8450 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
8454 * Validates the colour that was entered by the user
8456 * @param string $data
8457 * @return string|false
8459 protected function validate($data) {
8461 * List of valid HTML colour names
8463 * @var array
8465 $colornames = array(
8466 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
8467 'beige', 'bisque', 'black', 'blanchedalmond', 'blue',
8468 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
8469 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
8470 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
8471 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta',
8472 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred',
8473 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray',
8474 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
8475 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick',
8476 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
8477 'ghostwhite', 'gold', 'goldenrod', 'gray', 'grey', 'green',
8478 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
8479 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen',
8480 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
8481 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen',
8482 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
8483 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow',
8484 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
8485 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
8486 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
8487 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
8488 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
8489 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
8490 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
8491 'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
8492 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
8493 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
8494 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
8495 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
8496 'whitesmoke', 'yellow', 'yellowgreen'
8499 if (preg_match('/^#?([[:xdigit:]]{3}){1,2}$/', $data)) {
8500 if (strpos($data, '#')!==0) {
8501 $data = '#'.$data;
8503 return $data;
8504 } else if (in_array(strtolower($data), $colornames)) {
8505 return $data;
8506 } else if (preg_match('/rgb\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\)/i', $data)) {
8507 return $data;
8508 } else if (preg_match('/rgba\(\d{0,3}%?\, ?\d{0,3}%?, ?\d{0,3}%?\, ?\d(\.\d)?\)/i', $data)) {
8509 return $data;
8510 } else if (preg_match('/hsl\(\d{0,3}\, ?\d{0,3}%, ?\d{0,3}%\)/i', $data)) {
8511 return $data;
8512 } else if (preg_match('/hsla\(\d{0,3}\, ?\d{0,3}%,\d{0,3}%\, ?\d(\.\d)?\)/i', $data)) {
8513 return $data;
8514 } else if (($data == 'transparent') || ($data == 'currentColor') || ($data == 'inherit')) {
8515 return $data;
8516 } else if (empty($data)) {
8517 if ($this->usedefaultwhenempty){
8518 return $this->defaultsetting;
8519 } else {
8520 return '';
8522 } else {
8523 return false;
8528 * Generates the HTML for the setting
8530 * @global moodle_page $PAGE
8531 * @global core_renderer $OUTPUT
8532 * @param string $data
8533 * @param string $query
8535 public function output_html($data, $query = '') {
8536 global $PAGE, $OUTPUT;
8537 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
8538 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
8539 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
8540 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
8541 if (!empty($this->previewconfig)) {
8542 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
8544 $content .= html_writer::end_tag('div');
8545 return format_admin_setting($this, $this->visiblename, $content, $this->description, true, '', $this->get_defaultsetting(), $query);
8551 * Class used for uploading of one file into file storage,
8552 * the file name is stored in config table.
8554 * Please note you need to implement your own '_pluginfile' callback function,
8555 * this setting only stores the file, it does not deal with file serving.
8557 * @copyright 2013 Petr Skoda {@link http://skodak.org}
8558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8560 class admin_setting_configstoredfile extends admin_setting {
8561 /** @var array file area options - should be one file only */
8562 protected $options;
8563 /** @var string name of the file area */
8564 protected $filearea;
8565 /** @var int intemid */
8566 protected $itemid;
8567 /** @var string used for detection of changes */
8568 protected $oldhashes;
8571 * Create new stored file setting.
8573 * @param string $name low level setting name
8574 * @param string $visiblename human readable setting name
8575 * @param string $description description of setting
8576 * @param mixed $filearea file area for file storage
8577 * @param int $itemid itemid for file storage
8578 * @param array $options file area options
8580 public function __construct($name, $visiblename, $description, $filearea, $itemid = 0, array $options = null) {
8581 parent::__construct($name, $visiblename, $description, '');
8582 $this->filearea = $filearea;
8583 $this->itemid = $itemid;
8584 $this->options = (array)$options;
8588 * Applies defaults and returns all options.
8589 * @return array
8591 protected function get_options() {
8592 global $CFG;
8594 require_once("$CFG->libdir/filelib.php");
8595 require_once("$CFG->dirroot/repository/lib.php");
8596 $defaults = array(
8597 'mainfile' => '', 'subdirs' => 0, 'maxbytes' => -1, 'maxfiles' => 1,
8598 'accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'areamaxbytes' => FILE_AREA_MAX_BYTES_UNLIMITED,
8599 'context' => context_system::instance());
8600 foreach($this->options as $k => $v) {
8601 $defaults[$k] = $v;
8604 return $defaults;
8607 public function get_setting() {
8608 return $this->config_read($this->name);
8611 public function write_setting($data) {
8612 global $USER;
8614 // Let's not deal with validation here, this is for admins only.
8615 $current = $this->get_setting();
8616 if (empty($data) && $current === null) {
8617 // This will be the case when applying default settings (installation).
8618 return ($this->config_write($this->name, '') ? '' : get_string('errorsetting', 'admin'));
8619 } else if (!is_number($data)) {
8620 // Draft item id is expected here!
8621 return get_string('errorsetting', 'admin');
8624 $options = $this->get_options();
8625 $fs = get_file_storage();
8626 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8628 $this->oldhashes = null;
8629 if ($current) {
8630 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8631 if ($file = $fs->get_file_by_hash($hash)) {
8632 $this->oldhashes = $file->get_contenthash().$file->get_pathnamehash();
8634 unset($file);
8637 if ($fs->file_exists($options['context']->id, $component, $this->filearea, $this->itemid, '/', '.')) {
8638 // Make sure the settings form was not open for more than 4 days and draft areas deleted in the meantime.
8639 // But we can safely ignore that if the destination area is empty, so that the user is not prompt
8640 // with an error because the draft area does not exist, as he did not use it.
8641 $usercontext = context_user::instance($USER->id);
8642 if (!$fs->file_exists($usercontext->id, 'user', 'draft', $data, '/', '.') && $current !== '') {
8643 return get_string('errorsetting', 'admin');
8647 file_save_draft_area_files($data, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8648 $files = $fs->get_area_files($options['context']->id, $component, $this->filearea, $this->itemid, 'sortorder,filepath,filename', false);
8650 $filepath = '';
8651 if ($files) {
8652 /** @var stored_file $file */
8653 $file = reset($files);
8654 $filepath = $file->get_filepath().$file->get_filename();
8657 return ($this->config_write($this->name, $filepath) ? '' : get_string('errorsetting', 'admin'));
8660 public function post_write_settings($original) {
8661 $options = $this->get_options();
8662 $fs = get_file_storage();
8663 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8665 $current = $this->get_setting();
8666 $newhashes = null;
8667 if ($current) {
8668 $hash = sha1('/'.$options['context']->id.'/'.$component.'/'.$this->filearea.'/'.$this->itemid.$current);
8669 if ($file = $fs->get_file_by_hash($hash)) {
8670 $newhashes = $file->get_contenthash().$file->get_pathnamehash();
8672 unset($file);
8675 if ($this->oldhashes === $newhashes) {
8676 $this->oldhashes = null;
8677 return false;
8679 $this->oldhashes = null;
8681 $callbackfunction = $this->updatedcallback;
8682 if (!empty($callbackfunction) and function_exists($callbackfunction)) {
8683 $callbackfunction($this->get_full_name());
8685 return true;
8688 public function output_html($data, $query = '') {
8689 global $PAGE, $CFG;
8691 $options = $this->get_options();
8692 $id = $this->get_id();
8693 $elname = $this->get_full_name();
8694 $draftitemid = file_get_submitted_draft_itemid($elname);
8695 $component = is_null($this->plugin) ? 'core' : $this->plugin;
8696 file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->filearea, $this->itemid, $options);
8698 // Filemanager form element implementation is far from optimal, we need to rework this if we ever fix it...
8699 require_once("$CFG->dirroot/lib/form/filemanager.php");
8701 $fmoptions = new stdClass();
8702 $fmoptions->mainfile = $options['mainfile'];
8703 $fmoptions->maxbytes = $options['maxbytes'];
8704 $fmoptions->maxfiles = $options['maxfiles'];
8705 $fmoptions->client_id = uniqid();
8706 $fmoptions->itemid = $draftitemid;
8707 $fmoptions->subdirs = $options['subdirs'];
8708 $fmoptions->target = $id;
8709 $fmoptions->accepted_types = $options['accepted_types'];
8710 $fmoptions->return_types = $options['return_types'];
8711 $fmoptions->context = $options['context'];
8712 $fmoptions->areamaxbytes = $options['areamaxbytes'];
8714 $fm = new form_filemanager($fmoptions);
8715 $output = $PAGE->get_renderer('core', 'files');
8716 $html = $output->render($fm);
8718 $html .= '<input value="'.$draftitemid.'" name="'.$elname.'" type="hidden" />';
8719 $html .= '<input value="" id="'.$id.'" type="hidden" />';
8721 return format_admin_setting($this, $this->visiblename,
8722 '<div class="form-filemanager">'.$html.'</div>', $this->description, true, '', '', $query);
8728 * Administration interface for user specified regular expressions for device detection.
8730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8732 class admin_setting_devicedetectregex extends admin_setting {
8735 * Calls parent::__construct with specific args
8737 * @param string $name
8738 * @param string $visiblename
8739 * @param string $description
8740 * @param mixed $defaultsetting
8742 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
8743 global $CFG;
8744 parent::__construct($name, $visiblename, $description, $defaultsetting);
8748 * Return the current setting(s)
8750 * @return array Current settings array
8752 public function get_setting() {
8753 global $CFG;
8755 $config = $this->config_read($this->name);
8756 if (is_null($config)) {
8757 return null;
8760 return $this->prepare_form_data($config);
8764 * Save selected settings
8766 * @param array $data Array of settings to save
8767 * @return bool
8769 public function write_setting($data) {
8770 if (empty($data)) {
8771 $data = array();
8774 if ($this->config_write($this->name, $this->process_form_data($data))) {
8775 return ''; // success
8776 } else {
8777 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8782 * Return XHTML field(s) for regexes
8784 * @param array $data Array of options to set in HTML
8785 * @return string XHTML string for the fields and wrapping div(s)
8787 public function output_html($data, $query='') {
8788 global $OUTPUT;
8790 $out = html_writer::start_tag('table', array('class' => 'generaltable'));
8791 $out .= html_writer::start_tag('thead');
8792 $out .= html_writer::start_tag('tr');
8793 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8794 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8795 $out .= html_writer::end_tag('tr');
8796 $out .= html_writer::end_tag('thead');
8797 $out .= html_writer::start_tag('tbody');
8799 if (empty($data)) {
8800 $looplimit = 1;
8801 } else {
8802 $looplimit = (count($data)/2)+1;
8805 for ($i=0; $i<$looplimit; $i++) {
8806 $out .= html_writer::start_tag('tr');
8808 $expressionname = 'expression'.$i;
8810 if (!empty($data[$expressionname])){
8811 $expression = $data[$expressionname];
8812 } else {
8813 $expression = '';
8816 $out .= html_writer::tag('td',
8817 html_writer::empty_tag('input',
8818 array(
8819 'type' => 'text',
8820 'class' => 'form-text',
8821 'name' => $this->get_full_name().'[expression'.$i.']',
8822 'value' => $expression,
8824 ), array('class' => 'c'.$i)
8827 $valuename = 'value'.$i;
8829 if (!empty($data[$valuename])){
8830 $value = $data[$valuename];
8831 } else {
8832 $value= '';
8835 $out .= html_writer::tag('td',
8836 html_writer::empty_tag('input',
8837 array(
8838 'type' => 'text',
8839 'class' => 'form-text',
8840 'name' => $this->get_full_name().'[value'.$i.']',
8841 'value' => $value,
8843 ), array('class' => 'c'.$i)
8846 $out .= html_writer::end_tag('tr');
8849 $out .= html_writer::end_tag('tbody');
8850 $out .= html_writer::end_tag('table');
8852 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8856 * Converts the string of regexes
8858 * @see self::process_form_data()
8859 * @param $regexes string of regexes
8860 * @return array of form fields and their values
8862 protected function prepare_form_data($regexes) {
8864 $regexes = json_decode($regexes);
8866 $form = array();
8868 $i = 0;
8870 foreach ($regexes as $value => $regex) {
8871 $expressionname = 'expression'.$i;
8872 $valuename = 'value'.$i;
8874 $form[$expressionname] = $regex;
8875 $form[$valuename] = $value;
8876 $i++;
8879 return $form;
8883 * Converts the data from admin settings form into a string of regexes
8885 * @see self::prepare_form_data()
8886 * @param array $data array of admin form fields and values
8887 * @return false|string of regexes
8889 protected function process_form_data(array $form) {
8891 $count = count($form); // number of form field values
8893 if ($count % 2) {
8894 // we must get five fields per expression
8895 return false;
8898 $regexes = array();
8899 for ($i = 0; $i < $count / 2; $i++) {
8900 $expressionname = "expression".$i;
8901 $valuename = "value".$i;
8903 $expression = trim($form['expression'.$i]);
8904 $value = trim($form['value'.$i]);
8906 if (empty($expression)){
8907 continue;
8910 $regexes[$value] = $expression;
8913 $regexes = json_encode($regexes);
8915 return $regexes;
8920 * Multiselect for current modules
8922 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8924 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8925 private $excludesystem;
8928 * Calls parent::__construct - note array $choices is not required
8930 * @param string $name setting name
8931 * @param string $visiblename localised setting name
8932 * @param string $description setting description
8933 * @param array $defaultsetting a plain array of default module ids
8934 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8936 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8937 $excludesystem = true) {
8938 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8939 $this->excludesystem = $excludesystem;
8943 * Loads an array of current module choices
8945 * @return bool always return true
8947 public function load_choices() {
8948 if (is_array($this->choices)) {
8949 return true;
8951 $this->choices = array();
8953 global $CFG, $DB;
8954 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8955 foreach ($records as $record) {
8956 // Exclude modules if the code doesn't exist
8957 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8958 // Also exclude system modules (if specified)
8959 if (!($this->excludesystem &&
8960 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8961 MOD_ARCHETYPE_SYSTEM)) {
8962 $this->choices[$record->id] = $record->name;
8966 return true;
8971 * Admin setting to show if a php extension is enabled or not.
8973 * @copyright 2013 Damyon Wiese
8974 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8976 class admin_setting_php_extension_enabled extends admin_setting {
8978 /** @var string The name of the extension to check for */
8979 private $extension;
8982 * Calls parent::__construct with specific arguments
8984 public function __construct($name, $visiblename, $description, $extension) {
8985 $this->extension = $extension;
8986 $this->nosave = true;
8987 parent::__construct($name, $visiblename, $description, '');
8991 * Always returns true, does nothing
8993 * @return true
8995 public function get_setting() {
8996 return true;
9000 * Always returns true, does nothing
9002 * @return true
9004 public function get_defaultsetting() {
9005 return true;
9009 * Always returns '', does not write anything
9011 * @return string Always returns ''
9013 public function write_setting($data) {
9014 // Do not write any setting.
9015 return '';
9019 * Outputs the html for this setting.
9020 * @return string Returns an XHTML string
9022 public function output_html($data, $query='') {
9023 global $OUTPUT;
9025 $o = '';
9026 if (!extension_loaded($this->extension)) {
9027 $warning = $OUTPUT->pix_icon('i/warning', '', '', array('role' => 'presentation')) . ' ' . $this->description;
9029 $o .= format_admin_setting($this, $this->visiblename, $warning);
9031 return $o;