MDL-35701 respect case of external column names in enrol_database
[moodle.git] / lib / adminlib.php
blob1bc2a439b7a9b765dd2fb3e047ad84218c6056b7
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 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
119 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
120 * @uses global $OUTPUT to produce notices and other messages
121 * @return void
123 function uninstall_plugin($type, $name) {
124 global $CFG, $DB, $OUTPUT;
126 // recursively uninstall all module/editor subplugins first
127 if ($type === 'mod' || $type === 'editor') {
128 $base = get_component_directory($type . '_' . $name);
129 if (file_exists("$base/db/subplugins.php")) {
130 $subplugins = array();
131 include("$base/db/subplugins.php");
132 foreach ($subplugins as $subplugintype=>$dir) {
133 $instances = get_plugin_list($subplugintype);
134 foreach ($instances as $subpluginname => $notusedpluginpath) {
135 uninstall_plugin($subplugintype, $subpluginname);
142 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
144 if ($type === 'mod') {
145 $pluginname = $name; // eg. 'forum'
146 if (get_string_manager()->string_exists('modulename', $component)) {
147 $strpluginname = get_string('modulename', $component);
148 } else {
149 $strpluginname = $component;
152 } else {
153 $pluginname = $component;
154 if (get_string_manager()->string_exists('pluginname', $component)) {
155 $strpluginname = get_string('pluginname', $component);
156 } else {
157 $strpluginname = $component;
161 echo $OUTPUT->heading($pluginname);
163 $plugindirectory = get_plugin_directory($type, $name);
164 $uninstalllib = $plugindirectory . '/db/uninstall.php';
165 if (file_exists($uninstalllib)) {
166 require_once($uninstalllib);
167 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
168 if (function_exists($uninstallfunction)) {
169 if (!$uninstallfunction()) {
170 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
175 if ($type === 'mod') {
176 // perform cleanup tasks specific for activity modules
178 if (!$module = $DB->get_record('modules', array('name' => $name))) {
179 print_error('moduledoesnotexist', 'error');
182 // delete all the relevant instances from all course sections
183 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
184 foreach ($coursemods as $coursemod) {
185 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
186 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
191 // clear course.modinfo for courses that used this module
192 $sql = "UPDATE {course}
193 SET modinfo=''
194 WHERE id IN (SELECT DISTINCT course
195 FROM {course_modules}
196 WHERE module=?)";
197 $DB->execute($sql, array($module->id));
199 // delete all the course module records
200 $DB->delete_records('course_modules', array('module' => $module->id));
202 // delete module contexts
203 if ($coursemods) {
204 foreach ($coursemods as $coursemod) {
205 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
206 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
211 // delete the module entry itself
212 $DB->delete_records('modules', array('name' => $module->name));
214 // cleanup the gradebook
215 require_once($CFG->libdir.'/gradelib.php');
216 grade_uninstalled_module($module->name);
218 // Perform any custom uninstall tasks
219 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
220 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
221 $uninstallfunction = $module->name . '_uninstall';
222 if (function_exists($uninstallfunction)) {
223 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
224 if (!$uninstallfunction()) {
225 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
230 } else if ($type === 'enrol') {
231 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
232 // nuke all role assignments
233 role_unassign_all(array('component'=>$component));
234 // purge participants
235 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
236 // purge enrol instances
237 $DB->delete_records('enrol', array('enrol'=>$name));
238 // tweak enrol settings
239 if (!empty($CFG->enrol_plugins_enabled)) {
240 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
241 $enabledenrols = array_unique($enabledenrols);
242 $enabledenrols = array_flip($enabledenrols);
243 unset($enabledenrols[$name]);
244 $enabledenrols = array_flip($enabledenrols);
245 if (is_array($enabledenrols)) {
246 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
250 } else if ($type === 'block') {
251 if ($block = $DB->get_record('block', array('name'=>$name))) {
252 // Inform block it's about to be deleted
253 if (file_exists("$CFG->dirroot/blocks/$block->name/block_$block->name.php")) {
254 $blockobject = block_instance($block->name);
255 if ($blockobject) {
256 $blockobject->before_delete(); //only if we can create instance, block might have been already removed
260 // First delete instances and related contexts
261 $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
262 foreach($instances as $instance) {
263 blocks_delete_instance($instance);
266 // Delete block
267 $DB->delete_records('block', array('id'=>$block->id));
271 // perform clean-up task common for all the plugin/subplugin types
273 //delete the web service functions and pre-built services
274 require_once($CFG->dirroot.'/lib/externallib.php');
275 external_delete_descriptions($component);
277 // delete calendar events
278 $DB->delete_records('event', array('modulename' => $pluginname));
280 // delete all the logs
281 $DB->delete_records('log', array('module' => $pluginname));
283 // delete log_display information
284 $DB->delete_records('log_display', array('component' => $component));
286 // delete the module configuration records
287 unset_all_config_for_plugin($pluginname);
289 // delete message provider
290 message_provider_uninstall($component);
292 // delete message processor
293 if ($type === 'message') {
294 message_processor_uninstall($name);
297 // delete the plugin tables
298 $xmldbfilepath = $plugindirectory . '/db/install.xml';
299 drop_plugin_tables($component, $xmldbfilepath, false);
300 if ($type === 'mod' or $type === 'block') {
301 // non-frankenstyle table prefixes
302 drop_plugin_tables($name, $xmldbfilepath, false);
305 // delete the capabilities that were defined by this module
306 capabilities_cleanup($component);
308 // remove event handlers and dequeue pending events
309 events_uninstall($component);
311 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
315 * Returns the version of installed component
317 * @param string $component component name
318 * @param string $source either 'disk' or 'installed' - where to get the version information from
319 * @return string|bool version number or false if the component is not found
321 function get_component_version($component, $source='installed') {
322 global $CFG, $DB;
324 list($type, $name) = normalize_component($component);
326 // moodle core or a core subsystem
327 if ($type === 'core') {
328 if ($source === 'installed') {
329 if (empty($CFG->version)) {
330 return false;
331 } else {
332 return $CFG->version;
334 } else {
335 if (!is_readable($CFG->dirroot.'/version.php')) {
336 return false;
337 } else {
338 $version = null; //initialize variable for IDEs
339 include($CFG->dirroot.'/version.php');
340 return $version;
345 // activity module
346 if ($type === 'mod') {
347 if ($source === 'installed') {
348 return $DB->get_field('modules', 'version', array('name'=>$name));
349 } else {
350 $mods = get_plugin_list('mod');
351 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
352 return false;
353 } else {
354 $module = new stdclass();
355 include($mods[$name].'/version.php');
356 return $module->version;
361 // block
362 if ($type === 'block') {
363 if ($source === 'installed') {
364 return $DB->get_field('block', 'version', array('name'=>$name));
365 } else {
366 $blocks = get_plugin_list('block');
367 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
368 return false;
369 } else {
370 $plugin = new stdclass();
371 include($blocks[$name].'/version.php');
372 return $plugin->version;
377 // all other plugin types
378 if ($source === 'installed') {
379 return get_config($type.'_'.$name, 'version');
380 } else {
381 $plugins = get_plugin_list($type);
382 if (empty($plugins[$name])) {
383 return false;
384 } else {
385 $plugin = new stdclass();
386 include($plugins[$name].'/version.php');
387 return $plugin->version;
393 * Delete all plugin tables
395 * @param string $name Name of plugin, used as table prefix
396 * @param string $file Path to install.xml file
397 * @param bool $feedback defaults to true
398 * @return bool Always returns true
400 function drop_plugin_tables($name, $file, $feedback=true) {
401 global $CFG, $DB;
403 // first try normal delete
404 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
405 return true;
408 // then try to find all tables that start with name and are not in any xml file
409 $used_tables = get_used_table_names();
411 $tables = $DB->get_tables();
413 /// Iterate over, fixing id fields as necessary
414 foreach ($tables as $table) {
415 if (in_array($table, $used_tables)) {
416 continue;
419 if (strpos($table, $name) !== 0) {
420 continue;
423 // found orphan table --> delete it
424 if ($DB->get_manager()->table_exists($table)) {
425 $xmldb_table = new xmldb_table($table);
426 $DB->get_manager()->drop_table($xmldb_table);
430 return true;
434 * Returns names of all known tables == tables that moodle knows about.
436 * @return array Array of lowercase table names
438 function get_used_table_names() {
439 $table_names = array();
440 $dbdirs = get_db_directories();
442 foreach ($dbdirs as $dbdir) {
443 $file = $dbdir.'/install.xml';
445 $xmldb_file = new xmldb_file($file);
447 if (!$xmldb_file->fileExists()) {
448 continue;
451 $loaded = $xmldb_file->loadXMLStructure();
452 $structure = $xmldb_file->getStructure();
454 if ($loaded and $tables = $structure->getTables()) {
455 foreach($tables as $table) {
456 $table_names[] = strtolower($table->getName());
461 return $table_names;
465 * Returns list of all directories where we expect install.xml files
466 * @return array Array of paths
468 function get_db_directories() {
469 global $CFG;
471 $dbdirs = array();
473 /// First, the main one (lib/db)
474 $dbdirs[] = $CFG->libdir.'/db';
476 /// Then, all the ones defined by get_plugin_types()
477 $plugintypes = get_plugin_types();
478 foreach ($plugintypes as $plugintype => $pluginbasedir) {
479 if ($plugins = get_plugin_list($plugintype)) {
480 foreach ($plugins as $plugin => $plugindir) {
481 $dbdirs[] = $plugindir.'/db';
486 return $dbdirs;
490 * Try to obtain or release the cron lock.
491 * @param string $name name of lock
492 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
493 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
494 * @return bool true if lock obtained
496 function set_cron_lock($name, $until, $ignorecurrent=false) {
497 global $DB;
498 if (empty($name)) {
499 debugging("Tried to get a cron lock for a null fieldname");
500 return false;
503 // remove lock by force == remove from config table
504 if (is_null($until)) {
505 set_config($name, null);
506 return true;
509 if (!$ignorecurrent) {
510 // read value from db - other processes might have changed it
511 $value = $DB->get_field('config', 'value', array('name'=>$name));
513 if ($value and $value > time()) {
514 //lock active
515 return false;
519 set_config($name, $until);
520 return true;
524 * Test if and critical warnings are present
525 * @return bool
527 function admin_critical_warnings_present() {
528 global $SESSION;
530 if (!has_capability('moodle/site:config', context_system::instance())) {
531 return 0;
534 if (!isset($SESSION->admin_critical_warning)) {
535 $SESSION->admin_critical_warning = 0;
536 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
537 $SESSION->admin_critical_warning = 1;
541 return $SESSION->admin_critical_warning;
545 * Detects if float supports at least 10 decimal digits
547 * Detects if float supports at least 10 decimal digits
548 * and also if float-->string conversion works as expected.
550 * @return bool true if problem found
552 function is_float_problem() {
553 $num1 = 2009010200.01;
554 $num2 = 2009010200.02;
556 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
560 * Try to verify that dataroot is not accessible from web.
562 * Try to verify that dataroot is not accessible from web.
563 * It is not 100% correct but might help to reduce number of vulnerable sites.
564 * Protection from httpd.conf and .htaccess is not detected properly.
566 * @uses INSECURE_DATAROOT_WARNING
567 * @uses INSECURE_DATAROOT_ERROR
568 * @param bool $fetchtest try to test public access by fetching file, default false
569 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
571 function is_dataroot_insecure($fetchtest=false) {
572 global $CFG;
574 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
576 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
577 $rp = strrev(trim($rp, '/'));
578 $rp = explode('/', $rp);
579 foreach($rp as $r) {
580 if (strpos($siteroot, '/'.$r.'/') === 0) {
581 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
582 } else {
583 break; // probably alias root
587 $siteroot = strrev($siteroot);
588 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
590 if (strpos($dataroot, $siteroot) !== 0) {
591 return false;
594 if (!$fetchtest) {
595 return INSECURE_DATAROOT_WARNING;
598 // now try all methods to fetch a test file using http protocol
600 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
601 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
602 $httpdocroot = $matches[1];
603 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
604 make_upload_directory('diag');
605 $testfile = $CFG->dataroot.'/diag/public.txt';
606 if (!file_exists($testfile)) {
607 file_put_contents($testfile, 'test file, do not delete');
609 $teststr = trim(file_get_contents($testfile));
610 if (empty($teststr)) {
611 // hmm, strange
612 return INSECURE_DATAROOT_WARNING;
615 $testurl = $datarooturl.'/diag/public.txt';
616 if (extension_loaded('curl') and
617 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
618 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
619 ($ch = @curl_init($testurl)) !== false) {
620 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
621 curl_setopt($ch, CURLOPT_HEADER, false);
622 $data = curl_exec($ch);
623 if (!curl_errno($ch)) {
624 $data = trim($data);
625 if ($data === $teststr) {
626 curl_close($ch);
627 return INSECURE_DATAROOT_ERROR;
630 curl_close($ch);
633 if ($data = @file_get_contents($testurl)) {
634 $data = trim($data);
635 if ($data === $teststr) {
636 return INSECURE_DATAROOT_ERROR;
640 preg_match('|https?://([^/]+)|i', $testurl, $matches);
641 $sitename = $matches[1];
642 $error = 0;
643 if ($fp = @fsockopen($sitename, 80, $error)) {
644 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
645 $localurl = $matches[1];
646 $out = "GET $localurl HTTP/1.1\r\n";
647 $out .= "Host: $sitename\r\n";
648 $out .= "Connection: Close\r\n\r\n";
649 fwrite($fp, $out);
650 $data = '';
651 $incoming = false;
652 while (!feof($fp)) {
653 if ($incoming) {
654 $data .= fgets($fp, 1024);
655 } else if (@fgets($fp, 1024) === "\r\n") {
656 $incoming = true;
659 fclose($fp);
660 $data = trim($data);
661 if ($data === $teststr) {
662 return INSECURE_DATAROOT_ERROR;
666 return INSECURE_DATAROOT_WARNING;
669 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
673 * Interface for anything appearing in the admin tree
675 * The interface that is implemented by anything that appears in the admin tree
676 * block. It forces inheriting classes to define a method for checking user permissions
677 * and methods for finding something in the admin tree.
679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681 interface part_of_admin_tree {
684 * Finds a named part_of_admin_tree.
686 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
687 * and not parentable_part_of_admin_tree, then this function should only check if
688 * $this->name matches $name. If it does, it should return a reference to $this,
689 * otherwise, it should return a reference to NULL.
691 * If a class inherits parentable_part_of_admin_tree, this method should be called
692 * recursively on all child objects (assuming, of course, the parent object's name
693 * doesn't match the search criterion).
695 * @param string $name The internal name of the part_of_admin_tree we're searching for.
696 * @return mixed An object reference or a NULL reference.
698 public function locate($name);
701 * Removes named part_of_admin_tree.
703 * @param string $name The internal name of the part_of_admin_tree we want to remove.
704 * @return bool success.
706 public function prune($name);
709 * Search using query
710 * @param string $query
711 * @return mixed array-object structure of found settings and pages
713 public function search($query);
716 * Verifies current user's access to this part_of_admin_tree.
718 * Used to check if the current user has access to this part of the admin tree or
719 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
720 * then this method is usually just a call to has_capability() in the site context.
722 * If a class inherits parentable_part_of_admin_tree, this method should return the
723 * logical OR of the return of check_access() on all child objects.
725 * @return bool True if the user has access, false if she doesn't.
727 public function check_access();
730 * Mostly useful for removing of some parts of the tree in admin tree block.
732 * @return True is hidden from normal list view
734 public function is_hidden();
737 * Show we display Save button at the page bottom?
738 * @return bool
740 public function show_save();
745 * Interface implemented by any part_of_admin_tree that has children.
747 * The interface implemented by any part_of_admin_tree that can be a parent
748 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
749 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
750 * include an add method for adding other part_of_admin_tree objects as children.
752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
754 interface parentable_part_of_admin_tree extends part_of_admin_tree {
757 * Adds a part_of_admin_tree object to the admin tree.
759 * Used to add a part_of_admin_tree object to this object or a child of this
760 * object. $something should only be added if $destinationname matches
761 * $this->name. If it doesn't, add should be called on child objects that are
762 * also parentable_part_of_admin_tree's.
764 * @param string $destinationname The internal name of the new parent for $something.
765 * @param part_of_admin_tree $something The object to be added.
766 * @return bool True on success, false on failure.
768 public function add($destinationname, $something);
774 * The object used to represent folders (a.k.a. categories) in the admin tree block.
776 * Each admin_category object contains a number of part_of_admin_tree objects.
778 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
780 class admin_category implements parentable_part_of_admin_tree {
782 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
783 public $children;
784 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
785 public $name;
786 /** @var string The displayed name for this category. Usually obtained through get_string() */
787 public $visiblename;
788 /** @var bool Should this category be hidden in admin tree block? */
789 public $hidden;
790 /** @var mixed Either a string or an array or strings */
791 public $path;
792 /** @var mixed Either a string or an array or strings */
793 public $visiblepath;
795 /** @var array fast lookup category cache, all categories of one tree point to one cache */
796 protected $category_cache;
799 * Constructor for an empty admin category
801 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
802 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
803 * @param bool $hidden hide category in admin tree block, defaults to false
805 public function __construct($name, $visiblename, $hidden=false) {
806 $this->children = array();
807 $this->name = $name;
808 $this->visiblename = $visiblename;
809 $this->hidden = $hidden;
813 * Returns a reference to the part_of_admin_tree object with internal name $name.
815 * @param string $name The internal name of the object we want.
816 * @param bool $findpath initialize path and visiblepath arrays
817 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
818 * defaults to false
820 public function locate($name, $findpath=false) {
821 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
822 // somebody much have purged the cache
823 $this->category_cache[$this->name] = $this;
826 if ($this->name == $name) {
827 if ($findpath) {
828 $this->visiblepath[] = $this->visiblename;
829 $this->path[] = $this->name;
831 return $this;
834 // quick category lookup
835 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
836 return $this->category_cache[$name];
839 $return = NULL;
840 foreach($this->children as $childid=>$unused) {
841 if ($return = $this->children[$childid]->locate($name, $findpath)) {
842 break;
846 if (!is_null($return) and $findpath) {
847 $return->visiblepath[] = $this->visiblename;
848 $return->path[] = $this->name;
851 return $return;
855 * Search using query
857 * @param string query
858 * @return mixed array-object structure of found settings and pages
860 public function search($query) {
861 $result = array();
862 foreach ($this->children as $child) {
863 $subsearch = $child->search($query);
864 if (!is_array($subsearch)) {
865 debugging('Incorrect search result from '.$child->name);
866 continue;
868 $result = array_merge($result, $subsearch);
870 return $result;
874 * Removes part_of_admin_tree object with internal name $name.
876 * @param string $name The internal name of the object we want to remove.
877 * @return bool success
879 public function prune($name) {
881 if ($this->name == $name) {
882 return false; //can not remove itself
885 foreach($this->children as $precedence => $child) {
886 if ($child->name == $name) {
887 // clear cache and delete self
888 if (is_array($this->category_cache)) {
889 while($this->category_cache) {
890 // delete the cache, but keep the original array address
891 array_pop($this->category_cache);
894 unset($this->children[$precedence]);
895 return true;
896 } else if ($this->children[$precedence]->prune($name)) {
897 return true;
900 return false;
904 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
906 * @param string $destinationame The internal name of the immediate parent that we want for $something.
907 * @param mixed $something A part_of_admin_tree or setting instance to be added.
908 * @return bool True if successfully added, false if $something can not be added.
910 public function add($parentname, $something) {
911 $parent = $this->locate($parentname);
912 if (is_null($parent)) {
913 debugging('parent does not exist!');
914 return false;
917 if ($something instanceof part_of_admin_tree) {
918 if (!($parent instanceof parentable_part_of_admin_tree)) {
919 debugging('error - parts of tree can be inserted only into parentable parts');
920 return false;
922 $parent->children[] = $something;
923 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
924 if (isset($this->category_cache[$something->name])) {
925 debugging('Duplicate admin category name: '.$something->name);
926 } else {
927 $this->category_cache[$something->name] = $something;
928 $something->category_cache =& $this->category_cache;
929 foreach ($something->children as $child) {
930 // just in case somebody already added subcategories
931 if ($child instanceof admin_category) {
932 if (isset($this->category_cache[$child->name])) {
933 debugging('Duplicate admin category name: '.$child->name);
934 } else {
935 $this->category_cache[$child->name] = $child;
936 $child->category_cache =& $this->category_cache;
942 return true;
944 } else {
945 debugging('error - can not add this element');
946 return false;
952 * Checks if the user has access to anything in this category.
954 * @return bool True if the user has access to at least one child in this category, false otherwise.
956 public function check_access() {
957 foreach ($this->children as $child) {
958 if ($child->check_access()) {
959 return true;
962 return false;
966 * Is this category hidden in admin tree block?
968 * @return bool True if hidden
970 public function is_hidden() {
971 return $this->hidden;
975 * Show we display Save button at the page bottom?
976 * @return bool
978 public function show_save() {
979 foreach ($this->children as $child) {
980 if ($child->show_save()) {
981 return true;
984 return false;
990 * Root of admin settings tree, does not have any parent.
992 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
994 class admin_root extends admin_category {
995 /** @var array List of errors */
996 public $errors;
997 /** @var string search query */
998 public $search;
999 /** @var bool full tree flag - true means all settings required, false only pages required */
1000 public $fulltree;
1001 /** @var bool flag indicating loaded tree */
1002 public $loaded;
1003 /** @var mixed site custom defaults overriding defaults in settings files*/
1004 public $custom_defaults;
1007 * @param bool $fulltree true means all settings required,
1008 * false only pages required
1010 public function __construct($fulltree) {
1011 global $CFG;
1013 parent::__construct('root', get_string('administration'), false);
1014 $this->errors = array();
1015 $this->search = '';
1016 $this->fulltree = $fulltree;
1017 $this->loaded = false;
1019 $this->category_cache = array();
1021 // load custom defaults if found
1022 $this->custom_defaults = null;
1023 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1024 if (is_readable($defaultsfile)) {
1025 $defaults = array();
1026 include($defaultsfile);
1027 if (is_array($defaults) and count($defaults)) {
1028 $this->custom_defaults = $defaults;
1034 * Empties children array, and sets loaded to false
1036 * @param bool $requirefulltree
1038 public function purge_children($requirefulltree) {
1039 $this->children = array();
1040 $this->fulltree = ($requirefulltree || $this->fulltree);
1041 $this->loaded = false;
1042 //break circular dependencies - this helps PHP 5.2
1043 while($this->category_cache) {
1044 array_pop($this->category_cache);
1046 $this->category_cache = array();
1052 * Links external PHP pages into the admin tree.
1054 * See detailed usage example at the top of this document (adminlib.php)
1056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1058 class admin_externalpage implements part_of_admin_tree {
1060 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1061 public $name;
1063 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1064 public $visiblename;
1066 /** @var string The external URL that we should link to when someone requests this external page. */
1067 public $url;
1069 /** @var string The role capability/permission a user must have to access this external page. */
1070 public $req_capability;
1072 /** @var object The context in which capability/permission should be checked, default is site context. */
1073 public $context;
1075 /** @var bool hidden in admin tree block. */
1076 public $hidden;
1078 /** @var mixed either string or array of string */
1079 public $path;
1081 /** @var array list of visible names of page parents */
1082 public $visiblepath;
1085 * Constructor for adding an external page into the admin tree.
1087 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1088 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1089 * @param string $url The external URL that we should link to when someone requests this external page.
1090 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1091 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1092 * @param stdClass $context The context the page relates to. Not sure what happens
1093 * if you specify something other than system or front page. Defaults to system.
1095 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1096 $this->name = $name;
1097 $this->visiblename = $visiblename;
1098 $this->url = $url;
1099 if (is_array($req_capability)) {
1100 $this->req_capability = $req_capability;
1101 } else {
1102 $this->req_capability = array($req_capability);
1104 $this->hidden = $hidden;
1105 $this->context = $context;
1109 * Returns a reference to the part_of_admin_tree object with internal name $name.
1111 * @param string $name The internal name of the object we want.
1112 * @param bool $findpath defaults to false
1113 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1115 public function locate($name, $findpath=false) {
1116 if ($this->name == $name) {
1117 if ($findpath) {
1118 $this->visiblepath = array($this->visiblename);
1119 $this->path = array($this->name);
1121 return $this;
1122 } else {
1123 $return = NULL;
1124 return $return;
1129 * This function always returns false, required function by interface
1131 * @param string $name
1132 * @return false
1134 public function prune($name) {
1135 return false;
1139 * Search using query
1141 * @param string $query
1142 * @return mixed array-object structure of found settings and pages
1144 public function search($query) {
1145 $found = false;
1146 if (strpos(strtolower($this->name), $query) !== false) {
1147 $found = true;
1148 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1149 $found = true;
1151 if ($found) {
1152 $result = new stdClass();
1153 $result->page = $this;
1154 $result->settings = array();
1155 return array($this->name => $result);
1156 } else {
1157 return array();
1162 * Determines if the current user has access to this external page based on $this->req_capability.
1164 * @return bool True if user has access, false otherwise.
1166 public function check_access() {
1167 global $CFG;
1168 $context = empty($this->context) ? context_system::instance() : $this->context;
1169 foreach($this->req_capability as $cap) {
1170 if (has_capability($cap, $context)) {
1171 return true;
1174 return false;
1178 * Is this external page hidden in admin tree block?
1180 * @return bool True if hidden
1182 public function is_hidden() {
1183 return $this->hidden;
1187 * Show we display Save button at the page bottom?
1188 * @return bool
1190 public function show_save() {
1191 return false;
1197 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1199 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1201 class admin_settingpage implements part_of_admin_tree {
1203 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1204 public $name;
1206 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1207 public $visiblename;
1209 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1210 public $settings;
1212 /** @var string The role capability/permission a user must have to access this external page. */
1213 public $req_capability;
1215 /** @var object The context in which capability/permission should be checked, default is site context. */
1216 public $context;
1218 /** @var bool hidden in admin tree block. */
1219 public $hidden;
1221 /** @var mixed string of paths or array of strings of paths */
1222 public $path;
1224 /** @var array list of visible names of page parents */
1225 public $visiblepath;
1228 * see admin_settingpage for details of this function
1230 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1231 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1232 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1233 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1234 * @param stdClass $context The context the page relates to. Not sure what happens
1235 * if you specify something other than system or front page. Defaults to system.
1237 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1238 $this->settings = new stdClass();
1239 $this->name = $name;
1240 $this->visiblename = $visiblename;
1241 if (is_array($req_capability)) {
1242 $this->req_capability = $req_capability;
1243 } else {
1244 $this->req_capability = array($req_capability);
1246 $this->hidden = $hidden;
1247 $this->context = $context;
1251 * see admin_category
1253 * @param string $name
1254 * @param bool $findpath
1255 * @return mixed Object (this) if name == this->name, else returns null
1257 public function locate($name, $findpath=false) {
1258 if ($this->name == $name) {
1259 if ($findpath) {
1260 $this->visiblepath = array($this->visiblename);
1261 $this->path = array($this->name);
1263 return $this;
1264 } else {
1265 $return = NULL;
1266 return $return;
1271 * Search string in settings page.
1273 * @param string $query
1274 * @return array
1276 public function search($query) {
1277 $found = array();
1279 foreach ($this->settings as $setting) {
1280 if ($setting->is_related($query)) {
1281 $found[] = $setting;
1285 if ($found) {
1286 $result = new stdClass();
1287 $result->page = $this;
1288 $result->settings = $found;
1289 return array($this->name => $result);
1292 $found = false;
1293 if (strpos(strtolower($this->name), $query) !== false) {
1294 $found = true;
1295 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1296 $found = true;
1298 if ($found) {
1299 $result = new stdClass();
1300 $result->page = $this;
1301 $result->settings = array();
1302 return array($this->name => $result);
1303 } else {
1304 return array();
1309 * This function always returns false, required by interface
1311 * @param string $name
1312 * @return bool Always false
1314 public function prune($name) {
1315 return false;
1319 * adds an admin_setting to this admin_settingpage
1321 * 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
1322 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1324 * @param object $setting is the admin_setting object you want to add
1325 * @return bool true if successful, false if not
1327 public function add($setting) {
1328 if (!($setting instanceof admin_setting)) {
1329 debugging('error - not a setting instance');
1330 return false;
1333 $this->settings->{$setting->name} = $setting;
1334 return true;
1338 * see admin_externalpage
1340 * @return bool Returns true for yes false for no
1342 public function check_access() {
1343 global $CFG;
1344 $context = empty($this->context) ? context_system::instance() : $this->context;
1345 foreach($this->req_capability as $cap) {
1346 if (has_capability($cap, $context)) {
1347 return true;
1350 return false;
1354 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1355 * @return string Returns an XHTML string
1357 public function output_html() {
1358 $adminroot = admin_get_root();
1359 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1360 foreach($this->settings as $setting) {
1361 $fullname = $setting->get_full_name();
1362 if (array_key_exists($fullname, $adminroot->errors)) {
1363 $data = $adminroot->errors[$fullname]->data;
1364 } else {
1365 $data = $setting->get_setting();
1366 // do not use defaults if settings not available - upgrade settings handles the defaults!
1368 $return .= $setting->output_html($data);
1370 $return .= '</fieldset>';
1371 return $return;
1375 * Is this settings page hidden in admin tree block?
1377 * @return bool True if hidden
1379 public function is_hidden() {
1380 return $this->hidden;
1384 * Show we display Save button at the page bottom?
1385 * @return bool
1387 public function show_save() {
1388 foreach($this->settings as $setting) {
1389 if (empty($setting->nosave)) {
1390 return true;
1393 return false;
1399 * Admin settings class. Only exists on setting pages.
1400 * Read & write happens at this level; no authentication.
1402 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1404 abstract class admin_setting {
1405 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1406 public $name;
1407 /** @var string localised name */
1408 public $visiblename;
1409 /** @var string localised long description in Markdown format */
1410 public $description;
1411 /** @var mixed Can be string or array of string */
1412 public $defaultsetting;
1413 /** @var string */
1414 public $updatedcallback;
1415 /** @var mixed can be String or Null. Null means main config table */
1416 public $plugin; // null means main config table
1417 /** @var bool true indicates this setting does not actually save anything, just information */
1418 public $nosave = false;
1419 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1420 public $affectsmodinfo = false;
1423 * Constructor
1424 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1425 * or 'myplugin/mysetting' for ones in config_plugins.
1426 * @param string $visiblename localised name
1427 * @param string $description localised long description
1428 * @param mixed $defaultsetting string or array depending on implementation
1430 public function __construct($name, $visiblename, $description, $defaultsetting) {
1431 $this->parse_setting_name($name);
1432 $this->visiblename = $visiblename;
1433 $this->description = $description;
1434 $this->defaultsetting = $defaultsetting;
1438 * Set up $this->name and potentially $this->plugin
1440 * Set up $this->name and possibly $this->plugin based on whether $name looks
1441 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1442 * on the names, that is, output a developer debug warning if the name
1443 * contains anything other than [a-zA-Z0-9_]+.
1445 * @param string $name the setting name passed in to the constructor.
1447 private function parse_setting_name($name) {
1448 $bits = explode('/', $name);
1449 if (count($bits) > 2) {
1450 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1452 $this->name = array_pop($bits);
1453 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1454 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1456 if (!empty($bits)) {
1457 $this->plugin = array_pop($bits);
1458 if ($this->plugin === 'moodle') {
1459 $this->plugin = null;
1460 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1461 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1467 * Returns the fullname prefixed by the plugin
1468 * @return string
1470 public function get_full_name() {
1471 return 's_'.$this->plugin.'_'.$this->name;
1475 * Returns the ID string based on plugin and name
1476 * @return string
1478 public function get_id() {
1479 return 'id_s_'.$this->plugin.'_'.$this->name;
1483 * @param bool $affectsmodinfo If true, changes to this setting will
1484 * cause the course cache to be rebuilt
1486 public function set_affects_modinfo($affectsmodinfo) {
1487 $this->affectsmodinfo = $affectsmodinfo;
1491 * Returns the config if possible
1493 * @return mixed returns config if successful else null
1495 public function config_read($name) {
1496 global $CFG;
1497 if (!empty($this->plugin)) {
1498 $value = get_config($this->plugin, $name);
1499 return $value === false ? NULL : $value;
1501 } else {
1502 if (isset($CFG->$name)) {
1503 return $CFG->$name;
1504 } else {
1505 return NULL;
1511 * Used to set a config pair and log change
1513 * @param string $name
1514 * @param mixed $value Gets converted to string if not null
1515 * @return bool Write setting to config table
1517 public function config_write($name, $value) {
1518 global $DB, $USER, $CFG;
1520 if ($this->nosave) {
1521 return true;
1524 // make sure it is a real change
1525 $oldvalue = get_config($this->plugin, $name);
1526 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1527 $value = is_null($value) ? null : (string)$value;
1529 if ($oldvalue === $value) {
1530 return true;
1533 // store change
1534 set_config($name, $value, $this->plugin);
1536 // Some admin settings affect course modinfo
1537 if ($this->affectsmodinfo) {
1538 // Clear course cache for all courses
1539 rebuild_course_cache(0, true);
1542 // log change
1543 $log = new stdClass();
1544 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1545 $log->timemodified = time();
1546 $log->plugin = $this->plugin;
1547 $log->name = $name;
1548 $log->value = $value;
1549 $log->oldvalue = $oldvalue;
1550 $DB->insert_record('config_log', $log);
1552 return true; // BC only
1556 * Returns current value of this setting
1557 * @return mixed array or string depending on instance, NULL means not set yet
1559 public abstract function get_setting();
1562 * Returns default setting if exists
1563 * @return mixed array or string depending on instance; NULL means no default, user must supply
1565 public function get_defaultsetting() {
1566 $adminroot = admin_get_root(false, false);
1567 if (!empty($adminroot->custom_defaults)) {
1568 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1569 if (isset($adminroot->custom_defaults[$plugin])) {
1570 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1571 return $adminroot->custom_defaults[$plugin][$this->name];
1575 return $this->defaultsetting;
1579 * Store new setting
1581 * @param mixed $data string or array, must not be NULL
1582 * @return string empty string if ok, string error message otherwise
1584 public abstract function write_setting($data);
1587 * Return part of form with setting
1588 * This function should always be overwritten
1590 * @param mixed $data array or string depending on setting
1591 * @param string $query
1592 * @return string
1594 public function output_html($data, $query='') {
1595 // should be overridden
1596 return;
1600 * Function called if setting updated - cleanup, cache reset, etc.
1601 * @param string $functionname Sets the function name
1602 * @return void
1604 public function set_updatedcallback($functionname) {
1605 $this->updatedcallback = $functionname;
1609 * Is setting related to query text - used when searching
1610 * @param string $query
1611 * @return bool
1613 public function is_related($query) {
1614 if (strpos(strtolower($this->name), $query) !== false) {
1615 return true;
1617 if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1618 return true;
1620 if (strpos(textlib::strtolower($this->description), $query) !== false) {
1621 return true;
1623 $current = $this->get_setting();
1624 if (!is_null($current)) {
1625 if (is_string($current)) {
1626 if (strpos(textlib::strtolower($current), $query) !== false) {
1627 return true;
1631 $default = $this->get_defaultsetting();
1632 if (!is_null($default)) {
1633 if (is_string($default)) {
1634 if (strpos(textlib::strtolower($default), $query) !== false) {
1635 return true;
1639 return false;
1645 * No setting - just heading and text.
1647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1649 class admin_setting_heading extends admin_setting {
1652 * not a setting, just text
1653 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1654 * @param string $heading heading
1655 * @param string $information text in box
1657 public function __construct($name, $heading, $information) {
1658 $this->nosave = true;
1659 parent::__construct($name, $heading, $information, '');
1663 * Always returns true
1664 * @return bool Always returns true
1666 public function get_setting() {
1667 return true;
1671 * Always returns true
1672 * @return bool Always returns true
1674 public function get_defaultsetting() {
1675 return true;
1679 * Never write settings
1680 * @return string Always returns an empty string
1682 public function write_setting($data) {
1683 // do not write any setting
1684 return '';
1688 * Returns an HTML string
1689 * @return string Returns an HTML string
1691 public function output_html($data, $query='') {
1692 global $OUTPUT;
1693 $return = '';
1694 if ($this->visiblename != '') {
1695 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1697 if ($this->description != '') {
1698 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1700 return $return;
1706 * The most flexibly setting, user is typing text
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1710 class admin_setting_configtext extends admin_setting {
1712 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1713 public $paramtype;
1714 /** @var int default field size */
1715 public $size;
1718 * Config text constructor
1720 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1721 * @param string $visiblename localised
1722 * @param string $description long localised info
1723 * @param string $defaultsetting
1724 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1725 * @param int $size default field size
1727 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1728 $this->paramtype = $paramtype;
1729 if (!is_null($size)) {
1730 $this->size = $size;
1731 } else {
1732 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1734 parent::__construct($name, $visiblename, $description, $defaultsetting);
1738 * Return the setting
1740 * @return mixed returns config if successful else null
1742 public function get_setting() {
1743 return $this->config_read($this->name);
1746 public function write_setting($data) {
1747 if ($this->paramtype === PARAM_INT and $data === '') {
1748 // do not complain if '' used instead of 0
1749 $data = 0;
1751 // $data is a string
1752 $validated = $this->validate($data);
1753 if ($validated !== true) {
1754 return $validated;
1756 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1760 * Validate data before storage
1761 * @param string data
1762 * @return mixed true if ok string if error found
1764 public function validate($data) {
1765 // allow paramtype to be a custom regex if it is the form of /pattern/
1766 if (preg_match('#^/.*/$#', $this->paramtype)) {
1767 if (preg_match($this->paramtype, $data)) {
1768 return true;
1769 } else {
1770 return get_string('validateerror', 'admin');
1773 } else if ($this->paramtype === PARAM_RAW) {
1774 return true;
1776 } else {
1777 $cleaned = clean_param($data, $this->paramtype);
1778 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1779 return true;
1780 } else {
1781 return get_string('validateerror', 'admin');
1787 * Return an XHTML string for the setting
1788 * @return string Returns an XHTML string
1790 public function output_html($data, $query='') {
1791 $default = $this->get_defaultsetting();
1793 return format_admin_setting($this, $this->visiblename,
1794 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1795 $this->description, true, '', $default, $query);
1801 * General text area without html editor.
1803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1805 class admin_setting_configtextarea extends admin_setting_configtext {
1806 private $rows;
1807 private $cols;
1810 * @param string $name
1811 * @param string $visiblename
1812 * @param string $description
1813 * @param mixed $defaultsetting string or array
1814 * @param mixed $paramtype
1815 * @param string $cols The number of columns to make the editor
1816 * @param string $rows The number of rows to make the editor
1818 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1819 $this->rows = $rows;
1820 $this->cols = $cols;
1821 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1825 * Returns an XHTML string for the editor
1827 * @param string $data
1828 * @param string $query
1829 * @return string XHTML string for the editor
1831 public function output_html($data, $query='') {
1832 $default = $this->get_defaultsetting();
1834 $defaultinfo = $default;
1835 if (!is_null($default) and $default !== '') {
1836 $defaultinfo = "\n".$default;
1839 return format_admin_setting($this, $this->visiblename,
1840 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1841 $this->description, true, '', $defaultinfo, $query);
1847 * General text area with html editor.
1849 class admin_setting_confightmleditor extends admin_setting_configtext {
1850 private $rows;
1851 private $cols;
1854 * @param string $name
1855 * @param string $visiblename
1856 * @param string $description
1857 * @param mixed $defaultsetting string or array
1858 * @param mixed $paramtype
1860 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1861 $this->rows = $rows;
1862 $this->cols = $cols;
1863 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1864 editors_head_setup();
1868 * Returns an XHTML string for the editor
1870 * @param string $data
1871 * @param string $query
1872 * @return string XHTML string for the editor
1874 public function output_html($data, $query='') {
1875 $default = $this->get_defaultsetting();
1877 $defaultinfo = $default;
1878 if (!is_null($default) and $default !== '') {
1879 $defaultinfo = "\n".$default;
1882 $editor = editors_get_preferred_editor(FORMAT_HTML);
1883 $editor->use_editor($this->get_id(), array('noclean'=>true));
1885 return format_admin_setting($this, $this->visiblename,
1886 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1887 $this->description, true, '', $defaultinfo, $query);
1893 * Password field, allows unmasking of password
1895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1897 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1899 * Constructor
1900 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1901 * @param string $visiblename localised
1902 * @param string $description long localised info
1903 * @param string $defaultsetting default password
1905 public function __construct($name, $visiblename, $description, $defaultsetting) {
1906 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1910 * Returns XHTML for the field
1911 * Writes Javascript into the HTML below right before the last div
1913 * @todo Make javascript available through newer methods if possible
1914 * @param string $data Value for the field
1915 * @param string $query Passed as final argument for format_admin_setting
1916 * @return string XHTML field
1918 public function output_html($data, $query='') {
1919 $id = $this->get_id();
1920 $unmask = get_string('unmaskpassword', 'form');
1921 $unmaskjs = '<script type="text/javascript">
1922 //<![CDATA[
1923 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1925 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1927 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1929 var unmaskchb = document.createElement("input");
1930 unmaskchb.setAttribute("type", "checkbox");
1931 unmaskchb.setAttribute("id", "'.$id.'unmask");
1932 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1933 unmaskdiv.appendChild(unmaskchb);
1935 var unmasklbl = document.createElement("label");
1936 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1937 if (is_ie) {
1938 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1939 } else {
1940 unmasklbl.setAttribute("for", "'.$id.'unmask");
1942 unmaskdiv.appendChild(unmasklbl);
1944 if (is_ie) {
1945 // ugly hack to work around the famous onchange IE bug
1946 unmaskchb.onclick = function() {this.blur();};
1947 unmaskdiv.onclick = function() {this.blur();};
1949 //]]>
1950 </script>';
1951 return format_admin_setting($this, $this->visiblename,
1952 '<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>',
1953 $this->description, true, '', NULL, $query);
1959 * Path to directory
1961 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1963 class admin_setting_configfile extends admin_setting_configtext {
1965 * Constructor
1966 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1967 * @param string $visiblename localised
1968 * @param string $description long localised info
1969 * @param string $defaultdirectory default directory location
1971 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1972 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1976 * Returns XHTML for the field
1978 * Returns XHTML for the field and also checks whether the file
1979 * specified in $data exists using file_exists()
1981 * @param string $data File name and path to use in value attr
1982 * @param string $query
1983 * @return string XHTML field
1985 public function output_html($data, $query='') {
1986 $default = $this->get_defaultsetting();
1988 if ($data) {
1989 if (file_exists($data)) {
1990 $executable = '<span class="pathok">&#x2714;</span>';
1991 } else {
1992 $executable = '<span class="patherror">&#x2718;</span>';
1994 } else {
1995 $executable = '';
1998 return format_admin_setting($this, $this->visiblename,
1999 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2000 $this->description, true, '', $default, $query);
2006 * Path to executable file
2008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2010 class admin_setting_configexecutable extends admin_setting_configfile {
2013 * Returns an XHTML field
2015 * @param string $data This is the value for the field
2016 * @param string $query
2017 * @return string XHTML field
2019 public function output_html($data, $query='') {
2020 $default = $this->get_defaultsetting();
2022 if ($data) {
2023 if (file_exists($data) and is_executable($data)) {
2024 $executable = '<span class="pathok">&#x2714;</span>';
2025 } else {
2026 $executable = '<span class="patherror">&#x2718;</span>';
2028 } else {
2029 $executable = '';
2032 return format_admin_setting($this, $this->visiblename,
2033 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2034 $this->description, true, '', $default, $query);
2040 * Path to directory
2042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2044 class admin_setting_configdirectory extends admin_setting_configfile {
2047 * Returns an XHTML field
2049 * @param string $data This is the value for the field
2050 * @param string $query
2051 * @return string XHTML
2053 public function output_html($data, $query='') {
2054 $default = $this->get_defaultsetting();
2056 if ($data) {
2057 if (file_exists($data) and is_dir($data)) {
2058 $executable = '<span class="pathok">&#x2714;</span>';
2059 } else {
2060 $executable = '<span class="patherror">&#x2718;</span>';
2062 } else {
2063 $executable = '';
2066 return format_admin_setting($this, $this->visiblename,
2067 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2068 $this->description, true, '', $default, $query);
2074 * Checkbox
2076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2078 class admin_setting_configcheckbox extends admin_setting {
2079 /** @var string Value used when checked */
2080 public $yes;
2081 /** @var string Value used when not checked */
2082 public $no;
2085 * Constructor
2086 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2087 * @param string $visiblename localised
2088 * @param string $description long localised info
2089 * @param string $defaultsetting
2090 * @param string $yes value used when checked
2091 * @param string $no value used when not checked
2093 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2094 parent::__construct($name, $visiblename, $description, $defaultsetting);
2095 $this->yes = (string)$yes;
2096 $this->no = (string)$no;
2100 * Retrieves the current setting using the objects name
2102 * @return string
2104 public function get_setting() {
2105 return $this->config_read($this->name);
2109 * Sets the value for the setting
2111 * Sets the value for the setting to either the yes or no values
2112 * of the object by comparing $data to yes
2114 * @param mixed $data Gets converted to str for comparison against yes value
2115 * @return string empty string or error
2117 public function write_setting($data) {
2118 if ((string)$data === $this->yes) { // convert to strings before comparison
2119 $data = $this->yes;
2120 } else {
2121 $data = $this->no;
2123 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2127 * Returns an XHTML checkbox field
2129 * @param string $data If $data matches yes then checkbox is checked
2130 * @param string $query
2131 * @return string XHTML field
2133 public function output_html($data, $query='') {
2134 $default = $this->get_defaultsetting();
2136 if (!is_null($default)) {
2137 if ((string)$default === $this->yes) {
2138 $defaultinfo = get_string('checkboxyes', 'admin');
2139 } else {
2140 $defaultinfo = get_string('checkboxno', 'admin');
2142 } else {
2143 $defaultinfo = NULL;
2146 if ((string)$data === $this->yes) { // convert to strings before comparison
2147 $checked = 'checked="checked"';
2148 } else {
2149 $checked = '';
2152 return format_admin_setting($this, $this->visiblename,
2153 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2154 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2155 $this->description, true, '', $defaultinfo, $query);
2161 * Multiple checkboxes, each represents different value, stored in csv format
2163 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2165 class admin_setting_configmulticheckbox extends admin_setting {
2166 /** @var array Array of choices value=>label */
2167 public $choices;
2170 * Constructor: uses parent::__construct
2172 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2173 * @param string $visiblename localised
2174 * @param string $description long localised info
2175 * @param array $defaultsetting array of selected
2176 * @param array $choices array of $value=>$label for each checkbox
2178 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2179 $this->choices = $choices;
2180 parent::__construct($name, $visiblename, $description, $defaultsetting);
2184 * This public function may be used in ancestors for lazy loading of choices
2186 * @todo Check if this function is still required content commented out only returns true
2187 * @return bool true if loaded, false if error
2189 public function load_choices() {
2191 if (is_array($this->choices)) {
2192 return true;
2194 .... load choices here
2196 return true;
2200 * Is setting related to query text - used when searching
2202 * @param string $query
2203 * @return bool true on related, false on not or failure
2205 public function is_related($query) {
2206 if (!$this->load_choices() or empty($this->choices)) {
2207 return false;
2209 if (parent::is_related($query)) {
2210 return true;
2213 foreach ($this->choices as $desc) {
2214 if (strpos(textlib::strtolower($desc), $query) !== false) {
2215 return true;
2218 return false;
2222 * Returns the current setting if it is set
2224 * @return mixed null if null, else an array
2226 public function get_setting() {
2227 $result = $this->config_read($this->name);
2229 if (is_null($result)) {
2230 return NULL;
2232 if ($result === '') {
2233 return array();
2235 $enabled = explode(',', $result);
2236 $setting = array();
2237 foreach ($enabled as $option) {
2238 $setting[$option] = 1;
2240 return $setting;
2244 * Saves the setting(s) provided in $data
2246 * @param array $data An array of data, if not array returns empty str
2247 * @return mixed empty string on useless data or bool true=success, false=failed
2249 public function write_setting($data) {
2250 if (!is_array($data)) {
2251 return ''; // ignore it
2253 if (!$this->load_choices() or empty($this->choices)) {
2254 return '';
2256 unset($data['xxxxx']);
2257 $result = array();
2258 foreach ($data as $key => $value) {
2259 if ($value and array_key_exists($key, $this->choices)) {
2260 $result[] = $key;
2263 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2267 * Returns XHTML field(s) as required by choices
2269 * Relies on data being an array should data ever be another valid vartype with
2270 * acceptable value this may cause a warning/error
2271 * if (!is_array($data)) would fix the problem
2273 * @todo Add vartype handling to ensure $data is an array
2275 * @param array $data An array of checked values
2276 * @param string $query
2277 * @return string XHTML field
2279 public function output_html($data, $query='') {
2280 if (!$this->load_choices() or empty($this->choices)) {
2281 return '';
2283 $default = $this->get_defaultsetting();
2284 if (is_null($default)) {
2285 $default = array();
2287 if (is_null($data)) {
2288 $data = array();
2290 $options = array();
2291 $defaults = array();
2292 foreach ($this->choices as $key=>$description) {
2293 if (!empty($data[$key])) {
2294 $checked = 'checked="checked"';
2295 } else {
2296 $checked = '';
2298 if (!empty($default[$key])) {
2299 $defaults[] = $description;
2302 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2303 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2306 if (is_null($default)) {
2307 $defaultinfo = NULL;
2308 } else if (!empty($defaults)) {
2309 $defaultinfo = implode(', ', $defaults);
2310 } else {
2311 $defaultinfo = get_string('none');
2314 $return = '<div class="form-multicheckbox">';
2315 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2316 if ($options) {
2317 $return .= '<ul>';
2318 foreach ($options as $option) {
2319 $return .= '<li>'.$option.'</li>';
2321 $return .= '</ul>';
2323 $return .= '</div>';
2325 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2332 * Multiple checkboxes 2, value stored as string 00101011
2334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2336 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2339 * Returns the setting if set
2341 * @return mixed null if not set, else an array of set settings
2343 public function get_setting() {
2344 $result = $this->config_read($this->name);
2345 if (is_null($result)) {
2346 return NULL;
2348 if (!$this->load_choices()) {
2349 return NULL;
2351 $result = str_pad($result, count($this->choices), '0');
2352 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2353 $setting = array();
2354 foreach ($this->choices as $key=>$unused) {
2355 $value = array_shift($result);
2356 if ($value) {
2357 $setting[$key] = 1;
2360 return $setting;
2364 * Save setting(s) provided in $data param
2366 * @param array $data An array of settings to save
2367 * @return mixed empty string for bad data or bool true=>success, false=>error
2369 public function write_setting($data) {
2370 if (!is_array($data)) {
2371 return ''; // ignore it
2373 if (!$this->load_choices() or empty($this->choices)) {
2374 return '';
2376 $result = '';
2377 foreach ($this->choices as $key=>$unused) {
2378 if (!empty($data[$key])) {
2379 $result .= '1';
2380 } else {
2381 $result .= '0';
2384 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2390 * Select one value from list
2392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2394 class admin_setting_configselect extends admin_setting {
2395 /** @var array Array of choices value=>label */
2396 public $choices;
2399 * Constructor
2400 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2401 * @param string $visiblename localised
2402 * @param string $description long localised info
2403 * @param string|int $defaultsetting
2404 * @param array $choices array of $value=>$label for each selection
2406 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2407 $this->choices = $choices;
2408 parent::__construct($name, $visiblename, $description, $defaultsetting);
2412 * This function may be used in ancestors for lazy loading of choices
2414 * Override this method if loading of choices is expensive, such
2415 * as when it requires multiple db requests.
2417 * @return bool true if loaded, false if error
2419 public function load_choices() {
2421 if (is_array($this->choices)) {
2422 return true;
2424 .... load choices here
2426 return true;
2430 * Check if this is $query is related to a choice
2432 * @param string $query
2433 * @return bool true if related, false if not
2435 public function is_related($query) {
2436 if (parent::is_related($query)) {
2437 return true;
2439 if (!$this->load_choices()) {
2440 return false;
2442 foreach ($this->choices as $key=>$value) {
2443 if (strpos(textlib::strtolower($key), $query) !== false) {
2444 return true;
2446 if (strpos(textlib::strtolower($value), $query) !== false) {
2447 return true;
2450 return false;
2454 * Return the setting
2456 * @return mixed returns config if successful else null
2458 public function get_setting() {
2459 return $this->config_read($this->name);
2463 * Save a setting
2465 * @param string $data
2466 * @return string empty of error string
2468 public function write_setting($data) {
2469 if (!$this->load_choices() or empty($this->choices)) {
2470 return '';
2472 if (!array_key_exists($data, $this->choices)) {
2473 return ''; // ignore it
2476 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2480 * Returns XHTML select field
2482 * Ensure the options are loaded, and generate the XHTML for the select
2483 * element and any warning message. Separating this out from output_html
2484 * makes it easier to subclass this class.
2486 * @param string $data the option to show as selected.
2487 * @param string $current the currently selected option in the database, null if none.
2488 * @param string $default the default selected option.
2489 * @return array the HTML for the select element, and a warning message.
2491 public function output_select_html($data, $current, $default, $extraname = '') {
2492 if (!$this->load_choices() or empty($this->choices)) {
2493 return array('', '');
2496 $warning = '';
2497 if (is_null($current)) {
2498 // first run
2499 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2500 // no warning
2501 } else if (!array_key_exists($current, $this->choices)) {
2502 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2503 if (!is_null($default) and $data == $current) {
2504 $data = $default; // use default instead of first value when showing the form
2508 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2509 foreach ($this->choices as $key => $value) {
2510 // the string cast is needed because key may be integer - 0 is equal to most strings!
2511 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2513 $selecthtml .= '</select>';
2514 return array($selecthtml, $warning);
2518 * Returns XHTML select field and wrapping div(s)
2520 * @see output_select_html()
2522 * @param string $data the option to show as selected
2523 * @param string $query
2524 * @return string XHTML field and wrapping div
2526 public function output_html($data, $query='') {
2527 $default = $this->get_defaultsetting();
2528 $current = $this->get_setting();
2530 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2531 if (!$selecthtml) {
2532 return '';
2535 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2536 $defaultinfo = $this->choices[$default];
2537 } else {
2538 $defaultinfo = NULL;
2541 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2543 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2549 * Select multiple items from list
2551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2553 class admin_setting_configmultiselect extends admin_setting_configselect {
2555 * Constructor
2556 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2557 * @param string $visiblename localised
2558 * @param string $description long localised info
2559 * @param array $defaultsetting array of selected items
2560 * @param array $choices array of $value=>$label for each list item
2562 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2563 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2567 * Returns the select setting(s)
2569 * @return mixed null or array. Null if no settings else array of setting(s)
2571 public function get_setting() {
2572 $result = $this->config_read($this->name);
2573 if (is_null($result)) {
2574 return NULL;
2576 if ($result === '') {
2577 return array();
2579 return explode(',', $result);
2583 * Saves setting(s) provided through $data
2585 * Potential bug in the works should anyone call with this function
2586 * using a vartype that is not an array
2588 * @param array $data
2590 public function write_setting($data) {
2591 if (!is_array($data)) {
2592 return ''; //ignore it
2594 if (!$this->load_choices() or empty($this->choices)) {
2595 return '';
2598 unset($data['xxxxx']);
2600 $save = array();
2601 foreach ($data as $value) {
2602 if (!array_key_exists($value, $this->choices)) {
2603 continue; // ignore it
2605 $save[] = $value;
2608 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2612 * Is setting related to query text - used when searching
2614 * @param string $query
2615 * @return bool true if related, false if not
2617 public function is_related($query) {
2618 if (!$this->load_choices() or empty($this->choices)) {
2619 return false;
2621 if (parent::is_related($query)) {
2622 return true;
2625 foreach ($this->choices as $desc) {
2626 if (strpos(textlib::strtolower($desc), $query) !== false) {
2627 return true;
2630 return false;
2634 * Returns XHTML multi-select field
2636 * @todo Add vartype handling to ensure $data is an array
2637 * @param array $data Array of values to select by default
2638 * @param string $query
2639 * @return string XHTML multi-select field
2641 public function output_html($data, $query='') {
2642 if (!$this->load_choices() or empty($this->choices)) {
2643 return '';
2645 $choices = $this->choices;
2646 $default = $this->get_defaultsetting();
2647 if (is_null($default)) {
2648 $default = array();
2650 if (is_null($data)) {
2651 $data = array();
2654 $defaults = array();
2655 $size = min(10, count($this->choices));
2656 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2657 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2658 foreach ($this->choices as $key => $description) {
2659 if (in_array($key, $data)) {
2660 $selected = 'selected="selected"';
2661 } else {
2662 $selected = '';
2664 if (in_array($key, $default)) {
2665 $defaults[] = $description;
2668 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2671 if (is_null($default)) {
2672 $defaultinfo = NULL;
2673 } if (!empty($defaults)) {
2674 $defaultinfo = implode(', ', $defaults);
2675 } else {
2676 $defaultinfo = get_string('none');
2679 $return .= '</select></div>';
2680 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2685 * Time selector
2687 * This is a liiitle bit messy. we're using two selects, but we're returning
2688 * them as an array named after $name (so we only use $name2 internally for the setting)
2690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2692 class admin_setting_configtime extends admin_setting {
2693 /** @var string Used for setting second select (minutes) */
2694 public $name2;
2697 * Constructor
2698 * @param string $hoursname setting for hours
2699 * @param string $minutesname setting for hours
2700 * @param string $visiblename localised
2701 * @param string $description long localised info
2702 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2704 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2705 $this->name2 = $minutesname;
2706 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2710 * Get the selected time
2712 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2714 public function get_setting() {
2715 $result1 = $this->config_read($this->name);
2716 $result2 = $this->config_read($this->name2);
2717 if (is_null($result1) or is_null($result2)) {
2718 return NULL;
2721 return array('h' => $result1, 'm' => $result2);
2725 * Store the time (hours and minutes)
2727 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2728 * @return bool true if success, false if not
2730 public function write_setting($data) {
2731 if (!is_array($data)) {
2732 return '';
2735 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2736 return ($result ? '' : get_string('errorsetting', 'admin'));
2740 * Returns XHTML time select fields
2742 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2743 * @param string $query
2744 * @return string XHTML time select fields and wrapping div(s)
2746 public function output_html($data, $query='') {
2747 $default = $this->get_defaultsetting();
2749 if (is_array($default)) {
2750 $defaultinfo = $default['h'].':'.$default['m'];
2751 } else {
2752 $defaultinfo = NULL;
2755 $return = '<div class="form-time defaultsnext">'.
2756 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2757 for ($i = 0; $i < 24; $i++) {
2758 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2760 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2761 for ($i = 0; $i < 60; $i += 5) {
2762 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2764 $return .= '</select></div>';
2765 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2772 * Seconds duration setting.
2774 * @copyright 2012 Petr Skoda (http://skodak.org)
2775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2777 class admin_setting_configduration extends admin_setting {
2779 /** @var int default duration unit */
2780 protected $defaultunit;
2783 * Constructor
2784 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2785 * or 'myplugin/mysetting' for ones in config_plugins.
2786 * @param string $visiblename localised name
2787 * @param string $description localised long description
2788 * @param mixed $defaultsetting string or array depending on implementation
2789 * @param int $defaultunit - day, week, etc. (in seconds)
2791 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
2792 if (is_number($defaultsetting)) {
2793 $defaultsetting = self::parse_seconds($defaultsetting);
2795 $units = self::get_units();
2796 if (isset($units[$defaultunit])) {
2797 $this->defaultunit = $defaultunit;
2798 } else {
2799 $this->defaultunit = 86400;
2801 parent::__construct($name, $visiblename, $description, $defaultsetting);
2805 * Returns selectable units.
2806 * @static
2807 * @return array
2809 protected static function get_units() {
2810 return array(
2811 604800 => get_string('weeks'),
2812 86400 => get_string('days'),
2813 3600 => get_string('hours'),
2814 60 => get_string('minutes'),
2815 1 => get_string('seconds'),
2820 * Converts seconds to some more user friendly string.
2821 * @static
2822 * @param int $seconds
2823 * @return string
2825 protected static function get_duration_text($seconds) {
2826 if (empty($seconds)) {
2827 return get_string('none');
2829 $data = self::parse_seconds($seconds);
2830 switch ($data['u']) {
2831 case (60*60*24*7):
2832 return get_string('numweeks', '', $data['v']);
2833 case (60*60*24):
2834 return get_string('numdays', '', $data['v']);
2835 case (60*60):
2836 return get_string('numhours', '', $data['v']);
2837 case (60):
2838 return get_string('numminutes', '', $data['v']);
2839 default:
2840 return get_string('numseconds', '', $data['v']*$data['u']);
2845 * Finds suitable units for given duration.
2846 * @static
2847 * @param int $seconds
2848 * @return array
2850 protected static function parse_seconds($seconds) {
2851 foreach (self::get_units() as $unit => $unused) {
2852 if ($seconds % $unit === 0) {
2853 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
2856 return array('v'=>(int)$seconds, 'u'=>1);
2860 * Get the selected duration as array.
2862 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
2864 public function get_setting() {
2865 $seconds = $this->config_read($this->name);
2866 if (is_null($seconds)) {
2867 return null;
2870 return self::parse_seconds($seconds);
2874 * Store the duration as seconds.
2876 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2877 * @return bool true if success, false if not
2879 public function write_setting($data) {
2880 if (!is_array($data)) {
2881 return '';
2884 $seconds = (int)($data['v']*$data['u']);
2885 if ($seconds < 0) {
2886 return get_string('errorsetting', 'admin');
2889 $result = $this->config_write($this->name, $seconds);
2890 return ($result ? '' : get_string('errorsetting', 'admin'));
2894 * Returns duration text+select fields.
2896 * @param array $data Must be form 'v'=>xx, 'u'=>xx
2897 * @param string $query
2898 * @return string duration text+select fields and wrapping div(s)
2900 public function output_html($data, $query='') {
2901 $default = $this->get_defaultsetting();
2903 if (is_number($default)) {
2904 $defaultinfo = self::get_duration_text($default);
2905 } else if (is_array($default)) {
2906 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
2907 } else {
2908 $defaultinfo = null;
2911 $units = self::get_units();
2913 $return = '<div class="form-duration defaultsnext">';
2914 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
2915 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
2916 foreach ($units as $val => $text) {
2917 $selected = '';
2918 if ($data['v'] == 0) {
2919 if ($val == $this->defaultunit) {
2920 $selected = ' selected="selected"';
2922 } else if ($val == $data['u']) {
2923 $selected = ' selected="selected"';
2925 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
2927 $return .= '</select></div>';
2928 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2934 * Used to validate a textarea used for ip addresses
2936 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2938 class admin_setting_configiplist extends admin_setting_configtextarea {
2941 * Validate the contents of the textarea as IP addresses
2943 * Used to validate a new line separated list of IP addresses collected from
2944 * a textarea control
2946 * @param string $data A list of IP Addresses separated by new lines
2947 * @return mixed bool true for success or string:error on failure
2949 public function validate($data) {
2950 if(!empty($data)) {
2951 $ips = explode("\n", $data);
2952 } else {
2953 return true;
2955 $result = true;
2956 foreach($ips as $ip) {
2957 $ip = trim($ip);
2958 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2959 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2960 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2961 $result = true;
2962 } else {
2963 $result = false;
2964 break;
2967 if($result) {
2968 return true;
2969 } else {
2970 return get_string('validateerror', 'admin');
2977 * An admin setting for selecting one or more users who have a capability
2978 * in the system context
2980 * An admin setting for selecting one or more users, who have a particular capability
2981 * in the system context. Warning, make sure the list will never be too long. There is
2982 * no paging or searching of this list.
2984 * To correctly get a list of users from this config setting, you need to call the
2985 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2987 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2989 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2990 /** @var string The capabilities name */
2991 protected $capability;
2992 /** @var int include admin users too */
2993 protected $includeadmins;
2996 * Constructor.
2998 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2999 * @param string $visiblename localised name
3000 * @param string $description localised long description
3001 * @param array $defaultsetting array of usernames
3002 * @param string $capability string capability name.
3003 * @param bool $includeadmins include administrators
3005 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3006 $this->capability = $capability;
3007 $this->includeadmins = $includeadmins;
3008 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3012 * Load all of the uses who have the capability into choice array
3014 * @return bool Always returns true
3016 function load_choices() {
3017 if (is_array($this->choices)) {
3018 return true;
3020 $users = get_users_by_capability(context_system::instance(),
3021 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
3022 $this->choices = array(
3023 '$@NONE@$' => get_string('nobody'),
3024 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3026 if ($this->includeadmins) {
3027 $admins = get_admins();
3028 foreach ($admins as $user) {
3029 $this->choices[$user->id] = fullname($user);
3032 if (is_array($users)) {
3033 foreach ($users as $user) {
3034 $this->choices[$user->id] = fullname($user);
3037 return true;
3041 * Returns the default setting for class
3043 * @return mixed Array, or string. Empty string if no default
3045 public function get_defaultsetting() {
3046 $this->load_choices();
3047 $defaultsetting = parent::get_defaultsetting();
3048 if (empty($defaultsetting)) {
3049 return array('$@NONE@$');
3050 } else if (array_key_exists($defaultsetting, $this->choices)) {
3051 return $defaultsetting;
3052 } else {
3053 return '';
3058 * Returns the current setting
3060 * @return mixed array or string
3062 public function get_setting() {
3063 $result = parent::get_setting();
3064 if ($result === null) {
3065 // this is necessary for settings upgrade
3066 return null;
3068 if (empty($result)) {
3069 $result = array('$@NONE@$');
3071 return $result;
3075 * Save the chosen setting provided as $data
3077 * @param array $data
3078 * @return mixed string or array
3080 public function write_setting($data) {
3081 // If all is selected, remove any explicit options.
3082 if (in_array('$@ALL@$', $data)) {
3083 $data = array('$@ALL@$');
3085 // None never needs to be written to the DB.
3086 if (in_array('$@NONE@$', $data)) {
3087 unset($data[array_search('$@NONE@$', $data)]);
3089 return parent::write_setting($data);
3095 * Special checkbox for calendar - resets SESSION vars.
3097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3099 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3101 * Calls the parent::__construct with default values
3103 * name => calendar_adminseesall
3104 * visiblename => get_string('adminseesall', 'admin')
3105 * description => get_string('helpadminseesall', 'admin')
3106 * defaultsetting => 0
3108 public function __construct() {
3109 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3110 get_string('helpadminseesall', 'admin'), '0');
3114 * Stores the setting passed in $data
3116 * @param mixed gets converted to string for comparison
3117 * @return string empty string or error message
3119 public function write_setting($data) {
3120 global $SESSION;
3121 return parent::write_setting($data);
3126 * Special select for settings that are altered in setup.php and can not be altered on the fly
3128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3130 class admin_setting_special_selectsetup extends admin_setting_configselect {
3132 * Reads the setting directly from the database
3134 * @return mixed
3136 public function get_setting() {
3137 // read directly from db!
3138 return get_config(NULL, $this->name);
3142 * Save the setting passed in $data
3144 * @param string $data The setting to save
3145 * @return string empty or error message
3147 public function write_setting($data) {
3148 global $CFG;
3149 // do not change active CFG setting!
3150 $current = $CFG->{$this->name};
3151 $result = parent::write_setting($data);
3152 $CFG->{$this->name} = $current;
3153 return $result;
3159 * Special select for frontpage - stores data in course table
3161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3163 class admin_setting_sitesetselect extends admin_setting_configselect {
3165 * Returns the site name for the selected site
3167 * @see get_site()
3168 * @return string The site name of the selected site
3170 public function get_setting() {
3171 $site = get_site();
3172 return $site->{$this->name};
3176 * Updates the database and save the setting
3178 * @param string data
3179 * @return string empty or error message
3181 public function write_setting($data) {
3182 global $DB, $SITE;
3183 if (!in_array($data, array_keys($this->choices))) {
3184 return get_string('errorsetting', 'admin');
3186 $record = new stdClass();
3187 $record->id = SITEID;
3188 $temp = $this->name;
3189 $record->$temp = $data;
3190 $record->timemodified = time();
3191 // update $SITE
3192 $SITE->{$this->name} = $data;
3193 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3199 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3200 * block to hidden.
3202 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3204 class admin_setting_bloglevel extends admin_setting_configselect {
3206 * Updates the database and save the setting
3208 * @param string data
3209 * @return string empty or error message
3211 public function write_setting($data) {
3212 global $DB, $CFG;
3213 if ($data == 0) {
3214 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3215 foreach ($blogblocks as $block) {
3216 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3218 } else {
3219 // reenable all blocks only when switching from disabled blogs
3220 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3221 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3222 foreach ($blogblocks as $block) {
3223 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3227 return parent::write_setting($data);
3233 * Special select - lists on the frontpage - hacky
3235 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3237 class admin_setting_courselist_frontpage extends admin_setting {
3238 /** @var array Array of choices value=>label */
3239 public $choices;
3242 * Construct override, requires one param
3244 * @param bool $loggedin Is the user logged in
3246 public function __construct($loggedin) {
3247 global $CFG;
3248 require_once($CFG->dirroot.'/course/lib.php');
3249 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3250 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3251 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3252 $defaults = array(FRONTPAGECOURSELIST);
3253 parent::__construct($name, $visiblename, $description, $defaults);
3257 * Loads the choices available
3259 * @return bool always returns true
3261 public function load_choices() {
3262 global $DB;
3263 if (is_array($this->choices)) {
3264 return true;
3266 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3267 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3268 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3269 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3270 'none' => get_string('none'));
3271 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3272 unset($this->choices[FRONTPAGECOURSELIST]);
3274 return true;
3278 * Returns the selected settings
3280 * @param mixed array or setting or null
3282 public function get_setting() {
3283 $result = $this->config_read($this->name);
3284 if (is_null($result)) {
3285 return NULL;
3287 if ($result === '') {
3288 return array();
3290 return explode(',', $result);
3294 * Save the selected options
3296 * @param array $data
3297 * @return mixed empty string (data is not an array) or bool true=success false=failure
3299 public function write_setting($data) {
3300 if (!is_array($data)) {
3301 return '';
3303 $this->load_choices();
3304 $save = array();
3305 foreach($data as $datum) {
3306 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3307 continue;
3309 $save[$datum] = $datum; // no duplicates
3311 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3315 * Return XHTML select field and wrapping div
3317 * @todo Add vartype handling to make sure $data is an array
3318 * @param array $data Array of elements to select by default
3319 * @return string XHTML select field and wrapping div
3321 public function output_html($data, $query='') {
3322 $this->load_choices();
3323 $currentsetting = array();
3324 foreach ($data as $key) {
3325 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3326 $currentsetting[] = $key; // already selected first
3330 $return = '<div class="form-group">';
3331 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3332 if (!array_key_exists($i, $currentsetting)) {
3333 $currentsetting[$i] = 'none'; //none
3335 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3336 foreach ($this->choices as $key => $value) {
3337 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3339 $return .= '</select>';
3340 if ($i !== count($this->choices) - 2) {
3341 $return .= '<br />';
3344 $return .= '</div>';
3346 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3352 * Special checkbox for frontpage - stores data in course table
3354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3356 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3358 * Returns the current sites name
3360 * @return string
3362 public function get_setting() {
3363 $site = get_site();
3364 return $site->{$this->name};
3368 * Save the selected setting
3370 * @param string $data The selected site
3371 * @return string empty string or error message
3373 public function write_setting($data) {
3374 global $DB, $SITE;
3375 $record = new stdClass();
3376 $record->id = SITEID;
3377 $record->{$this->name} = ($data == '1' ? 1 : 0);
3378 $record->timemodified = time();
3379 // update $SITE
3380 $SITE->{$this->name} = $data;
3381 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3386 * Special text for frontpage - stores data in course table.
3387 * Empty string means not set here. Manual setting is required.
3389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3391 class admin_setting_sitesettext extends admin_setting_configtext {
3393 * Return the current setting
3395 * @return mixed string or null
3397 public function get_setting() {
3398 $site = get_site();
3399 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3403 * Validate the selected data
3405 * @param string $data The selected value to validate
3406 * @return mixed true or message string
3408 public function validate($data) {
3409 $cleaned = clean_param($data, PARAM_TEXT);
3410 if ($cleaned === '') {
3411 return get_string('required');
3413 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3414 return true;
3415 } else {
3416 return get_string('validateerror', 'admin');
3421 * Save the selected setting
3423 * @param string $data The selected value
3424 * @return string empty or error message
3426 public function write_setting($data) {
3427 global $DB, $SITE;
3428 $data = trim($data);
3429 $validated = $this->validate($data);
3430 if ($validated !== true) {
3431 return $validated;
3434 $record = new stdClass();
3435 $record->id = SITEID;
3436 $record->{$this->name} = $data;
3437 $record->timemodified = time();
3438 // update $SITE
3439 $SITE->{$this->name} = $data;
3440 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3446 * Special text editor for site description.
3448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3450 class admin_setting_special_frontpagedesc extends admin_setting {
3452 * Calls parent::__construct with specific arguments
3454 public function __construct() {
3455 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3456 editors_head_setup();
3460 * Return the current setting
3461 * @return string The current setting
3463 public function get_setting() {
3464 $site = get_site();
3465 return $site->{$this->name};
3469 * Save the new setting
3471 * @param string $data The new value to save
3472 * @return string empty or error message
3474 public function write_setting($data) {
3475 global $DB, $SITE;
3476 $record = new stdClass();
3477 $record->id = SITEID;
3478 $record->{$this->name} = $data;
3479 $record->timemodified = time();
3480 $SITE->{$this->name} = $data;
3481 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3485 * Returns XHTML for the field plus wrapping div
3487 * @param string $data The current value
3488 * @param string $query
3489 * @return string The XHTML output
3491 public function output_html($data, $query='') {
3492 global $CFG;
3494 $CFG->adminusehtmleditor = can_use_html_editor();
3495 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3497 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3503 * Administration interface for emoticon_manager settings.
3505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3507 class admin_setting_emoticons extends admin_setting {
3510 * Calls parent::__construct with specific args
3512 public function __construct() {
3513 global $CFG;
3515 $manager = get_emoticon_manager();
3516 $defaults = $this->prepare_form_data($manager->default_emoticons());
3517 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3521 * Return the current setting(s)
3523 * @return array Current settings array
3525 public function get_setting() {
3526 global $CFG;
3528 $manager = get_emoticon_manager();
3530 $config = $this->config_read($this->name);
3531 if (is_null($config)) {
3532 return null;
3535 $config = $manager->decode_stored_config($config);
3536 if (is_null($config)) {
3537 return null;
3540 return $this->prepare_form_data($config);
3544 * Save selected settings
3546 * @param array $data Array of settings to save
3547 * @return bool
3549 public function write_setting($data) {
3551 $manager = get_emoticon_manager();
3552 $emoticons = $this->process_form_data($data);
3554 if ($emoticons === false) {
3555 return false;
3558 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3559 return ''; // success
3560 } else {
3561 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3566 * Return XHTML field(s) for options
3568 * @param array $data Array of options to set in HTML
3569 * @return string XHTML string for the fields and wrapping div(s)
3571 public function output_html($data, $query='') {
3572 global $OUTPUT;
3574 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3575 $out .= html_writer::start_tag('thead');
3576 $out .= html_writer::start_tag('tr');
3577 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3578 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3579 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3580 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3581 $out .= html_writer::tag('th', '');
3582 $out .= html_writer::end_tag('tr');
3583 $out .= html_writer::end_tag('thead');
3584 $out .= html_writer::start_tag('tbody');
3585 $i = 0;
3586 foreach($data as $field => $value) {
3587 switch ($i) {
3588 case 0:
3589 $out .= html_writer::start_tag('tr');
3590 $current_text = $value;
3591 $current_filename = '';
3592 $current_imagecomponent = '';
3593 $current_altidentifier = '';
3594 $current_altcomponent = '';
3595 case 1:
3596 $current_filename = $value;
3597 case 2:
3598 $current_imagecomponent = $value;
3599 case 3:
3600 $current_altidentifier = $value;
3601 case 4:
3602 $current_altcomponent = $value;
3605 $out .= html_writer::tag('td',
3606 html_writer::empty_tag('input',
3607 array(
3608 'type' => 'text',
3609 'class' => 'form-text',
3610 'name' => $this->get_full_name().'['.$field.']',
3611 'value' => $value,
3613 ), array('class' => 'c'.$i)
3616 if ($i == 4) {
3617 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3618 $alt = get_string($current_altidentifier, $current_altcomponent);
3619 } else {
3620 $alt = $current_text;
3622 if ($current_filename) {
3623 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3624 } else {
3625 $out .= html_writer::tag('td', '');
3627 $out .= html_writer::end_tag('tr');
3628 $i = 0;
3629 } else {
3630 $i++;
3634 $out .= html_writer::end_tag('tbody');
3635 $out .= html_writer::end_tag('table');
3636 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3637 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3639 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3643 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3645 * @see self::process_form_data()
3646 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3647 * @return array of form fields and their values
3649 protected function prepare_form_data(array $emoticons) {
3651 $form = array();
3652 $i = 0;
3653 foreach ($emoticons as $emoticon) {
3654 $form['text'.$i] = $emoticon->text;
3655 $form['imagename'.$i] = $emoticon->imagename;
3656 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3657 $form['altidentifier'.$i] = $emoticon->altidentifier;
3658 $form['altcomponent'.$i] = $emoticon->altcomponent;
3659 $i++;
3661 // add one more blank field set for new object
3662 $form['text'.$i] = '';
3663 $form['imagename'.$i] = '';
3664 $form['imagecomponent'.$i] = '';
3665 $form['altidentifier'.$i] = '';
3666 $form['altcomponent'.$i] = '';
3668 return $form;
3672 * Converts the data from admin settings form into an array of emoticon objects
3674 * @see self::prepare_form_data()
3675 * @param array $data array of admin form fields and values
3676 * @return false|array of emoticon objects
3678 protected function process_form_data(array $form) {
3680 $count = count($form); // number of form field values
3682 if ($count % 5) {
3683 // we must get five fields per emoticon object
3684 return false;
3687 $emoticons = array();
3688 for ($i = 0; $i < $count / 5; $i++) {
3689 $emoticon = new stdClass();
3690 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3691 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3692 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3693 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3694 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3696 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3697 // prevent from breaking http://url.addresses by accident
3698 $emoticon->text = '';
3701 if (strlen($emoticon->text) < 2) {
3702 // do not allow single character emoticons
3703 $emoticon->text = '';
3706 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3707 // emoticon text must contain some non-alphanumeric character to prevent
3708 // breaking HTML tags
3709 $emoticon->text = '';
3712 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3713 $emoticons[] = $emoticon;
3716 return $emoticons;
3722 * Special setting for limiting of the list of available languages.
3724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3726 class admin_setting_langlist extends admin_setting_configtext {
3728 * Calls parent::__construct with specific arguments
3730 public function __construct() {
3731 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3735 * Save the new setting
3737 * @param string $data The new setting
3738 * @return bool
3740 public function write_setting($data) {
3741 $return = parent::write_setting($data);
3742 get_string_manager()->reset_caches();
3743 return $return;
3749 * Selection of one of the recognised countries using the list
3750 * returned by {@link get_list_of_countries()}.
3752 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3754 class admin_settings_country_select extends admin_setting_configselect {
3755 protected $includeall;
3756 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3757 $this->includeall = $includeall;
3758 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3762 * Lazy-load the available choices for the select box
3764 public function load_choices() {
3765 global $CFG;
3766 if (is_array($this->choices)) {
3767 return true;
3769 $this->choices = array_merge(
3770 array('0' => get_string('choosedots')),
3771 get_string_manager()->get_list_of_countries($this->includeall));
3772 return true;
3778 * admin_setting_configselect for the default number of sections in a course,
3779 * simply so we can lazy-load the choices.
3781 * @copyright 2011 The Open University
3782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3784 class admin_settings_num_course_sections extends admin_setting_configselect {
3785 public function __construct($name, $visiblename, $description, $defaultsetting) {
3786 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3789 /** Lazy-load the available choices for the select box */
3790 public function load_choices() {
3791 $max = get_config('moodlecourse', 'maxsections');
3792 if (empty($max)) {
3793 $max = 52;
3795 for ($i = 0; $i <= $max; $i++) {
3796 $this->choices[$i] = "$i";
3798 return true;
3804 * Course category selection
3806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3808 class admin_settings_coursecat_select extends admin_setting_configselect {
3810 * Calls parent::__construct with specific arguments
3812 public function __construct($name, $visiblename, $description, $defaultsetting) {
3813 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3817 * Load the available choices for the select box
3819 * @return bool
3821 public function load_choices() {
3822 global $CFG;
3823 require_once($CFG->dirroot.'/course/lib.php');
3824 if (is_array($this->choices)) {
3825 return true;
3827 $this->choices = make_categories_options();
3828 return true;
3834 * Special control for selecting days to backup
3836 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3838 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3840 * Calls parent::__construct with specific arguments
3842 public function __construct() {
3843 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3844 $this->plugin = 'backup';
3848 * Load the available choices for the select box
3850 * @return bool Always returns true
3852 public function load_choices() {
3853 if (is_array($this->choices)) {
3854 return true;
3856 $this->choices = array();
3857 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3858 foreach ($days as $day) {
3859 $this->choices[$day] = get_string($day, 'calendar');
3861 return true;
3867 * Special debug setting
3869 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3871 class admin_setting_special_debug extends admin_setting_configselect {
3873 * Calls parent::__construct with specific arguments
3875 public function __construct() {
3876 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3880 * Load the available choices for the select box
3882 * @return bool
3884 public function load_choices() {
3885 if (is_array($this->choices)) {
3886 return true;
3888 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3889 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3890 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3891 DEBUG_ALL => get_string('debugall', 'admin'),
3892 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3893 return true;
3899 * Special admin control
3901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3903 class admin_setting_special_calendar_weekend extends admin_setting {
3905 * Calls parent::__construct with specific arguments
3907 public function __construct() {
3908 $name = 'calendar_weekend';
3909 $visiblename = get_string('calendar_weekend', 'admin');
3910 $description = get_string('helpweekenddays', 'admin');
3911 $default = array ('0', '6'); // Saturdays and Sundays
3912 parent::__construct($name, $visiblename, $description, $default);
3916 * Gets the current settings as an array
3918 * @return mixed Null if none, else array of settings
3920 public function get_setting() {
3921 $result = $this->config_read($this->name);
3922 if (is_null($result)) {
3923 return NULL;
3925 if ($result === '') {
3926 return array();
3928 $settings = array();
3929 for ($i=0; $i<7; $i++) {
3930 if ($result & (1 << $i)) {
3931 $settings[] = $i;
3934 return $settings;
3938 * Save the new settings
3940 * @param array $data Array of new settings
3941 * @return bool
3943 public function write_setting($data) {
3944 if (!is_array($data)) {
3945 return '';
3947 unset($data['xxxxx']);
3948 $result = 0;
3949 foreach($data as $index) {
3950 $result |= 1 << $index;
3952 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3956 * Return XHTML to display the control
3958 * @param array $data array of selected days
3959 * @param string $query
3960 * @return string XHTML for display (field + wrapping div(s)
3962 public function output_html($data, $query='') {
3963 // The order matters very much because of the implied numeric keys
3964 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3965 $return = '<table><thead><tr>';
3966 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3967 foreach($days as $index => $day) {
3968 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3970 $return .= '</tr></thead><tbody><tr>';
3971 foreach($days as $index => $day) {
3972 $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>';
3974 $return .= '</tr></tbody></table>';
3976 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3983 * Admin setting that allows a user to pick a behaviour.
3985 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3987 class admin_setting_question_behaviour extends admin_setting_configselect {
3989 * @param string $name name of config variable
3990 * @param string $visiblename display name
3991 * @param string $description description
3992 * @param string $default default.
3994 public function __construct($name, $visiblename, $description, $default) {
3995 parent::__construct($name, $visiblename, $description, $default, NULL);
3999 * Load list of behaviours as choices
4000 * @return bool true => success, false => error.
4002 public function load_choices() {
4003 global $CFG;
4004 require_once($CFG->dirroot . '/question/engine/lib.php');
4005 $this->choices = question_engine::get_archetypal_behaviours();
4006 return true;
4012 * Admin setting that allows a user to pick appropriate roles for something.
4014 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4016 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4017 /** @var array Array of capabilities which identify roles */
4018 private $types;
4021 * @param string $name Name of config variable
4022 * @param string $visiblename Display name
4023 * @param string $description Description
4024 * @param array $types Array of archetypes which identify
4025 * roles that will be enabled by default.
4027 public function __construct($name, $visiblename, $description, $types) {
4028 parent::__construct($name, $visiblename, $description, NULL, NULL);
4029 $this->types = $types;
4033 * Load roles as choices
4035 * @return bool true=>success, false=>error
4037 public function load_choices() {
4038 global $CFG, $DB;
4039 if (during_initial_install()) {
4040 return false;
4042 if (is_array($this->choices)) {
4043 return true;
4045 if ($roles = get_all_roles()) {
4046 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4047 return true;
4048 } else {
4049 return false;
4054 * Return the default setting for this control
4056 * @return array Array of default settings
4058 public function get_defaultsetting() {
4059 global $CFG;
4061 if (during_initial_install()) {
4062 return null;
4064 $result = array();
4065 foreach($this->types as $archetype) {
4066 if ($caproles = get_archetype_roles($archetype)) {
4067 foreach ($caproles as $caprole) {
4068 $result[$caprole->id] = 1;
4072 return $result;
4078 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4082 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4084 * Constructor
4085 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4086 * @param string $visiblename localised
4087 * @param string $description long localised info
4088 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4089 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4090 * @param int $size default field size
4092 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4093 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4097 * Loads the current setting and returns array
4099 * @return array Returns array value=>xx, __construct=>xx
4101 public function get_setting() {
4102 $value = parent::get_setting();
4103 $adv = $this->config_read($this->name.'_adv');
4104 if (is_null($value) or is_null($adv)) {
4105 return NULL;
4107 return array('value' => $value, 'adv' => $adv);
4111 * Saves the new settings passed in $data
4113 * @todo Add vartype handling to ensure $data is an array
4114 * @param array $data
4115 * @return mixed string or Array
4117 public function write_setting($data) {
4118 $error = parent::write_setting($data['value']);
4119 if (!$error) {
4120 $value = empty($data['adv']) ? 0 : 1;
4121 $this->config_write($this->name.'_adv', $value);
4123 return $error;
4127 * Return XHTML for the control
4129 * @param array $data Default data array
4130 * @param string $query
4131 * @return string XHTML to display control
4133 public function output_html($data, $query='') {
4134 $default = $this->get_defaultsetting();
4135 $defaultinfo = array();
4136 if (isset($default['value'])) {
4137 if ($default['value'] === '') {
4138 $defaultinfo[] = "''";
4139 } else {
4140 $defaultinfo[] = $default['value'];
4143 if (!empty($default['adv'])) {
4144 $defaultinfo[] = get_string('advanced');
4146 $defaultinfo = implode(', ', $defaultinfo);
4148 $adv = !empty($data['adv']);
4149 $return = '<div class="form-text defaultsnext">' .
4150 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
4151 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
4152 ' <input type="checkbox" class="form-checkbox" id="' .
4153 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4154 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4155 ' <label for="' . $this->get_id() . '_adv">' .
4156 get_string('advanced') . '</label></div>';
4158 return format_admin_setting($this, $this->visiblename, $return,
4159 $this->description, true, '', $defaultinfo, $query);
4165 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4167 * @copyright 2009 Petr Skoda (http://skodak.org)
4168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4170 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4173 * Constructor
4174 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4175 * @param string $visiblename localised
4176 * @param string $description long localised info
4177 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4178 * @param string $yes value used when checked
4179 * @param string $no value used when not checked
4181 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4182 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4186 * Loads the current setting and returns array
4188 * @return array Returns array value=>xx, adv=>xx
4190 public function get_setting() {
4191 $value = parent::get_setting();
4192 $adv = $this->config_read($this->name.'_adv');
4193 if (is_null($value) or is_null($adv)) {
4194 return NULL;
4196 return array('value' => $value, 'adv' => $adv);
4200 * Sets the value for the setting
4202 * Sets the value for the setting to either the yes or no values
4203 * of the object by comparing $data to yes
4205 * @param mixed $data Gets converted to str for comparison against yes value
4206 * @return string empty string or error
4208 public function write_setting($data) {
4209 $error = parent::write_setting($data['value']);
4210 if (!$error) {
4211 $value = empty($data['adv']) ? 0 : 1;
4212 $this->config_write($this->name.'_adv', $value);
4214 return $error;
4218 * Returns an XHTML checkbox field and with extra advanced cehckbox
4220 * @param string $data If $data matches yes then checkbox is checked
4221 * @param string $query
4222 * @return string XHTML field
4224 public function output_html($data, $query='') {
4225 $defaults = $this->get_defaultsetting();
4226 $defaultinfo = array();
4227 if (!is_null($defaults)) {
4228 if ((string)$defaults['value'] === $this->yes) {
4229 $defaultinfo[] = get_string('checkboxyes', 'admin');
4230 } else {
4231 $defaultinfo[] = get_string('checkboxno', 'admin');
4233 if (!empty($defaults['adv'])) {
4234 $defaultinfo[] = get_string('advanced');
4237 $defaultinfo = implode(', ', $defaultinfo);
4239 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4240 $checked = 'checked="checked"';
4241 } else {
4242 $checked = '';
4244 if (!empty($data['adv'])) {
4245 $advanced = 'checked="checked"';
4246 } else {
4247 $advanced = '';
4250 $fullname = $this->get_full_name();
4251 $novalue = s($this->no);
4252 $yesvalue = s($this->yes);
4253 $id = $this->get_id();
4254 $stradvanced = get_string('advanced');
4255 $return = <<<EOT
4256 <div class="form-checkbox defaultsnext" >
4257 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4258 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4259 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4260 <label for="{$id}_adv">$stradvanced</label>
4261 </div>
4262 EOT;
4263 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4264 true, '', $defaultinfo, $query);
4270 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4272 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4274 * @copyright 2010 Sam Hemelryk
4275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4277 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4279 * Constructor
4280 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4281 * @param string $visiblename localised
4282 * @param string $description long localised info
4283 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4284 * @param string $yes value used when checked
4285 * @param string $no value used when not checked
4287 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4288 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4292 * Loads the current setting and returns array
4294 * @return array Returns array value=>xx, adv=>xx
4296 public function get_setting() {
4297 $value = parent::get_setting();
4298 $locked = $this->config_read($this->name.'_locked');
4299 if (is_null($value) or is_null($locked)) {
4300 return NULL;
4302 return array('value' => $value, 'locked' => $locked);
4306 * Sets the value for the setting
4308 * Sets the value for the setting to either the yes or no values
4309 * of the object by comparing $data to yes
4311 * @param mixed $data Gets converted to str for comparison against yes value
4312 * @return string empty string or error
4314 public function write_setting($data) {
4315 $error = parent::write_setting($data['value']);
4316 if (!$error) {
4317 $value = empty($data['locked']) ? 0 : 1;
4318 $this->config_write($this->name.'_locked', $value);
4320 return $error;
4324 * Returns an XHTML checkbox field and with extra locked checkbox
4326 * @param string $data If $data matches yes then checkbox is checked
4327 * @param string $query
4328 * @return string XHTML field
4330 public function output_html($data, $query='') {
4331 $defaults = $this->get_defaultsetting();
4332 $defaultinfo = array();
4333 if (!is_null($defaults)) {
4334 if ((string)$defaults['value'] === $this->yes) {
4335 $defaultinfo[] = get_string('checkboxyes', 'admin');
4336 } else {
4337 $defaultinfo[] = get_string('checkboxno', 'admin');
4339 if (!empty($defaults['locked'])) {
4340 $defaultinfo[] = get_string('locked', 'admin');
4343 $defaultinfo = implode(', ', $defaultinfo);
4345 $fullname = $this->get_full_name();
4346 $novalue = s($this->no);
4347 $yesvalue = s($this->yes);
4348 $id = $this->get_id();
4350 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4351 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4352 $checkboxparams['checked'] = 'checked';
4355 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4356 if (!empty($data['locked'])) { // convert to strings before comparison
4357 $lockcheckboxparams['checked'] = 'checked';
4360 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4361 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4362 $return .= html_writer::empty_tag('input', $checkboxparams);
4363 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4364 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4365 $return .= html_writer::end_tag('div');
4366 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4372 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4376 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4378 * Calls parent::__construct with specific arguments
4380 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4381 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4385 * Loads the current setting and returns array
4387 * @return array Returns array value=>xx, adv=>xx
4389 public function get_setting() {
4390 $value = parent::get_setting();
4391 $adv = $this->config_read($this->name.'_adv');
4392 if (is_null($value) or is_null($adv)) {
4393 return NULL;
4395 return array('value' => $value, 'adv' => $adv);
4399 * Saves the new settings passed in $data
4401 * @todo Add vartype handling to ensure $data is an array
4402 * @param array $data
4403 * @return mixed string or Array
4405 public function write_setting($data) {
4406 $error = parent::write_setting($data['value']);
4407 if (!$error) {
4408 $value = empty($data['adv']) ? 0 : 1;
4409 $this->config_write($this->name.'_adv', $value);
4411 return $error;
4415 * Return XHTML for the control
4417 * @param array $data Default data array
4418 * @param string $query
4419 * @return string XHTML to display control
4421 public function output_html($data, $query='') {
4422 $default = $this->get_defaultsetting();
4423 $current = $this->get_setting();
4425 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4426 $current['value'], $default['value'], '[value]');
4427 if (!$selecthtml) {
4428 return '';
4431 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4432 $defaultinfo = array();
4433 if (isset($this->choices[$default['value']])) {
4434 $defaultinfo[] = $this->choices[$default['value']];
4436 if (!empty($default['adv'])) {
4437 $defaultinfo[] = get_string('advanced');
4439 $defaultinfo = implode(', ', $defaultinfo);
4440 } else {
4441 $defaultinfo = '';
4444 $adv = !empty($data['adv']);
4445 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4446 ' <input type="checkbox" class="form-checkbox" id="' .
4447 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4448 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4449 ' <label for="' . $this->get_id() . '_adv">' .
4450 get_string('advanced') . '</label></div>';
4452 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4458 * Graded roles in gradebook
4460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4462 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4464 * Calls parent::__construct with specific arguments
4466 public function __construct() {
4467 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4468 get_string('configgradebookroles', 'admin'),
4469 array('student'));
4476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4478 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4480 * Saves the new settings passed in $data
4482 * @param string $data
4483 * @return mixed string or Array
4485 public function write_setting($data) {
4486 global $CFG, $DB;
4488 $oldvalue = $this->config_read($this->name);
4489 $return = parent::write_setting($data);
4490 $newvalue = $this->config_read($this->name);
4492 if ($oldvalue !== $newvalue) {
4493 // force full regrading
4494 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4497 return $return;
4503 * Which roles to show on course description page
4505 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4507 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4509 * Calls parent::__construct with specific arguments
4511 public function __construct() {
4512 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4513 get_string('coursecontact_desc', 'admin'),
4514 array('editingteacher'));
4521 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4523 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4525 * Calls parent::__construct with specific arguments
4527 function admin_setting_special_gradelimiting() {
4528 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4529 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4533 * Force site regrading
4535 function regrade_all() {
4536 global $CFG;
4537 require_once("$CFG->libdir/gradelib.php");
4538 grade_force_site_regrading();
4542 * Saves the new settings
4544 * @param mixed $data
4545 * @return string empty string or error message
4547 function write_setting($data) {
4548 $previous = $this->get_setting();
4550 if ($previous === null) {
4551 if ($data) {
4552 $this->regrade_all();
4554 } else {
4555 if ($data != $previous) {
4556 $this->regrade_all();
4559 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4566 * Primary grade export plugin - has state tracking.
4568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4570 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4572 * Calls parent::__construct with specific arguments
4574 public function __construct() {
4575 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4576 get_string('configgradeexport', 'admin'), array(), NULL);
4580 * Load the available choices for the multicheckbox
4582 * @return bool always returns true
4584 public function load_choices() {
4585 if (is_array($this->choices)) {
4586 return true;
4588 $this->choices = array();
4590 if ($plugins = get_plugin_list('gradeexport')) {
4591 foreach($plugins as $plugin => $unused) {
4592 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4595 return true;
4601 * Grade category settings
4603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4605 class admin_setting_gradecat_combo extends admin_setting {
4606 /** @var array Array of choices */
4607 public $choices;
4610 * Sets choices and calls parent::__construct with passed arguments
4611 * @param string $name
4612 * @param string $visiblename
4613 * @param string $description
4614 * @param mixed $defaultsetting string or array depending on implementation
4615 * @param array $choices An array of choices for the control
4617 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4618 $this->choices = $choices;
4619 parent::__construct($name, $visiblename, $description, $defaultsetting);
4623 * Return the current setting(s) array
4625 * @return array Array of value=>xx, forced=>xx, adv=>xx
4627 public function get_setting() {
4628 global $CFG;
4630 $value = $this->config_read($this->name);
4631 $flag = $this->config_read($this->name.'_flag');
4633 if (is_null($value) or is_null($flag)) {
4634 return NULL;
4637 $flag = (int)$flag;
4638 $forced = (boolean)(1 & $flag); // first bit
4639 $adv = (boolean)(2 & $flag); // second bit
4641 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4645 * Save the new settings passed in $data
4647 * @todo Add vartype handling to ensure $data is array
4648 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4649 * @return string empty or error message
4651 public function write_setting($data) {
4652 global $CFG;
4654 $value = $data['value'];
4655 $forced = empty($data['forced']) ? 0 : 1;
4656 $adv = empty($data['adv']) ? 0 : 2;
4657 $flag = ($forced | $adv); //bitwise or
4659 if (!in_array($value, array_keys($this->choices))) {
4660 return 'Error setting ';
4663 $oldvalue = $this->config_read($this->name);
4664 $oldflag = (int)$this->config_read($this->name.'_flag');
4665 $oldforced = (1 & $oldflag); // first bit
4667 $result1 = $this->config_write($this->name, $value);
4668 $result2 = $this->config_write($this->name.'_flag', $flag);
4670 // force regrade if needed
4671 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4672 require_once($CFG->libdir.'/gradelib.php');
4673 grade_category::updated_forced_settings();
4676 if ($result1 and $result2) {
4677 return '';
4678 } else {
4679 return get_string('errorsetting', 'admin');
4684 * Return XHTML to display the field and wrapping div
4686 * @todo Add vartype handling to ensure $data is array
4687 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4688 * @param string $query
4689 * @return string XHTML to display control
4691 public function output_html($data, $query='') {
4692 $value = $data['value'];
4693 $forced = !empty($data['forced']);
4694 $adv = !empty($data['adv']);
4696 $default = $this->get_defaultsetting();
4697 if (!is_null($default)) {
4698 $defaultinfo = array();
4699 if (isset($this->choices[$default['value']])) {
4700 $defaultinfo[] = $this->choices[$default['value']];
4702 if (!empty($default['forced'])) {
4703 $defaultinfo[] = get_string('force');
4705 if (!empty($default['adv'])) {
4706 $defaultinfo[] = get_string('advanced');
4708 $defaultinfo = implode(', ', $defaultinfo);
4710 } else {
4711 $defaultinfo = NULL;
4715 $return = '<div class="form-group">';
4716 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4717 foreach ($this->choices as $key => $val) {
4718 // the string cast is needed because key may be integer - 0 is equal to most strings!
4719 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4721 $return .= '</select>';
4722 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4723 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4724 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4725 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4726 $return .= '</div>';
4728 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4734 * Selection of grade report in user profiles
4736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4738 class admin_setting_grade_profilereport extends admin_setting_configselect {
4740 * Calls parent::__construct with specific arguments
4742 public function __construct() {
4743 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4747 * Loads an array of choices for the configselect control
4749 * @return bool always return true
4751 public function load_choices() {
4752 if (is_array($this->choices)) {
4753 return true;
4755 $this->choices = array();
4757 global $CFG;
4758 require_once($CFG->libdir.'/gradelib.php');
4760 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4761 if (file_exists($plugindir.'/lib.php')) {
4762 require_once($plugindir.'/lib.php');
4763 $functionname = 'grade_report_'.$plugin.'_profilereport';
4764 if (function_exists($functionname)) {
4765 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4769 return true;
4775 * Special class for register auth selection
4777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4779 class admin_setting_special_registerauth extends admin_setting_configselect {
4781 * Calls parent::__construct with specific arguments
4783 public function __construct() {
4784 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4788 * Returns the default option
4790 * @return string empty or default option
4792 public function get_defaultsetting() {
4793 $this->load_choices();
4794 $defaultsetting = parent::get_defaultsetting();
4795 if (array_key_exists($defaultsetting, $this->choices)) {
4796 return $defaultsetting;
4797 } else {
4798 return '';
4803 * Loads the possible choices for the array
4805 * @return bool always returns true
4807 public function load_choices() {
4808 global $CFG;
4810 if (is_array($this->choices)) {
4811 return true;
4813 $this->choices = array();
4814 $this->choices[''] = get_string('disable');
4816 $authsenabled = get_enabled_auth_plugins(true);
4818 foreach ($authsenabled as $auth) {
4819 $authplugin = get_auth_plugin($auth);
4820 if (!$authplugin->can_signup()) {
4821 continue;
4823 // Get the auth title (from core or own auth lang files)
4824 $authtitle = $authplugin->get_title();
4825 $this->choices[$auth] = $authtitle;
4827 return true;
4833 * General plugins manager
4835 class admin_page_pluginsoverview extends admin_externalpage {
4838 * Sets basic information about the external page
4840 public function __construct() {
4841 global $CFG;
4842 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4843 "$CFG->wwwroot/$CFG->admin/plugins.php");
4848 * Module manage page
4850 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4852 class admin_page_managemods extends admin_externalpage {
4854 * Calls parent::__construct with specific arguments
4856 public function __construct() {
4857 global $CFG;
4858 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4862 * Try to find the specified module
4864 * @param string $query The module to search for
4865 * @return array
4867 public function search($query) {
4868 global $CFG, $DB;
4869 if ($result = parent::search($query)) {
4870 return $result;
4873 $found = false;
4874 if ($modules = $DB->get_records('modules')) {
4875 foreach ($modules as $module) {
4876 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4877 continue;
4879 if (strpos($module->name, $query) !== false) {
4880 $found = true;
4881 break;
4883 $strmodulename = get_string('modulename', $module->name);
4884 if (strpos(textlib::strtolower($strmodulename), $query) !== false) {
4885 $found = true;
4886 break;
4890 if ($found) {
4891 $result = new stdClass();
4892 $result->page = $this;
4893 $result->settings = array();
4894 return array($this->name => $result);
4895 } else {
4896 return array();
4903 * Special class for enrol plugins management.
4905 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4906 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4908 class admin_setting_manageenrols extends admin_setting {
4910 * Calls parent::__construct with specific arguments
4912 public function __construct() {
4913 $this->nosave = true;
4914 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4918 * Always returns true, does nothing
4920 * @return true
4922 public function get_setting() {
4923 return true;
4927 * Always returns true, does nothing
4929 * @return true
4931 public function get_defaultsetting() {
4932 return true;
4936 * Always returns '', does not write anything
4938 * @return string Always returns ''
4940 public function write_setting($data) {
4941 // do not write any setting
4942 return '';
4946 * Checks if $query is one of the available enrol plugins
4948 * @param string $query The string to search for
4949 * @return bool Returns true if found, false if not
4951 public function is_related($query) {
4952 if (parent::is_related($query)) {
4953 return true;
4956 $query = textlib::strtolower($query);
4957 $enrols = enrol_get_plugins(false);
4958 foreach ($enrols as $name=>$enrol) {
4959 $localised = get_string('pluginname', 'enrol_'.$name);
4960 if (strpos(textlib::strtolower($name), $query) !== false) {
4961 return true;
4963 if (strpos(textlib::strtolower($localised), $query) !== false) {
4964 return true;
4967 return false;
4971 * Builds the XHTML to display the control
4973 * @param string $data Unused
4974 * @param string $query
4975 * @return string
4977 public function output_html($data, $query='') {
4978 global $CFG, $OUTPUT, $DB;
4980 // display strings
4981 $strup = get_string('up');
4982 $strdown = get_string('down');
4983 $strsettings = get_string('settings');
4984 $strenable = get_string('enable');
4985 $strdisable = get_string('disable');
4986 $struninstall = get_string('uninstallplugin', 'admin');
4987 $strusage = get_string('enrolusage', 'enrol');
4989 $enrols_available = enrol_get_plugins(false);
4990 $active_enrols = enrol_get_plugins(true);
4992 $allenrols = array();
4993 foreach ($active_enrols as $key=>$enrol) {
4994 $allenrols[$key] = true;
4996 foreach ($enrols_available as $key=>$enrol) {
4997 $allenrols[$key] = true;
4999 // now find all borked plugins and at least allow then to uninstall
5000 $borked = array();
5001 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5002 foreach ($condidates as $candidate) {
5003 if (empty($allenrols[$candidate])) {
5004 $allenrols[$candidate] = true;
5008 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5009 $return .= $OUTPUT->box_start('generalbox enrolsui');
5011 $table = new html_table();
5012 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
5013 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
5014 $table->width = '90%';
5015 $table->data = array();
5017 // iterate through enrol plugins and add to the display table
5018 $updowncount = 1;
5019 $enrolcount = count($active_enrols);
5020 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5021 $printed = array();
5022 foreach($allenrols as $enrol => $unused) {
5023 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5024 $name = get_string('pluginname', 'enrol_'.$enrol);
5025 } else {
5026 $name = $enrol;
5028 //usage
5029 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5030 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5031 $usage = "$ci / $cp";
5033 // hide/show link
5034 if (isset($active_enrols[$enrol])) {
5035 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5036 $hideshow = "<a href=\"$aurl\">";
5037 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
5038 $enabled = true;
5039 $displayname = "<span>$name</span>";
5040 } else if (isset($enrols_available[$enrol])) {
5041 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5042 $hideshow = "<a href=\"$aurl\">";
5043 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
5044 $enabled = false;
5045 $displayname = "<span class=\"dimmed_text\">$name</span>";
5046 } else {
5047 $hideshow = '';
5048 $enabled = false;
5049 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5052 // up/down link (only if enrol is enabled)
5053 $updown = '';
5054 if ($enabled) {
5055 if ($updowncount > 1) {
5056 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5057 $updown .= "<a href=\"$aurl\">";
5058 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
5059 } else {
5060 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5062 if ($updowncount < $enrolcount) {
5063 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5064 $updown .= "<a href=\"$aurl\">";
5065 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
5066 } else {
5067 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5069 ++$updowncount;
5072 // settings link
5073 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
5074 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
5075 $settings = "<a href=\"$surl\">$strsettings</a>";
5076 } else {
5077 $settings = '';
5080 // uninstall
5081 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
5082 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
5084 // add a row to the table
5085 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
5087 $printed[$enrol] = true;
5090 $return .= html_writer::table($table);
5091 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5092 $return .= $OUTPUT->box_end();
5093 return highlight($query, $return);
5099 * Blocks manage page
5101 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5103 class admin_page_manageblocks extends admin_externalpage {
5105 * Calls parent::__construct with specific arguments
5107 public function __construct() {
5108 global $CFG;
5109 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5113 * Search for a specific block
5115 * @param string $query The string to search for
5116 * @return array
5118 public function search($query) {
5119 global $CFG, $DB;
5120 if ($result = parent::search($query)) {
5121 return $result;
5124 $found = false;
5125 if ($blocks = $DB->get_records('block')) {
5126 foreach ($blocks as $block) {
5127 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5128 continue;
5130 if (strpos($block->name, $query) !== false) {
5131 $found = true;
5132 break;
5134 $strblockname = get_string('pluginname', 'block_'.$block->name);
5135 if (strpos(textlib::strtolower($strblockname), $query) !== false) {
5136 $found = true;
5137 break;
5141 if ($found) {
5142 $result = new stdClass();
5143 $result->page = $this;
5144 $result->settings = array();
5145 return array($this->name => $result);
5146 } else {
5147 return array();
5153 * Message outputs configuration
5155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5157 class admin_page_managemessageoutputs extends admin_externalpage {
5159 * Calls parent::__construct with specific arguments
5161 public function __construct() {
5162 global $CFG;
5163 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5167 * Search for a specific message processor
5169 * @param string $query The string to search for
5170 * @return array
5172 public function search($query) {
5173 global $CFG, $DB;
5174 if ($result = parent::search($query)) {
5175 return $result;
5178 $found = false;
5179 if ($processors = get_message_processors()) {
5180 foreach ($processors as $processor) {
5181 if (!$processor->available) {
5182 continue;
5184 if (strpos($processor->name, $query) !== false) {
5185 $found = true;
5186 break;
5188 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5189 if (strpos(textlib::strtolower($strprocessorname), $query) !== false) {
5190 $found = true;
5191 break;
5195 if ($found) {
5196 $result = new stdClass();
5197 $result->page = $this;
5198 $result->settings = array();
5199 return array($this->name => $result);
5200 } else {
5201 return array();
5207 * Default message outputs configuration
5209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5211 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5213 * Calls parent::__construct with specific arguments
5215 public function __construct() {
5216 global $CFG;
5217 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5223 * Manage question behaviours page
5225 * @copyright 2011 The Open University
5226 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5228 class admin_page_manageqbehaviours extends admin_externalpage {
5230 * Constructor
5232 public function __construct() {
5233 global $CFG;
5234 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5235 new moodle_url('/admin/qbehaviours.php'));
5239 * Search question behaviours for the specified string
5241 * @param string $query The string to search for in question behaviours
5242 * @return array
5244 public function search($query) {
5245 global $CFG;
5246 if ($result = parent::search($query)) {
5247 return $result;
5250 $found = false;
5251 require_once($CFG->dirroot . '/question/engine/lib.php');
5252 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5253 if (strpos(textlib::strtolower(question_engine::get_behaviour_name($behaviour)),
5254 $query) !== false) {
5255 $found = true;
5256 break;
5259 if ($found) {
5260 $result = new stdClass();
5261 $result->page = $this;
5262 $result->settings = array();
5263 return array($this->name => $result);
5264 } else {
5265 return array();
5272 * Question type manage page
5274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5276 class admin_page_manageqtypes extends admin_externalpage {
5278 * Calls parent::__construct with specific arguments
5280 public function __construct() {
5281 global $CFG;
5282 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5286 * Search question types for the specified string
5288 * @param string $query The string to search for in question types
5289 * @return array
5291 public function search($query) {
5292 global $CFG;
5293 if ($result = parent::search($query)) {
5294 return $result;
5297 $found = false;
5298 require_once($CFG->dirroot . '/question/engine/bank.php');
5299 foreach (question_bank::get_all_qtypes() as $qtype) {
5300 if (strpos(textlib::strtolower($qtype->local_name()), $query) !== false) {
5301 $found = true;
5302 break;
5305 if ($found) {
5306 $result = new stdClass();
5307 $result->page = $this;
5308 $result->settings = array();
5309 return array($this->name => $result);
5310 } else {
5311 return array();
5317 class admin_page_manageportfolios extends admin_externalpage {
5319 * Calls parent::__construct with specific arguments
5321 public function __construct() {
5322 global $CFG;
5323 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5324 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5328 * Searches page for the specified string.
5329 * @param string $query The string to search for
5330 * @return bool True if it is found on this page
5332 public function search($query) {
5333 global $CFG;
5334 if ($result = parent::search($query)) {
5335 return $result;
5338 $found = false;
5339 $portfolios = get_plugin_list('portfolio');
5340 foreach ($portfolios as $p => $dir) {
5341 if (strpos($p, $query) !== false) {
5342 $found = true;
5343 break;
5346 if (!$found) {
5347 foreach (portfolio_instances(false, false) as $instance) {
5348 $title = $instance->get('name');
5349 if (strpos(textlib::strtolower($title), $query) !== false) {
5350 $found = true;
5351 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();
5368 class admin_page_managerepositories extends admin_externalpage {
5370 * Calls parent::__construct with specific arguments
5372 public function __construct() {
5373 global $CFG;
5374 parent::__construct('managerepositories', get_string('manage',
5375 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5379 * Searches page for the specified string.
5380 * @param string $query The string to search for
5381 * @return bool True if it is found on this page
5383 public function search($query) {
5384 global $CFG;
5385 if ($result = parent::search($query)) {
5386 return $result;
5389 $found = false;
5390 $repositories= get_plugin_list('repository');
5391 foreach ($repositories as $p => $dir) {
5392 if (strpos($p, $query) !== false) {
5393 $found = true;
5394 break;
5397 if (!$found) {
5398 foreach (repository::get_types() as $instance) {
5399 $title = $instance->get_typename();
5400 if (strpos(textlib::strtolower($title), $query) !== false) {
5401 $found = true;
5402 break;
5407 if ($found) {
5408 $result = new stdClass();
5409 $result->page = $this;
5410 $result->settings = array();
5411 return array($this->name => $result);
5412 } else {
5413 return array();
5420 * Special class for authentication administration.
5422 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5424 class admin_setting_manageauths extends admin_setting {
5426 * Calls parent::__construct with specific arguments
5428 public function __construct() {
5429 $this->nosave = true;
5430 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5434 * Always returns true
5436 * @return true
5438 public function get_setting() {
5439 return true;
5443 * Always returns true
5445 * @return true
5447 public function get_defaultsetting() {
5448 return true;
5452 * Always returns '' and doesn't write anything
5454 * @return string Always returns ''
5456 public function write_setting($data) {
5457 // do not write any setting
5458 return '';
5462 * Search to find if Query is related to auth plugin
5464 * @param string $query The string to search for
5465 * @return bool true for related false for not
5467 public function is_related($query) {
5468 if (parent::is_related($query)) {
5469 return true;
5472 $authsavailable = get_plugin_list('auth');
5473 foreach ($authsavailable as $auth => $dir) {
5474 if (strpos($auth, $query) !== false) {
5475 return true;
5477 $authplugin = get_auth_plugin($auth);
5478 $authtitle = $authplugin->get_title();
5479 if (strpos(textlib::strtolower($authtitle), $query) !== false) {
5480 return true;
5483 return false;
5487 * Return XHTML to display control
5489 * @param mixed $data Unused
5490 * @param string $query
5491 * @return string highlight
5493 public function output_html($data, $query='') {
5494 global $CFG, $OUTPUT;
5497 // display strings
5498 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5499 'settings', 'edit', 'name', 'enable', 'disable',
5500 'up', 'down', 'none'));
5501 $txt->updown = "$txt->up/$txt->down";
5503 $authsavailable = get_plugin_list('auth');
5504 get_enabled_auth_plugins(true); // fix the list of enabled auths
5505 if (empty($CFG->auth)) {
5506 $authsenabled = array();
5507 } else {
5508 $authsenabled = explode(',', $CFG->auth);
5511 // construct the display array, with enabled auth plugins at the top, in order
5512 $displayauths = array();
5513 $registrationauths = array();
5514 $registrationauths[''] = $txt->disable;
5515 foreach ($authsenabled as $auth) {
5516 $authplugin = get_auth_plugin($auth);
5517 /// Get the auth title (from core or own auth lang files)
5518 $authtitle = $authplugin->get_title();
5519 /// Apply titles
5520 $displayauths[$auth] = $authtitle;
5521 if ($authplugin->can_signup()) {
5522 $registrationauths[$auth] = $authtitle;
5526 foreach ($authsavailable as $auth => $dir) {
5527 if (array_key_exists($auth, $displayauths)) {
5528 continue; //already in the list
5530 $authplugin = get_auth_plugin($auth);
5531 /// Get the auth title (from core or own auth lang files)
5532 $authtitle = $authplugin->get_title();
5533 /// Apply titles
5534 $displayauths[$auth] = $authtitle;
5535 if ($authplugin->can_signup()) {
5536 $registrationauths[$auth] = $authtitle;
5540 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5541 $return .= $OUTPUT->box_start('generalbox authsui');
5543 $table = new html_table();
5544 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5545 $table->align = array('left', 'center', 'center', 'center');
5546 $table->data = array();
5547 $table->attributes['class'] = 'manageauthtable generaltable';
5549 //add always enabled plugins first
5550 $displayname = "<span>".$displayauths['manual']."</span>";
5551 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5552 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5553 $table->data[] = array($displayname, '', '', $settings);
5554 $displayname = "<span>".$displayauths['nologin']."</span>";
5555 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5556 $table->data[] = array($displayname, '', '', $settings);
5559 // iterate through auth plugins and add to the display table
5560 $updowncount = 1;
5561 $authcount = count($authsenabled);
5562 $url = "auth.php?sesskey=" . sesskey();
5563 foreach ($displayauths as $auth => $name) {
5564 if ($auth == 'manual' or $auth == 'nologin') {
5565 continue;
5567 // hide/show link
5568 if (in_array($auth, $authsenabled)) {
5569 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5570 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5571 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5572 $enabled = true;
5573 $displayname = "<span>$name</span>";
5575 else {
5576 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5577 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5578 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5579 $enabled = false;
5580 $displayname = "<span class=\"dimmed_text\">$name</span>";
5583 // up/down link (only if auth is enabled)
5584 $updown = '';
5585 if ($enabled) {
5586 if ($updowncount > 1) {
5587 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5588 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5590 else {
5591 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5593 if ($updowncount < $authcount) {
5594 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5595 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5597 else {
5598 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5600 ++ $updowncount;
5603 // settings link
5604 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5605 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5606 } else {
5607 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5610 // add a row to the table
5611 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5613 $return .= html_writer::table($table);
5614 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5615 $return .= $OUTPUT->box_end();
5616 return highlight($query, $return);
5622 * Special class for authentication administration.
5624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5626 class admin_setting_manageeditors extends admin_setting {
5628 * Calls parent::__construct with specific arguments
5630 public function __construct() {
5631 $this->nosave = true;
5632 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5636 * Always returns true, does nothing
5638 * @return true
5640 public function get_setting() {
5641 return true;
5645 * Always returns true, does nothing
5647 * @return true
5649 public function get_defaultsetting() {
5650 return true;
5654 * Always returns '', does not write anything
5656 * @return string Always returns ''
5658 public function write_setting($data) {
5659 // do not write any setting
5660 return '';
5664 * Checks if $query is one of the available editors
5666 * @param string $query The string to search for
5667 * @return bool Returns true if found, false if not
5669 public function is_related($query) {
5670 if (parent::is_related($query)) {
5671 return true;
5674 $editors_available = editors_get_available();
5675 foreach ($editors_available as $editor=>$editorstr) {
5676 if (strpos($editor, $query) !== false) {
5677 return true;
5679 if (strpos(textlib::strtolower($editorstr), $query) !== false) {
5680 return true;
5683 return false;
5687 * Builds the XHTML to display the control
5689 * @param string $data Unused
5690 * @param string $query
5691 * @return string
5693 public function output_html($data, $query='') {
5694 global $CFG, $OUTPUT;
5696 // display strings
5697 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5698 'up', 'down', 'none'));
5699 $txt->updown = "$txt->up/$txt->down";
5701 $editors_available = editors_get_available();
5702 $active_editors = explode(',', $CFG->texteditors);
5704 $active_editors = array_reverse($active_editors);
5705 foreach ($active_editors as $key=>$editor) {
5706 if (empty($editors_available[$editor])) {
5707 unset($active_editors[$key]);
5708 } else {
5709 $name = $editors_available[$editor];
5710 unset($editors_available[$editor]);
5711 $editors_available[$editor] = $name;
5714 if (empty($active_editors)) {
5715 //$active_editors = array('textarea');
5717 $editors_available = array_reverse($editors_available, true);
5718 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5719 $return .= $OUTPUT->box_start('generalbox editorsui');
5721 $table = new html_table();
5722 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5723 $table->align = array('left', 'center', 'center', 'center');
5724 $table->width = '90%';
5725 $table->data = array();
5727 // iterate through auth plugins and add to the display table
5728 $updowncount = 1;
5729 $editorcount = count($active_editors);
5730 $url = "editors.php?sesskey=" . sesskey();
5731 foreach ($editors_available as $editor => $name) {
5732 // hide/show link
5733 if (in_array($editor, $active_editors)) {
5734 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5735 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5736 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5737 $enabled = true;
5738 $displayname = "<span>$name</span>";
5740 else {
5741 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5742 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5743 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5744 $enabled = false;
5745 $displayname = "<span class=\"dimmed_text\">$name</span>";
5748 // up/down link (only if auth is enabled)
5749 $updown = '';
5750 if ($enabled) {
5751 if ($updowncount > 1) {
5752 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5753 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5755 else {
5756 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5758 if ($updowncount < $editorcount) {
5759 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5760 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5762 else {
5763 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5765 ++ $updowncount;
5768 // settings link
5769 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5770 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5771 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5772 } else {
5773 $settings = '';
5776 // add a row to the table
5777 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5779 $return .= html_writer::table($table);
5780 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5781 $return .= $OUTPUT->box_end();
5782 return highlight($query, $return);
5788 * Special class for license administration.
5790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5792 class admin_setting_managelicenses extends admin_setting {
5794 * Calls parent::__construct with specific arguments
5796 public function __construct() {
5797 $this->nosave = true;
5798 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5802 * Always returns true, does nothing
5804 * @return true
5806 public function get_setting() {
5807 return true;
5811 * Always returns true, does nothing
5813 * @return true
5815 public function get_defaultsetting() {
5816 return true;
5820 * Always returns '', does not write anything
5822 * @return string Always returns ''
5824 public function write_setting($data) {
5825 // do not write any setting
5826 return '';
5830 * Builds the XHTML to display the control
5832 * @param string $data Unused
5833 * @param string $query
5834 * @return string
5836 public function output_html($data, $query='') {
5837 global $CFG, $OUTPUT;
5838 require_once($CFG->libdir . '/licenselib.php');
5839 $url = "licenses.php?sesskey=" . sesskey();
5841 // display strings
5842 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5843 $licenses = license_manager::get_licenses();
5845 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5847 $return .= $OUTPUT->box_start('generalbox editorsui');
5849 $table = new html_table();
5850 $table->head = array($txt->name, $txt->enable);
5851 $table->align = array('left', 'center');
5852 $table->width = '100%';
5853 $table->data = array();
5855 foreach ($licenses as $value) {
5856 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5858 if ($value->enabled == 1) {
5859 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5860 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5861 } else {
5862 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5863 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5866 if ($value->shortname == $CFG->sitedefaultlicense) {
5867 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5868 $hideshow = '';
5871 $enabled = true;
5873 $table->data[] =array($displayname, $hideshow);
5875 $return .= html_writer::table($table);
5876 $return .= $OUTPUT->box_end();
5877 return highlight($query, $return);
5883 * Special class for filter administration.
5885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5887 class admin_page_managefilters extends admin_externalpage {
5889 * Calls parent::__construct with specific arguments
5891 public function __construct() {
5892 global $CFG;
5893 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5897 * Searches all installed filters for specified filter
5899 * @param string $query The filter(string) to search for
5900 * @param string $query
5902 public function search($query) {
5903 global $CFG;
5904 if ($result = parent::search($query)) {
5905 return $result;
5908 $found = false;
5909 $filternames = filter_get_all_installed();
5910 foreach ($filternames as $path => $strfiltername) {
5911 if (strpos(textlib::strtolower($strfiltername), $query) !== false) {
5912 $found = true;
5913 break;
5915 list($type, $filter) = explode('/', $path);
5916 if (strpos($filter, $query) !== false) {
5917 $found = true;
5918 break;
5922 if ($found) {
5923 $result = new stdClass;
5924 $result->page = $this;
5925 $result->settings = array();
5926 return array($this->name => $result);
5927 } else {
5928 return array();
5935 * Initialise admin page - this function does require login and permission
5936 * checks specified in page definition.
5938 * This function must be called on each admin page before other code.
5940 * @global moodle_page $PAGE
5942 * @param string $section name of page
5943 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5944 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5945 * added to the turn blocks editing on/off form, so this page reloads correctly.
5946 * @param string $actualurl if the actual page being viewed is not the normal one for this
5947 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5948 * @param array $options Additional options that can be specified for page setup.
5949 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5951 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5952 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5954 $PAGE->set_context(null); // hack - set context to something, by default to system context
5956 $site = get_site();
5957 require_login();
5959 if (!empty($options['pagelayout'])) {
5960 // A specific page layout has been requested.
5961 $PAGE->set_pagelayout($options['pagelayout']);
5962 } else if ($section === 'upgradesettings') {
5963 $PAGE->set_pagelayout('maintenance');
5964 } else {
5965 $PAGE->set_pagelayout('admin');
5968 $adminroot = admin_get_root(false, false); // settings not required for external pages
5969 $extpage = $adminroot->locate($section, true);
5971 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5972 // The requested section isn't in the admin tree
5973 // It could be because the user has inadequate capapbilities or because the section doesn't exist
5974 if (!has_capability('moodle/site:config', context_system::instance())) {
5975 // The requested section could depend on a different capability
5976 // but most likely the user has inadequate capabilities
5977 print_error('accessdenied', 'admin');
5978 } else {
5979 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5983 // this eliminates our need to authenticate on the actual pages
5984 if (!$extpage->check_access()) {
5985 print_error('accessdenied', 'admin');
5986 die;
5989 // $PAGE->set_extra_button($extrabutton); TODO
5991 if (!$actualurl) {
5992 $actualurl = $extpage->url;
5995 $PAGE->set_url($actualurl, $extraurlparams);
5996 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5997 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6000 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6001 // During initial install.
6002 $strinstallation = get_string('installation', 'install');
6003 $strsettings = get_string('settings');
6004 $PAGE->navbar->add($strsettings);
6005 $PAGE->set_title($strinstallation);
6006 $PAGE->set_heading($strinstallation);
6007 $PAGE->set_cacheable(false);
6008 return;
6011 // Locate the current item on the navigation and make it active when found.
6012 $path = $extpage->path;
6013 $node = $PAGE->settingsnav;
6014 while ($node && count($path) > 0) {
6015 $node = $node->get(array_pop($path));
6017 if ($node) {
6018 $node->make_active();
6021 // Normal case.
6022 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6023 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6024 $USER->editing = $adminediting;
6027 $visiblepathtosection = array_reverse($extpage->visiblepath);
6029 if ($PAGE->user_allowed_editing()) {
6030 if ($PAGE->user_is_editing()) {
6031 $caption = get_string('blockseditoff');
6032 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
6033 } else {
6034 $caption = get_string('blocksediton');
6035 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
6037 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6040 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6041 $PAGE->set_heading($SITE->fullname);
6043 // prevent caching in nav block
6044 $PAGE->navigation->clear_cache();
6048 * Returns the reference to admin tree root
6050 * @return object admin_root object
6052 function admin_get_root($reload=false, $requirefulltree=true) {
6053 global $CFG, $DB, $OUTPUT;
6055 static $ADMIN = NULL;
6057 if (is_null($ADMIN)) {
6058 // create the admin tree!
6059 $ADMIN = new admin_root($requirefulltree);
6062 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6063 $ADMIN->purge_children($requirefulltree);
6066 if (!$ADMIN->loaded) {
6067 // we process this file first to create categories first and in correct order
6068 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6070 // now we process all other files in admin/settings to build the admin tree
6071 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6072 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6073 continue;
6075 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6076 // plugins are loaded last - they may insert pages anywhere
6077 continue;
6079 require($file);
6081 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6083 $ADMIN->loaded = true;
6086 return $ADMIN;
6089 /// settings utility functions
6092 * This function applies default settings.
6094 * @param object $node, NULL means complete tree, null by default
6095 * @param bool $unconditional if true overrides all values with defaults, null buy default
6097 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6098 global $CFG;
6100 if (is_null($node)) {
6101 $node = admin_get_root(true, true);
6104 if ($node instanceof admin_category) {
6105 $entries = array_keys($node->children);
6106 foreach ($entries as $entry) {
6107 admin_apply_default_settings($node->children[$entry], $unconditional);
6110 } else if ($node instanceof admin_settingpage) {
6111 foreach ($node->settings as $setting) {
6112 if (!$unconditional and !is_null($setting->get_setting())) {
6113 //do not override existing defaults
6114 continue;
6116 $defaultsetting = $setting->get_defaultsetting();
6117 if (is_null($defaultsetting)) {
6118 // no value yet - default maybe applied after admin user creation or in upgradesettings
6119 continue;
6121 $setting->write_setting($defaultsetting);
6127 * Store changed settings, this function updates the errors variable in $ADMIN
6129 * @param object $formdata from form
6130 * @return int number of changed settings
6132 function admin_write_settings($formdata) {
6133 global $CFG, $SITE, $DB;
6135 $olddbsessions = !empty($CFG->dbsessions);
6136 $formdata = (array)$formdata;
6138 $data = array();
6139 foreach ($formdata as $fullname=>$value) {
6140 if (strpos($fullname, 's_') !== 0) {
6141 continue; // not a config value
6143 $data[$fullname] = $value;
6146 $adminroot = admin_get_root();
6147 $settings = admin_find_write_settings($adminroot, $data);
6149 $count = 0;
6150 foreach ($settings as $fullname=>$setting) {
6151 $original = serialize($setting->get_setting()); // comparison must work for arrays too
6152 $error = $setting->write_setting($data[$fullname]);
6153 if ($error !== '') {
6154 $adminroot->errors[$fullname] = new stdClass();
6155 $adminroot->errors[$fullname]->data = $data[$fullname];
6156 $adminroot->errors[$fullname]->id = $setting->get_id();
6157 $adminroot->errors[$fullname]->error = $error;
6159 if ($original !== serialize($setting->get_setting())) {
6160 $count++;
6161 $callbackfunction = $setting->updatedcallback;
6162 if (function_exists($callbackfunction)) {
6163 $callbackfunction($fullname);
6168 if ($olddbsessions != !empty($CFG->dbsessions)) {
6169 require_logout();
6172 // Now update $SITE - just update the fields, in case other people have a
6173 // a reference to it (e.g. $PAGE, $COURSE).
6174 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6175 foreach (get_object_vars($newsite) as $field => $value) {
6176 $SITE->$field = $value;
6179 // now reload all settings - some of them might depend on the changed
6180 admin_get_root(true);
6181 return $count;
6185 * Internal recursive function - finds all settings from submitted form
6187 * @param object $node Instance of admin_category, or admin_settingpage
6188 * @param array $data
6189 * @return array
6191 function admin_find_write_settings($node, $data) {
6192 $return = array();
6194 if (empty($data)) {
6195 return $return;
6198 if ($node instanceof admin_category) {
6199 $entries = array_keys($node->children);
6200 foreach ($entries as $entry) {
6201 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6204 } else if ($node instanceof admin_settingpage) {
6205 foreach ($node->settings as $setting) {
6206 $fullname = $setting->get_full_name();
6207 if (array_key_exists($fullname, $data)) {
6208 $return[$fullname] = $setting;
6214 return $return;
6218 * Internal function - prints the search results
6220 * @param string $query String to search for
6221 * @return string empty or XHTML
6223 function admin_search_settings_html($query) {
6224 global $CFG, $OUTPUT;
6226 if (textlib::strlen($query) < 2) {
6227 return '';
6229 $query = textlib::strtolower($query);
6231 $adminroot = admin_get_root();
6232 $findings = $adminroot->search($query);
6233 $return = '';
6234 $savebutton = false;
6236 foreach ($findings as $found) {
6237 $page = $found->page;
6238 $settings = $found->settings;
6239 if ($page->is_hidden()) {
6240 // hidden pages are not displayed in search results
6241 continue;
6243 if ($page instanceof admin_externalpage) {
6244 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6245 } else if ($page instanceof admin_settingpage) {
6246 $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');
6247 } else {
6248 continue;
6250 if (!empty($settings)) {
6251 $return .= '<fieldset class="adminsettings">'."\n";
6252 foreach ($settings as $setting) {
6253 if (empty($setting->nosave)) {
6254 $savebutton = true;
6256 $return .= '<div class="clearer"><!-- --></div>'."\n";
6257 $fullname = $setting->get_full_name();
6258 if (array_key_exists($fullname, $adminroot->errors)) {
6259 $data = $adminroot->errors[$fullname]->data;
6260 } else {
6261 $data = $setting->get_setting();
6262 // do not use defaults if settings not available - upgradesettings handles the defaults!
6264 $return .= $setting->output_html($data, $query);
6266 $return .= '</fieldset>';
6270 if ($savebutton) {
6271 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6274 return $return;
6278 * Internal function - returns arrays of html pages with uninitialised settings
6280 * @param object $node Instance of admin_category or admin_settingpage
6281 * @return array
6283 function admin_output_new_settings_by_page($node) {
6284 global $OUTPUT;
6285 $return = array();
6287 if ($node instanceof admin_category) {
6288 $entries = array_keys($node->children);
6289 foreach ($entries as $entry) {
6290 $return += admin_output_new_settings_by_page($node->children[$entry]);
6293 } else if ($node instanceof admin_settingpage) {
6294 $newsettings = array();
6295 foreach ($node->settings as $setting) {
6296 if (is_null($setting->get_setting())) {
6297 $newsettings[] = $setting;
6300 if (count($newsettings) > 0) {
6301 $adminroot = admin_get_root();
6302 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6303 $page .= '<fieldset class="adminsettings">'."\n";
6304 foreach ($newsettings as $setting) {
6305 $fullname = $setting->get_full_name();
6306 if (array_key_exists($fullname, $adminroot->errors)) {
6307 $data = $adminroot->errors[$fullname]->data;
6308 } else {
6309 $data = $setting->get_setting();
6310 if (is_null($data)) {
6311 $data = $setting->get_defaultsetting();
6314 $page .= '<div class="clearer"><!-- --></div>'."\n";
6315 $page .= $setting->output_html($data);
6317 $page .= '</fieldset>';
6318 $return[$node->name] = $page;
6322 return $return;
6326 * Format admin settings
6328 * @param object $setting
6329 * @param string $title label element
6330 * @param string $form form fragment, html code - not highlighted automatically
6331 * @param string $description
6332 * @param bool $label link label to id, true by default
6333 * @param string $warning warning text
6334 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6335 * @param string $query search query to be highlighted
6336 * @return string XHTML
6338 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6339 global $CFG;
6341 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6342 $fullname = $setting->get_full_name();
6344 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6345 if ($label) {
6346 $labelfor = 'for = "'.$setting->get_id().'"';
6347 } else {
6348 $labelfor = '';
6351 $override = '';
6352 if (empty($setting->plugin)) {
6353 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6354 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6356 } else {
6357 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6358 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6362 if ($warning !== '') {
6363 $warning = '<div class="form-warning">'.$warning.'</div>';
6366 if (is_null($defaultinfo)) {
6367 $defaultinfo = '';
6368 } else {
6369 if ($defaultinfo === '') {
6370 $defaultinfo = get_string('emptysettingvalue', 'admin');
6372 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6373 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6377 $str = '
6378 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6379 <div class="form-label">
6380 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6381 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6382 </div>
6383 <div class="form-setting">'.$form.$defaultinfo.'</div>
6384 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6385 </div>';
6387 $adminroot = admin_get_root();
6388 if (array_key_exists($fullname, $adminroot->errors)) {
6389 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6392 return $str;
6396 * Based on find_new_settings{@link ()} in upgradesettings.php
6397 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6399 * @param object $node Instance of admin_category, or admin_settingpage
6400 * @return boolean true if any settings haven't been initialised, false if they all have
6402 function any_new_admin_settings($node) {
6404 if ($node instanceof admin_category) {
6405 $entries = array_keys($node->children);
6406 foreach ($entries as $entry) {
6407 if (any_new_admin_settings($node->children[$entry])) {
6408 return true;
6412 } else if ($node instanceof admin_settingpage) {
6413 foreach ($node->settings as $setting) {
6414 if ($setting->get_setting() === NULL) {
6415 return true;
6420 return false;
6424 * Moved from admin/replace.php so that we can use this in cron
6426 * @param string $search string to look for
6427 * @param string $replace string to replace
6428 * @return bool success or fail
6430 function db_replace($search, $replace) {
6431 global $DB, $CFG, $OUTPUT;
6433 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6434 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6435 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6436 'block_instances', '');
6438 // Turn off time limits, sometimes upgrades can be slow.
6439 @set_time_limit(0);
6441 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6442 return false;
6444 foreach ($tables as $table) {
6446 if (in_array($table, $skiptables)) { // Don't process these
6447 continue;
6450 if ($columns = $DB->get_columns($table)) {
6451 $DB->set_debug(true);
6452 foreach ($columns as $column => $data) {
6453 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6454 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6455 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6458 $DB->set_debug(false);
6462 // delete modinfo caches
6463 rebuild_course_cache(0, true);
6465 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6466 $blocks = get_plugin_list('block');
6467 foreach ($blocks as $blockname=>$fullblock) {
6468 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6469 continue;
6472 if (!is_readable($fullblock.'/lib.php')) {
6473 continue;
6476 $function = 'block_'.$blockname.'_global_db_replace';
6477 include_once($fullblock.'/lib.php');
6478 if (!function_exists($function)) {
6479 continue;
6482 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6483 $function($search, $replace);
6484 echo $OUTPUT->notification("...finished", 'notifysuccess');
6487 return true;
6491 * Manage repository settings
6493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6495 class admin_setting_managerepository extends admin_setting {
6496 /** @var string */
6497 private $baseurl;
6500 * calls parent::__construct with specific arguments
6502 public function __construct() {
6503 global $CFG;
6504 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6505 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6509 * Always returns true, does nothing
6511 * @return true
6513 public function get_setting() {
6514 return true;
6518 * Always returns true does nothing
6520 * @return true
6522 public function get_defaultsetting() {
6523 return true;
6527 * Always returns s_managerepository
6529 * @return string Always return 's_managerepository'
6531 public function get_full_name() {
6532 return 's_managerepository';
6536 * Always returns '' doesn't do anything
6538 public function write_setting($data) {
6539 $url = $this->baseurl . '&amp;new=' . $data;
6540 return '';
6541 // TODO
6542 // Should not use redirect and exit here
6543 // Find a better way to do this.
6544 // redirect($url);
6545 // exit;
6549 * Searches repository plugins for one that matches $query
6551 * @param string $query The string to search for
6552 * @return bool true if found, false if not
6554 public function is_related($query) {
6555 if (parent::is_related($query)) {
6556 return true;
6559 $repositories= get_plugin_list('repository');
6560 foreach ($repositories as $p => $dir) {
6561 if (strpos($p, $query) !== false) {
6562 return true;
6565 foreach (repository::get_types() as $instance) {
6566 $title = $instance->get_typename();
6567 if (strpos(textlib::strtolower($title), $query) !== false) {
6568 return true;
6571 return false;
6575 * Helper function that generates a moodle_url object
6576 * relevant to the repository
6579 function repository_action_url($repository) {
6580 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6584 * Builds XHTML to display the control
6586 * @param string $data Unused
6587 * @param string $query
6588 * @return string XHTML
6590 public function output_html($data, $query='') {
6591 global $CFG, $USER, $OUTPUT;
6593 // Get strings that are used
6594 $strshow = get_string('on', 'repository');
6595 $strhide = get_string('off', 'repository');
6596 $strdelete = get_string('disabled', 'repository');
6598 $actionchoicesforexisting = array(
6599 'show' => $strshow,
6600 'hide' => $strhide,
6601 'delete' => $strdelete
6604 $actionchoicesfornew = array(
6605 'newon' => $strshow,
6606 'newoff' => $strhide,
6607 'delete' => $strdelete
6610 $return = '';
6611 $return .= $OUTPUT->box_start('generalbox');
6613 // Set strings that are used multiple times
6614 $settingsstr = get_string('settings');
6615 $disablestr = get_string('disable');
6617 // Table to list plug-ins
6618 $table = new html_table();
6619 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6620 $table->align = array('left', 'center', 'center', 'center', 'center');
6621 $table->data = array();
6623 // Get list of used plug-ins
6624 $instances = repository::get_types();
6625 if (!empty($instances)) {
6626 // Array to store plugins being used
6627 $alreadyplugins = array();
6628 $totalinstances = count($instances);
6629 $updowncount = 1;
6630 foreach ($instances as $i) {
6631 $settings = '';
6632 $typename = $i->get_typename();
6633 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6634 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6635 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6637 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6638 // Calculate number of instances in order to display them for the Moodle administrator
6639 if (!empty($instanceoptionnames)) {
6640 $params = array();
6641 $params['context'] = array(get_system_context());
6642 $params['onlyvisible'] = false;
6643 $params['type'] = $typename;
6644 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6645 // site instances
6646 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6647 $params['context'] = array();
6648 $instances = repository::static_function($typename, 'get_instances', $params);
6649 $courseinstances = array();
6650 $userinstances = array();
6652 foreach ($instances as $instance) {
6653 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6654 $courseinstances[] = $instance;
6655 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6656 $userinstances[] = $instance;
6659 // course instances
6660 $instancenumber = count($courseinstances);
6661 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6663 // user private instances
6664 $instancenumber = count($userinstances);
6665 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6666 } else {
6667 $admininstancenumbertext = "";
6668 $courseinstancenumbertext = "";
6669 $userinstancenumbertext = "";
6672 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6674 $settings .= $OUTPUT->container_start('mdl-left');
6675 $settings .= '<br/>';
6676 $settings .= $admininstancenumbertext;
6677 $settings .= '<br/>';
6678 $settings .= $courseinstancenumbertext;
6679 $settings .= '<br/>';
6680 $settings .= $userinstancenumbertext;
6681 $settings .= $OUTPUT->container_end();
6683 // Get the current visibility
6684 if ($i->get_visible()) {
6685 $currentaction = 'show';
6686 } else {
6687 $currentaction = 'hide';
6690 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6692 // Display up/down link
6693 $updown = '';
6694 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6696 if ($updowncount > 1) {
6697 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6698 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6700 else {
6701 $updown .= $spacer;
6703 if ($updowncount < $totalinstances) {
6704 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6705 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6707 else {
6708 $updown .= $spacer;
6711 $updowncount++;
6713 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6715 if (!in_array($typename, $alreadyplugins)) {
6716 $alreadyplugins[] = $typename;
6721 // Get all the plugins that exist on disk
6722 $plugins = get_plugin_list('repository');
6723 if (!empty($plugins)) {
6724 foreach ($plugins as $plugin => $dir) {
6725 // Check that it has not already been listed
6726 if (!in_array($plugin, $alreadyplugins)) {
6727 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6728 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6733 $return .= html_writer::table($table);
6734 $return .= $OUTPUT->box_end();
6735 return highlight($query, $return);
6740 * Special checkbox for enable mobile web service
6741 * If enable then we store the service id of the mobile service into config table
6742 * If disable then we unstore the service id from the config table
6744 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6746 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6749 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6750 * @return boolean
6752 private function is_xmlrpc_cap_allowed() {
6753 global $DB, $CFG;
6755 //if the $this->xmlrpcuse variable is not set, it needs to be set
6756 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6757 $params = array();
6758 $params['permission'] = CAP_ALLOW;
6759 $params['roleid'] = $CFG->defaultuserroleid;
6760 $params['capability'] = 'webservice/xmlrpc:use';
6761 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6764 return $this->xmlrpcuse;
6768 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6769 * @param type $status true to allow, false to not set
6771 private function set_xmlrpc_cap($status) {
6772 global $CFG;
6773 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6774 //need to allow the cap
6775 $permission = CAP_ALLOW;
6776 $assign = true;
6777 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6778 //need to disallow the cap
6779 $permission = CAP_INHERIT;
6780 $assign = true;
6782 if (!empty($assign)) {
6783 $systemcontext = get_system_context();
6784 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6789 * Builds XHTML to display the control.
6790 * The main purpose of this overloading is to display a warning when https
6791 * is not supported by the server
6792 * @param string $data Unused
6793 * @param string $query
6794 * @return string XHTML
6796 public function output_html($data, $query='') {
6797 global $CFG, $OUTPUT;
6798 $html = parent::output_html($data, $query);
6800 if ((string)$data === $this->yes) {
6801 require_once($CFG->dirroot . "/lib/filelib.php");
6802 $curl = new curl();
6803 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6804 $curl->head($httpswwwroot . "/login/index.php");
6805 $info = $curl->get_info();
6806 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6807 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6811 return $html;
6815 * Retrieves the current setting using the objects name
6817 * @return string
6819 public function get_setting() {
6820 global $CFG;
6822 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6823 // Or if web services aren't enabled this can't be,
6824 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6825 return 0;
6828 require_once($CFG->dirroot . '/webservice/lib.php');
6829 $webservicemanager = new webservice();
6830 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6831 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6832 return $this->config_read($this->name); //same as returning 1
6833 } else {
6834 return 0;
6839 * Save the selected setting
6841 * @param string $data The selected site
6842 * @return string empty string or error message
6844 public function write_setting($data) {
6845 global $DB, $CFG;
6847 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6848 if (empty($CFG->defaultuserroleid)) {
6849 return '';
6852 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6854 require_once($CFG->dirroot . '/webservice/lib.php');
6855 $webservicemanager = new webservice();
6857 if ((string)$data === $this->yes) {
6858 //code run when enable mobile web service
6859 //enable web service systeme if necessary
6860 set_config('enablewebservices', true);
6862 //enable mobile service
6863 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6864 $mobileservice->enabled = 1;
6865 $webservicemanager->update_external_service($mobileservice);
6867 //enable xml-rpc server
6868 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6870 if (!in_array('xmlrpc', $activeprotocols)) {
6871 $activeprotocols[] = 'xmlrpc';
6872 set_config('webserviceprotocols', implode(',', $activeprotocols));
6875 //allow xml-rpc:use capability for authenticated user
6876 $this->set_xmlrpc_cap(true);
6878 } else {
6879 //disable web service system if no other services are enabled
6880 $otherenabledservices = $DB->get_records_select('external_services',
6881 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6882 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6883 if (empty($otherenabledservices)) {
6884 set_config('enablewebservices', false);
6886 //also disable xml-rpc server
6887 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6888 $protocolkey = array_search('xmlrpc', $activeprotocols);
6889 if ($protocolkey !== false) {
6890 unset($activeprotocols[$protocolkey]);
6891 set_config('webserviceprotocols', implode(',', $activeprotocols));
6894 //disallow xml-rpc:use capability for authenticated user
6895 $this->set_xmlrpc_cap(false);
6898 //disable the mobile service
6899 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6900 $mobileservice->enabled = 0;
6901 $webservicemanager->update_external_service($mobileservice);
6904 return (parent::write_setting($data));
6909 * Special class for management of external services
6911 * @author Petr Skoda (skodak)
6913 class admin_setting_manageexternalservices extends admin_setting {
6915 * Calls parent::__construct with specific arguments
6917 public function __construct() {
6918 $this->nosave = true;
6919 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6923 * Always returns true, does nothing
6925 * @return true
6927 public function get_setting() {
6928 return true;
6932 * Always returns true, does nothing
6934 * @return true
6936 public function get_defaultsetting() {
6937 return true;
6941 * Always returns '', does not write anything
6943 * @return string Always returns ''
6945 public function write_setting($data) {
6946 // do not write any setting
6947 return '';
6951 * Checks if $query is one of the available external services
6953 * @param string $query The string to search for
6954 * @return bool Returns true if found, false if not
6956 public function is_related($query) {
6957 global $DB;
6959 if (parent::is_related($query)) {
6960 return true;
6963 $services = $DB->get_records('external_services', array(), 'id, name');
6964 foreach ($services as $service) {
6965 if (strpos(textlib::strtolower($service->name), $query) !== false) {
6966 return true;
6969 return false;
6973 * Builds the XHTML to display the control
6975 * @param string $data Unused
6976 * @param string $query
6977 * @return string
6979 public function output_html($data, $query='') {
6980 global $CFG, $OUTPUT, $DB;
6982 // display strings
6983 $stradministration = get_string('administration');
6984 $stredit = get_string('edit');
6985 $strservice = get_string('externalservice', 'webservice');
6986 $strdelete = get_string('delete');
6987 $strplugin = get_string('plugin', 'admin');
6988 $stradd = get_string('add');
6989 $strfunctions = get_string('functions', 'webservice');
6990 $strusers = get_string('users');
6991 $strserviceusers = get_string('serviceusers', 'webservice');
6993 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6994 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6995 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6997 // built in services
6998 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6999 $return = "";
7000 if (!empty($services)) {
7001 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7005 $table = new html_table();
7006 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7007 $table->align = array('left', 'left', 'center', 'center', 'center');
7008 $table->size = array('30%', '20%', '20%', '20%', '10%');
7009 $table->width = '100%';
7010 $table->data = array();
7012 // iterate through auth plugins and add to the display table
7013 foreach ($services as $service) {
7014 $name = $service->name;
7016 // hide/show link
7017 if ($service->enabled) {
7018 $displayname = "<span>$name</span>";
7019 } else {
7020 $displayname = "<span class=\"dimmed_text\">$name</span>";
7023 $plugin = $service->component;
7025 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7027 if ($service->restrictedusers) {
7028 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7029 } else {
7030 $users = get_string('allusers', 'webservice');
7033 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7035 // add a row to the table
7036 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7038 $return .= html_writer::table($table);
7041 // Custom services
7042 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7043 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7045 $table = new html_table();
7046 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7047 $table->align = array('left', 'center', 'center', 'center', 'center');
7048 $table->size = array('30%', '20%', '20%', '20%', '10%');
7049 $table->width = '100%';
7050 $table->data = array();
7052 // iterate through auth plugins and add to the display table
7053 foreach ($services as $service) {
7054 $name = $service->name;
7056 // hide/show link
7057 if ($service->enabled) {
7058 $displayname = "<span>$name</span>";
7059 } else {
7060 $displayname = "<span class=\"dimmed_text\">$name</span>";
7063 // delete link
7064 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7066 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7068 if ($service->restrictedusers) {
7069 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7070 } else {
7071 $users = get_string('allusers', 'webservice');
7074 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7076 // add a row to the table
7077 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7079 // add new custom service option
7080 $return .= html_writer::table($table);
7082 $return .= '<br />';
7083 // add a token to the table
7084 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7086 return highlight($query, $return);
7091 * Special class for overview of external services
7093 * @author Jerome Mouneyrac
7095 class admin_setting_webservicesoverview extends admin_setting {
7098 * Calls parent::__construct with specific arguments
7100 public function __construct() {
7101 $this->nosave = true;
7102 parent::__construct('webservicesoverviewui',
7103 get_string('webservicesoverview', 'webservice'), '', '');
7107 * Always returns true, does nothing
7109 * @return true
7111 public function get_setting() {
7112 return true;
7116 * Always returns true, does nothing
7118 * @return true
7120 public function get_defaultsetting() {
7121 return true;
7125 * Always returns '', does not write anything
7127 * @return string Always returns ''
7129 public function write_setting($data) {
7130 // do not write any setting
7131 return '';
7135 * Builds the XHTML to display the control
7137 * @param string $data Unused
7138 * @param string $query
7139 * @return string
7141 public function output_html($data, $query='') {
7142 global $CFG, $OUTPUT;
7144 $return = "";
7145 $brtag = html_writer::empty_tag('br');
7147 // Enable mobile web service
7148 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7149 get_string('enablemobilewebservice', 'admin'),
7150 get_string('configenablemobilewebservice',
7151 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7152 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7153 $wsmobileparam = new stdClass();
7154 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7155 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7156 get_string('externalservices', 'webservice'));
7157 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7158 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7159 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7160 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7161 . $brtag . $brtag;
7163 /// One system controlling Moodle with Token
7164 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7165 $table = new html_table();
7166 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7167 get_string('description'));
7168 $table->size = array('30%', '10%', '60%');
7169 $table->align = array('left', 'left', 'left');
7170 $table->width = '90%';
7171 $table->data = array();
7173 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7174 . $brtag . $brtag;
7176 /// 1. Enable Web Services
7177 $row = array();
7178 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7179 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7180 array('href' => $url));
7181 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7182 if ($CFG->enablewebservices) {
7183 $status = get_string('yes');
7185 $row[1] = $status;
7186 $row[2] = get_string('enablewsdescription', 'webservice');
7187 $table->data[] = $row;
7189 /// 2. Enable protocols
7190 $row = array();
7191 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7192 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7193 array('href' => $url));
7194 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7195 //retrieve activated protocol
7196 $active_protocols = empty($CFG->webserviceprotocols) ?
7197 array() : explode(',', $CFG->webserviceprotocols);
7198 if (!empty($active_protocols)) {
7199 $status = "";
7200 foreach ($active_protocols as $protocol) {
7201 $status .= $protocol . $brtag;
7204 $row[1] = $status;
7205 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7206 $table->data[] = $row;
7208 /// 3. Create user account
7209 $row = array();
7210 $url = new moodle_url("/user/editadvanced.php?id=-1");
7211 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7212 array('href' => $url));
7213 $row[1] = "";
7214 $row[2] = get_string('createuserdescription', 'webservice');
7215 $table->data[] = $row;
7217 /// 4. Add capability to users
7218 $row = array();
7219 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7220 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7221 array('href' => $url));
7222 $row[1] = "";
7223 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7224 $table->data[] = $row;
7226 /// 5. Select a web service
7227 $row = array();
7228 $url = new moodle_url("/admin/settings.php?section=externalservices");
7229 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7230 array('href' => $url));
7231 $row[1] = "";
7232 $row[2] = get_string('createservicedescription', 'webservice');
7233 $table->data[] = $row;
7235 /// 6. Add functions
7236 $row = array();
7237 $url = new moodle_url("/admin/settings.php?section=externalservices");
7238 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7239 array('href' => $url));
7240 $row[1] = "";
7241 $row[2] = get_string('addfunctionsdescription', 'webservice');
7242 $table->data[] = $row;
7244 /// 7. Add the specific user
7245 $row = array();
7246 $url = new moodle_url("/admin/settings.php?section=externalservices");
7247 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7248 array('href' => $url));
7249 $row[1] = "";
7250 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7251 $table->data[] = $row;
7253 /// 8. Create token for the specific user
7254 $row = array();
7255 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7256 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7257 array('href' => $url));
7258 $row[1] = "";
7259 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7260 $table->data[] = $row;
7262 /// 9. Enable the documentation
7263 $row = array();
7264 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7265 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7266 array('href' => $url));
7267 $status = '<span class="warning">' . get_string('no') . '</span>';
7268 if ($CFG->enablewsdocumentation) {
7269 $status = get_string('yes');
7271 $row[1] = $status;
7272 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7273 $table->data[] = $row;
7275 /// 10. Test the service
7276 $row = array();
7277 $url = new moodle_url("/admin/webservice/testclient.php");
7278 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7279 array('href' => $url));
7280 $row[1] = "";
7281 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7282 $table->data[] = $row;
7284 $return .= html_writer::table($table);
7286 /// Users as clients with token
7287 $return .= $brtag . $brtag . $brtag;
7288 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7289 $table = new html_table();
7290 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7291 get_string('description'));
7292 $table->size = array('30%', '10%', '60%');
7293 $table->align = array('left', 'left', 'left');
7294 $table->width = '90%';
7295 $table->data = array();
7297 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7298 $brtag . $brtag;
7300 /// 1. Enable Web Services
7301 $row = array();
7302 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7303 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7304 array('href' => $url));
7305 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7306 if ($CFG->enablewebservices) {
7307 $status = get_string('yes');
7309 $row[1] = $status;
7310 $row[2] = get_string('enablewsdescription', 'webservice');
7311 $table->data[] = $row;
7313 /// 2. Enable protocols
7314 $row = array();
7315 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7316 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7317 array('href' => $url));
7318 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7319 //retrieve activated protocol
7320 $active_protocols = empty($CFG->webserviceprotocols) ?
7321 array() : explode(',', $CFG->webserviceprotocols);
7322 if (!empty($active_protocols)) {
7323 $status = "";
7324 foreach ($active_protocols as $protocol) {
7325 $status .= $protocol . $brtag;
7328 $row[1] = $status;
7329 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7330 $table->data[] = $row;
7333 /// 3. Select a web service
7334 $row = array();
7335 $url = new moodle_url("/admin/settings.php?section=externalservices");
7336 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7337 array('href' => $url));
7338 $row[1] = "";
7339 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7340 $table->data[] = $row;
7342 /// 4. Add functions
7343 $row = array();
7344 $url = new moodle_url("/admin/settings.php?section=externalservices");
7345 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7346 array('href' => $url));
7347 $row[1] = "";
7348 $row[2] = get_string('addfunctionsdescription', 'webservice');
7349 $table->data[] = $row;
7351 /// 5. Add capability to users
7352 $row = array();
7353 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7354 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7355 array('href' => $url));
7356 $row[1] = "";
7357 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7358 $table->data[] = $row;
7360 /// 6. Test the service
7361 $row = array();
7362 $url = new moodle_url("/admin/webservice/testclient.php");
7363 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7364 array('href' => $url));
7365 $row[1] = "";
7366 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7367 $table->data[] = $row;
7369 $return .= html_writer::table($table);
7371 return highlight($query, $return);
7378 * Special class for web service protocol administration.
7380 * @author Petr Skoda (skodak)
7382 class admin_setting_managewebserviceprotocols extends admin_setting {
7385 * Calls parent::__construct with specific arguments
7387 public function __construct() {
7388 $this->nosave = true;
7389 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7393 * Always returns true, does nothing
7395 * @return true
7397 public function get_setting() {
7398 return true;
7402 * Always returns true, does nothing
7404 * @return true
7406 public function get_defaultsetting() {
7407 return true;
7411 * Always returns '', does not write anything
7413 * @return string Always returns ''
7415 public function write_setting($data) {
7416 // do not write any setting
7417 return '';
7421 * Checks if $query is one of the available webservices
7423 * @param string $query The string to search for
7424 * @return bool Returns true if found, false if not
7426 public function is_related($query) {
7427 if (parent::is_related($query)) {
7428 return true;
7431 $protocols = get_plugin_list('webservice');
7432 foreach ($protocols as $protocol=>$location) {
7433 if (strpos($protocol, $query) !== false) {
7434 return true;
7436 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7437 if (strpos(textlib::strtolower($protocolstr), $query) !== false) {
7438 return true;
7441 return false;
7445 * Builds the XHTML to display the control
7447 * @param string $data Unused
7448 * @param string $query
7449 * @return string
7451 public function output_html($data, $query='') {
7452 global $CFG, $OUTPUT;
7454 // display strings
7455 $stradministration = get_string('administration');
7456 $strsettings = get_string('settings');
7457 $stredit = get_string('edit');
7458 $strprotocol = get_string('protocol', 'webservice');
7459 $strenable = get_string('enable');
7460 $strdisable = get_string('disable');
7461 $strversion = get_string('version');
7462 $struninstall = get_string('uninstallplugin', 'admin');
7464 $protocols_available = get_plugin_list('webservice');
7465 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7466 ksort($protocols_available);
7468 foreach ($active_protocols as $key=>$protocol) {
7469 if (empty($protocols_available[$protocol])) {
7470 unset($active_protocols[$key]);
7474 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7475 $return .= $OUTPUT->box_start('generalbox webservicesui');
7477 $table = new html_table();
7478 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7479 $table->align = array('left', 'center', 'center', 'center', 'center');
7480 $table->width = '100%';
7481 $table->data = array();
7483 // iterate through auth plugins and add to the display table
7484 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7485 foreach ($protocols_available as $protocol => $location) {
7486 $name = get_string('pluginname', 'webservice_'.$protocol);
7488 $plugin = new stdClass();
7489 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7490 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7492 $version = isset($plugin->version) ? $plugin->version : '';
7494 // hide/show link
7495 if (in_array($protocol, $active_protocols)) {
7496 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7497 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
7498 $displayname = "<span>$name</span>";
7499 } else {
7500 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7501 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
7502 $displayname = "<span class=\"dimmed_text\">$name</span>";
7505 // delete link
7506 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7508 // settings link
7509 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7510 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7511 } else {
7512 $settings = '';
7515 // add a row to the table
7516 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7518 $return .= html_writer::table($table);
7519 $return .= get_string('configwebserviceplugins', 'webservice');
7520 $return .= $OUTPUT->box_end();
7522 return highlight($query, $return);
7528 * Special class for web service token administration.
7530 * @author Jerome Mouneyrac
7532 class admin_setting_managewebservicetokens extends admin_setting {
7535 * Calls parent::__construct with specific arguments
7537 public function __construct() {
7538 $this->nosave = true;
7539 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7543 * Always returns true, does nothing
7545 * @return true
7547 public function get_setting() {
7548 return true;
7552 * Always returns true, does nothing
7554 * @return true
7556 public function get_defaultsetting() {
7557 return true;
7561 * Always returns '', does not write anything
7563 * @return string Always returns ''
7565 public function write_setting($data) {
7566 // do not write any setting
7567 return '';
7571 * Builds the XHTML to display the control
7573 * @param string $data Unused
7574 * @param string $query
7575 * @return string
7577 public function output_html($data, $query='') {
7578 global $CFG, $OUTPUT, $DB, $USER;
7580 // display strings
7581 $stroperation = get_string('operation', 'webservice');
7582 $strtoken = get_string('token', 'webservice');
7583 $strservice = get_string('service', 'webservice');
7584 $struser = get_string('user');
7585 $strcontext = get_string('context', 'webservice');
7586 $strvaliduntil = get_string('validuntil', 'webservice');
7587 $striprestriction = get_string('iprestriction', 'webservice');
7589 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7591 $table = new html_table();
7592 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7593 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7594 $table->width = '100%';
7595 $table->data = array();
7597 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7599 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7601 //here retrieve token list (including linked users firstname/lastname and linked services name)
7602 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
7603 FROM {external_tokens} t, {user} u, {external_services} s
7604 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7605 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7606 if (!empty($tokens)) {
7607 foreach ($tokens as $token) {
7608 //TODO: retrieve context
7610 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7611 $delete .= get_string('delete')."</a>";
7613 $validuntil = '';
7614 if (!empty($token->validuntil)) {
7615 $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
7618 $iprestriction = '';
7619 if (!empty($token->iprestriction)) {
7620 $iprestriction = $token->iprestriction;
7623 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7624 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7625 $useratag .= $token->firstname." ".$token->lastname;
7626 $useratag .= html_writer::end_tag('a');
7628 //check user missing capabilities
7629 require_once($CFG->dirroot . '/webservice/lib.php');
7630 $webservicemanager = new webservice();
7631 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7632 array(array('id' => $token->userid)), $token->serviceid);
7634 if (!is_siteadmin($token->userid) and
7635 key_exists($token->userid, $usermissingcaps)) {
7636 $missingcapabilities = implode(', ',
7637 $usermissingcaps[$token->userid]);
7638 if (!empty($missingcapabilities)) {
7639 $useratag .= html_writer::tag('div',
7640 get_string('usermissingcaps', 'webservice',
7641 $missingcapabilities)
7642 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7643 array('class' => 'missingcaps'));
7647 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7650 $return .= html_writer::table($table);
7651 } else {
7652 $return .= get_string('notoken', 'webservice');
7655 $return .= $OUTPUT->box_end();
7656 // add a token to the table
7657 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7658 $return .= get_string('add')."</a>";
7660 return highlight($query, $return);
7666 * Colour picker
7668 * @copyright 2010 Sam Hemelryk
7669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7671 class admin_setting_configcolourpicker extends admin_setting {
7674 * Information for previewing the colour
7676 * @var array|null
7678 protected $previewconfig = null;
7682 * @param string $name
7683 * @param string $visiblename
7684 * @param string $description
7685 * @param string $defaultsetting
7686 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7688 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7689 $this->previewconfig = $previewconfig;
7690 parent::__construct($name, $visiblename, $description, $defaultsetting);
7694 * Return the setting
7696 * @return mixed returns config if successful else null
7698 public function get_setting() {
7699 return $this->config_read($this->name);
7703 * Saves the setting
7705 * @param string $data
7706 * @return bool
7708 public function write_setting($data) {
7709 $data = $this->validate($data);
7710 if ($data === false) {
7711 return get_string('validateerror', 'admin');
7713 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7717 * Validates the colour that was entered by the user
7719 * @param string $data
7720 * @return string|false
7722 protected function validate($data) {
7723 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7724 if (strpos($data, '#')!==0) {
7725 $data = '#'.$data;
7727 return $data;
7728 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7729 return $data;
7730 } else if (empty($data)) {
7731 return $this->defaultsetting;
7732 } else {
7733 return false;
7738 * Generates the HTML for the setting
7740 * @global moodle_page $PAGE
7741 * @global core_renderer $OUTPUT
7742 * @param string $data
7743 * @param string $query
7745 public function output_html($data, $query = '') {
7746 global $PAGE, $OUTPUT;
7747 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7748 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7749 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7750 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
7751 if (!empty($this->previewconfig)) {
7752 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7754 $content .= html_writer::end_tag('div');
7755 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7760 * Administration interface for user specified regular expressions for device detection.
7762 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7764 class admin_setting_devicedetectregex extends admin_setting {
7767 * Calls parent::__construct with specific args
7769 * @param string $name
7770 * @param string $visiblename
7771 * @param string $description
7772 * @param mixed $defaultsetting
7774 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7775 global $CFG;
7776 parent::__construct($name, $visiblename, $description, $defaultsetting);
7780 * Return the current setting(s)
7782 * @return array Current settings array
7784 public function get_setting() {
7785 global $CFG;
7787 $config = $this->config_read($this->name);
7788 if (is_null($config)) {
7789 return null;
7792 return $this->prepare_form_data($config);
7796 * Save selected settings
7798 * @param array $data Array of settings to save
7799 * @return bool
7801 public function write_setting($data) {
7802 if (empty($data)) {
7803 $data = array();
7806 if ($this->config_write($this->name, $this->process_form_data($data))) {
7807 return ''; // success
7808 } else {
7809 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
7814 * Return XHTML field(s) for regexes
7816 * @param array $data Array of options to set in HTML
7817 * @return string XHTML string for the fields and wrapping div(s)
7819 public function output_html($data, $query='') {
7820 global $OUTPUT;
7822 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
7823 $out .= html_writer::start_tag('thead');
7824 $out .= html_writer::start_tag('tr');
7825 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
7826 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
7827 $out .= html_writer::end_tag('tr');
7828 $out .= html_writer::end_tag('thead');
7829 $out .= html_writer::start_tag('tbody');
7831 if (empty($data)) {
7832 $looplimit = 1;
7833 } else {
7834 $looplimit = (count($data)/2)+1;
7837 for ($i=0; $i<$looplimit; $i++) {
7838 $out .= html_writer::start_tag('tr');
7840 $expressionname = 'expression'.$i;
7842 if (!empty($data[$expressionname])){
7843 $expression = $data[$expressionname];
7844 } else {
7845 $expression = '';
7848 $out .= html_writer::tag('td',
7849 html_writer::empty_tag('input',
7850 array(
7851 'type' => 'text',
7852 'class' => 'form-text',
7853 'name' => $this->get_full_name().'[expression'.$i.']',
7854 'value' => $expression,
7856 ), array('class' => 'c'.$i)
7859 $valuename = 'value'.$i;
7861 if (!empty($data[$valuename])){
7862 $value = $data[$valuename];
7863 } else {
7864 $value= '';
7867 $out .= html_writer::tag('td',
7868 html_writer::empty_tag('input',
7869 array(
7870 'type' => 'text',
7871 'class' => 'form-text',
7872 'name' => $this->get_full_name().'[value'.$i.']',
7873 'value' => $value,
7875 ), array('class' => 'c'.$i)
7878 $out .= html_writer::end_tag('tr');
7881 $out .= html_writer::end_tag('tbody');
7882 $out .= html_writer::end_tag('table');
7884 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
7888 * Converts the string of regexes
7890 * @see self::process_form_data()
7891 * @param $regexes string of regexes
7892 * @return array of form fields and their values
7894 protected function prepare_form_data($regexes) {
7896 $regexes = json_decode($regexes);
7898 $form = array();
7900 $i = 0;
7902 foreach ($regexes as $value => $regex) {
7903 $expressionname = 'expression'.$i;
7904 $valuename = 'value'.$i;
7906 $form[$expressionname] = $regex;
7907 $form[$valuename] = $value;
7908 $i++;
7911 return $form;
7915 * Converts the data from admin settings form into a string of regexes
7917 * @see self::prepare_form_data()
7918 * @param array $data array of admin form fields and values
7919 * @return false|string of regexes
7921 protected function process_form_data(array $form) {
7923 $count = count($form); // number of form field values
7925 if ($count % 2) {
7926 // we must get five fields per expression
7927 return false;
7930 $regexes = array();
7931 for ($i = 0; $i < $count / 2; $i++) {
7932 $expressionname = "expression".$i;
7933 $valuename = "value".$i;
7935 $expression = trim($form['expression'.$i]);
7936 $value = trim($form['value'.$i]);
7938 if (empty($expression)){
7939 continue;
7942 $regexes[$value] = $expression;
7945 $regexes = json_encode($regexes);
7947 return $regexes;
7952 * Multiselect for current modules
7954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7956 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
7957 private $excludesystem;
7960 * Calls parent::__construct - note array $choices is not required
7962 * @param string $name setting name
7963 * @param string $visiblename localised setting name
7964 * @param string $description setting description
7965 * @param array $defaultsetting a plain array of default module ids
7966 * @param bool $excludesystem If true, excludes modules with 'system' archetype
7968 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
7969 $excludesystem = true) {
7970 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
7971 $this->excludesystem = $excludesystem;
7975 * Loads an array of current module choices
7977 * @return bool always return true
7979 public function load_choices() {
7980 if (is_array($this->choices)) {
7981 return true;
7983 $this->choices = array();
7985 global $CFG, $DB;
7986 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7987 foreach ($records as $record) {
7988 // Exclude modules if the code doesn't exist
7989 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7990 // Also exclude system modules (if specified)
7991 if (!($this->excludesystem &&
7992 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
7993 MOD_ARCHETYPE_SYSTEM)) {
7994 $this->choices[$record->id] = $record->name;
7998 return true;