MDL-35129 add missing recordset closing in db transfer
[moodle.git] / lib / adminlib.php
blob2e8121bcc320584e388389387882bbdb1021401a
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 subplugins first
127 if ($type === 'mod') {
128 if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
129 $subplugins = array();
130 include("$CFG->dirroot/mod/$name/db/subplugins.php");
131 foreach ($subplugins as $subplugintype=>$dir) {
132 $instances = get_plugin_list($subplugintype);
133 foreach ($instances as $subpluginname => $notusedpluginpath) {
134 uninstall_plugin($subplugintype, $subpluginname);
141 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
143 if ($type === 'mod') {
144 $pluginname = $name; // eg. 'forum'
145 if (get_string_manager()->string_exists('modulename', $component)) {
146 $strpluginname = get_string('modulename', $component);
147 } else {
148 $strpluginname = $component;
151 } else {
152 $pluginname = $component;
153 if (get_string_manager()->string_exists('pluginname', $component)) {
154 $strpluginname = get_string('pluginname', $component);
155 } else {
156 $strpluginname = $component;
160 echo $OUTPUT->heading($pluginname);
162 $plugindirectory = get_plugin_directory($type, $name);
163 $uninstalllib = $plugindirectory . '/db/uninstall.php';
164 if (file_exists($uninstalllib)) {
165 require_once($uninstalllib);
166 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
167 if (function_exists($uninstallfunction)) {
168 if (!$uninstallfunction()) {
169 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
174 if ($type === 'mod') {
175 // perform cleanup tasks specific for activity modules
177 if (!$module = $DB->get_record('modules', array('name' => $name))) {
178 print_error('moduledoesnotexist', 'error');
181 // delete all the relevant instances from all course sections
182 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
183 foreach ($coursemods as $coursemod) {
184 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
185 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
190 // clear course.modinfo for courses that used this module
191 $sql = "UPDATE {course}
192 SET modinfo=''
193 WHERE id IN (SELECT DISTINCT course
194 FROM {course_modules}
195 WHERE module=?)";
196 $DB->execute($sql, array($module->id));
198 // delete all the course module records
199 $DB->delete_records('course_modules', array('module' => $module->id));
201 // delete module contexts
202 if ($coursemods) {
203 foreach ($coursemods as $coursemod) {
204 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
205 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
210 // delete the module entry itself
211 $DB->delete_records('modules', array('name' => $module->name));
213 // cleanup the gradebook
214 require_once($CFG->libdir.'/gradelib.php');
215 grade_uninstalled_module($module->name);
217 // Perform any custom uninstall tasks
218 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
219 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
220 $uninstallfunction = $module->name . '_uninstall';
221 if (function_exists($uninstallfunction)) {
222 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
223 if (!$uninstallfunction()) {
224 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
229 } else if ($type === 'enrol') {
230 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
231 // nuke all role assignments
232 role_unassign_all(array('component'=>$component));
233 // purge participants
234 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
235 // purge enrol instances
236 $DB->delete_records('enrol', array('enrol'=>$name));
237 // tweak enrol settings
238 if (!empty($CFG->enrol_plugins_enabled)) {
239 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
240 $enabledenrols = array_unique($enabledenrols);
241 $enabledenrols = array_flip($enabledenrols);
242 unset($enabledenrols[$name]);
243 $enabledenrols = array_flip($enabledenrols);
244 if (is_array($enabledenrols)) {
245 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
249 } else if ($type === 'block') {
250 if ($block = $DB->get_record('block', array('name'=>$name))) {
251 // Inform block it's about to be deleted
252 if (file_exists("$CFG->dirroot/blocks/$block->name/block_$block->name.php")) {
253 $blockobject = block_instance($block->name);
254 if ($blockobject) {
255 $blockobject->before_delete(); //only if we can create instance, block might have been already removed
259 // First delete instances and related contexts
260 $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
261 foreach($instances as $instance) {
262 blocks_delete_instance($instance);
265 // Delete block
266 $DB->delete_records('block', array('id'=>$block->id));
270 // perform clean-up task common for all the plugin/subplugin types
272 //delete the web service functions and pre-built services
273 require_once($CFG->dirroot.'/lib/externallib.php');
274 external_delete_descriptions($component);
276 // delete calendar events
277 $DB->delete_records('event', array('modulename' => $pluginname));
279 // delete all the logs
280 $DB->delete_records('log', array('module' => $pluginname));
282 // delete log_display information
283 $DB->delete_records('log_display', array('component' => $component));
285 // delete the module configuration records
286 unset_all_config_for_plugin($pluginname);
288 // delete message provider
289 message_provider_uninstall($component);
291 // delete message processor
292 if ($type === 'message') {
293 message_processor_uninstall($name);
296 // delete the plugin tables
297 $xmldbfilepath = $plugindirectory . '/db/install.xml';
298 drop_plugin_tables($component, $xmldbfilepath, false);
299 if ($type === 'mod' or $type === 'block') {
300 // non-frankenstyle table prefixes
301 drop_plugin_tables($name, $xmldbfilepath, false);
304 // delete the capabilities that were defined by this module
305 capabilities_cleanup($component);
307 // remove event handlers and dequeue pending events
308 events_uninstall($component);
310 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
314 * Returns the version of installed component
316 * @param string $component component name
317 * @param string $source either 'disk' or 'installed' - where to get the version information from
318 * @return string|bool version number or false if the component is not found
320 function get_component_version($component, $source='installed') {
321 global $CFG, $DB;
323 list($type, $name) = normalize_component($component);
325 // moodle core or a core subsystem
326 if ($type === 'core') {
327 if ($source === 'installed') {
328 if (empty($CFG->version)) {
329 return false;
330 } else {
331 return $CFG->version;
333 } else {
334 if (!is_readable($CFG->dirroot.'/version.php')) {
335 return false;
336 } else {
337 $version = null; //initialize variable for IDEs
338 include($CFG->dirroot.'/version.php');
339 return $version;
344 // activity module
345 if ($type === 'mod') {
346 if ($source === 'installed') {
347 return $DB->get_field('modules', 'version', array('name'=>$name));
348 } else {
349 $mods = get_plugin_list('mod');
350 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
351 return false;
352 } else {
353 $module = new stdclass();
354 include($mods[$name].'/version.php');
355 return $module->version;
360 // block
361 if ($type === 'block') {
362 if ($source === 'installed') {
363 return $DB->get_field('block', 'version', array('name'=>$name));
364 } else {
365 $blocks = get_plugin_list('block');
366 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
367 return false;
368 } else {
369 $plugin = new stdclass();
370 include($blocks[$name].'/version.php');
371 return $plugin->version;
376 // all other plugin types
377 if ($source === 'installed') {
378 return get_config($type.'_'.$name, 'version');
379 } else {
380 $plugins = get_plugin_list($type);
381 if (empty($plugins[$name])) {
382 return false;
383 } else {
384 $plugin = new stdclass();
385 include($plugins[$name].'/version.php');
386 return $plugin->version;
392 * Delete all plugin tables
394 * @param string $name Name of plugin, used as table prefix
395 * @param string $file Path to install.xml file
396 * @param bool $feedback defaults to true
397 * @return bool Always returns true
399 function drop_plugin_tables($name, $file, $feedback=true) {
400 global $CFG, $DB;
402 // first try normal delete
403 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
404 return true;
407 // then try to find all tables that start with name and are not in any xml file
408 $used_tables = get_used_table_names();
410 $tables = $DB->get_tables();
412 /// Iterate over, fixing id fields as necessary
413 foreach ($tables as $table) {
414 if (in_array($table, $used_tables)) {
415 continue;
418 if (strpos($table, $name) !== 0) {
419 continue;
422 // found orphan table --> delete it
423 if ($DB->get_manager()->table_exists($table)) {
424 $xmldb_table = new xmldb_table($table);
425 $DB->get_manager()->drop_table($xmldb_table);
429 return true;
433 * Returns names of all known tables == tables that moodle knows about.
435 * @return array Array of lowercase table names
437 function get_used_table_names() {
438 $table_names = array();
439 $dbdirs = get_db_directories();
441 foreach ($dbdirs as $dbdir) {
442 $file = $dbdir.'/install.xml';
444 $xmldb_file = new xmldb_file($file);
446 if (!$xmldb_file->fileExists()) {
447 continue;
450 $loaded = $xmldb_file->loadXMLStructure();
451 $structure = $xmldb_file->getStructure();
453 if ($loaded and $tables = $structure->getTables()) {
454 foreach($tables as $table) {
455 $table_names[] = strtolower($table->getName());
460 return $table_names;
464 * Returns list of all directories where we expect install.xml files
465 * @return array Array of paths
467 function get_db_directories() {
468 global $CFG;
470 $dbdirs = array();
472 /// First, the main one (lib/db)
473 $dbdirs[] = $CFG->libdir.'/db';
475 /// Then, all the ones defined by get_plugin_types()
476 $plugintypes = get_plugin_types();
477 foreach ($plugintypes as $plugintype => $pluginbasedir) {
478 if ($plugins = get_plugin_list($plugintype)) {
479 foreach ($plugins as $plugin => $plugindir) {
480 $dbdirs[] = $plugindir.'/db';
485 return $dbdirs;
489 * Try to obtain or release the cron lock.
490 * @param string $name name of lock
491 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
492 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
493 * @return bool true if lock obtained
495 function set_cron_lock($name, $until, $ignorecurrent=false) {
496 global $DB;
497 if (empty($name)) {
498 debugging("Tried to get a cron lock for a null fieldname");
499 return false;
502 // remove lock by force == remove from config table
503 if (is_null($until)) {
504 set_config($name, null);
505 return true;
508 if (!$ignorecurrent) {
509 // read value from db - other processes might have changed it
510 $value = $DB->get_field('config', 'value', array('name'=>$name));
512 if ($value and $value > time()) {
513 //lock active
514 return false;
518 set_config($name, $until);
519 return true;
523 * Test if and critical warnings are present
524 * @return bool
526 function admin_critical_warnings_present() {
527 global $SESSION;
529 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
530 return 0;
533 if (!isset($SESSION->admin_critical_warning)) {
534 $SESSION->admin_critical_warning = 0;
535 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
536 $SESSION->admin_critical_warning = 1;
540 return $SESSION->admin_critical_warning;
544 * Detects if float supports at least 10 decimal digits
546 * Detects if float supports at least 10 decimal digits
547 * and also if float-->string conversion works as expected.
549 * @return bool true if problem found
551 function is_float_problem() {
552 $num1 = 2009010200.01;
553 $num2 = 2009010200.02;
555 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
559 * Try to verify that dataroot is not accessible from web.
561 * Try to verify that dataroot is not accessible from web.
562 * It is not 100% correct but might help to reduce number of vulnerable sites.
563 * Protection from httpd.conf and .htaccess is not detected properly.
565 * @uses INSECURE_DATAROOT_WARNING
566 * @uses INSECURE_DATAROOT_ERROR
567 * @param bool $fetchtest try to test public access by fetching file, default false
568 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
570 function is_dataroot_insecure($fetchtest=false) {
571 global $CFG;
573 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
575 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
576 $rp = strrev(trim($rp, '/'));
577 $rp = explode('/', $rp);
578 foreach($rp as $r) {
579 if (strpos($siteroot, '/'.$r.'/') === 0) {
580 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
581 } else {
582 break; // probably alias root
586 $siteroot = strrev($siteroot);
587 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
589 if (strpos($dataroot, $siteroot) !== 0) {
590 return false;
593 if (!$fetchtest) {
594 return INSECURE_DATAROOT_WARNING;
597 // now try all methods to fetch a test file using http protocol
599 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
600 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
601 $httpdocroot = $matches[1];
602 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
603 make_upload_directory('diag');
604 $testfile = $CFG->dataroot.'/diag/public.txt';
605 if (!file_exists($testfile)) {
606 file_put_contents($testfile, 'test file, do not delete');
608 $teststr = trim(file_get_contents($testfile));
609 if (empty($teststr)) {
610 // hmm, strange
611 return INSECURE_DATAROOT_WARNING;
614 $testurl = $datarooturl.'/diag/public.txt';
615 if (extension_loaded('curl') and
616 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
617 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
618 ($ch = @curl_init($testurl)) !== false) {
619 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
620 curl_setopt($ch, CURLOPT_HEADER, false);
621 $data = curl_exec($ch);
622 if (!curl_errno($ch)) {
623 $data = trim($data);
624 if ($data === $teststr) {
625 curl_close($ch);
626 return INSECURE_DATAROOT_ERROR;
629 curl_close($ch);
632 if ($data = @file_get_contents($testurl)) {
633 $data = trim($data);
634 if ($data === $teststr) {
635 return INSECURE_DATAROOT_ERROR;
639 preg_match('|https?://([^/]+)|i', $testurl, $matches);
640 $sitename = $matches[1];
641 $error = 0;
642 if ($fp = @fsockopen($sitename, 80, $error)) {
643 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
644 $localurl = $matches[1];
645 $out = "GET $localurl HTTP/1.1\r\n";
646 $out .= "Host: $sitename\r\n";
647 $out .= "Connection: Close\r\n\r\n";
648 fwrite($fp, $out);
649 $data = '';
650 $incoming = false;
651 while (!feof($fp)) {
652 if ($incoming) {
653 $data .= fgets($fp, 1024);
654 } else if (@fgets($fp, 1024) === "\r\n") {
655 $incoming = true;
658 fclose($fp);
659 $data = trim($data);
660 if ($data === $teststr) {
661 return INSECURE_DATAROOT_ERROR;
665 return INSECURE_DATAROOT_WARNING;
668 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
672 * Interface for anything appearing in the admin tree
674 * The interface that is implemented by anything that appears in the admin tree
675 * block. It forces inheriting classes to define a method for checking user permissions
676 * and methods for finding something in the admin tree.
678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
680 interface part_of_admin_tree {
683 * Finds a named part_of_admin_tree.
685 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
686 * and not parentable_part_of_admin_tree, then this function should only check if
687 * $this->name matches $name. If it does, it should return a reference to $this,
688 * otherwise, it should return a reference to NULL.
690 * If a class inherits parentable_part_of_admin_tree, this method should be called
691 * recursively on all child objects (assuming, of course, the parent object's name
692 * doesn't match the search criterion).
694 * @param string $name The internal name of the part_of_admin_tree we're searching for.
695 * @return mixed An object reference or a NULL reference.
697 public function locate($name);
700 * Removes named part_of_admin_tree.
702 * @param string $name The internal name of the part_of_admin_tree we want to remove.
703 * @return bool success.
705 public function prune($name);
708 * Search using query
709 * @param string $query
710 * @return mixed array-object structure of found settings and pages
712 public function search($query);
715 * Verifies current user's access to this part_of_admin_tree.
717 * Used to check if the current user has access to this part of the admin tree or
718 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
719 * then this method is usually just a call to has_capability() in the site context.
721 * If a class inherits parentable_part_of_admin_tree, this method should return the
722 * logical OR of the return of check_access() on all child objects.
724 * @return bool True if the user has access, false if she doesn't.
726 public function check_access();
729 * Mostly useful for removing of some parts of the tree in admin tree block.
731 * @return True is hidden from normal list view
733 public function is_hidden();
736 * Show we display Save button at the page bottom?
737 * @return bool
739 public function show_save();
744 * Interface implemented by any part_of_admin_tree that has children.
746 * The interface implemented by any part_of_admin_tree that can be a parent
747 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
748 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
749 * include an add method for adding other part_of_admin_tree objects as children.
751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
753 interface parentable_part_of_admin_tree extends part_of_admin_tree {
756 * Adds a part_of_admin_tree object to the admin tree.
758 * Used to add a part_of_admin_tree object to this object or a child of this
759 * object. $something should only be added if $destinationname matches
760 * $this->name. If it doesn't, add should be called on child objects that are
761 * also parentable_part_of_admin_tree's.
763 * @param string $destinationname The internal name of the new parent for $something.
764 * @param part_of_admin_tree $something The object to be added.
765 * @return bool True on success, false on failure.
767 public function add($destinationname, $something);
773 * The object used to represent folders (a.k.a. categories) in the admin tree block.
775 * Each admin_category object contains a number of part_of_admin_tree objects.
777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
779 class admin_category implements parentable_part_of_admin_tree {
781 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
782 public $children;
783 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
784 public $name;
785 /** @var string The displayed name for this category. Usually obtained through get_string() */
786 public $visiblename;
787 /** @var bool Should this category be hidden in admin tree block? */
788 public $hidden;
789 /** @var mixed Either a string or an array or strings */
790 public $path;
791 /** @var mixed Either a string or an array or strings */
792 public $visiblepath;
794 /** @var array fast lookup category cache, all categories of one tree point to one cache */
795 protected $category_cache;
798 * Constructor for an empty admin category
800 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
801 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
802 * @param bool $hidden hide category in admin tree block, defaults to false
804 public function __construct($name, $visiblename, $hidden=false) {
805 $this->children = array();
806 $this->name = $name;
807 $this->visiblename = $visiblename;
808 $this->hidden = $hidden;
812 * Returns a reference to the part_of_admin_tree object with internal name $name.
814 * @param string $name The internal name of the object we want.
815 * @param bool $findpath initialize path and visiblepath arrays
816 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
817 * defaults to false
819 public function locate($name, $findpath=false) {
820 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
821 // somebody much have purged the cache
822 $this->category_cache[$this->name] = $this;
825 if ($this->name == $name) {
826 if ($findpath) {
827 $this->visiblepath[] = $this->visiblename;
828 $this->path[] = $this->name;
830 return $this;
833 // quick category lookup
834 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
835 return $this->category_cache[$name];
838 $return = NULL;
839 foreach($this->children as $childid=>$unused) {
840 if ($return = $this->children[$childid]->locate($name, $findpath)) {
841 break;
845 if (!is_null($return) and $findpath) {
846 $return->visiblepath[] = $this->visiblename;
847 $return->path[] = $this->name;
850 return $return;
854 * Search using query
856 * @param string query
857 * @return mixed array-object structure of found settings and pages
859 public function search($query) {
860 $result = array();
861 foreach ($this->children as $child) {
862 $subsearch = $child->search($query);
863 if (!is_array($subsearch)) {
864 debugging('Incorrect search result from '.$child->name);
865 continue;
867 $result = array_merge($result, $subsearch);
869 return $result;
873 * Removes part_of_admin_tree object with internal name $name.
875 * @param string $name The internal name of the object we want to remove.
876 * @return bool success
878 public function prune($name) {
880 if ($this->name == $name) {
881 return false; //can not remove itself
884 foreach($this->children as $precedence => $child) {
885 if ($child->name == $name) {
886 // clear cache and delete self
887 if (is_array($this->category_cache)) {
888 while($this->category_cache) {
889 // delete the cache, but keep the original array address
890 array_pop($this->category_cache);
893 unset($this->children[$precedence]);
894 return true;
895 } else if ($this->children[$precedence]->prune($name)) {
896 return true;
899 return false;
903 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
905 * @param string $destinationame The internal name of the immediate parent that we want for $something.
906 * @param mixed $something A part_of_admin_tree or setting instance to be added.
907 * @return bool True if successfully added, false if $something can not be added.
909 public function add($parentname, $something) {
910 $parent = $this->locate($parentname);
911 if (is_null($parent)) {
912 debugging('parent does not exist!');
913 return false;
916 if ($something instanceof part_of_admin_tree) {
917 if (!($parent instanceof parentable_part_of_admin_tree)) {
918 debugging('error - parts of tree can be inserted only into parentable parts');
919 return false;
921 $parent->children[] = $something;
922 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
923 if (isset($this->category_cache[$something->name])) {
924 debugging('Duplicate admin category name: '.$something->name);
925 } else {
926 $this->category_cache[$something->name] = $something;
927 $something->category_cache =& $this->category_cache;
928 foreach ($something->children as $child) {
929 // just in case somebody already added subcategories
930 if ($child instanceof admin_category) {
931 if (isset($this->category_cache[$child->name])) {
932 debugging('Duplicate admin category name: '.$child->name);
933 } else {
934 $this->category_cache[$child->name] = $child;
935 $child->category_cache =& $this->category_cache;
941 return true;
943 } else {
944 debugging('error - can not add this element');
945 return false;
951 * Checks if the user has access to anything in this category.
953 * @return bool True if the user has access to at least one child in this category, false otherwise.
955 public function check_access() {
956 foreach ($this->children as $child) {
957 if ($child->check_access()) {
958 return true;
961 return false;
965 * Is this category hidden in admin tree block?
967 * @return bool True if hidden
969 public function is_hidden() {
970 return $this->hidden;
974 * Show we display Save button at the page bottom?
975 * @return bool
977 public function show_save() {
978 foreach ($this->children as $child) {
979 if ($child->show_save()) {
980 return true;
983 return false;
989 * Root of admin settings tree, does not have any parent.
991 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
993 class admin_root extends admin_category {
994 /** @var array List of errors */
995 public $errors;
996 /** @var string search query */
997 public $search;
998 /** @var bool full tree flag - true means all settings required, false only pages required */
999 public $fulltree;
1000 /** @var bool flag indicating loaded tree */
1001 public $loaded;
1002 /** @var mixed site custom defaults overriding defaults in settings files*/
1003 public $custom_defaults;
1006 * @param bool $fulltree true means all settings required,
1007 * false only pages required
1009 public function __construct($fulltree) {
1010 global $CFG;
1012 parent::__construct('root', get_string('administration'), false);
1013 $this->errors = array();
1014 $this->search = '';
1015 $this->fulltree = $fulltree;
1016 $this->loaded = false;
1018 $this->category_cache = array();
1020 // load custom defaults if found
1021 $this->custom_defaults = null;
1022 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1023 if (is_readable($defaultsfile)) {
1024 $defaults = array();
1025 include($defaultsfile);
1026 if (is_array($defaults) and count($defaults)) {
1027 $this->custom_defaults = $defaults;
1033 * Empties children array, and sets loaded to false
1035 * @param bool $requirefulltree
1037 public function purge_children($requirefulltree) {
1038 $this->children = array();
1039 $this->fulltree = ($requirefulltree || $this->fulltree);
1040 $this->loaded = false;
1041 //break circular dependencies - this helps PHP 5.2
1042 while($this->category_cache) {
1043 array_pop($this->category_cache);
1045 $this->category_cache = array();
1051 * Links external PHP pages into the admin tree.
1053 * See detailed usage example at the top of this document (adminlib.php)
1055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1057 class admin_externalpage implements part_of_admin_tree {
1059 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1060 public $name;
1062 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1063 public $visiblename;
1065 /** @var string The external URL that we should link to when someone requests this external page. */
1066 public $url;
1068 /** @var string The role capability/permission a user must have to access this external page. */
1069 public $req_capability;
1071 /** @var object The context in which capability/permission should be checked, default is site context. */
1072 public $context;
1074 /** @var bool hidden in admin tree block. */
1075 public $hidden;
1077 /** @var mixed either string or array of string */
1078 public $path;
1080 /** @var array list of visible names of page parents */
1081 public $visiblepath;
1084 * Constructor for adding an external page into the admin tree.
1086 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1087 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1088 * @param string $url The external URL that we should link to when someone requests this external page.
1089 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1090 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1091 * @param stdClass $context The context the page relates to. Not sure what happens
1092 * if you specify something other than system or front page. Defaults to system.
1094 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1095 $this->name = $name;
1096 $this->visiblename = $visiblename;
1097 $this->url = $url;
1098 if (is_array($req_capability)) {
1099 $this->req_capability = $req_capability;
1100 } else {
1101 $this->req_capability = array($req_capability);
1103 $this->hidden = $hidden;
1104 $this->context = $context;
1108 * Returns a reference to the part_of_admin_tree object with internal name $name.
1110 * @param string $name The internal name of the object we want.
1111 * @param bool $findpath defaults to false
1112 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1114 public function locate($name, $findpath=false) {
1115 if ($this->name == $name) {
1116 if ($findpath) {
1117 $this->visiblepath = array($this->visiblename);
1118 $this->path = array($this->name);
1120 return $this;
1121 } else {
1122 $return = NULL;
1123 return $return;
1128 * This function always returns false, required function by interface
1130 * @param string $name
1131 * @return false
1133 public function prune($name) {
1134 return false;
1138 * Search using query
1140 * @param string $query
1141 * @return mixed array-object structure of found settings and pages
1143 public function search($query) {
1144 $found = false;
1145 if (strpos(strtolower($this->name), $query) !== false) {
1146 $found = true;
1147 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1148 $found = true;
1150 if ($found) {
1151 $result = new stdClass();
1152 $result->page = $this;
1153 $result->settings = array();
1154 return array($this->name => $result);
1155 } else {
1156 return array();
1161 * Determines if the current user has access to this external page based on $this->req_capability.
1163 * @return bool True if user has access, false otherwise.
1165 public function check_access() {
1166 global $CFG;
1167 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1168 foreach($this->req_capability as $cap) {
1169 if (has_capability($cap, $context)) {
1170 return true;
1173 return false;
1177 * Is this external page hidden in admin tree block?
1179 * @return bool True if hidden
1181 public function is_hidden() {
1182 return $this->hidden;
1186 * Show we display Save button at the page bottom?
1187 * @return bool
1189 public function show_save() {
1190 return false;
1196 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1200 class admin_settingpage implements part_of_admin_tree {
1202 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1203 public $name;
1205 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1206 public $visiblename;
1208 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1209 public $settings;
1211 /** @var string The role capability/permission a user must have to access this external page. */
1212 public $req_capability;
1214 /** @var object The context in which capability/permission should be checked, default is site context. */
1215 public $context;
1217 /** @var bool hidden in admin tree block. */
1218 public $hidden;
1220 /** @var mixed string of paths or array of strings of paths */
1221 public $path;
1223 /** @var array list of visible names of page parents */
1224 public $visiblepath;
1227 * see admin_settingpage for details of this function
1229 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1230 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1231 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1232 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1233 * @param stdClass $context The context the page relates to. Not sure what happens
1234 * if you specify something other than system or front page. Defaults to system.
1236 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1237 $this->settings = new stdClass();
1238 $this->name = $name;
1239 $this->visiblename = $visiblename;
1240 if (is_array($req_capability)) {
1241 $this->req_capability = $req_capability;
1242 } else {
1243 $this->req_capability = array($req_capability);
1245 $this->hidden = $hidden;
1246 $this->context = $context;
1250 * see admin_category
1252 * @param string $name
1253 * @param bool $findpath
1254 * @return mixed Object (this) if name == this->name, else returns null
1256 public function locate($name, $findpath=false) {
1257 if ($this->name == $name) {
1258 if ($findpath) {
1259 $this->visiblepath = array($this->visiblename);
1260 $this->path = array($this->name);
1262 return $this;
1263 } else {
1264 $return = NULL;
1265 return $return;
1270 * Search string in settings page.
1272 * @param string $query
1273 * @return array
1275 public function search($query) {
1276 $found = array();
1278 foreach ($this->settings as $setting) {
1279 if ($setting->is_related($query)) {
1280 $found[] = $setting;
1284 if ($found) {
1285 $result = new stdClass();
1286 $result->page = $this;
1287 $result->settings = $found;
1288 return array($this->name => $result);
1291 $found = false;
1292 if (strpos(strtolower($this->name), $query) !== false) {
1293 $found = true;
1294 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1295 $found = true;
1297 if ($found) {
1298 $result = new stdClass();
1299 $result->page = $this;
1300 $result->settings = array();
1301 return array($this->name => $result);
1302 } else {
1303 return array();
1308 * This function always returns false, required by interface
1310 * @param string $name
1311 * @return bool Always false
1313 public function prune($name) {
1314 return false;
1318 * adds an admin_setting to this admin_settingpage
1320 * 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
1321 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1323 * @param object $setting is the admin_setting object you want to add
1324 * @return bool true if successful, false if not
1326 public function add($setting) {
1327 if (!($setting instanceof admin_setting)) {
1328 debugging('error - not a setting instance');
1329 return false;
1332 $this->settings->{$setting->name} = $setting;
1333 return true;
1337 * see admin_externalpage
1339 * @return bool Returns true for yes false for no
1341 public function check_access() {
1342 global $CFG;
1343 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1344 foreach($this->req_capability as $cap) {
1345 if (has_capability($cap, $context)) {
1346 return true;
1349 return false;
1353 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1354 * @return string Returns an XHTML string
1356 public function output_html() {
1357 $adminroot = admin_get_root();
1358 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1359 foreach($this->settings as $setting) {
1360 $fullname = $setting->get_full_name();
1361 if (array_key_exists($fullname, $adminroot->errors)) {
1362 $data = $adminroot->errors[$fullname]->data;
1363 } else {
1364 $data = $setting->get_setting();
1365 // do not use defaults if settings not available - upgrade settings handles the defaults!
1367 $return .= $setting->output_html($data);
1369 $return .= '</fieldset>';
1370 return $return;
1374 * Is this settings page hidden in admin tree block?
1376 * @return bool True if hidden
1378 public function is_hidden() {
1379 return $this->hidden;
1383 * Show we display Save button at the page bottom?
1384 * @return bool
1386 public function show_save() {
1387 foreach($this->settings as $setting) {
1388 if (empty($setting->nosave)) {
1389 return true;
1392 return false;
1398 * Admin settings class. Only exists on setting pages.
1399 * Read & write happens at this level; no authentication.
1401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1403 abstract class admin_setting {
1404 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1405 public $name;
1406 /** @var string localised name */
1407 public $visiblename;
1408 /** @var string localised long description in Markdown format */
1409 public $description;
1410 /** @var mixed Can be string or array of string */
1411 public $defaultsetting;
1412 /** @var string */
1413 public $updatedcallback;
1414 /** @var mixed can be String or Null. Null means main config table */
1415 public $plugin; // null means main config table
1416 /** @var bool true indicates this setting does not actually save anything, just information */
1417 public $nosave = false;
1418 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1419 public $affectsmodinfo = false;
1422 * Constructor
1423 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1424 * or 'myplugin/mysetting' for ones in config_plugins.
1425 * @param string $visiblename localised name
1426 * @param string $description localised long description
1427 * @param mixed $defaultsetting string or array depending on implementation
1429 public function __construct($name, $visiblename, $description, $defaultsetting) {
1430 $this->parse_setting_name($name);
1431 $this->visiblename = $visiblename;
1432 $this->description = $description;
1433 $this->defaultsetting = $defaultsetting;
1437 * Set up $this->name and potentially $this->plugin
1439 * Set up $this->name and possibly $this->plugin based on whether $name looks
1440 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1441 * on the names, that is, output a developer debug warning if the name
1442 * contains anything other than [a-zA-Z0-9_]+.
1444 * @param string $name the setting name passed in to the constructor.
1446 private function parse_setting_name($name) {
1447 $bits = explode('/', $name);
1448 if (count($bits) > 2) {
1449 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1451 $this->name = array_pop($bits);
1452 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1453 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1455 if (!empty($bits)) {
1456 $this->plugin = array_pop($bits);
1457 if ($this->plugin === 'moodle') {
1458 $this->plugin = null;
1459 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1460 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1466 * Returns the fullname prefixed by the plugin
1467 * @return string
1469 public function get_full_name() {
1470 return 's_'.$this->plugin.'_'.$this->name;
1474 * Returns the ID string based on plugin and name
1475 * @return string
1477 public function get_id() {
1478 return 'id_s_'.$this->plugin.'_'.$this->name;
1482 * @param bool $affectsmodinfo If true, changes to this setting will
1483 * cause the course cache to be rebuilt
1485 public function set_affects_modinfo($affectsmodinfo) {
1486 $this->affectsmodinfo = $affectsmodinfo;
1490 * Returns the config if possible
1492 * @return mixed returns config if successful else null
1494 public function config_read($name) {
1495 global $CFG;
1496 if (!empty($this->plugin)) {
1497 $value = get_config($this->plugin, $name);
1498 return $value === false ? NULL : $value;
1500 } else {
1501 if (isset($CFG->$name)) {
1502 return $CFG->$name;
1503 } else {
1504 return NULL;
1510 * Used to set a config pair and log change
1512 * @param string $name
1513 * @param mixed $value Gets converted to string if not null
1514 * @return bool Write setting to config table
1516 public function config_write($name, $value) {
1517 global $DB, $USER, $CFG;
1519 if ($this->nosave) {
1520 return true;
1523 // make sure it is a real change
1524 $oldvalue = get_config($this->plugin, $name);
1525 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1526 $value = is_null($value) ? null : (string)$value;
1528 if ($oldvalue === $value) {
1529 return true;
1532 // store change
1533 set_config($name, $value, $this->plugin);
1535 // Some admin settings affect course modinfo
1536 if ($this->affectsmodinfo) {
1537 // Clear course cache for all courses
1538 rebuild_course_cache(0, true);
1541 // log change
1542 $log = new stdClass();
1543 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1544 $log->timemodified = time();
1545 $log->plugin = $this->plugin;
1546 $log->name = $name;
1547 $log->value = $value;
1548 $log->oldvalue = $oldvalue;
1549 $DB->insert_record('config_log', $log);
1551 return true; // BC only
1555 * Returns current value of this setting
1556 * @return mixed array or string depending on instance, NULL means not set yet
1558 public abstract function get_setting();
1561 * Returns default setting if exists
1562 * @return mixed array or string depending on instance; NULL means no default, user must supply
1564 public function get_defaultsetting() {
1565 $adminroot = admin_get_root(false, false);
1566 if (!empty($adminroot->custom_defaults)) {
1567 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1568 if (isset($adminroot->custom_defaults[$plugin])) {
1569 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1570 return $adminroot->custom_defaults[$plugin][$this->name];
1574 return $this->defaultsetting;
1578 * Store new setting
1580 * @param mixed $data string or array, must not be NULL
1581 * @return string empty string if ok, string error message otherwise
1583 public abstract function write_setting($data);
1586 * Return part of form with setting
1587 * This function should always be overwritten
1589 * @param mixed $data array or string depending on setting
1590 * @param string $query
1591 * @return string
1593 public function output_html($data, $query='') {
1594 // should be overridden
1595 return;
1599 * Function called if setting updated - cleanup, cache reset, etc.
1600 * @param string $functionname Sets the function name
1601 * @return void
1603 public function set_updatedcallback($functionname) {
1604 $this->updatedcallback = $functionname;
1608 * Is setting related to query text - used when searching
1609 * @param string $query
1610 * @return bool
1612 public function is_related($query) {
1613 if (strpos(strtolower($this->name), $query) !== false) {
1614 return true;
1616 if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1617 return true;
1619 if (strpos(textlib::strtolower($this->description), $query) !== false) {
1620 return true;
1622 $current = $this->get_setting();
1623 if (!is_null($current)) {
1624 if (is_string($current)) {
1625 if (strpos(textlib::strtolower($current), $query) !== false) {
1626 return true;
1630 $default = $this->get_defaultsetting();
1631 if (!is_null($default)) {
1632 if (is_string($default)) {
1633 if (strpos(textlib::strtolower($default), $query) !== false) {
1634 return true;
1638 return false;
1644 * No setting - just heading and text.
1646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1648 class admin_setting_heading extends admin_setting {
1651 * not a setting, just text
1652 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1653 * @param string $heading heading
1654 * @param string $information text in box
1656 public function __construct($name, $heading, $information) {
1657 $this->nosave = true;
1658 parent::__construct($name, $heading, $information, '');
1662 * Always returns true
1663 * @return bool Always returns true
1665 public function get_setting() {
1666 return true;
1670 * Always returns true
1671 * @return bool Always returns true
1673 public function get_defaultsetting() {
1674 return true;
1678 * Never write settings
1679 * @return string Always returns an empty string
1681 public function write_setting($data) {
1682 // do not write any setting
1683 return '';
1687 * Returns an HTML string
1688 * @return string Returns an HTML string
1690 public function output_html($data, $query='') {
1691 global $OUTPUT;
1692 $return = '';
1693 if ($this->visiblename != '') {
1694 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1696 if ($this->description != '') {
1697 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1699 return $return;
1705 * The most flexibly setting, user is typing text
1707 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1709 class admin_setting_configtext extends admin_setting {
1711 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1712 public $paramtype;
1713 /** @var int default field size */
1714 public $size;
1717 * Config text constructor
1719 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1720 * @param string $visiblename localised
1721 * @param string $description long localised info
1722 * @param string $defaultsetting
1723 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1724 * @param int $size default field size
1726 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1727 $this->paramtype = $paramtype;
1728 if (!is_null($size)) {
1729 $this->size = $size;
1730 } else {
1731 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1733 parent::__construct($name, $visiblename, $description, $defaultsetting);
1737 * Return the setting
1739 * @return mixed returns config if successful else null
1741 public function get_setting() {
1742 return $this->config_read($this->name);
1745 public function write_setting($data) {
1746 if ($this->paramtype === PARAM_INT and $data === '') {
1747 // do not complain if '' used instead of 0
1748 $data = 0;
1750 // $data is a string
1751 $validated = $this->validate($data);
1752 if ($validated !== true) {
1753 return $validated;
1755 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1759 * Validate data before storage
1760 * @param string data
1761 * @return mixed true if ok string if error found
1763 public function validate($data) {
1764 // allow paramtype to be a custom regex if it is the form of /pattern/
1765 if (preg_match('#^/.*/$#', $this->paramtype)) {
1766 if (preg_match($this->paramtype, $data)) {
1767 return true;
1768 } else {
1769 return get_string('validateerror', 'admin');
1772 } else if ($this->paramtype === PARAM_RAW) {
1773 return true;
1775 } else {
1776 $cleaned = clean_param($data, $this->paramtype);
1777 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1778 return true;
1779 } else {
1780 return get_string('validateerror', 'admin');
1786 * Return an XHTML string for the setting
1787 * @return string Returns an XHTML string
1789 public function output_html($data, $query='') {
1790 $default = $this->get_defaultsetting();
1792 return format_admin_setting($this, $this->visiblename,
1793 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1794 $this->description, true, '', $default, $query);
1800 * General text area without html editor.
1802 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1804 class admin_setting_configtextarea extends admin_setting_configtext {
1805 private $rows;
1806 private $cols;
1809 * @param string $name
1810 * @param string $visiblename
1811 * @param string $description
1812 * @param mixed $defaultsetting string or array
1813 * @param mixed $paramtype
1814 * @param string $cols The number of columns to make the editor
1815 * @param string $rows The number of rows to make the editor
1817 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1818 $this->rows = $rows;
1819 $this->cols = $cols;
1820 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1824 * Returns an XHTML string for the editor
1826 * @param string $data
1827 * @param string $query
1828 * @return string XHTML string for the editor
1830 public function output_html($data, $query='') {
1831 $default = $this->get_defaultsetting();
1833 $defaultinfo = $default;
1834 if (!is_null($default) and $default !== '') {
1835 $defaultinfo = "\n".$default;
1838 return format_admin_setting($this, $this->visiblename,
1839 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1840 $this->description, true, '', $defaultinfo, $query);
1846 * General text area with html editor.
1848 class admin_setting_confightmleditor extends admin_setting_configtext {
1849 private $rows;
1850 private $cols;
1853 * @param string $name
1854 * @param string $visiblename
1855 * @param string $description
1856 * @param mixed $defaultsetting string or array
1857 * @param mixed $paramtype
1859 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1860 $this->rows = $rows;
1861 $this->cols = $cols;
1862 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1863 editors_head_setup();
1867 * Returns an XHTML string for the editor
1869 * @param string $data
1870 * @param string $query
1871 * @return string XHTML string for the editor
1873 public function output_html($data, $query='') {
1874 $default = $this->get_defaultsetting();
1876 $defaultinfo = $default;
1877 if (!is_null($default) and $default !== '') {
1878 $defaultinfo = "\n".$default;
1881 $editor = editors_get_preferred_editor(FORMAT_HTML);
1882 $editor->use_editor($this->get_id(), array('noclean'=>true));
1884 return format_admin_setting($this, $this->visiblename,
1885 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1886 $this->description, true, '', $defaultinfo, $query);
1892 * Password field, allows unmasking of password
1894 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1896 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1898 * Constructor
1899 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1900 * @param string $visiblename localised
1901 * @param string $description long localised info
1902 * @param string $defaultsetting default password
1904 public function __construct($name, $visiblename, $description, $defaultsetting) {
1905 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1909 * Returns XHTML for the field
1910 * Writes Javascript into the HTML below right before the last div
1912 * @todo Make javascript available through newer methods if possible
1913 * @param string $data Value for the field
1914 * @param string $query Passed as final argument for format_admin_setting
1915 * @return string XHTML field
1917 public function output_html($data, $query='') {
1918 $id = $this->get_id();
1919 $unmask = get_string('unmaskpassword', 'form');
1920 $unmaskjs = '<script type="text/javascript">
1921 //<![CDATA[
1922 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1924 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1926 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1928 var unmaskchb = document.createElement("input");
1929 unmaskchb.setAttribute("type", "checkbox");
1930 unmaskchb.setAttribute("id", "'.$id.'unmask");
1931 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1932 unmaskdiv.appendChild(unmaskchb);
1934 var unmasklbl = document.createElement("label");
1935 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1936 if (is_ie) {
1937 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1938 } else {
1939 unmasklbl.setAttribute("for", "'.$id.'unmask");
1941 unmaskdiv.appendChild(unmasklbl);
1943 if (is_ie) {
1944 // ugly hack to work around the famous onchange IE bug
1945 unmaskchb.onclick = function() {this.blur();};
1946 unmaskdiv.onclick = function() {this.blur();};
1948 //]]>
1949 </script>';
1950 return format_admin_setting($this, $this->visiblename,
1951 '<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>',
1952 $this->description, true, '', NULL, $query);
1958 * Path to directory
1960 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1962 class admin_setting_configfile extends admin_setting_configtext {
1964 * Constructor
1965 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1966 * @param string $visiblename localised
1967 * @param string $description long localised info
1968 * @param string $defaultdirectory default directory location
1970 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1971 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1975 * Returns XHTML for the field
1977 * Returns XHTML for the field and also checks whether the file
1978 * specified in $data exists using file_exists()
1980 * @param string $data File name and path to use in value attr
1981 * @param string $query
1982 * @return string XHTML field
1984 public function output_html($data, $query='') {
1985 $default = $this->get_defaultsetting();
1987 if ($data) {
1988 if (file_exists($data)) {
1989 $executable = '<span class="pathok">&#x2714;</span>';
1990 } else {
1991 $executable = '<span class="patherror">&#x2718;</span>';
1993 } else {
1994 $executable = '';
1997 return format_admin_setting($this, $this->visiblename,
1998 '<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>',
1999 $this->description, true, '', $default, $query);
2005 * Path to executable file
2007 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2009 class admin_setting_configexecutable extends admin_setting_configfile {
2012 * Returns an XHTML field
2014 * @param string $data This is the value for the field
2015 * @param string $query
2016 * @return string XHTML field
2018 public function output_html($data, $query='') {
2019 $default = $this->get_defaultsetting();
2021 if ($data) {
2022 if (file_exists($data) and is_executable($data)) {
2023 $executable = '<span class="pathok">&#x2714;</span>';
2024 } else {
2025 $executable = '<span class="patherror">&#x2718;</span>';
2027 } else {
2028 $executable = '';
2031 return format_admin_setting($this, $this->visiblename,
2032 '<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>',
2033 $this->description, true, '', $default, $query);
2039 * Path to directory
2041 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2043 class admin_setting_configdirectory extends admin_setting_configfile {
2046 * Returns an XHTML field
2048 * @param string $data This is the value for the field
2049 * @param string $query
2050 * @return string XHTML
2052 public function output_html($data, $query='') {
2053 $default = $this->get_defaultsetting();
2055 if ($data) {
2056 if (file_exists($data) and is_dir($data)) {
2057 $executable = '<span class="pathok">&#x2714;</span>';
2058 } else {
2059 $executable = '<span class="patherror">&#x2718;</span>';
2061 } else {
2062 $executable = '';
2065 return format_admin_setting($this, $this->visiblename,
2066 '<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>',
2067 $this->description, true, '', $default, $query);
2073 * Checkbox
2075 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2077 class admin_setting_configcheckbox extends admin_setting {
2078 /** @var string Value used when checked */
2079 public $yes;
2080 /** @var string Value used when not checked */
2081 public $no;
2084 * Constructor
2085 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2086 * @param string $visiblename localised
2087 * @param string $description long localised info
2088 * @param string $defaultsetting
2089 * @param string $yes value used when checked
2090 * @param string $no value used when not checked
2092 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2093 parent::__construct($name, $visiblename, $description, $defaultsetting);
2094 $this->yes = (string)$yes;
2095 $this->no = (string)$no;
2099 * Retrieves the current setting using the objects name
2101 * @return string
2103 public function get_setting() {
2104 return $this->config_read($this->name);
2108 * Sets the value for the setting
2110 * Sets the value for the setting to either the yes or no values
2111 * of the object by comparing $data to yes
2113 * @param mixed $data Gets converted to str for comparison against yes value
2114 * @return string empty string or error
2116 public function write_setting($data) {
2117 if ((string)$data === $this->yes) { // convert to strings before comparison
2118 $data = $this->yes;
2119 } else {
2120 $data = $this->no;
2122 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2126 * Returns an XHTML checkbox field
2128 * @param string $data If $data matches yes then checkbox is checked
2129 * @param string $query
2130 * @return string XHTML field
2132 public function output_html($data, $query='') {
2133 $default = $this->get_defaultsetting();
2135 if (!is_null($default)) {
2136 if ((string)$default === $this->yes) {
2137 $defaultinfo = get_string('checkboxyes', 'admin');
2138 } else {
2139 $defaultinfo = get_string('checkboxno', 'admin');
2141 } else {
2142 $defaultinfo = NULL;
2145 if ((string)$data === $this->yes) { // convert to strings before comparison
2146 $checked = 'checked="checked"';
2147 } else {
2148 $checked = '';
2151 return format_admin_setting($this, $this->visiblename,
2152 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2153 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2154 $this->description, true, '', $defaultinfo, $query);
2160 * Multiple checkboxes, each represents different value, stored in csv format
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2164 class admin_setting_configmulticheckbox extends admin_setting {
2165 /** @var array Array of choices value=>label */
2166 public $choices;
2169 * Constructor: uses parent::__construct
2171 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2172 * @param string $visiblename localised
2173 * @param string $description long localised info
2174 * @param array $defaultsetting array of selected
2175 * @param array $choices array of $value=>$label for each checkbox
2177 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2178 $this->choices = $choices;
2179 parent::__construct($name, $visiblename, $description, $defaultsetting);
2183 * This public function may be used in ancestors for lazy loading of choices
2185 * @todo Check if this function is still required content commented out only returns true
2186 * @return bool true if loaded, false if error
2188 public function load_choices() {
2190 if (is_array($this->choices)) {
2191 return true;
2193 .... load choices here
2195 return true;
2199 * Is setting related to query text - used when searching
2201 * @param string $query
2202 * @return bool true on related, false on not or failure
2204 public function is_related($query) {
2205 if (!$this->load_choices() or empty($this->choices)) {
2206 return false;
2208 if (parent::is_related($query)) {
2209 return true;
2212 foreach ($this->choices as $desc) {
2213 if (strpos(textlib::strtolower($desc), $query) !== false) {
2214 return true;
2217 return false;
2221 * Returns the current setting if it is set
2223 * @return mixed null if null, else an array
2225 public function get_setting() {
2226 $result = $this->config_read($this->name);
2228 if (is_null($result)) {
2229 return NULL;
2231 if ($result === '') {
2232 return array();
2234 $enabled = explode(',', $result);
2235 $setting = array();
2236 foreach ($enabled as $option) {
2237 $setting[$option] = 1;
2239 return $setting;
2243 * Saves the setting(s) provided in $data
2245 * @param array $data An array of data, if not array returns empty str
2246 * @return mixed empty string on useless data or bool true=success, false=failed
2248 public function write_setting($data) {
2249 if (!is_array($data)) {
2250 return ''; // ignore it
2252 if (!$this->load_choices() or empty($this->choices)) {
2253 return '';
2255 unset($data['xxxxx']);
2256 $result = array();
2257 foreach ($data as $key => $value) {
2258 if ($value and array_key_exists($key, $this->choices)) {
2259 $result[] = $key;
2262 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2266 * Returns XHTML field(s) as required by choices
2268 * Relies on data being an array should data ever be another valid vartype with
2269 * acceptable value this may cause a warning/error
2270 * if (!is_array($data)) would fix the problem
2272 * @todo Add vartype handling to ensure $data is an array
2274 * @param array $data An array of checked values
2275 * @param string $query
2276 * @return string XHTML field
2278 public function output_html($data, $query='') {
2279 if (!$this->load_choices() or empty($this->choices)) {
2280 return '';
2282 $default = $this->get_defaultsetting();
2283 if (is_null($default)) {
2284 $default = array();
2286 if (is_null($data)) {
2287 $data = array();
2289 $options = array();
2290 $defaults = array();
2291 foreach ($this->choices as $key=>$description) {
2292 if (!empty($data[$key])) {
2293 $checked = 'checked="checked"';
2294 } else {
2295 $checked = '';
2297 if (!empty($default[$key])) {
2298 $defaults[] = $description;
2301 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2302 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2305 if (is_null($default)) {
2306 $defaultinfo = NULL;
2307 } else if (!empty($defaults)) {
2308 $defaultinfo = implode(', ', $defaults);
2309 } else {
2310 $defaultinfo = get_string('none');
2313 $return = '<div class="form-multicheckbox">';
2314 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2315 if ($options) {
2316 $return .= '<ul>';
2317 foreach ($options as $option) {
2318 $return .= '<li>'.$option.'</li>';
2320 $return .= '</ul>';
2322 $return .= '</div>';
2324 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2331 * Multiple checkboxes 2, value stored as string 00101011
2333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2335 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2338 * Returns the setting if set
2340 * @return mixed null if not set, else an array of set settings
2342 public function get_setting() {
2343 $result = $this->config_read($this->name);
2344 if (is_null($result)) {
2345 return NULL;
2347 if (!$this->load_choices()) {
2348 return NULL;
2350 $result = str_pad($result, count($this->choices), '0');
2351 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2352 $setting = array();
2353 foreach ($this->choices as $key=>$unused) {
2354 $value = array_shift($result);
2355 if ($value) {
2356 $setting[$key] = 1;
2359 return $setting;
2363 * Save setting(s) provided in $data param
2365 * @param array $data An array of settings to save
2366 * @return mixed empty string for bad data or bool true=>success, false=>error
2368 public function write_setting($data) {
2369 if (!is_array($data)) {
2370 return ''; // ignore it
2372 if (!$this->load_choices() or empty($this->choices)) {
2373 return '';
2375 $result = '';
2376 foreach ($this->choices as $key=>$unused) {
2377 if (!empty($data[$key])) {
2378 $result .= '1';
2379 } else {
2380 $result .= '0';
2383 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2389 * Select one value from list
2391 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2393 class admin_setting_configselect extends admin_setting {
2394 /** @var array Array of choices value=>label */
2395 public $choices;
2398 * Constructor
2399 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2400 * @param string $visiblename localised
2401 * @param string $description long localised info
2402 * @param string|int $defaultsetting
2403 * @param array $choices array of $value=>$label for each selection
2405 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2406 $this->choices = $choices;
2407 parent::__construct($name, $visiblename, $description, $defaultsetting);
2411 * This function may be used in ancestors for lazy loading of choices
2413 * Override this method if loading of choices is expensive, such
2414 * as when it requires multiple db requests.
2416 * @return bool true if loaded, false if error
2418 public function load_choices() {
2420 if (is_array($this->choices)) {
2421 return true;
2423 .... load choices here
2425 return true;
2429 * Check if this is $query is related to a choice
2431 * @param string $query
2432 * @return bool true if related, false if not
2434 public function is_related($query) {
2435 if (parent::is_related($query)) {
2436 return true;
2438 if (!$this->load_choices()) {
2439 return false;
2441 foreach ($this->choices as $key=>$value) {
2442 if (strpos(textlib::strtolower($key), $query) !== false) {
2443 return true;
2445 if (strpos(textlib::strtolower($value), $query) !== false) {
2446 return true;
2449 return false;
2453 * Return the setting
2455 * @return mixed returns config if successful else null
2457 public function get_setting() {
2458 return $this->config_read($this->name);
2462 * Save a setting
2464 * @param string $data
2465 * @return string empty of error string
2467 public function write_setting($data) {
2468 if (!$this->load_choices() or empty($this->choices)) {
2469 return '';
2471 if (!array_key_exists($data, $this->choices)) {
2472 return ''; // ignore it
2475 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2479 * Returns XHTML select field
2481 * Ensure the options are loaded, and generate the XHTML for the select
2482 * element and any warning message. Separating this out from output_html
2483 * makes it easier to subclass this class.
2485 * @param string $data the option to show as selected.
2486 * @param string $current the currently selected option in the database, null if none.
2487 * @param string $default the default selected option.
2488 * @return array the HTML for the select element, and a warning message.
2490 public function output_select_html($data, $current, $default, $extraname = '') {
2491 if (!$this->load_choices() or empty($this->choices)) {
2492 return array('', '');
2495 $warning = '';
2496 if (is_null($current)) {
2497 // first run
2498 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2499 // no warning
2500 } else if (!array_key_exists($current, $this->choices)) {
2501 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2502 if (!is_null($default) and $data == $current) {
2503 $data = $default; // use default instead of first value when showing the form
2507 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2508 foreach ($this->choices as $key => $value) {
2509 // the string cast is needed because key may be integer - 0 is equal to most strings!
2510 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2512 $selecthtml .= '</select>';
2513 return array($selecthtml, $warning);
2517 * Returns XHTML select field and wrapping div(s)
2519 * @see output_select_html()
2521 * @param string $data the option to show as selected
2522 * @param string $query
2523 * @return string XHTML field and wrapping div
2525 public function output_html($data, $query='') {
2526 $default = $this->get_defaultsetting();
2527 $current = $this->get_setting();
2529 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2530 if (!$selecthtml) {
2531 return '';
2534 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2535 $defaultinfo = $this->choices[$default];
2536 } else {
2537 $defaultinfo = NULL;
2540 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2542 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2548 * Select multiple items from list
2550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2552 class admin_setting_configmultiselect extends admin_setting_configselect {
2554 * Constructor
2555 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2556 * @param string $visiblename localised
2557 * @param string $description long localised info
2558 * @param array $defaultsetting array of selected items
2559 * @param array $choices array of $value=>$label for each list item
2561 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2562 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2566 * Returns the select setting(s)
2568 * @return mixed null or array. Null if no settings else array of setting(s)
2570 public function get_setting() {
2571 $result = $this->config_read($this->name);
2572 if (is_null($result)) {
2573 return NULL;
2575 if ($result === '') {
2576 return array();
2578 return explode(',', $result);
2582 * Saves setting(s) provided through $data
2584 * Potential bug in the works should anyone call with this function
2585 * using a vartype that is not an array
2587 * @param array $data
2589 public function write_setting($data) {
2590 if (!is_array($data)) {
2591 return ''; //ignore it
2593 if (!$this->load_choices() or empty($this->choices)) {
2594 return '';
2597 unset($data['xxxxx']);
2599 $save = array();
2600 foreach ($data as $value) {
2601 if (!array_key_exists($value, $this->choices)) {
2602 continue; // ignore it
2604 $save[] = $value;
2607 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2611 * Is setting related to query text - used when searching
2613 * @param string $query
2614 * @return bool true if related, false if not
2616 public function is_related($query) {
2617 if (!$this->load_choices() or empty($this->choices)) {
2618 return false;
2620 if (parent::is_related($query)) {
2621 return true;
2624 foreach ($this->choices as $desc) {
2625 if (strpos(textlib::strtolower($desc), $query) !== false) {
2626 return true;
2629 return false;
2633 * Returns XHTML multi-select field
2635 * @todo Add vartype handling to ensure $data is an array
2636 * @param array $data Array of values to select by default
2637 * @param string $query
2638 * @return string XHTML multi-select field
2640 public function output_html($data, $query='') {
2641 if (!$this->load_choices() or empty($this->choices)) {
2642 return '';
2644 $choices = $this->choices;
2645 $default = $this->get_defaultsetting();
2646 if (is_null($default)) {
2647 $default = array();
2649 if (is_null($data)) {
2650 $data = array();
2653 $defaults = array();
2654 $size = min(10, count($this->choices));
2655 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2656 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2657 foreach ($this->choices as $key => $description) {
2658 if (in_array($key, $data)) {
2659 $selected = 'selected="selected"';
2660 } else {
2661 $selected = '';
2663 if (in_array($key, $default)) {
2664 $defaults[] = $description;
2667 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2670 if (is_null($default)) {
2671 $defaultinfo = NULL;
2672 } if (!empty($defaults)) {
2673 $defaultinfo = implode(', ', $defaults);
2674 } else {
2675 $defaultinfo = get_string('none');
2678 $return .= '</select></div>';
2679 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2684 * Time selector
2686 * This is a liiitle bit messy. we're using two selects, but we're returning
2687 * them as an array named after $name (so we only use $name2 internally for the setting)
2689 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2691 class admin_setting_configtime extends admin_setting {
2692 /** @var string Used for setting second select (minutes) */
2693 public $name2;
2696 * Constructor
2697 * @param string $hoursname setting for hours
2698 * @param string $minutesname setting for hours
2699 * @param string $visiblename localised
2700 * @param string $description long localised info
2701 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2703 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2704 $this->name2 = $minutesname;
2705 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2709 * Get the selected time
2711 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2713 public function get_setting() {
2714 $result1 = $this->config_read($this->name);
2715 $result2 = $this->config_read($this->name2);
2716 if (is_null($result1) or is_null($result2)) {
2717 return NULL;
2720 return array('h' => $result1, 'm' => $result2);
2724 * Store the time (hours and minutes)
2726 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2727 * @return bool true if success, false if not
2729 public function write_setting($data) {
2730 if (!is_array($data)) {
2731 return '';
2734 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2735 return ($result ? '' : get_string('errorsetting', 'admin'));
2739 * Returns XHTML time select fields
2741 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2742 * @param string $query
2743 * @return string XHTML time select fields and wrapping div(s)
2745 public function output_html($data, $query='') {
2746 $default = $this->get_defaultsetting();
2748 if (is_array($default)) {
2749 $defaultinfo = $default['h'].':'.$default['m'];
2750 } else {
2751 $defaultinfo = NULL;
2754 $return = '<div class="form-time defaultsnext">'.
2755 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2756 for ($i = 0; $i < 24; $i++) {
2757 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2759 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2760 for ($i = 0; $i < 60; $i += 5) {
2761 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2763 $return .= '</select></div>';
2764 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2771 * Used to validate a textarea used for ip addresses
2773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2775 class admin_setting_configiplist extends admin_setting_configtextarea {
2778 * Validate the contents of the textarea as IP addresses
2780 * Used to validate a new line separated list of IP addresses collected from
2781 * a textarea control
2783 * @param string $data A list of IP Addresses separated by new lines
2784 * @return mixed bool true for success or string:error on failure
2786 public function validate($data) {
2787 if(!empty($data)) {
2788 $ips = explode("\n", $data);
2789 } else {
2790 return true;
2792 $result = true;
2793 foreach($ips as $ip) {
2794 $ip = trim($ip);
2795 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2796 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2797 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2798 $result = true;
2799 } else {
2800 $result = false;
2801 break;
2804 if($result) {
2805 return true;
2806 } else {
2807 return get_string('validateerror', 'admin');
2814 * An admin setting for selecting one or more users who have a capability
2815 * in the system context
2817 * An admin setting for selecting one or more users, who have a particular capability
2818 * in the system context. Warning, make sure the list will never be too long. There is
2819 * no paging or searching of this list.
2821 * To correctly get a list of users from this config setting, you need to call the
2822 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2824 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2826 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2827 /** @var string The capabilities name */
2828 protected $capability;
2829 /** @var int include admin users too */
2830 protected $includeadmins;
2833 * Constructor.
2835 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2836 * @param string $visiblename localised name
2837 * @param string $description localised long description
2838 * @param array $defaultsetting array of usernames
2839 * @param string $capability string capability name.
2840 * @param bool $includeadmins include administrators
2842 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2843 $this->capability = $capability;
2844 $this->includeadmins = $includeadmins;
2845 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2849 * Load all of the uses who have the capability into choice array
2851 * @return bool Always returns true
2853 function load_choices() {
2854 if (is_array($this->choices)) {
2855 return true;
2857 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2858 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2859 $this->choices = array(
2860 '$@NONE@$' => get_string('nobody'),
2861 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2863 if ($this->includeadmins) {
2864 $admins = get_admins();
2865 foreach ($admins as $user) {
2866 $this->choices[$user->id] = fullname($user);
2869 if (is_array($users)) {
2870 foreach ($users as $user) {
2871 $this->choices[$user->id] = fullname($user);
2874 return true;
2878 * Returns the default setting for class
2880 * @return mixed Array, or string. Empty string if no default
2882 public function get_defaultsetting() {
2883 $this->load_choices();
2884 $defaultsetting = parent::get_defaultsetting();
2885 if (empty($defaultsetting)) {
2886 return array('$@NONE@$');
2887 } else if (array_key_exists($defaultsetting, $this->choices)) {
2888 return $defaultsetting;
2889 } else {
2890 return '';
2895 * Returns the current setting
2897 * @return mixed array or string
2899 public function get_setting() {
2900 $result = parent::get_setting();
2901 if ($result === null) {
2902 // this is necessary for settings upgrade
2903 return null;
2905 if (empty($result)) {
2906 $result = array('$@NONE@$');
2908 return $result;
2912 * Save the chosen setting provided as $data
2914 * @param array $data
2915 * @return mixed string or array
2917 public function write_setting($data) {
2918 // If all is selected, remove any explicit options.
2919 if (in_array('$@ALL@$', $data)) {
2920 $data = array('$@ALL@$');
2922 // None never needs to be written to the DB.
2923 if (in_array('$@NONE@$', $data)) {
2924 unset($data[array_search('$@NONE@$', $data)]);
2926 return parent::write_setting($data);
2932 * Special checkbox for calendar - resets SESSION vars.
2934 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2936 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2938 * Calls the parent::__construct with default values
2940 * name => calendar_adminseesall
2941 * visiblename => get_string('adminseesall', 'admin')
2942 * description => get_string('helpadminseesall', 'admin')
2943 * defaultsetting => 0
2945 public function __construct() {
2946 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2947 get_string('helpadminseesall', 'admin'), '0');
2951 * Stores the setting passed in $data
2953 * @param mixed gets converted to string for comparison
2954 * @return string empty string or error message
2956 public function write_setting($data) {
2957 global $SESSION;
2958 return parent::write_setting($data);
2963 * Special select for settings that are altered in setup.php and can not be altered on the fly
2965 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2967 class admin_setting_special_selectsetup extends admin_setting_configselect {
2969 * Reads the setting directly from the database
2971 * @return mixed
2973 public function get_setting() {
2974 // read directly from db!
2975 return get_config(NULL, $this->name);
2979 * Save the setting passed in $data
2981 * @param string $data The setting to save
2982 * @return string empty or error message
2984 public function write_setting($data) {
2985 global $CFG;
2986 // do not change active CFG setting!
2987 $current = $CFG->{$this->name};
2988 $result = parent::write_setting($data);
2989 $CFG->{$this->name} = $current;
2990 return $result;
2996 * Special select for frontpage - stores data in course table
2998 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3000 class admin_setting_sitesetselect extends admin_setting_configselect {
3002 * Returns the site name for the selected site
3004 * @see get_site()
3005 * @return string The site name of the selected site
3007 public function get_setting() {
3008 $site = get_site();
3009 return $site->{$this->name};
3013 * Updates the database and save the setting
3015 * @param string data
3016 * @return string empty or error message
3018 public function write_setting($data) {
3019 global $DB, $SITE;
3020 if (!in_array($data, array_keys($this->choices))) {
3021 return get_string('errorsetting', 'admin');
3023 $record = new stdClass();
3024 $record->id = SITEID;
3025 $temp = $this->name;
3026 $record->$temp = $data;
3027 $record->timemodified = time();
3028 // update $SITE
3029 $SITE->{$this->name} = $data;
3030 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3036 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3037 * block to hidden.
3039 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3041 class admin_setting_bloglevel extends admin_setting_configselect {
3043 * Updates the database and save the setting
3045 * @param string data
3046 * @return string empty or error message
3048 public function write_setting($data) {
3049 global $DB, $CFG;
3050 if ($data == 0) {
3051 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3052 foreach ($blogblocks as $block) {
3053 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3055 } else {
3056 // reenable all blocks only when switching from disabled blogs
3057 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3058 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3059 foreach ($blogblocks as $block) {
3060 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3064 return parent::write_setting($data);
3070 * Special select - lists on the frontpage - hacky
3072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3074 class admin_setting_courselist_frontpage extends admin_setting {
3075 /** @var array Array of choices value=>label */
3076 public $choices;
3079 * Construct override, requires one param
3081 * @param bool $loggedin Is the user logged in
3083 public function __construct($loggedin) {
3084 global $CFG;
3085 require_once($CFG->dirroot.'/course/lib.php');
3086 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3087 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3088 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3089 $defaults = array(FRONTPAGECOURSELIST);
3090 parent::__construct($name, $visiblename, $description, $defaults);
3094 * Loads the choices available
3096 * @return bool always returns true
3098 public function load_choices() {
3099 global $DB;
3100 if (is_array($this->choices)) {
3101 return true;
3103 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3104 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3105 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3106 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3107 'none' => get_string('none'));
3108 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3109 unset($this->choices[FRONTPAGECOURSELIST]);
3111 return true;
3115 * Returns the selected settings
3117 * @param mixed array or setting or null
3119 public function get_setting() {
3120 $result = $this->config_read($this->name);
3121 if (is_null($result)) {
3122 return NULL;
3124 if ($result === '') {
3125 return array();
3127 return explode(',', $result);
3131 * Save the selected options
3133 * @param array $data
3134 * @return mixed empty string (data is not an array) or bool true=success false=failure
3136 public function write_setting($data) {
3137 if (!is_array($data)) {
3138 return '';
3140 $this->load_choices();
3141 $save = array();
3142 foreach($data as $datum) {
3143 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3144 continue;
3146 $save[$datum] = $datum; // no duplicates
3148 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3152 * Return XHTML select field and wrapping div
3154 * @todo Add vartype handling to make sure $data is an array
3155 * @param array $data Array of elements to select by default
3156 * @return string XHTML select field and wrapping div
3158 public function output_html($data, $query='') {
3159 $this->load_choices();
3160 $currentsetting = array();
3161 foreach ($data as $key) {
3162 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3163 $currentsetting[] = $key; // already selected first
3167 $return = '<div class="form-group">';
3168 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3169 if (!array_key_exists($i, $currentsetting)) {
3170 $currentsetting[$i] = 'none'; //none
3172 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3173 foreach ($this->choices as $key => $value) {
3174 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3176 $return .= '</select>';
3177 if ($i !== count($this->choices) - 2) {
3178 $return .= '<br />';
3181 $return .= '</div>';
3183 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3189 * Special checkbox for frontpage - stores data in course table
3191 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3193 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3195 * Returns the current sites name
3197 * @return string
3199 public function get_setting() {
3200 $site = get_site();
3201 return $site->{$this->name};
3205 * Save the selected setting
3207 * @param string $data The selected site
3208 * @return string empty string or error message
3210 public function write_setting($data) {
3211 global $DB, $SITE;
3212 $record = new stdClass();
3213 $record->id = SITEID;
3214 $record->{$this->name} = ($data == '1' ? 1 : 0);
3215 $record->timemodified = time();
3216 // update $SITE
3217 $SITE->{$this->name} = $data;
3218 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3223 * Special text for frontpage - stores data in course table.
3224 * Empty string means not set here. Manual setting is required.
3226 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3228 class admin_setting_sitesettext extends admin_setting_configtext {
3230 * Return the current setting
3232 * @return mixed string or null
3234 public function get_setting() {
3235 $site = get_site();
3236 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3240 * Validate the selected data
3242 * @param string $data The selected value to validate
3243 * @return mixed true or message string
3245 public function validate($data) {
3246 $cleaned = clean_param($data, PARAM_MULTILANG);
3247 if ($cleaned === '') {
3248 return get_string('required');
3250 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3251 return true;
3252 } else {
3253 return get_string('validateerror', 'admin');
3258 * Save the selected setting
3260 * @param string $data The selected value
3261 * @return string empty or error message
3263 public function write_setting($data) {
3264 global $DB, $SITE;
3265 $data = trim($data);
3266 $validated = $this->validate($data);
3267 if ($validated !== true) {
3268 return $validated;
3271 $record = new stdClass();
3272 $record->id = SITEID;
3273 $record->{$this->name} = $data;
3274 $record->timemodified = time();
3275 // update $SITE
3276 $SITE->{$this->name} = $data;
3277 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3283 * Special text editor for site description.
3285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3287 class admin_setting_special_frontpagedesc extends admin_setting {
3289 * Calls parent::__construct with specific arguments
3291 public function __construct() {
3292 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3293 editors_head_setup();
3297 * Return the current setting
3298 * @return string The current setting
3300 public function get_setting() {
3301 $site = get_site();
3302 return $site->{$this->name};
3306 * Save the new setting
3308 * @param string $data The new value to save
3309 * @return string empty or error message
3311 public function write_setting($data) {
3312 global $DB, $SITE;
3313 $record = new stdClass();
3314 $record->id = SITEID;
3315 $record->{$this->name} = $data;
3316 $record->timemodified = time();
3317 $SITE->{$this->name} = $data;
3318 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3322 * Returns XHTML for the field plus wrapping div
3324 * @param string $data The current value
3325 * @param string $query
3326 * @return string The XHTML output
3328 public function output_html($data, $query='') {
3329 global $CFG;
3331 $CFG->adminusehtmleditor = can_use_html_editor();
3332 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3334 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3340 * Administration interface for emoticon_manager settings.
3342 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3344 class admin_setting_emoticons extends admin_setting {
3347 * Calls parent::__construct with specific args
3349 public function __construct() {
3350 global $CFG;
3352 $manager = get_emoticon_manager();
3353 $defaults = $this->prepare_form_data($manager->default_emoticons());
3354 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3358 * Return the current setting(s)
3360 * @return array Current settings array
3362 public function get_setting() {
3363 global $CFG;
3365 $manager = get_emoticon_manager();
3367 $config = $this->config_read($this->name);
3368 if (is_null($config)) {
3369 return null;
3372 $config = $manager->decode_stored_config($config);
3373 if (is_null($config)) {
3374 return null;
3377 return $this->prepare_form_data($config);
3381 * Save selected settings
3383 * @param array $data Array of settings to save
3384 * @return bool
3386 public function write_setting($data) {
3388 $manager = get_emoticon_manager();
3389 $emoticons = $this->process_form_data($data);
3391 if ($emoticons === false) {
3392 return false;
3395 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3396 return ''; // success
3397 } else {
3398 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3403 * Return XHTML field(s) for options
3405 * @param array $data Array of options to set in HTML
3406 * @return string XHTML string for the fields and wrapping div(s)
3408 public function output_html($data, $query='') {
3409 global $OUTPUT;
3411 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3412 $out .= html_writer::start_tag('thead');
3413 $out .= html_writer::start_tag('tr');
3414 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3415 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3416 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3417 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3418 $out .= html_writer::tag('th', '');
3419 $out .= html_writer::end_tag('tr');
3420 $out .= html_writer::end_tag('thead');
3421 $out .= html_writer::start_tag('tbody');
3422 $i = 0;
3423 foreach($data as $field => $value) {
3424 switch ($i) {
3425 case 0:
3426 $out .= html_writer::start_tag('tr');
3427 $current_text = $value;
3428 $current_filename = '';
3429 $current_imagecomponent = '';
3430 $current_altidentifier = '';
3431 $current_altcomponent = '';
3432 case 1:
3433 $current_filename = $value;
3434 case 2:
3435 $current_imagecomponent = $value;
3436 case 3:
3437 $current_altidentifier = $value;
3438 case 4:
3439 $current_altcomponent = $value;
3442 $out .= html_writer::tag('td',
3443 html_writer::empty_tag('input',
3444 array(
3445 'type' => 'text',
3446 'class' => 'form-text',
3447 'name' => $this->get_full_name().'['.$field.']',
3448 'value' => $value,
3450 ), array('class' => 'c'.$i)
3453 if ($i == 4) {
3454 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3455 $alt = get_string($current_altidentifier, $current_altcomponent);
3456 } else {
3457 $alt = $current_text;
3459 if ($current_filename) {
3460 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3461 } else {
3462 $out .= html_writer::tag('td', '');
3464 $out .= html_writer::end_tag('tr');
3465 $i = 0;
3466 } else {
3467 $i++;
3471 $out .= html_writer::end_tag('tbody');
3472 $out .= html_writer::end_tag('table');
3473 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3474 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3476 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3480 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3482 * @see self::process_form_data()
3483 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3484 * @return array of form fields and their values
3486 protected function prepare_form_data(array $emoticons) {
3488 $form = array();
3489 $i = 0;
3490 foreach ($emoticons as $emoticon) {
3491 $form['text'.$i] = $emoticon->text;
3492 $form['imagename'.$i] = $emoticon->imagename;
3493 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3494 $form['altidentifier'.$i] = $emoticon->altidentifier;
3495 $form['altcomponent'.$i] = $emoticon->altcomponent;
3496 $i++;
3498 // add one more blank field set for new object
3499 $form['text'.$i] = '';
3500 $form['imagename'.$i] = '';
3501 $form['imagecomponent'.$i] = '';
3502 $form['altidentifier'.$i] = '';
3503 $form['altcomponent'.$i] = '';
3505 return $form;
3509 * Converts the data from admin settings form into an array of emoticon objects
3511 * @see self::prepare_form_data()
3512 * @param array $data array of admin form fields and values
3513 * @return false|array of emoticon objects
3515 protected function process_form_data(array $form) {
3517 $count = count($form); // number of form field values
3519 if ($count % 5) {
3520 // we must get five fields per emoticon object
3521 return false;
3524 $emoticons = array();
3525 for ($i = 0; $i < $count / 5; $i++) {
3526 $emoticon = new stdClass();
3527 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3528 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3529 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3530 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3531 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3533 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3534 // prevent from breaking http://url.addresses by accident
3535 $emoticon->text = '';
3538 if (strlen($emoticon->text) < 2) {
3539 // do not allow single character emoticons
3540 $emoticon->text = '';
3543 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3544 // emoticon text must contain some non-alphanumeric character to prevent
3545 // breaking HTML tags
3546 $emoticon->text = '';
3549 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3550 $emoticons[] = $emoticon;
3553 return $emoticons;
3559 * Special setting for limiting of the list of available languages.
3561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3563 class admin_setting_langlist extends admin_setting_configtext {
3565 * Calls parent::__construct with specific arguments
3567 public function __construct() {
3568 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3572 * Save the new setting
3574 * @param string $data The new setting
3575 * @return bool
3577 public function write_setting($data) {
3578 $return = parent::write_setting($data);
3579 get_string_manager()->reset_caches();
3580 return $return;
3586 * Selection of one of the recognised countries using the list
3587 * returned by {@link get_list_of_countries()}.
3589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3591 class admin_settings_country_select extends admin_setting_configselect {
3592 protected $includeall;
3593 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3594 $this->includeall = $includeall;
3595 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3599 * Lazy-load the available choices for the select box
3601 public function load_choices() {
3602 global $CFG;
3603 if (is_array($this->choices)) {
3604 return true;
3606 $this->choices = array_merge(
3607 array('0' => get_string('choosedots')),
3608 get_string_manager()->get_list_of_countries($this->includeall));
3609 return true;
3615 * admin_setting_configselect for the default number of sections in a course,
3616 * simply so we can lazy-load the choices.
3618 * @copyright 2011 The Open University
3619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3621 class admin_settings_num_course_sections extends admin_setting_configselect {
3622 public function __construct($name, $visiblename, $description, $defaultsetting) {
3623 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3626 /** Lazy-load the available choices for the select box */
3627 public function load_choices() {
3628 $max = get_config('moodlecourse', 'maxsections');
3629 if (empty($max)) {
3630 $max = 52;
3632 for ($i = 0; $i <= $max; $i++) {
3633 $this->choices[$i] = "$i";
3635 return true;
3641 * Course category selection
3643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3645 class admin_settings_coursecat_select extends admin_setting_configselect {
3647 * Calls parent::__construct with specific arguments
3649 public function __construct($name, $visiblename, $description, $defaultsetting) {
3650 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3654 * Load the available choices for the select box
3656 * @return bool
3658 public function load_choices() {
3659 global $CFG;
3660 require_once($CFG->dirroot.'/course/lib.php');
3661 if (is_array($this->choices)) {
3662 return true;
3664 $this->choices = make_categories_options();
3665 return true;
3671 * Special control for selecting days to backup
3673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3675 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3677 * Calls parent::__construct with specific arguments
3679 public function __construct() {
3680 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3681 $this->plugin = 'backup';
3685 * Load the available choices for the select box
3687 * @return bool Always returns true
3689 public function load_choices() {
3690 if (is_array($this->choices)) {
3691 return true;
3693 $this->choices = array();
3694 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3695 foreach ($days as $day) {
3696 $this->choices[$day] = get_string($day, 'calendar');
3698 return true;
3704 * Special debug setting
3706 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3708 class admin_setting_special_debug extends admin_setting_configselect {
3710 * Calls parent::__construct with specific arguments
3712 public function __construct() {
3713 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3717 * Load the available choices for the select box
3719 * @return bool
3721 public function load_choices() {
3722 if (is_array($this->choices)) {
3723 return true;
3725 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3726 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3727 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3728 DEBUG_ALL => get_string('debugall', 'admin'),
3729 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3730 return true;
3736 * Special admin control
3738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3740 class admin_setting_special_calendar_weekend extends admin_setting {
3742 * Calls parent::__construct with specific arguments
3744 public function __construct() {
3745 $name = 'calendar_weekend';
3746 $visiblename = get_string('calendar_weekend', 'admin');
3747 $description = get_string('helpweekenddays', 'admin');
3748 $default = array ('0', '6'); // Saturdays and Sundays
3749 parent::__construct($name, $visiblename, $description, $default);
3753 * Gets the current settings as an array
3755 * @return mixed Null if none, else array of settings
3757 public function get_setting() {
3758 $result = $this->config_read($this->name);
3759 if (is_null($result)) {
3760 return NULL;
3762 if ($result === '') {
3763 return array();
3765 $settings = array();
3766 for ($i=0; $i<7; $i++) {
3767 if ($result & (1 << $i)) {
3768 $settings[] = $i;
3771 return $settings;
3775 * Save the new settings
3777 * @param array $data Array of new settings
3778 * @return bool
3780 public function write_setting($data) {
3781 if (!is_array($data)) {
3782 return '';
3784 unset($data['xxxxx']);
3785 $result = 0;
3786 foreach($data as $index) {
3787 $result |= 1 << $index;
3789 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3793 * Return XHTML to display the control
3795 * @param array $data array of selected days
3796 * @param string $query
3797 * @return string XHTML for display (field + wrapping div(s)
3799 public function output_html($data, $query='') {
3800 // The order matters very much because of the implied numeric keys
3801 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3802 $return = '<table><thead><tr>';
3803 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3804 foreach($days as $index => $day) {
3805 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3807 $return .= '</tr></thead><tbody><tr>';
3808 foreach($days as $index => $day) {
3809 $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>';
3811 $return .= '</tr></tbody></table>';
3813 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3820 * Admin setting that allows a user to pick a behaviour.
3822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3824 class admin_setting_question_behaviour extends admin_setting_configselect {
3826 * @param string $name name of config variable
3827 * @param string $visiblename display name
3828 * @param string $description description
3829 * @param string $default default.
3831 public function __construct($name, $visiblename, $description, $default) {
3832 parent::__construct($name, $visiblename, $description, $default, NULL);
3836 * Load list of behaviours as choices
3837 * @return bool true => success, false => error.
3839 public function load_choices() {
3840 global $CFG;
3841 require_once($CFG->dirroot . '/question/engine/lib.php');
3842 $this->choices = question_engine::get_archetypal_behaviours();
3843 return true;
3849 * Admin setting that allows a user to pick appropriate roles for something.
3851 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3853 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
3854 /** @var array Array of capabilities which identify roles */
3855 private $types;
3858 * @param string $name Name of config variable
3859 * @param string $visiblename Display name
3860 * @param string $description Description
3861 * @param array $types Array of archetypes which identify
3862 * roles that will be enabled by default.
3864 public function __construct($name, $visiblename, $description, $types) {
3865 parent::__construct($name, $visiblename, $description, NULL, NULL);
3866 $this->types = $types;
3870 * Load roles as choices
3872 * @return bool true=>success, false=>error
3874 public function load_choices() {
3875 global $CFG, $DB;
3876 if (during_initial_install()) {
3877 return false;
3879 if (is_array($this->choices)) {
3880 return true;
3882 if ($roles = get_all_roles()) {
3883 $this->choices = array();
3884 foreach($roles as $role) {
3885 $this->choices[$role->id] = format_string($role->name);
3887 return true;
3888 } else {
3889 return false;
3894 * Return the default setting for this control
3896 * @return array Array of default settings
3898 public function get_defaultsetting() {
3899 global $CFG;
3901 if (during_initial_install()) {
3902 return null;
3904 $result = array();
3905 foreach($this->types as $archetype) {
3906 if ($caproles = get_archetype_roles($archetype)) {
3907 foreach ($caproles as $caprole) {
3908 $result[$caprole->id] = 1;
3912 return $result;
3918 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
3920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3922 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
3924 * Constructor
3925 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3926 * @param string $visiblename localised
3927 * @param string $description long localised info
3928 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
3929 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
3930 * @param int $size default field size
3932 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
3933 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
3937 * Loads the current setting and returns array
3939 * @return array Returns array value=>xx, __construct=>xx
3941 public function get_setting() {
3942 $value = parent::get_setting();
3943 $adv = $this->config_read($this->name.'_adv');
3944 if (is_null($value) or is_null($adv)) {
3945 return NULL;
3947 return array('value' => $value, 'adv' => $adv);
3951 * Saves the new settings passed in $data
3953 * @todo Add vartype handling to ensure $data is an array
3954 * @param array $data
3955 * @return mixed string or Array
3957 public function write_setting($data) {
3958 $error = parent::write_setting($data['value']);
3959 if (!$error) {
3960 $value = empty($data['adv']) ? 0 : 1;
3961 $this->config_write($this->name.'_adv', $value);
3963 return $error;
3967 * Return XHTML for the control
3969 * @param array $data Default data array
3970 * @param string $query
3971 * @return string XHTML to display control
3973 public function output_html($data, $query='') {
3974 $default = $this->get_defaultsetting();
3975 $defaultinfo = array();
3976 if (isset($default['value'])) {
3977 if ($default['value'] === '') {
3978 $defaultinfo[] = "''";
3979 } else {
3980 $defaultinfo[] = $default['value'];
3983 if (!empty($default['adv'])) {
3984 $defaultinfo[] = get_string('advanced');
3986 $defaultinfo = implode(', ', $defaultinfo);
3988 $adv = !empty($data['adv']);
3989 $return = '<div class="form-text defaultsnext">' .
3990 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
3991 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
3992 ' <input type="checkbox" class="form-checkbox" id="' .
3993 $this->get_id() . '_adv" name="' . $this->get_full_name() .
3994 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
3995 ' <label for="' . $this->get_id() . '_adv">' .
3996 get_string('advanced') . '</label></div>';
3998 return format_admin_setting($this, $this->visiblename, $return,
3999 $this->description, true, '', $defaultinfo, $query);
4005 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4007 * @copyright 2009 Petr Skoda (http://skodak.org)
4008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4010 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4013 * Constructor
4014 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4015 * @param string $visiblename localised
4016 * @param string $description long localised info
4017 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4018 * @param string $yes value used when checked
4019 * @param string $no value used when not checked
4021 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4022 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4026 * Loads the current setting and returns array
4028 * @return array Returns array value=>xx, adv=>xx
4030 public function get_setting() {
4031 $value = parent::get_setting();
4032 $adv = $this->config_read($this->name.'_adv');
4033 if (is_null($value) or is_null($adv)) {
4034 return NULL;
4036 return array('value' => $value, 'adv' => $adv);
4040 * Sets the value for the setting
4042 * Sets the value for the setting to either the yes or no values
4043 * of the object by comparing $data to yes
4045 * @param mixed $data Gets converted to str for comparison against yes value
4046 * @return string empty string or error
4048 public function write_setting($data) {
4049 $error = parent::write_setting($data['value']);
4050 if (!$error) {
4051 $value = empty($data['adv']) ? 0 : 1;
4052 $this->config_write($this->name.'_adv', $value);
4054 return $error;
4058 * Returns an XHTML checkbox field and with extra advanced cehckbox
4060 * @param string $data If $data matches yes then checkbox is checked
4061 * @param string $query
4062 * @return string XHTML field
4064 public function output_html($data, $query='') {
4065 $defaults = $this->get_defaultsetting();
4066 $defaultinfo = array();
4067 if (!is_null($defaults)) {
4068 if ((string)$defaults['value'] === $this->yes) {
4069 $defaultinfo[] = get_string('checkboxyes', 'admin');
4070 } else {
4071 $defaultinfo[] = get_string('checkboxno', 'admin');
4073 if (!empty($defaults['adv'])) {
4074 $defaultinfo[] = get_string('advanced');
4077 $defaultinfo = implode(', ', $defaultinfo);
4079 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4080 $checked = 'checked="checked"';
4081 } else {
4082 $checked = '';
4084 if (!empty($data['adv'])) {
4085 $advanced = 'checked="checked"';
4086 } else {
4087 $advanced = '';
4090 $fullname = $this->get_full_name();
4091 $novalue = s($this->no);
4092 $yesvalue = s($this->yes);
4093 $id = $this->get_id();
4094 $stradvanced = get_string('advanced');
4095 $return = <<<EOT
4096 <div class="form-checkbox defaultsnext" >
4097 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4098 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4099 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4100 <label for="{$id}_adv">$stradvanced</label>
4101 </div>
4102 EOT;
4103 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4104 true, '', $defaultinfo, $query);
4110 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4112 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4114 * @copyright 2010 Sam Hemelryk
4115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4117 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4119 * Constructor
4120 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4121 * @param string $visiblename localised
4122 * @param string $description long localised info
4123 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4124 * @param string $yes value used when checked
4125 * @param string $no value used when not checked
4127 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4128 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4132 * Loads the current setting and returns array
4134 * @return array Returns array value=>xx, adv=>xx
4136 public function get_setting() {
4137 $value = parent::get_setting();
4138 $locked = $this->config_read($this->name.'_locked');
4139 if (is_null($value) or is_null($locked)) {
4140 return NULL;
4142 return array('value' => $value, 'locked' => $locked);
4146 * Sets the value for the setting
4148 * Sets the value for the setting to either the yes or no values
4149 * of the object by comparing $data to yes
4151 * @param mixed $data Gets converted to str for comparison against yes value
4152 * @return string empty string or error
4154 public function write_setting($data) {
4155 $error = parent::write_setting($data['value']);
4156 if (!$error) {
4157 $value = empty($data['locked']) ? 0 : 1;
4158 $this->config_write($this->name.'_locked', $value);
4160 return $error;
4164 * Returns an XHTML checkbox field and with extra locked checkbox
4166 * @param string $data If $data matches yes then checkbox is checked
4167 * @param string $query
4168 * @return string XHTML field
4170 public function output_html($data, $query='') {
4171 $defaults = $this->get_defaultsetting();
4172 $defaultinfo = array();
4173 if (!is_null($defaults)) {
4174 if ((string)$defaults['value'] === $this->yes) {
4175 $defaultinfo[] = get_string('checkboxyes', 'admin');
4176 } else {
4177 $defaultinfo[] = get_string('checkboxno', 'admin');
4179 if (!empty($defaults['locked'])) {
4180 $defaultinfo[] = get_string('locked', 'admin');
4183 $defaultinfo = implode(', ', $defaultinfo);
4185 $fullname = $this->get_full_name();
4186 $novalue = s($this->no);
4187 $yesvalue = s($this->yes);
4188 $id = $this->get_id();
4190 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4191 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4192 $checkboxparams['checked'] = 'checked';
4195 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4196 if (!empty($data['locked'])) { // convert to strings before comparison
4197 $lockcheckboxparams['checked'] = 'checked';
4200 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4201 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4202 $return .= html_writer::empty_tag('input', $checkboxparams);
4203 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4204 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4205 $return .= html_writer::end_tag('div');
4206 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4212 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4216 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4218 * Calls parent::__construct with specific arguments
4220 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4221 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4225 * Loads the current setting and returns array
4227 * @return array Returns array value=>xx, adv=>xx
4229 public function get_setting() {
4230 $value = parent::get_setting();
4231 $adv = $this->config_read($this->name.'_adv');
4232 if (is_null($value) or is_null($adv)) {
4233 return NULL;
4235 return array('value' => $value, 'adv' => $adv);
4239 * Saves the new settings passed in $data
4241 * @todo Add vartype handling to ensure $data is an array
4242 * @param array $data
4243 * @return mixed string or Array
4245 public function write_setting($data) {
4246 $error = parent::write_setting($data['value']);
4247 if (!$error) {
4248 $value = empty($data['adv']) ? 0 : 1;
4249 $this->config_write($this->name.'_adv', $value);
4251 return $error;
4255 * Return XHTML for the control
4257 * @param array $data Default data array
4258 * @param string $query
4259 * @return string XHTML to display control
4261 public function output_html($data, $query='') {
4262 $default = $this->get_defaultsetting();
4263 $current = $this->get_setting();
4265 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4266 $current['value'], $default['value'], '[value]');
4267 if (!$selecthtml) {
4268 return '';
4271 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4272 $defaultinfo = array();
4273 if (isset($this->choices[$default['value']])) {
4274 $defaultinfo[] = $this->choices[$default['value']];
4276 if (!empty($default['adv'])) {
4277 $defaultinfo[] = get_string('advanced');
4279 $defaultinfo = implode(', ', $defaultinfo);
4280 } else {
4281 $defaultinfo = '';
4284 $adv = !empty($data['adv']);
4285 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4286 ' <input type="checkbox" class="form-checkbox" id="' .
4287 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4288 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4289 ' <label for="' . $this->get_id() . '_adv">' .
4290 get_string('advanced') . '</label></div>';
4292 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4298 * Graded roles in gradebook
4300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4302 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4304 * Calls parent::__construct with specific arguments
4306 public function __construct() {
4307 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4308 get_string('configgradebookroles', 'admin'),
4309 array('student'));
4316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4318 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4320 * Saves the new settings passed in $data
4322 * @param string $data
4323 * @return mixed string or Array
4325 public function write_setting($data) {
4326 global $CFG, $DB;
4328 $oldvalue = $this->config_read($this->name);
4329 $return = parent::write_setting($data);
4330 $newvalue = $this->config_read($this->name);
4332 if ($oldvalue !== $newvalue) {
4333 // force full regrading
4334 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4337 return $return;
4343 * Which roles to show on course description page
4345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4347 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4349 * Calls parent::__construct with specific arguments
4351 public function __construct() {
4352 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4353 get_string('coursecontact_desc', 'admin'),
4354 array('editingteacher'));
4361 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4363 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4365 * Calls parent::__construct with specific arguments
4367 function admin_setting_special_gradelimiting() {
4368 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4369 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4373 * Force site regrading
4375 function regrade_all() {
4376 global $CFG;
4377 require_once("$CFG->libdir/gradelib.php");
4378 grade_force_site_regrading();
4382 * Saves the new settings
4384 * @param mixed $data
4385 * @return string empty string or error message
4387 function write_setting($data) {
4388 $previous = $this->get_setting();
4390 if ($previous === null) {
4391 if ($data) {
4392 $this->regrade_all();
4394 } else {
4395 if ($data != $previous) {
4396 $this->regrade_all();
4399 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4406 * Primary grade export plugin - has state tracking.
4408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4410 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4412 * Calls parent::__construct with specific arguments
4414 public function __construct() {
4415 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4416 get_string('configgradeexport', 'admin'), array(), NULL);
4420 * Load the available choices for the multicheckbox
4422 * @return bool always returns true
4424 public function load_choices() {
4425 if (is_array($this->choices)) {
4426 return true;
4428 $this->choices = array();
4430 if ($plugins = get_plugin_list('gradeexport')) {
4431 foreach($plugins as $plugin => $unused) {
4432 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4435 return true;
4441 * Grade category settings
4443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4445 class admin_setting_gradecat_combo extends admin_setting {
4446 /** @var array Array of choices */
4447 public $choices;
4450 * Sets choices and calls parent::__construct with passed arguments
4451 * @param string $name
4452 * @param string $visiblename
4453 * @param string $description
4454 * @param mixed $defaultsetting string or array depending on implementation
4455 * @param array $choices An array of choices for the control
4457 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4458 $this->choices = $choices;
4459 parent::__construct($name, $visiblename, $description, $defaultsetting);
4463 * Return the current setting(s) array
4465 * @return array Array of value=>xx, forced=>xx, adv=>xx
4467 public function get_setting() {
4468 global $CFG;
4470 $value = $this->config_read($this->name);
4471 $flag = $this->config_read($this->name.'_flag');
4473 if (is_null($value) or is_null($flag)) {
4474 return NULL;
4477 $flag = (int)$flag;
4478 $forced = (boolean)(1 & $flag); // first bit
4479 $adv = (boolean)(2 & $flag); // second bit
4481 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4485 * Save the new settings passed in $data
4487 * @todo Add vartype handling to ensure $data is array
4488 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4489 * @return string empty or error message
4491 public function write_setting($data) {
4492 global $CFG;
4494 $value = $data['value'];
4495 $forced = empty($data['forced']) ? 0 : 1;
4496 $adv = empty($data['adv']) ? 0 : 2;
4497 $flag = ($forced | $adv); //bitwise or
4499 if (!in_array($value, array_keys($this->choices))) {
4500 return 'Error setting ';
4503 $oldvalue = $this->config_read($this->name);
4504 $oldflag = (int)$this->config_read($this->name.'_flag');
4505 $oldforced = (1 & $oldflag); // first bit
4507 $result1 = $this->config_write($this->name, $value);
4508 $result2 = $this->config_write($this->name.'_flag', $flag);
4510 // force regrade if needed
4511 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4512 require_once($CFG->libdir.'/gradelib.php');
4513 grade_category::updated_forced_settings();
4516 if ($result1 and $result2) {
4517 return '';
4518 } else {
4519 return get_string('errorsetting', 'admin');
4524 * Return XHTML to display the field and wrapping div
4526 * @todo Add vartype handling to ensure $data is array
4527 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4528 * @param string $query
4529 * @return string XHTML to display control
4531 public function output_html($data, $query='') {
4532 $value = $data['value'];
4533 $forced = !empty($data['forced']);
4534 $adv = !empty($data['adv']);
4536 $default = $this->get_defaultsetting();
4537 if (!is_null($default)) {
4538 $defaultinfo = array();
4539 if (isset($this->choices[$default['value']])) {
4540 $defaultinfo[] = $this->choices[$default['value']];
4542 if (!empty($default['forced'])) {
4543 $defaultinfo[] = get_string('force');
4545 if (!empty($default['adv'])) {
4546 $defaultinfo[] = get_string('advanced');
4548 $defaultinfo = implode(', ', $defaultinfo);
4550 } else {
4551 $defaultinfo = NULL;
4555 $return = '<div class="form-group">';
4556 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4557 foreach ($this->choices as $key => $val) {
4558 // the string cast is needed because key may be integer - 0 is equal to most strings!
4559 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4561 $return .= '</select>';
4562 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4563 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4564 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4565 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4566 $return .= '</div>';
4568 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4574 * Selection of grade report in user profiles
4576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4578 class admin_setting_grade_profilereport extends admin_setting_configselect {
4580 * Calls parent::__construct with specific arguments
4582 public function __construct() {
4583 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4587 * Loads an array of choices for the configselect control
4589 * @return bool always return true
4591 public function load_choices() {
4592 if (is_array($this->choices)) {
4593 return true;
4595 $this->choices = array();
4597 global $CFG;
4598 require_once($CFG->libdir.'/gradelib.php');
4600 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4601 if (file_exists($plugindir.'/lib.php')) {
4602 require_once($plugindir.'/lib.php');
4603 $functionname = 'grade_report_'.$plugin.'_profilereport';
4604 if (function_exists($functionname)) {
4605 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4609 return true;
4615 * Special class for register auth selection
4617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4619 class admin_setting_special_registerauth extends admin_setting_configselect {
4621 * Calls parent::__construct with specific arguments
4623 public function __construct() {
4624 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4628 * Returns the default option
4630 * @return string empty or default option
4632 public function get_defaultsetting() {
4633 $this->load_choices();
4634 $defaultsetting = parent::get_defaultsetting();
4635 if (array_key_exists($defaultsetting, $this->choices)) {
4636 return $defaultsetting;
4637 } else {
4638 return '';
4643 * Loads the possible choices for the array
4645 * @return bool always returns true
4647 public function load_choices() {
4648 global $CFG;
4650 if (is_array($this->choices)) {
4651 return true;
4653 $this->choices = array();
4654 $this->choices[''] = get_string('disable');
4656 $authsenabled = get_enabled_auth_plugins(true);
4658 foreach ($authsenabled as $auth) {
4659 $authplugin = get_auth_plugin($auth);
4660 if (!$authplugin->can_signup()) {
4661 continue;
4663 // Get the auth title (from core or own auth lang files)
4664 $authtitle = $authplugin->get_title();
4665 $this->choices[$auth] = $authtitle;
4667 return true;
4673 * General plugins manager
4675 class admin_page_pluginsoverview extends admin_externalpage {
4678 * Sets basic information about the external page
4680 public function __construct() {
4681 global $CFG;
4682 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4683 "$CFG->wwwroot/$CFG->admin/plugins.php");
4688 * Module manage page
4690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4692 class admin_page_managemods extends admin_externalpage {
4694 * Calls parent::__construct with specific arguments
4696 public function __construct() {
4697 global $CFG;
4698 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4702 * Try to find the specified module
4704 * @param string $query The module to search for
4705 * @return array
4707 public function search($query) {
4708 global $CFG, $DB;
4709 if ($result = parent::search($query)) {
4710 return $result;
4713 $found = false;
4714 if ($modules = $DB->get_records('modules')) {
4715 foreach ($modules as $module) {
4716 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4717 continue;
4719 if (strpos($module->name, $query) !== false) {
4720 $found = true;
4721 break;
4723 $strmodulename = get_string('modulename', $module->name);
4724 if (strpos(textlib::strtolower($strmodulename), $query) !== false) {
4725 $found = true;
4726 break;
4730 if ($found) {
4731 $result = new stdClass();
4732 $result->page = $this;
4733 $result->settings = array();
4734 return array($this->name => $result);
4735 } else {
4736 return array();
4743 * Special class for enrol plugins management.
4745 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4746 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4748 class admin_setting_manageenrols extends admin_setting {
4750 * Calls parent::__construct with specific arguments
4752 public function __construct() {
4753 $this->nosave = true;
4754 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4758 * Always returns true, does nothing
4760 * @return true
4762 public function get_setting() {
4763 return true;
4767 * Always returns true, does nothing
4769 * @return true
4771 public function get_defaultsetting() {
4772 return true;
4776 * Always returns '', does not write anything
4778 * @return string Always returns ''
4780 public function write_setting($data) {
4781 // do not write any setting
4782 return '';
4786 * Checks if $query is one of the available enrol plugins
4788 * @param string $query The string to search for
4789 * @return bool Returns true if found, false if not
4791 public function is_related($query) {
4792 if (parent::is_related($query)) {
4793 return true;
4796 $query = textlib::strtolower($query);
4797 $enrols = enrol_get_plugins(false);
4798 foreach ($enrols as $name=>$enrol) {
4799 $localised = get_string('pluginname', 'enrol_'.$name);
4800 if (strpos(textlib::strtolower($name), $query) !== false) {
4801 return true;
4803 if (strpos(textlib::strtolower($localised), $query) !== false) {
4804 return true;
4807 return false;
4811 * Builds the XHTML to display the control
4813 * @param string $data Unused
4814 * @param string $query
4815 * @return string
4817 public function output_html($data, $query='') {
4818 global $CFG, $OUTPUT, $DB;
4820 // display strings
4821 $strup = get_string('up');
4822 $strdown = get_string('down');
4823 $strsettings = get_string('settings');
4824 $strenable = get_string('enable');
4825 $strdisable = get_string('disable');
4826 $struninstall = get_string('uninstallplugin', 'admin');
4827 $strusage = get_string('enrolusage', 'enrol');
4829 $enrols_available = enrol_get_plugins(false);
4830 $active_enrols = enrol_get_plugins(true);
4832 $allenrols = array();
4833 foreach ($active_enrols as $key=>$enrol) {
4834 $allenrols[$key] = true;
4836 foreach ($enrols_available as $key=>$enrol) {
4837 $allenrols[$key] = true;
4839 // now find all borked plugins and at least allow then to uninstall
4840 $borked = array();
4841 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
4842 foreach ($condidates as $candidate) {
4843 if (empty($allenrols[$candidate])) {
4844 $allenrols[$candidate] = true;
4848 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
4849 $return .= $OUTPUT->box_start('generalbox enrolsui');
4851 $table = new html_table();
4852 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
4853 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
4854 $table->width = '90%';
4855 $table->data = array();
4857 // iterate through enrol plugins and add to the display table
4858 $updowncount = 1;
4859 $enrolcount = count($active_enrols);
4860 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
4861 $printed = array();
4862 foreach($allenrols as $enrol => $unused) {
4863 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
4864 $name = get_string('pluginname', 'enrol_'.$enrol);
4865 } else {
4866 $name = $enrol;
4868 //usage
4869 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
4870 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
4871 $usage = "$ci / $cp";
4873 // hide/show link
4874 if (isset($active_enrols[$enrol])) {
4875 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
4876 $hideshow = "<a href=\"$aurl\">";
4877 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
4878 $enabled = true;
4879 $displayname = "<span>$name</span>";
4880 } else if (isset($enrols_available[$enrol])) {
4881 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
4882 $hideshow = "<a href=\"$aurl\">";
4883 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
4884 $enabled = false;
4885 $displayname = "<span class=\"dimmed_text\">$name</span>";
4886 } else {
4887 $hideshow = '';
4888 $enabled = false;
4889 $displayname = '<span class="notifyproblem">'.$name.'</span>';
4892 // up/down link (only if enrol is enabled)
4893 $updown = '';
4894 if ($enabled) {
4895 if ($updowncount > 1) {
4896 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
4897 $updown .= "<a href=\"$aurl\">";
4898 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
4899 } else {
4900 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
4902 if ($updowncount < $enrolcount) {
4903 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
4904 $updown .= "<a href=\"$aurl\">";
4905 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
4906 } else {
4907 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
4909 ++$updowncount;
4912 // settings link
4913 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
4914 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
4915 $settings = "<a href=\"$surl\">$strsettings</a>";
4916 } else {
4917 $settings = '';
4920 // uninstall
4921 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
4922 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
4924 // add a row to the table
4925 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
4927 $printed[$enrol] = true;
4930 $return .= html_writer::table($table);
4931 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
4932 $return .= $OUTPUT->box_end();
4933 return highlight($query, $return);
4939 * Blocks manage page
4941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4943 class admin_page_manageblocks extends admin_externalpage {
4945 * Calls parent::__construct with specific arguments
4947 public function __construct() {
4948 global $CFG;
4949 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
4953 * Search for a specific block
4955 * @param string $query The string to search for
4956 * @return array
4958 public function search($query) {
4959 global $CFG, $DB;
4960 if ($result = parent::search($query)) {
4961 return $result;
4964 $found = false;
4965 if ($blocks = $DB->get_records('block')) {
4966 foreach ($blocks as $block) {
4967 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
4968 continue;
4970 if (strpos($block->name, $query) !== false) {
4971 $found = true;
4972 break;
4974 $strblockname = get_string('pluginname', 'block_'.$block->name);
4975 if (strpos(textlib::strtolower($strblockname), $query) !== false) {
4976 $found = true;
4977 break;
4981 if ($found) {
4982 $result = new stdClass();
4983 $result->page = $this;
4984 $result->settings = array();
4985 return array($this->name => $result);
4986 } else {
4987 return array();
4993 * Message outputs configuration
4995 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4997 class admin_page_managemessageoutputs extends admin_externalpage {
4999 * Calls parent::__construct with specific arguments
5001 public function __construct() {
5002 global $CFG;
5003 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5007 * Search for a specific message processor
5009 * @param string $query The string to search for
5010 * @return array
5012 public function search($query) {
5013 global $CFG, $DB;
5014 if ($result = parent::search($query)) {
5015 return $result;
5018 $found = false;
5019 if ($processors = get_message_processors()) {
5020 foreach ($processors as $processor) {
5021 if (!$processor->available) {
5022 continue;
5024 if (strpos($processor->name, $query) !== false) {
5025 $found = true;
5026 break;
5028 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5029 if (strpos(textlib::strtolower($strprocessorname), $query) !== false) {
5030 $found = true;
5031 break;
5035 if ($found) {
5036 $result = new stdClass();
5037 $result->page = $this;
5038 $result->settings = array();
5039 return array($this->name => $result);
5040 } else {
5041 return array();
5047 * Default message outputs configuration
5049 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5051 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5053 * Calls parent::__construct with specific arguments
5055 public function __construct() {
5056 global $CFG;
5057 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5063 * Manage question behaviours page
5065 * @copyright 2011 The Open University
5066 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5068 class admin_page_manageqbehaviours extends admin_externalpage {
5070 * Constructor
5072 public function __construct() {
5073 global $CFG;
5074 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5075 new moodle_url('/admin/qbehaviours.php'));
5079 * Search question behaviours for the specified string
5081 * @param string $query The string to search for in question behaviours
5082 * @return array
5084 public function search($query) {
5085 global $CFG;
5086 if ($result = parent::search($query)) {
5087 return $result;
5090 $found = false;
5091 require_once($CFG->dirroot . '/question/engine/lib.php');
5092 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5093 if (strpos(textlib::strtolower(question_engine::get_behaviour_name($behaviour)),
5094 $query) !== false) {
5095 $found = true;
5096 break;
5099 if ($found) {
5100 $result = new stdClass();
5101 $result->page = $this;
5102 $result->settings = array();
5103 return array($this->name => $result);
5104 } else {
5105 return array();
5112 * Question type manage page
5114 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5116 class admin_page_manageqtypes extends admin_externalpage {
5118 * Calls parent::__construct with specific arguments
5120 public function __construct() {
5121 global $CFG;
5122 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5126 * Search question types for the specified string
5128 * @param string $query The string to search for in question types
5129 * @return array
5131 public function search($query) {
5132 global $CFG;
5133 if ($result = parent::search($query)) {
5134 return $result;
5137 $found = false;
5138 require_once($CFG->dirroot . '/question/engine/bank.php');
5139 foreach (question_bank::get_all_qtypes() as $qtype) {
5140 if (strpos(textlib::strtolower($qtype->local_name()), $query) !== false) {
5141 $found = true;
5142 break;
5145 if ($found) {
5146 $result = new stdClass();
5147 $result->page = $this;
5148 $result->settings = array();
5149 return array($this->name => $result);
5150 } else {
5151 return array();
5157 class admin_page_manageportfolios extends admin_externalpage {
5159 * Calls parent::__construct with specific arguments
5161 public function __construct() {
5162 global $CFG;
5163 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5164 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5168 * Searches page for the specified string.
5169 * @param string $query The string to search for
5170 * @return bool True if it is found on this page
5172 public function search($query) {
5173 global $CFG;
5174 if ($result = parent::search($query)) {
5175 return $result;
5178 $found = false;
5179 $portfolios = get_plugin_list('portfolio');
5180 foreach ($portfolios as $p => $dir) {
5181 if (strpos($p, $query) !== false) {
5182 $found = true;
5183 break;
5186 if (!$found) {
5187 foreach (portfolio_instances(false, false) as $instance) {
5188 $title = $instance->get('name');
5189 if (strpos(textlib::strtolower($title), $query) !== false) {
5190 $found = true;
5191 break;
5196 if ($found) {
5197 $result = new stdClass();
5198 $result->page = $this;
5199 $result->settings = array();
5200 return array($this->name => $result);
5201 } else {
5202 return array();
5208 class admin_page_managerepositories extends admin_externalpage {
5210 * Calls parent::__construct with specific arguments
5212 public function __construct() {
5213 global $CFG;
5214 parent::__construct('managerepositories', get_string('manage',
5215 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5219 * Searches page for the specified string.
5220 * @param string $query The string to search for
5221 * @return bool True if it is found on this page
5223 public function search($query) {
5224 global $CFG;
5225 if ($result = parent::search($query)) {
5226 return $result;
5229 $found = false;
5230 $repositories= get_plugin_list('repository');
5231 foreach ($repositories as $p => $dir) {
5232 if (strpos($p, $query) !== false) {
5233 $found = true;
5234 break;
5237 if (!$found) {
5238 foreach (repository::get_types() as $instance) {
5239 $title = $instance->get_typename();
5240 if (strpos(textlib::strtolower($title), $query) !== false) {
5241 $found = true;
5242 break;
5247 if ($found) {
5248 $result = new stdClass();
5249 $result->page = $this;
5250 $result->settings = array();
5251 return array($this->name => $result);
5252 } else {
5253 return array();
5260 * Special class for authentication administration.
5262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5264 class admin_setting_manageauths extends admin_setting {
5266 * Calls parent::__construct with specific arguments
5268 public function __construct() {
5269 $this->nosave = true;
5270 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5274 * Always returns true
5276 * @return true
5278 public function get_setting() {
5279 return true;
5283 * Always returns true
5285 * @return true
5287 public function get_defaultsetting() {
5288 return true;
5292 * Always returns '' and doesn't write anything
5294 * @return string Always returns ''
5296 public function write_setting($data) {
5297 // do not write any setting
5298 return '';
5302 * Search to find if Query is related to auth plugin
5304 * @param string $query The string to search for
5305 * @return bool true for related false for not
5307 public function is_related($query) {
5308 if (parent::is_related($query)) {
5309 return true;
5312 $authsavailable = get_plugin_list('auth');
5313 foreach ($authsavailable as $auth => $dir) {
5314 if (strpos($auth, $query) !== false) {
5315 return true;
5317 $authplugin = get_auth_plugin($auth);
5318 $authtitle = $authplugin->get_title();
5319 if (strpos(textlib::strtolower($authtitle), $query) !== false) {
5320 return true;
5323 return false;
5327 * Return XHTML to display control
5329 * @param mixed $data Unused
5330 * @param string $query
5331 * @return string highlight
5333 public function output_html($data, $query='') {
5334 global $CFG, $OUTPUT;
5337 // display strings
5338 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5339 'settings', 'edit', 'name', 'enable', 'disable',
5340 'up', 'down', 'none'));
5341 $txt->updown = "$txt->up/$txt->down";
5343 $authsavailable = get_plugin_list('auth');
5344 get_enabled_auth_plugins(true); // fix the list of enabled auths
5345 if (empty($CFG->auth)) {
5346 $authsenabled = array();
5347 } else {
5348 $authsenabled = explode(',', $CFG->auth);
5351 // construct the display array, with enabled auth plugins at the top, in order
5352 $displayauths = array();
5353 $registrationauths = array();
5354 $registrationauths[''] = $txt->disable;
5355 foreach ($authsenabled as $auth) {
5356 $authplugin = get_auth_plugin($auth);
5357 /// Get the auth title (from core or own auth lang files)
5358 $authtitle = $authplugin->get_title();
5359 /// Apply titles
5360 $displayauths[$auth] = $authtitle;
5361 if ($authplugin->can_signup()) {
5362 $registrationauths[$auth] = $authtitle;
5366 foreach ($authsavailable as $auth => $dir) {
5367 if (array_key_exists($auth, $displayauths)) {
5368 continue; //already in the list
5370 $authplugin = get_auth_plugin($auth);
5371 /// Get the auth title (from core or own auth lang files)
5372 $authtitle = $authplugin->get_title();
5373 /// Apply titles
5374 $displayauths[$auth] = $authtitle;
5375 if ($authplugin->can_signup()) {
5376 $registrationauths[$auth] = $authtitle;
5380 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5381 $return .= $OUTPUT->box_start('generalbox authsui');
5383 $table = new html_table();
5384 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5385 $table->align = array('left', 'center', 'center', 'center');
5386 $table->data = array();
5387 $table->attributes['class'] = 'manageauthtable generaltable';
5389 //add always enabled plugins first
5390 $displayname = "<span>".$displayauths['manual']."</span>";
5391 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5392 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5393 $table->data[] = array($displayname, '', '', $settings);
5394 $displayname = "<span>".$displayauths['nologin']."</span>";
5395 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5396 $table->data[] = array($displayname, '', '', $settings);
5399 // iterate through auth plugins and add to the display table
5400 $updowncount = 1;
5401 $authcount = count($authsenabled);
5402 $url = "auth.php?sesskey=" . sesskey();
5403 foreach ($displayauths as $auth => $name) {
5404 if ($auth == 'manual' or $auth == 'nologin') {
5405 continue;
5407 // hide/show link
5408 if (in_array($auth, $authsenabled)) {
5409 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5410 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5411 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5412 $enabled = true;
5413 $displayname = "<span>$name</span>";
5415 else {
5416 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5417 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5418 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5419 $enabled = false;
5420 $displayname = "<span class=\"dimmed_text\">$name</span>";
5423 // up/down link (only if auth is enabled)
5424 $updown = '';
5425 if ($enabled) {
5426 if ($updowncount > 1) {
5427 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5428 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5430 else {
5431 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5433 if ($updowncount < $authcount) {
5434 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5435 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5437 else {
5438 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5440 ++ $updowncount;
5443 // settings link
5444 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5445 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5446 } else {
5447 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5450 // add a row to the table
5451 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5453 $return .= html_writer::table($table);
5454 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5455 $return .= $OUTPUT->box_end();
5456 return highlight($query, $return);
5462 * Special class for authentication administration.
5464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5466 class admin_setting_manageeditors extends admin_setting {
5468 * Calls parent::__construct with specific arguments
5470 public function __construct() {
5471 $this->nosave = true;
5472 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5476 * Always returns true, does nothing
5478 * @return true
5480 public function get_setting() {
5481 return true;
5485 * Always returns true, does nothing
5487 * @return true
5489 public function get_defaultsetting() {
5490 return true;
5494 * Always returns '', does not write anything
5496 * @return string Always returns ''
5498 public function write_setting($data) {
5499 // do not write any setting
5500 return '';
5504 * Checks if $query is one of the available editors
5506 * @param string $query The string to search for
5507 * @return bool Returns true if found, false if not
5509 public function is_related($query) {
5510 if (parent::is_related($query)) {
5511 return true;
5514 $editors_available = editors_get_available();
5515 foreach ($editors_available as $editor=>$editorstr) {
5516 if (strpos($editor, $query) !== false) {
5517 return true;
5519 if (strpos(textlib::strtolower($editorstr), $query) !== false) {
5520 return true;
5523 return false;
5527 * Builds the XHTML to display the control
5529 * @param string $data Unused
5530 * @param string $query
5531 * @return string
5533 public function output_html($data, $query='') {
5534 global $CFG, $OUTPUT;
5536 // display strings
5537 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5538 'up', 'down', 'none'));
5539 $txt->updown = "$txt->up/$txt->down";
5541 $editors_available = editors_get_available();
5542 $active_editors = explode(',', $CFG->texteditors);
5544 $active_editors = array_reverse($active_editors);
5545 foreach ($active_editors as $key=>$editor) {
5546 if (empty($editors_available[$editor])) {
5547 unset($active_editors[$key]);
5548 } else {
5549 $name = $editors_available[$editor];
5550 unset($editors_available[$editor]);
5551 $editors_available[$editor] = $name;
5554 if (empty($active_editors)) {
5555 //$active_editors = array('textarea');
5557 $editors_available = array_reverse($editors_available, true);
5558 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5559 $return .= $OUTPUT->box_start('generalbox editorsui');
5561 $table = new html_table();
5562 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5563 $table->align = array('left', 'center', 'center', 'center');
5564 $table->width = '90%';
5565 $table->data = array();
5567 // iterate through auth plugins and add to the display table
5568 $updowncount = 1;
5569 $editorcount = count($active_editors);
5570 $url = "editors.php?sesskey=" . sesskey();
5571 foreach ($editors_available as $editor => $name) {
5572 // hide/show link
5573 if (in_array($editor, $active_editors)) {
5574 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5575 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5576 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5577 $enabled = true;
5578 $displayname = "<span>$name</span>";
5580 else {
5581 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5582 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5583 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5584 $enabled = false;
5585 $displayname = "<span class=\"dimmed_text\">$name</span>";
5588 // up/down link (only if auth is enabled)
5589 $updown = '';
5590 if ($enabled) {
5591 if ($updowncount > 1) {
5592 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5593 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5595 else {
5596 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5598 if ($updowncount < $editorcount) {
5599 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5600 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5602 else {
5603 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5605 ++ $updowncount;
5608 // settings link
5609 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5610 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5611 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5612 } else {
5613 $settings = '';
5616 // add a row to the table
5617 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5619 $return .= html_writer::table($table);
5620 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5621 $return .= $OUTPUT->box_end();
5622 return highlight($query, $return);
5628 * Special class for license administration.
5630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5632 class admin_setting_managelicenses extends admin_setting {
5634 * Calls parent::__construct with specific arguments
5636 public function __construct() {
5637 $this->nosave = true;
5638 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5642 * Always returns true, does nothing
5644 * @return true
5646 public function get_setting() {
5647 return true;
5651 * Always returns true, does nothing
5653 * @return true
5655 public function get_defaultsetting() {
5656 return true;
5660 * Always returns '', does not write anything
5662 * @return string Always returns ''
5664 public function write_setting($data) {
5665 // do not write any setting
5666 return '';
5670 * Builds the XHTML to display the control
5672 * @param string $data Unused
5673 * @param string $query
5674 * @return string
5676 public function output_html($data, $query='') {
5677 global $CFG, $OUTPUT;
5678 require_once($CFG->libdir . '/licenselib.php');
5679 $url = "licenses.php?sesskey=" . sesskey();
5681 // display strings
5682 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5683 $licenses = license_manager::get_licenses();
5685 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5687 $return .= $OUTPUT->box_start('generalbox editorsui');
5689 $table = new html_table();
5690 $table->head = array($txt->name, $txt->enable);
5691 $table->align = array('left', 'center');
5692 $table->width = '100%';
5693 $table->data = array();
5695 foreach ($licenses as $value) {
5696 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5698 if ($value->enabled == 1) {
5699 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5700 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5701 } else {
5702 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5703 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5706 if ($value->shortname == $CFG->sitedefaultlicense) {
5707 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5708 $hideshow = '';
5711 $enabled = true;
5713 $table->data[] =array($displayname, $hideshow);
5715 $return .= html_writer::table($table);
5716 $return .= $OUTPUT->box_end();
5717 return highlight($query, $return);
5723 * Special class for filter administration.
5725 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5727 class admin_page_managefilters extends admin_externalpage {
5729 * Calls parent::__construct with specific arguments
5731 public function __construct() {
5732 global $CFG;
5733 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5737 * Searches all installed filters for specified filter
5739 * @param string $query The filter(string) to search for
5740 * @param string $query
5742 public function search($query) {
5743 global $CFG;
5744 if ($result = parent::search($query)) {
5745 return $result;
5748 $found = false;
5749 $filternames = filter_get_all_installed();
5750 foreach ($filternames as $path => $strfiltername) {
5751 if (strpos(textlib::strtolower($strfiltername), $query) !== false) {
5752 $found = true;
5753 break;
5755 list($type, $filter) = explode('/', $path);
5756 if (strpos($filter, $query) !== false) {
5757 $found = true;
5758 break;
5762 if ($found) {
5763 $result = new stdClass;
5764 $result->page = $this;
5765 $result->settings = array();
5766 return array($this->name => $result);
5767 } else {
5768 return array();
5775 * Initialise admin page - this function does require login and permission
5776 * checks specified in page definition.
5778 * This function must be called on each admin page before other code.
5780 * @global moodle_page $PAGE
5782 * @param string $section name of page
5783 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5784 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5785 * added to the turn blocks editing on/off form, so this page reloads correctly.
5786 * @param string $actualurl if the actual page being viewed is not the normal one for this
5787 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5788 * @param array $options Additional options that can be specified for page setup.
5789 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5791 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5792 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5794 $PAGE->set_context(null); // hack - set context to something, by default to system context
5796 $site = get_site();
5797 require_login();
5799 if (!empty($options['pagelayout'])) {
5800 // A specific page layout has been requested.
5801 $PAGE->set_pagelayout($options['pagelayout']);
5802 } else if ($section === 'upgradesettings') {
5803 $PAGE->set_pagelayout('maintenance');
5804 } else {
5805 $PAGE->set_pagelayout('admin');
5808 $adminroot = admin_get_root(false, false); // settings not required for external pages
5809 $extpage = $adminroot->locate($section, true);
5811 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5812 // The requested section isn't in the admin tree
5813 // It could be because the user has inadequate capapbilities or because the section doesn't exist
5814 if (!has_capability('moodle/site:config', context_system::instance())) {
5815 // The requested section could depend on a different capability
5816 // but most likely the user has inadequate capabilities
5817 print_error('accessdenied', 'admin');
5818 } else {
5819 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5823 // this eliminates our need to authenticate on the actual pages
5824 if (!$extpage->check_access()) {
5825 print_error('accessdenied', 'admin');
5826 die;
5829 // $PAGE->set_extra_button($extrabutton); TODO
5831 if (!$actualurl) {
5832 $actualurl = $extpage->url;
5835 $PAGE->set_url($actualurl, $extraurlparams);
5836 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5837 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
5840 if (empty($SITE->fullname) || empty($SITE->shortname)) {
5841 // During initial install.
5842 $strinstallation = get_string('installation', 'install');
5843 $strsettings = get_string('settings');
5844 $PAGE->navbar->add($strsettings);
5845 $PAGE->set_title($strinstallation);
5846 $PAGE->set_heading($strinstallation);
5847 $PAGE->set_cacheable(false);
5848 return;
5851 // Locate the current item on the navigation and make it active when found.
5852 $path = $extpage->path;
5853 $node = $PAGE->settingsnav;
5854 while ($node && count($path) > 0) {
5855 $node = $node->get(array_pop($path));
5857 if ($node) {
5858 $node->make_active();
5861 // Normal case.
5862 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
5863 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
5864 $USER->editing = $adminediting;
5867 $visiblepathtosection = array_reverse($extpage->visiblepath);
5869 if ($PAGE->user_allowed_editing()) {
5870 if ($PAGE->user_is_editing()) {
5871 $caption = get_string('blockseditoff');
5872 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
5873 } else {
5874 $caption = get_string('blocksediton');
5875 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
5877 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
5880 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
5881 $PAGE->set_heading($SITE->fullname);
5883 // prevent caching in nav block
5884 $PAGE->navigation->clear_cache();
5888 * Returns the reference to admin tree root
5890 * @return object admin_root object
5892 function admin_get_root($reload=false, $requirefulltree=true) {
5893 global $CFG, $DB, $OUTPUT;
5895 static $ADMIN = NULL;
5897 if (is_null($ADMIN)) {
5898 // create the admin tree!
5899 $ADMIN = new admin_root($requirefulltree);
5902 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
5903 $ADMIN->purge_children($requirefulltree);
5906 if (!$ADMIN->loaded) {
5907 // we process this file first to create categories first and in correct order
5908 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
5910 // now we process all other files in admin/settings to build the admin tree
5911 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
5912 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
5913 continue;
5915 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
5916 // plugins are loaded last - they may insert pages anywhere
5917 continue;
5919 require($file);
5921 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
5923 $ADMIN->loaded = true;
5926 return $ADMIN;
5929 /// settings utility functions
5932 * This function applies default settings.
5934 * @param object $node, NULL means complete tree, null by default
5935 * @param bool $unconditional if true overrides all values with defaults, null buy default
5937 function admin_apply_default_settings($node=NULL, $unconditional=true) {
5938 global $CFG;
5940 if (is_null($node)) {
5941 $node = admin_get_root(true, true);
5944 if ($node instanceof admin_category) {
5945 $entries = array_keys($node->children);
5946 foreach ($entries as $entry) {
5947 admin_apply_default_settings($node->children[$entry], $unconditional);
5950 } else if ($node instanceof admin_settingpage) {
5951 foreach ($node->settings as $setting) {
5952 if (!$unconditional and !is_null($setting->get_setting())) {
5953 //do not override existing defaults
5954 continue;
5956 $defaultsetting = $setting->get_defaultsetting();
5957 if (is_null($defaultsetting)) {
5958 // no value yet - default maybe applied after admin user creation or in upgradesettings
5959 continue;
5961 $setting->write_setting($defaultsetting);
5967 * Store changed settings, this function updates the errors variable in $ADMIN
5969 * @param object $formdata from form
5970 * @return int number of changed settings
5972 function admin_write_settings($formdata) {
5973 global $CFG, $SITE, $DB;
5975 $olddbsessions = !empty($CFG->dbsessions);
5976 $formdata = (array)$formdata;
5978 $data = array();
5979 foreach ($formdata as $fullname=>$value) {
5980 if (strpos($fullname, 's_') !== 0) {
5981 continue; // not a config value
5983 $data[$fullname] = $value;
5986 $adminroot = admin_get_root();
5987 $settings = admin_find_write_settings($adminroot, $data);
5989 $count = 0;
5990 foreach ($settings as $fullname=>$setting) {
5991 $original = serialize($setting->get_setting()); // comparison must work for arrays too
5992 $error = $setting->write_setting($data[$fullname]);
5993 if ($error !== '') {
5994 $adminroot->errors[$fullname] = new stdClass();
5995 $adminroot->errors[$fullname]->data = $data[$fullname];
5996 $adminroot->errors[$fullname]->id = $setting->get_id();
5997 $adminroot->errors[$fullname]->error = $error;
5999 if ($original !== serialize($setting->get_setting())) {
6000 $count++;
6001 $callbackfunction = $setting->updatedcallback;
6002 if (function_exists($callbackfunction)) {
6003 $callbackfunction($fullname);
6008 if ($olddbsessions != !empty($CFG->dbsessions)) {
6009 require_logout();
6012 // Now update $SITE - just update the fields, in case other people have a
6013 // a reference to it (e.g. $PAGE, $COURSE).
6014 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6015 foreach (get_object_vars($newsite) as $field => $value) {
6016 $SITE->$field = $value;
6019 // now reload all settings - some of them might depend on the changed
6020 admin_get_root(true);
6021 return $count;
6025 * Internal recursive function - finds all settings from submitted form
6027 * @param object $node Instance of admin_category, or admin_settingpage
6028 * @param array $data
6029 * @return array
6031 function admin_find_write_settings($node, $data) {
6032 $return = array();
6034 if (empty($data)) {
6035 return $return;
6038 if ($node instanceof admin_category) {
6039 $entries = array_keys($node->children);
6040 foreach ($entries as $entry) {
6041 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6044 } else if ($node instanceof admin_settingpage) {
6045 foreach ($node->settings as $setting) {
6046 $fullname = $setting->get_full_name();
6047 if (array_key_exists($fullname, $data)) {
6048 $return[$fullname] = $setting;
6054 return $return;
6058 * Internal function - prints the search results
6060 * @param string $query String to search for
6061 * @return string empty or XHTML
6063 function admin_search_settings_html($query) {
6064 global $CFG, $OUTPUT;
6066 if (textlib::strlen($query) < 2) {
6067 return '';
6069 $query = textlib::strtolower($query);
6071 $adminroot = admin_get_root();
6072 $findings = $adminroot->search($query);
6073 $return = '';
6074 $savebutton = false;
6076 foreach ($findings as $found) {
6077 $page = $found->page;
6078 $settings = $found->settings;
6079 if ($page->is_hidden()) {
6080 // hidden pages are not displayed in search results
6081 continue;
6083 if ($page instanceof admin_externalpage) {
6084 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6085 } else if ($page instanceof admin_settingpage) {
6086 $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');
6087 } else {
6088 continue;
6090 if (!empty($settings)) {
6091 $return .= '<fieldset class="adminsettings">'."\n";
6092 foreach ($settings as $setting) {
6093 if (empty($setting->nosave)) {
6094 $savebutton = true;
6096 $return .= '<div class="clearer"><!-- --></div>'."\n";
6097 $fullname = $setting->get_full_name();
6098 if (array_key_exists($fullname, $adminroot->errors)) {
6099 $data = $adminroot->errors[$fullname]->data;
6100 } else {
6101 $data = $setting->get_setting();
6102 // do not use defaults if settings not available - upgradesettings handles the defaults!
6104 $return .= $setting->output_html($data, $query);
6106 $return .= '</fieldset>';
6110 if ($savebutton) {
6111 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6114 return $return;
6118 * Internal function - returns arrays of html pages with uninitialised settings
6120 * @param object $node Instance of admin_category or admin_settingpage
6121 * @return array
6123 function admin_output_new_settings_by_page($node) {
6124 global $OUTPUT;
6125 $return = array();
6127 if ($node instanceof admin_category) {
6128 $entries = array_keys($node->children);
6129 foreach ($entries as $entry) {
6130 $return += admin_output_new_settings_by_page($node->children[$entry]);
6133 } else if ($node instanceof admin_settingpage) {
6134 $newsettings = array();
6135 foreach ($node->settings as $setting) {
6136 if (is_null($setting->get_setting())) {
6137 $newsettings[] = $setting;
6140 if (count($newsettings) > 0) {
6141 $adminroot = admin_get_root();
6142 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6143 $page .= '<fieldset class="adminsettings">'."\n";
6144 foreach ($newsettings as $setting) {
6145 $fullname = $setting->get_full_name();
6146 if (array_key_exists($fullname, $adminroot->errors)) {
6147 $data = $adminroot->errors[$fullname]->data;
6148 } else {
6149 $data = $setting->get_setting();
6150 if (is_null($data)) {
6151 $data = $setting->get_defaultsetting();
6154 $page .= '<div class="clearer"><!-- --></div>'."\n";
6155 $page .= $setting->output_html($data);
6157 $page .= '</fieldset>';
6158 $return[$node->name] = $page;
6162 return $return;
6166 * Format admin settings
6168 * @param object $setting
6169 * @param string $title label element
6170 * @param string $form form fragment, html code - not highlighted automatically
6171 * @param string $description
6172 * @param bool $label link label to id, true by default
6173 * @param string $warning warning text
6174 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6175 * @param string $query search query to be highlighted
6176 * @return string XHTML
6178 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6179 global $CFG;
6181 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6182 $fullname = $setting->get_full_name();
6184 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6185 if ($label) {
6186 $labelfor = 'for = "'.$setting->get_id().'"';
6187 } else {
6188 $labelfor = '';
6191 $override = '';
6192 if (empty($setting->plugin)) {
6193 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6194 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6196 } else {
6197 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6198 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6202 if ($warning !== '') {
6203 $warning = '<div class="form-warning">'.$warning.'</div>';
6206 if (is_null($defaultinfo)) {
6207 $defaultinfo = '';
6208 } else {
6209 if ($defaultinfo === '') {
6210 $defaultinfo = get_string('emptysettingvalue', 'admin');
6212 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6213 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6217 $str = '
6218 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6219 <div class="form-label">
6220 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6221 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6222 </div>
6223 <div class="form-setting">'.$form.$defaultinfo.'</div>
6224 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6225 </div>';
6227 $adminroot = admin_get_root();
6228 if (array_key_exists($fullname, $adminroot->errors)) {
6229 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6232 return $str;
6236 * Based on find_new_settings{@link ()} in upgradesettings.php
6237 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6239 * @param object $node Instance of admin_category, or admin_settingpage
6240 * @return boolean true if any settings haven't been initialised, false if they all have
6242 function any_new_admin_settings($node) {
6244 if ($node instanceof admin_category) {
6245 $entries = array_keys($node->children);
6246 foreach ($entries as $entry) {
6247 if (any_new_admin_settings($node->children[$entry])) {
6248 return true;
6252 } else if ($node instanceof admin_settingpage) {
6253 foreach ($node->settings as $setting) {
6254 if ($setting->get_setting() === NULL) {
6255 return true;
6260 return false;
6264 * Moved from admin/replace.php so that we can use this in cron
6266 * @param string $search string to look for
6267 * @param string $replace string to replace
6268 * @return bool success or fail
6270 function db_replace($search, $replace) {
6271 global $DB, $CFG, $OUTPUT;
6273 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6274 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6275 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6276 'block_instances', '');
6278 // Turn off time limits, sometimes upgrades can be slow.
6279 @set_time_limit(0);
6281 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6282 return false;
6284 foreach ($tables as $table) {
6286 if (in_array($table, $skiptables)) { // Don't process these
6287 continue;
6290 if ($columns = $DB->get_columns($table)) {
6291 $DB->set_debug(true);
6292 foreach ($columns as $column => $data) {
6293 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6294 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6295 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6298 $DB->set_debug(false);
6302 // delete modinfo caches
6303 rebuild_course_cache(0, true);
6305 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6306 $blocks = get_plugin_list('block');
6307 foreach ($blocks as $blockname=>$fullblock) {
6308 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6309 continue;
6312 if (!is_readable($fullblock.'/lib.php')) {
6313 continue;
6316 $function = 'block_'.$blockname.'_global_db_replace';
6317 include_once($fullblock.'/lib.php');
6318 if (!function_exists($function)) {
6319 continue;
6322 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6323 $function($search, $replace);
6324 echo $OUTPUT->notification("...finished", 'notifysuccess');
6327 return true;
6331 * Manage repository settings
6333 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6335 class admin_setting_managerepository extends admin_setting {
6336 /** @var string */
6337 private $baseurl;
6340 * calls parent::__construct with specific arguments
6342 public function __construct() {
6343 global $CFG;
6344 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6345 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6349 * Always returns true, does nothing
6351 * @return true
6353 public function get_setting() {
6354 return true;
6358 * Always returns true does nothing
6360 * @return true
6362 public function get_defaultsetting() {
6363 return true;
6367 * Always returns s_managerepository
6369 * @return string Always return 's_managerepository'
6371 public function get_full_name() {
6372 return 's_managerepository';
6376 * Always returns '' doesn't do anything
6378 public function write_setting($data) {
6379 $url = $this->baseurl . '&amp;new=' . $data;
6380 return '';
6381 // TODO
6382 // Should not use redirect and exit here
6383 // Find a better way to do this.
6384 // redirect($url);
6385 // exit;
6389 * Searches repository plugins for one that matches $query
6391 * @param string $query The string to search for
6392 * @return bool true if found, false if not
6394 public function is_related($query) {
6395 if (parent::is_related($query)) {
6396 return true;
6399 $repositories= get_plugin_list('repository');
6400 foreach ($repositories as $p => $dir) {
6401 if (strpos($p, $query) !== false) {
6402 return true;
6405 foreach (repository::get_types() as $instance) {
6406 $title = $instance->get_typename();
6407 if (strpos(textlib::strtolower($title), $query) !== false) {
6408 return true;
6411 return false;
6415 * Helper function that generates a moodle_url object
6416 * relevant to the repository
6419 function repository_action_url($repository) {
6420 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6424 * Builds XHTML to display the control
6426 * @param string $data Unused
6427 * @param string $query
6428 * @return string XHTML
6430 public function output_html($data, $query='') {
6431 global $CFG, $USER, $OUTPUT;
6433 // Get strings that are used
6434 $strshow = get_string('on', 'repository');
6435 $strhide = get_string('off', 'repository');
6436 $strdelete = get_string('disabled', 'repository');
6438 $actionchoicesforexisting = array(
6439 'show' => $strshow,
6440 'hide' => $strhide,
6441 'delete' => $strdelete
6444 $actionchoicesfornew = array(
6445 'newon' => $strshow,
6446 'newoff' => $strhide,
6447 'delete' => $strdelete
6450 $return = '';
6451 $return .= $OUTPUT->box_start('generalbox');
6453 // Set strings that are used multiple times
6454 $settingsstr = get_string('settings');
6455 $disablestr = get_string('disable');
6457 // Table to list plug-ins
6458 $table = new html_table();
6459 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6460 $table->align = array('left', 'center', 'center', 'center', 'center');
6461 $table->data = array();
6463 // Get list of used plug-ins
6464 $instances = repository::get_types();
6465 if (!empty($instances)) {
6466 // Array to store plugins being used
6467 $alreadyplugins = array();
6468 $totalinstances = count($instances);
6469 $updowncount = 1;
6470 foreach ($instances as $i) {
6471 $settings = '';
6472 $typename = $i->get_typename();
6473 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6474 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6475 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6477 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6478 // Calculate number of instances in order to display them for the Moodle administrator
6479 if (!empty($instanceoptionnames)) {
6480 $params = array();
6481 $params['context'] = array(get_system_context());
6482 $params['onlyvisible'] = false;
6483 $params['type'] = $typename;
6484 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6485 // site instances
6486 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6487 $params['context'] = array();
6488 $instances = repository::static_function($typename, 'get_instances', $params);
6489 $courseinstances = array();
6490 $userinstances = array();
6492 foreach ($instances as $instance) {
6493 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6494 $courseinstances[] = $instance;
6495 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6496 $userinstances[] = $instance;
6499 // course instances
6500 $instancenumber = count($courseinstances);
6501 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6503 // user private instances
6504 $instancenumber = count($userinstances);
6505 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6506 } else {
6507 $admininstancenumbertext = "";
6508 $courseinstancenumbertext = "";
6509 $userinstancenumbertext = "";
6512 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6514 $settings .= $OUTPUT->container_start('mdl-left');
6515 $settings .= '<br/>';
6516 $settings .= $admininstancenumbertext;
6517 $settings .= '<br/>';
6518 $settings .= $courseinstancenumbertext;
6519 $settings .= '<br/>';
6520 $settings .= $userinstancenumbertext;
6521 $settings .= $OUTPUT->container_end();
6523 // Get the current visibility
6524 if ($i->get_visible()) {
6525 $currentaction = 'show';
6526 } else {
6527 $currentaction = 'hide';
6530 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6532 // Display up/down link
6533 $updown = '';
6534 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6536 if ($updowncount > 1) {
6537 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6538 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6540 else {
6541 $updown .= $spacer;
6543 if ($updowncount < $totalinstances) {
6544 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6545 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6547 else {
6548 $updown .= $spacer;
6551 $updowncount++;
6553 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6555 if (!in_array($typename, $alreadyplugins)) {
6556 $alreadyplugins[] = $typename;
6561 // Get all the plugins that exist on disk
6562 $plugins = get_plugin_list('repository');
6563 if (!empty($plugins)) {
6564 foreach ($plugins as $plugin => $dir) {
6565 // Check that it has not already been listed
6566 if (!in_array($plugin, $alreadyplugins)) {
6567 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6568 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6573 $return .= html_writer::table($table);
6574 $return .= $OUTPUT->box_end();
6575 return highlight($query, $return);
6580 * Special checkbox for enable mobile web service
6581 * If enable then we store the service id of the mobile service into config table
6582 * If disable then we unstore the service id from the config table
6584 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6586 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6589 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6590 * @return boolean
6592 private function is_xmlrpc_cap_allowed() {
6593 global $DB, $CFG;
6595 //if the $this->xmlrpcuse variable is not set, it needs to be set
6596 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6597 $params = array();
6598 $params['permission'] = CAP_ALLOW;
6599 $params['roleid'] = $CFG->defaultuserroleid;
6600 $params['capability'] = 'webservice/xmlrpc:use';
6601 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6604 return $this->xmlrpcuse;
6608 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6609 * @param type $status true to allow, false to not set
6611 private function set_xmlrpc_cap($status) {
6612 global $CFG;
6613 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6614 //need to allow the cap
6615 $permission = CAP_ALLOW;
6616 $assign = true;
6617 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6618 //need to disallow the cap
6619 $permission = CAP_INHERIT;
6620 $assign = true;
6622 if (!empty($assign)) {
6623 $systemcontext = get_system_context();
6624 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6629 * Builds XHTML to display the control.
6630 * The main purpose of this overloading is to display a warning when https
6631 * is not supported by the server
6632 * @param string $data Unused
6633 * @param string $query
6634 * @return string XHTML
6636 public function output_html($data, $query='') {
6637 global $CFG, $OUTPUT;
6638 $html = parent::output_html($data, $query);
6640 if ((string)$data === $this->yes) {
6641 require_once($CFG->dirroot . "/lib/filelib.php");
6642 $curl = new curl();
6643 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6644 $curl->head($httpswwwroot . "/login/index.php");
6645 $info = $curl->get_info();
6646 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6647 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6651 return $html;
6655 * Retrieves the current setting using the objects name
6657 * @return string
6659 public function get_setting() {
6660 global $CFG;
6662 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6663 // Or if web services aren't enabled this can't be,
6664 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6665 return 0;
6668 require_once($CFG->dirroot . '/webservice/lib.php');
6669 $webservicemanager = new webservice();
6670 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6671 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6672 return $this->config_read($this->name); //same as returning 1
6673 } else {
6674 return 0;
6679 * Save the selected setting
6681 * @param string $data The selected site
6682 * @return string empty string or error message
6684 public function write_setting($data) {
6685 global $DB, $CFG;
6687 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6688 if (empty($CFG->defaultuserroleid)) {
6689 return '';
6692 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6694 require_once($CFG->dirroot . '/webservice/lib.php');
6695 $webservicemanager = new webservice();
6697 if ((string)$data === $this->yes) {
6698 //code run when enable mobile web service
6699 //enable web service systeme if necessary
6700 set_config('enablewebservices', true);
6702 //enable mobile service
6703 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6704 $mobileservice->enabled = 1;
6705 $webservicemanager->update_external_service($mobileservice);
6707 //enable xml-rpc server
6708 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6710 if (!in_array('xmlrpc', $activeprotocols)) {
6711 $activeprotocols[] = 'xmlrpc';
6712 set_config('webserviceprotocols', implode(',', $activeprotocols));
6715 //allow xml-rpc:use capability for authenticated user
6716 $this->set_xmlrpc_cap(true);
6718 } else {
6719 //disable web service system if no other services are enabled
6720 $otherenabledservices = $DB->get_records_select('external_services',
6721 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6722 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6723 if (empty($otherenabledservices)) {
6724 set_config('enablewebservices', false);
6726 //also disable xml-rpc server
6727 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6728 $protocolkey = array_search('xmlrpc', $activeprotocols);
6729 if ($protocolkey !== false) {
6730 unset($activeprotocols[$protocolkey]);
6731 set_config('webserviceprotocols', implode(',', $activeprotocols));
6734 //disallow xml-rpc:use capability for authenticated user
6735 $this->set_xmlrpc_cap(false);
6738 //disable the mobile service
6739 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6740 $mobileservice->enabled = 0;
6741 $webservicemanager->update_external_service($mobileservice);
6744 return (parent::write_setting($data));
6749 * Special class for management of external services
6751 * @author Petr Skoda (skodak)
6753 class admin_setting_manageexternalservices extends admin_setting {
6755 * Calls parent::__construct with specific arguments
6757 public function __construct() {
6758 $this->nosave = true;
6759 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6763 * Always returns true, does nothing
6765 * @return true
6767 public function get_setting() {
6768 return true;
6772 * Always returns true, does nothing
6774 * @return true
6776 public function get_defaultsetting() {
6777 return true;
6781 * Always returns '', does not write anything
6783 * @return string Always returns ''
6785 public function write_setting($data) {
6786 // do not write any setting
6787 return '';
6791 * Checks if $query is one of the available external services
6793 * @param string $query The string to search for
6794 * @return bool Returns true if found, false if not
6796 public function is_related($query) {
6797 global $DB;
6799 if (parent::is_related($query)) {
6800 return true;
6803 $services = $DB->get_records('external_services', array(), 'id, name');
6804 foreach ($services as $service) {
6805 if (strpos(textlib::strtolower($service->name), $query) !== false) {
6806 return true;
6809 return false;
6813 * Builds the XHTML to display the control
6815 * @param string $data Unused
6816 * @param string $query
6817 * @return string
6819 public function output_html($data, $query='') {
6820 global $CFG, $OUTPUT, $DB;
6822 // display strings
6823 $stradministration = get_string('administration');
6824 $stredit = get_string('edit');
6825 $strservice = get_string('externalservice', 'webservice');
6826 $strdelete = get_string('delete');
6827 $strplugin = get_string('plugin', 'admin');
6828 $stradd = get_string('add');
6829 $strfunctions = get_string('functions', 'webservice');
6830 $strusers = get_string('users');
6831 $strserviceusers = get_string('serviceusers', 'webservice');
6833 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6834 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6835 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6837 // built in services
6838 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6839 $return = "";
6840 if (!empty($services)) {
6841 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
6845 $table = new html_table();
6846 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
6847 $table->align = array('left', 'left', 'center', 'center', 'center');
6848 $table->size = array('30%', '20%', '20%', '20%', '10%');
6849 $table->width = '100%';
6850 $table->data = array();
6852 // iterate through auth plugins and add to the display table
6853 foreach ($services as $service) {
6854 $name = $service->name;
6856 // hide/show link
6857 if ($service->enabled) {
6858 $displayname = "<span>$name</span>";
6859 } else {
6860 $displayname = "<span class=\"dimmed_text\">$name</span>";
6863 $plugin = $service->component;
6865 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6867 if ($service->restrictedusers) {
6868 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6869 } else {
6870 $users = get_string('allusers', 'webservice');
6873 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6875 // add a row to the table
6876 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
6878 $return .= html_writer::table($table);
6881 // Custom services
6882 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
6883 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
6885 $table = new html_table();
6886 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
6887 $table->align = array('left', 'center', 'center', 'center', 'center');
6888 $table->size = array('30%', '20%', '20%', '20%', '10%');
6889 $table->width = '100%';
6890 $table->data = array();
6892 // iterate through auth plugins and add to the display table
6893 foreach ($services as $service) {
6894 $name = $service->name;
6896 // hide/show link
6897 if ($service->enabled) {
6898 $displayname = "<span>$name</span>";
6899 } else {
6900 $displayname = "<span class=\"dimmed_text\">$name</span>";
6903 // delete link
6904 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
6906 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6908 if ($service->restrictedusers) {
6909 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6910 } else {
6911 $users = get_string('allusers', 'webservice');
6914 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6916 // add a row to the table
6917 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
6919 // add new custom service option
6920 $return .= html_writer::table($table);
6922 $return .= '<br />';
6923 // add a token to the table
6924 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
6926 return highlight($query, $return);
6932 * Special class for plagiarism administration.
6934 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6936 class admin_setting_manageplagiarism extends admin_setting {
6938 * Calls parent::__construct with specific arguments
6940 public function __construct() {
6941 $this->nosave = true;
6942 parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
6946 * Always returns true
6948 * @return true
6950 public function get_setting() {
6951 return true;
6955 * Always returns true
6957 * @return true
6959 public function get_defaultsetting() {
6960 return true;
6964 * Always returns '' and doesn't write anything
6966 * @return string Always returns ''
6968 public function write_setting($data) {
6969 // do not write any setting
6970 return '';
6974 * Return XHTML to display control
6976 * @param mixed $data Unused
6977 * @param string $query
6978 * @return string highlight
6980 public function output_html($data, $query='') {
6981 global $CFG, $OUTPUT;
6983 // display strings
6984 $txt = get_strings(array('settings', 'name'));
6986 $plagiarismplugins = get_plugin_list('plagiarism');
6987 if (empty($plagiarismplugins)) {
6988 return get_string('nopluginsinstalled', 'plagiarism');
6991 $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
6992 $return .= $OUTPUT->box_start('generalbox authsui');
6994 $table = new html_table();
6995 $table->head = array($txt->name, $txt->settings);
6996 $table->align = array('left', 'center');
6997 $table->data = array();
6998 $table->attributes['class'] = 'manageplagiarismtable generaltable';
7000 // iterate through auth plugins and add to the display table
7001 $authcount = count($plagiarismplugins);
7002 foreach ($plagiarismplugins as $plugin => $dir) {
7003 if (file_exists($dir.'/settings.php')) {
7004 $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
7005 // settings link
7006 $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
7007 // add a row to the table
7008 $table->data[] =array($displayname, $settings);
7011 $return .= html_writer::table($table);
7012 $return .= get_string('configplagiarismplugins', 'plagiarism');
7013 $return .= $OUTPUT->box_end();
7014 return highlight($query, $return);
7020 * Special class for overview of external services
7022 * @author Jerome Mouneyrac
7024 class admin_setting_webservicesoverview extends admin_setting {
7027 * Calls parent::__construct with specific arguments
7029 public function __construct() {
7030 $this->nosave = true;
7031 parent::__construct('webservicesoverviewui',
7032 get_string('webservicesoverview', 'webservice'), '', '');
7036 * Always returns true, does nothing
7038 * @return true
7040 public function get_setting() {
7041 return true;
7045 * Always returns true, does nothing
7047 * @return true
7049 public function get_defaultsetting() {
7050 return true;
7054 * Always returns '', does not write anything
7056 * @return string Always returns ''
7058 public function write_setting($data) {
7059 // do not write any setting
7060 return '';
7064 * Builds the XHTML to display the control
7066 * @param string $data Unused
7067 * @param string $query
7068 * @return string
7070 public function output_html($data, $query='') {
7071 global $CFG, $OUTPUT;
7073 $return = "";
7074 $brtag = html_writer::empty_tag('br');
7076 // Enable mobile web service
7077 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7078 get_string('enablemobilewebservice', 'admin'),
7079 get_string('configenablemobilewebservice',
7080 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7081 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7082 $wsmobileparam = new stdClass();
7083 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7084 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7085 get_string('externalservices', 'webservice'));
7086 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7087 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7088 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7089 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7090 . $brtag . $brtag;
7092 /// One system controlling Moodle with Token
7093 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7094 $table = new html_table();
7095 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7096 get_string('description'));
7097 $table->size = array('30%', '10%', '60%');
7098 $table->align = array('left', 'left', 'left');
7099 $table->width = '90%';
7100 $table->data = array();
7102 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7103 . $brtag . $brtag;
7105 /// 1. Enable Web Services
7106 $row = array();
7107 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7108 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7109 array('href' => $url));
7110 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7111 if ($CFG->enablewebservices) {
7112 $status = get_string('yes');
7114 $row[1] = $status;
7115 $row[2] = get_string('enablewsdescription', 'webservice');
7116 $table->data[] = $row;
7118 /// 2. Enable protocols
7119 $row = array();
7120 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7121 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7122 array('href' => $url));
7123 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7124 //retrieve activated protocol
7125 $active_protocols = empty($CFG->webserviceprotocols) ?
7126 array() : explode(',', $CFG->webserviceprotocols);
7127 if (!empty($active_protocols)) {
7128 $status = "";
7129 foreach ($active_protocols as $protocol) {
7130 $status .= $protocol . $brtag;
7133 $row[1] = $status;
7134 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7135 $table->data[] = $row;
7137 /// 3. Create user account
7138 $row = array();
7139 $url = new moodle_url("/user/editadvanced.php?id=-1");
7140 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7141 array('href' => $url));
7142 $row[1] = "";
7143 $row[2] = get_string('createuserdescription', 'webservice');
7144 $table->data[] = $row;
7146 /// 4. Add capability to users
7147 $row = array();
7148 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7149 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7150 array('href' => $url));
7151 $row[1] = "";
7152 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7153 $table->data[] = $row;
7155 /// 5. Select a web service
7156 $row = array();
7157 $url = new moodle_url("/admin/settings.php?section=externalservices");
7158 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7159 array('href' => $url));
7160 $row[1] = "";
7161 $row[2] = get_string('createservicedescription', 'webservice');
7162 $table->data[] = $row;
7164 /// 6. Add functions
7165 $row = array();
7166 $url = new moodle_url("/admin/settings.php?section=externalservices");
7167 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7168 array('href' => $url));
7169 $row[1] = "";
7170 $row[2] = get_string('addfunctionsdescription', 'webservice');
7171 $table->data[] = $row;
7173 /// 7. Add the specific user
7174 $row = array();
7175 $url = new moodle_url("/admin/settings.php?section=externalservices");
7176 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7177 array('href' => $url));
7178 $row[1] = "";
7179 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7180 $table->data[] = $row;
7182 /// 8. Create token for the specific user
7183 $row = array();
7184 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7185 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7186 array('href' => $url));
7187 $row[1] = "";
7188 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7189 $table->data[] = $row;
7191 /// 9. Enable the documentation
7192 $row = array();
7193 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7194 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7195 array('href' => $url));
7196 $status = '<span class="warning">' . get_string('no') . '</span>';
7197 if ($CFG->enablewsdocumentation) {
7198 $status = get_string('yes');
7200 $row[1] = $status;
7201 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7202 $table->data[] = $row;
7204 /// 10. Test the service
7205 $row = array();
7206 $url = new moodle_url("/admin/webservice/testclient.php");
7207 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7208 array('href' => $url));
7209 $row[1] = "";
7210 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7211 $table->data[] = $row;
7213 $return .= html_writer::table($table);
7215 /// Users as clients with token
7216 $return .= $brtag . $brtag . $brtag;
7217 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7218 $table = new html_table();
7219 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7220 get_string('description'));
7221 $table->size = array('30%', '10%', '60%');
7222 $table->align = array('left', 'left', 'left');
7223 $table->width = '90%';
7224 $table->data = array();
7226 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7227 $brtag . $brtag;
7229 /// 1. Enable Web Services
7230 $row = array();
7231 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7232 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7233 array('href' => $url));
7234 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7235 if ($CFG->enablewebservices) {
7236 $status = get_string('yes');
7238 $row[1] = $status;
7239 $row[2] = get_string('enablewsdescription', 'webservice');
7240 $table->data[] = $row;
7242 /// 2. Enable protocols
7243 $row = array();
7244 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7245 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7246 array('href' => $url));
7247 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7248 //retrieve activated protocol
7249 $active_protocols = empty($CFG->webserviceprotocols) ?
7250 array() : explode(',', $CFG->webserviceprotocols);
7251 if (!empty($active_protocols)) {
7252 $status = "";
7253 foreach ($active_protocols as $protocol) {
7254 $status .= $protocol . $brtag;
7257 $row[1] = $status;
7258 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7259 $table->data[] = $row;
7262 /// 3. Select a web service
7263 $row = array();
7264 $url = new moodle_url("/admin/settings.php?section=externalservices");
7265 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7266 array('href' => $url));
7267 $row[1] = "";
7268 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7269 $table->data[] = $row;
7271 /// 4. Add functions
7272 $row = array();
7273 $url = new moodle_url("/admin/settings.php?section=externalservices");
7274 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7275 array('href' => $url));
7276 $row[1] = "";
7277 $row[2] = get_string('addfunctionsdescription', 'webservice');
7278 $table->data[] = $row;
7280 /// 5. Add capability to users
7281 $row = array();
7282 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7283 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7284 array('href' => $url));
7285 $row[1] = "";
7286 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7287 $table->data[] = $row;
7289 /// 6. Test the service
7290 $row = array();
7291 $url = new moodle_url("/admin/webservice/testclient.php");
7292 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7293 array('href' => $url));
7294 $row[1] = "";
7295 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7296 $table->data[] = $row;
7298 $return .= html_writer::table($table);
7300 return highlight($query, $return);
7307 * Special class for web service protocol administration.
7309 * @author Petr Skoda (skodak)
7311 class admin_setting_managewebserviceprotocols extends admin_setting {
7314 * Calls parent::__construct with specific arguments
7316 public function __construct() {
7317 $this->nosave = true;
7318 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7322 * Always returns true, does nothing
7324 * @return true
7326 public function get_setting() {
7327 return true;
7331 * Always returns true, does nothing
7333 * @return true
7335 public function get_defaultsetting() {
7336 return true;
7340 * Always returns '', does not write anything
7342 * @return string Always returns ''
7344 public function write_setting($data) {
7345 // do not write any setting
7346 return '';
7350 * Checks if $query is one of the available webservices
7352 * @param string $query The string to search for
7353 * @return bool Returns true if found, false if not
7355 public function is_related($query) {
7356 if (parent::is_related($query)) {
7357 return true;
7360 $protocols = get_plugin_list('webservice');
7361 foreach ($protocols as $protocol=>$location) {
7362 if (strpos($protocol, $query) !== false) {
7363 return true;
7365 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7366 if (strpos(textlib::strtolower($protocolstr), $query) !== false) {
7367 return true;
7370 return false;
7374 * Builds the XHTML to display the control
7376 * @param string $data Unused
7377 * @param string $query
7378 * @return string
7380 public function output_html($data, $query='') {
7381 global $CFG, $OUTPUT;
7383 // display strings
7384 $stradministration = get_string('administration');
7385 $strsettings = get_string('settings');
7386 $stredit = get_string('edit');
7387 $strprotocol = get_string('protocol', 'webservice');
7388 $strenable = get_string('enable');
7389 $strdisable = get_string('disable');
7390 $strversion = get_string('version');
7391 $struninstall = get_string('uninstallplugin', 'admin');
7393 $protocols_available = get_plugin_list('webservice');
7394 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7395 ksort($protocols_available);
7397 foreach ($active_protocols as $key=>$protocol) {
7398 if (empty($protocols_available[$protocol])) {
7399 unset($active_protocols[$key]);
7403 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7404 $return .= $OUTPUT->box_start('generalbox webservicesui');
7406 $table = new html_table();
7407 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7408 $table->align = array('left', 'center', 'center', 'center', 'center');
7409 $table->width = '100%';
7410 $table->data = array();
7412 // iterate through auth plugins and add to the display table
7413 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7414 foreach ($protocols_available as $protocol => $location) {
7415 $name = get_string('pluginname', 'webservice_'.$protocol);
7417 $plugin = new stdClass();
7418 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7419 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7421 $version = isset($plugin->version) ? $plugin->version : '';
7423 // hide/show link
7424 if (in_array($protocol, $active_protocols)) {
7425 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7426 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
7427 $displayname = "<span>$name</span>";
7428 } else {
7429 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7430 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
7431 $displayname = "<span class=\"dimmed_text\">$name</span>";
7434 // delete link
7435 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7437 // settings link
7438 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7439 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7440 } else {
7441 $settings = '';
7444 // add a row to the table
7445 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7447 $return .= html_writer::table($table);
7448 $return .= get_string('configwebserviceplugins', 'webservice');
7449 $return .= $OUTPUT->box_end();
7451 return highlight($query, $return);
7457 * Special class for web service token administration.
7459 * @author Jerome Mouneyrac
7461 class admin_setting_managewebservicetokens extends admin_setting {
7464 * Calls parent::__construct with specific arguments
7466 public function __construct() {
7467 $this->nosave = true;
7468 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7472 * Always returns true, does nothing
7474 * @return true
7476 public function get_setting() {
7477 return true;
7481 * Always returns true, does nothing
7483 * @return true
7485 public function get_defaultsetting() {
7486 return true;
7490 * Always returns '', does not write anything
7492 * @return string Always returns ''
7494 public function write_setting($data) {
7495 // do not write any setting
7496 return '';
7500 * Builds the XHTML to display the control
7502 * @param string $data Unused
7503 * @param string $query
7504 * @return string
7506 public function output_html($data, $query='') {
7507 global $CFG, $OUTPUT, $DB, $USER;
7509 // display strings
7510 $stroperation = get_string('operation', 'webservice');
7511 $strtoken = get_string('token', 'webservice');
7512 $strservice = get_string('service', 'webservice');
7513 $struser = get_string('user');
7514 $strcontext = get_string('context', 'webservice');
7515 $strvaliduntil = get_string('validuntil', 'webservice');
7516 $striprestriction = get_string('iprestriction', 'webservice');
7518 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7520 $table = new html_table();
7521 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7522 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7523 $table->width = '100%';
7524 $table->data = array();
7526 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7528 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7530 //here retrieve token list (including linked users firstname/lastname and linked services name)
7531 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
7532 FROM {external_tokens} t, {user} u, {external_services} s
7533 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7534 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7535 if (!empty($tokens)) {
7536 foreach ($tokens as $token) {
7537 //TODO: retrieve context
7539 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7540 $delete .= get_string('delete')."</a>";
7542 $validuntil = '';
7543 if (!empty($token->validuntil)) {
7544 $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
7547 $iprestriction = '';
7548 if (!empty($token->iprestriction)) {
7549 $iprestriction = $token->iprestriction;
7552 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7553 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7554 $useratag .= $token->firstname." ".$token->lastname;
7555 $useratag .= html_writer::end_tag('a');
7557 //check user missing capabilities
7558 require_once($CFG->dirroot . '/webservice/lib.php');
7559 $webservicemanager = new webservice();
7560 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7561 array(array('id' => $token->userid)), $token->serviceid);
7563 if (!is_siteadmin($token->userid) and
7564 key_exists($token->userid, $usermissingcaps)) {
7565 $missingcapabilities = implode(', ',
7566 $usermissingcaps[$token->userid]);
7567 if (!empty($missingcapabilities)) {
7568 $useratag .= html_writer::tag('div',
7569 get_string('usermissingcaps', 'webservice',
7570 $missingcapabilities)
7571 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7572 array('class' => 'missingcaps'));
7576 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7579 $return .= html_writer::table($table);
7580 } else {
7581 $return .= get_string('notoken', 'webservice');
7584 $return .= $OUTPUT->box_end();
7585 // add a token to the table
7586 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7587 $return .= get_string('add')."</a>";
7589 return highlight($query, $return);
7595 * Colour picker
7597 * @copyright 2010 Sam Hemelryk
7598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7600 class admin_setting_configcolourpicker extends admin_setting {
7603 * Information for previewing the colour
7605 * @var array|null
7607 protected $previewconfig = null;
7611 * @param string $name
7612 * @param string $visiblename
7613 * @param string $description
7614 * @param string $defaultsetting
7615 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7617 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7618 $this->previewconfig = $previewconfig;
7619 parent::__construct($name, $visiblename, $description, $defaultsetting);
7623 * Return the setting
7625 * @return mixed returns config if successful else null
7627 public function get_setting() {
7628 return $this->config_read($this->name);
7632 * Saves the setting
7634 * @param string $data
7635 * @return bool
7637 public function write_setting($data) {
7638 $data = $this->validate($data);
7639 if ($data === false) {
7640 return get_string('validateerror', 'admin');
7642 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7646 * Validates the colour that was entered by the user
7648 * @param string $data
7649 * @return string|false
7651 protected function validate($data) {
7652 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7653 if (strpos($data, '#')!==0) {
7654 $data = '#'.$data;
7656 return $data;
7657 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7658 return $data;
7659 } else if (empty($data)) {
7660 return $this->defaultsetting;
7661 } else {
7662 return false;
7667 * Generates the HTML for the setting
7669 * @global moodle_page $PAGE
7670 * @global core_renderer $OUTPUT
7671 * @param string $data
7672 * @param string $query
7674 public function output_html($data, $query = '') {
7675 global $PAGE, $OUTPUT;
7676 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7677 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7678 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7679 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
7680 if (!empty($this->previewconfig)) {
7681 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7683 $content .= html_writer::end_tag('div');
7684 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7689 * Administration interface for user specified regular expressions for device detection.
7691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7693 class admin_setting_devicedetectregex extends admin_setting {
7696 * Calls parent::__construct with specific args
7698 * @param string $name
7699 * @param string $visiblename
7700 * @param string $description
7701 * @param mixed $defaultsetting
7703 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7704 global $CFG;
7705 parent::__construct($name, $visiblename, $description, $defaultsetting);
7709 * Return the current setting(s)
7711 * @return array Current settings array
7713 public function get_setting() {
7714 global $CFG;
7716 $config = $this->config_read($this->name);
7717 if (is_null($config)) {
7718 return null;
7721 return $this->prepare_form_data($config);
7725 * Save selected settings
7727 * @param array $data Array of settings to save
7728 * @return bool
7730 public function write_setting($data) {
7731 if (empty($data)) {
7732 $data = array();
7735 if ($this->config_write($this->name, $this->process_form_data($data))) {
7736 return ''; // success
7737 } else {
7738 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
7743 * Return XHTML field(s) for regexes
7745 * @param array $data Array of options to set in HTML
7746 * @return string XHTML string for the fields and wrapping div(s)
7748 public function output_html($data, $query='') {
7749 global $OUTPUT;
7751 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
7752 $out .= html_writer::start_tag('thead');
7753 $out .= html_writer::start_tag('tr');
7754 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
7755 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
7756 $out .= html_writer::end_tag('tr');
7757 $out .= html_writer::end_tag('thead');
7758 $out .= html_writer::start_tag('tbody');
7760 if (empty($data)) {
7761 $looplimit = 1;
7762 } else {
7763 $looplimit = (count($data)/2)+1;
7766 for ($i=0; $i<$looplimit; $i++) {
7767 $out .= html_writer::start_tag('tr');
7769 $expressionname = 'expression'.$i;
7771 if (!empty($data[$expressionname])){
7772 $expression = $data[$expressionname];
7773 } else {
7774 $expression = '';
7777 $out .= html_writer::tag('td',
7778 html_writer::empty_tag('input',
7779 array(
7780 'type' => 'text',
7781 'class' => 'form-text',
7782 'name' => $this->get_full_name().'[expression'.$i.']',
7783 'value' => $expression,
7785 ), array('class' => 'c'.$i)
7788 $valuename = 'value'.$i;
7790 if (!empty($data[$valuename])){
7791 $value = $data[$valuename];
7792 } else {
7793 $value= '';
7796 $out .= html_writer::tag('td',
7797 html_writer::empty_tag('input',
7798 array(
7799 'type' => 'text',
7800 'class' => 'form-text',
7801 'name' => $this->get_full_name().'[value'.$i.']',
7802 'value' => $value,
7804 ), array('class' => 'c'.$i)
7807 $out .= html_writer::end_tag('tr');
7810 $out .= html_writer::end_tag('tbody');
7811 $out .= html_writer::end_tag('table');
7813 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
7817 * Converts the string of regexes
7819 * @see self::process_form_data()
7820 * @param $regexes string of regexes
7821 * @return array of form fields and their values
7823 protected function prepare_form_data($regexes) {
7825 $regexes = json_decode($regexes);
7827 $form = array();
7829 $i = 0;
7831 foreach ($regexes as $value => $regex) {
7832 $expressionname = 'expression'.$i;
7833 $valuename = 'value'.$i;
7835 $form[$expressionname] = $regex;
7836 $form[$valuename] = $value;
7837 $i++;
7840 return $form;
7844 * Converts the data from admin settings form into a string of regexes
7846 * @see self::prepare_form_data()
7847 * @param array $data array of admin form fields and values
7848 * @return false|string of regexes
7850 protected function process_form_data(array $form) {
7852 $count = count($form); // number of form field values
7854 if ($count % 2) {
7855 // we must get five fields per expression
7856 return false;
7859 $regexes = array();
7860 for ($i = 0; $i < $count / 2; $i++) {
7861 $expressionname = "expression".$i;
7862 $valuename = "value".$i;
7864 $expression = trim($form['expression'.$i]);
7865 $value = trim($form['value'.$i]);
7867 if (empty($expression)){
7868 continue;
7871 $regexes[$value] = $expression;
7874 $regexes = json_encode($regexes);
7876 return $regexes;
7881 * Multiselect for current modules
7883 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7885 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
7886 private $excludesystem;
7889 * Calls parent::__construct - note array $choices is not required
7891 * @param string $name setting name
7892 * @param string $visiblename localised setting name
7893 * @param string $description setting description
7894 * @param array $defaultsetting a plain array of default module ids
7895 * @param bool $excludesystem If true, excludes modules with 'system' archetype
7897 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
7898 $excludesystem = true) {
7899 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
7900 $this->excludesystem = $excludesystem;
7904 * Loads an array of current module choices
7906 * @return bool always return true
7908 public function load_choices() {
7909 if (is_array($this->choices)) {
7910 return true;
7912 $this->choices = array();
7914 global $CFG, $DB;
7915 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7916 foreach ($records as $record) {
7917 // Exclude modules if the code doesn't exist
7918 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7919 // Also exclude system modules (if specified)
7920 if (!($this->excludesystem &&
7921 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
7922 MOD_ARCHETYPE_SYSTEM)) {
7923 $this->choices[$record->id] = $record->name;
7927 return true;