weekly release 2.1.6+
[moodle.git] / lib / adminlib.php
blob5273fe31324bed8d5125024cb3043da93cd4a954
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));
250 // perform clean-up task common for all the plugin/subplugin types
252 //delete the web service functions and pre-built services
253 require_once($CFG->dirroot.'/lib/externallib.php');
254 external_delete_descriptions($component);
256 // delete calendar events
257 $DB->delete_records('event', array('modulename' => $pluginname));
259 // delete all the logs
260 $DB->delete_records('log', array('module' => $pluginname));
262 // delete log_display information
263 $DB->delete_records('log_display', array('component' => $component));
265 // delete the module configuration records
266 unset_all_config_for_plugin($pluginname);
268 // delete message provider
269 message_provider_uninstall($component);
271 // delete message processor
272 if ($type === 'message') {
273 message_processor_uninstall($name);
276 // delete the plugin tables
277 $xmldbfilepath = $plugindirectory . '/db/install.xml';
278 drop_plugin_tables($pluginname, $xmldbfilepath, false);
280 // delete the capabilities that were defined by this module
281 capabilities_cleanup($component);
283 // remove event handlers and dequeue pending events
284 events_uninstall($component);
286 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
290 * Returns the version of installed component
292 * @param string $component component name
293 * @param string $source either 'disk' or 'installed' - where to get the version information from
294 * @return string|bool version number or false if the component is not found
296 function get_component_version($component, $source='installed') {
297 global $CFG, $DB;
299 list($type, $name) = normalize_component($component);
301 // moodle core or a core subsystem
302 if ($type === 'core') {
303 if ($source === 'installed') {
304 if (empty($CFG->version)) {
305 return false;
306 } else {
307 return $CFG->version;
309 } else {
310 if (!is_readable($CFG->dirroot.'/version.php')) {
311 return false;
312 } else {
313 $version = null; //initialize variable for IDEs
314 include($CFG->dirroot.'/version.php');
315 return $version;
320 // activity module
321 if ($type === 'mod') {
322 if ($source === 'installed') {
323 return $DB->get_field('modules', 'version', array('name'=>$name));
324 } else {
325 $mods = get_plugin_list('mod');
326 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
327 return false;
328 } else {
329 $module = new stdclass();
330 include($mods[$name].'/version.php');
331 return $module->version;
336 // block
337 if ($type === 'block') {
338 if ($source === 'installed') {
339 return $DB->get_field('block', 'version', array('name'=>$name));
340 } else {
341 $blocks = get_plugin_list('block');
342 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
343 return false;
344 } else {
345 $plugin = new stdclass();
346 include($blocks[$name].'/version.php');
347 return $plugin->version;
352 // all other plugin types
353 if ($source === 'installed') {
354 return get_config($type.'_'.$name, 'version');
355 } else {
356 $plugins = get_plugin_list($type);
357 if (empty($plugins[$name])) {
358 return false;
359 } else {
360 $plugin = new stdclass();
361 include($plugins[$name].'/version.php');
362 return $plugin->version;
368 * Delete all plugin tables
370 * @param string $name Name of plugin, used as table prefix
371 * @param string $file Path to install.xml file
372 * @param bool $feedback defaults to true
373 * @return bool Always returns true
375 function drop_plugin_tables($name, $file, $feedback=true) {
376 global $CFG, $DB;
378 // first try normal delete
379 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
380 return true;
383 // then try to find all tables that start with name and are not in any xml file
384 $used_tables = get_used_table_names();
386 $tables = $DB->get_tables();
388 /// Iterate over, fixing id fields as necessary
389 foreach ($tables as $table) {
390 if (in_array($table, $used_tables)) {
391 continue;
394 if (strpos($table, $name) !== 0) {
395 continue;
398 // found orphan table --> delete it
399 if ($DB->get_manager()->table_exists($table)) {
400 $xmldb_table = new xmldb_table($table);
401 $DB->get_manager()->drop_table($xmldb_table);
405 return true;
409 * Returns names of all known tables == tables that moodle knows about.
411 * @return array Array of lowercase table names
413 function get_used_table_names() {
414 $table_names = array();
415 $dbdirs = get_db_directories();
417 foreach ($dbdirs as $dbdir) {
418 $file = $dbdir.'/install.xml';
420 $xmldb_file = new xmldb_file($file);
422 if (!$xmldb_file->fileExists()) {
423 continue;
426 $loaded = $xmldb_file->loadXMLStructure();
427 $structure = $xmldb_file->getStructure();
429 if ($loaded and $tables = $structure->getTables()) {
430 foreach($tables as $table) {
431 $table_names[] = strtolower($table->name);
436 return $table_names;
440 * Returns list of all directories where we expect install.xml files
441 * @return array Array of paths
443 function get_db_directories() {
444 global $CFG;
446 $dbdirs = array();
448 /// First, the main one (lib/db)
449 $dbdirs[] = $CFG->libdir.'/db';
451 /// Then, all the ones defined by get_plugin_types()
452 $plugintypes = get_plugin_types();
453 foreach ($plugintypes as $plugintype => $pluginbasedir) {
454 if ($plugins = get_plugin_list($plugintype)) {
455 foreach ($plugins as $plugin => $plugindir) {
456 $dbdirs[] = $plugindir.'/db';
461 return $dbdirs;
465 * Try to obtain or release the cron lock.
466 * @param string $name name of lock
467 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
468 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
469 * @return bool true if lock obtained
471 function set_cron_lock($name, $until, $ignorecurrent=false) {
472 global $DB;
473 if (empty($name)) {
474 debugging("Tried to get a cron lock for a null fieldname");
475 return false;
478 // remove lock by force == remove from config table
479 if (is_null($until)) {
480 set_config($name, null);
481 return true;
484 if (!$ignorecurrent) {
485 // read value from db - other processes might have changed it
486 $value = $DB->get_field('config', 'value', array('name'=>$name));
488 if ($value and $value > time()) {
489 //lock active
490 return false;
494 set_config($name, $until);
495 return true;
499 * Test if and critical warnings are present
500 * @return bool
502 function admin_critical_warnings_present() {
503 global $SESSION;
505 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
506 return 0;
509 if (!isset($SESSION->admin_critical_warning)) {
510 $SESSION->admin_critical_warning = 0;
511 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
512 $SESSION->admin_critical_warning = 1;
516 return $SESSION->admin_critical_warning;
520 * Detects if float supports at least 10 decimal digits
522 * Detects if float supports at least 10 decimal digits
523 * and also if float-->string conversion works as expected.
525 * @return bool true if problem found
527 function is_float_problem() {
528 $num1 = 2009010200.01;
529 $num2 = 2009010200.02;
531 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
535 * Try to verify that dataroot is not accessible from web.
537 * Try to verify that dataroot is not accessible from web.
538 * It is not 100% correct but might help to reduce number of vulnerable sites.
539 * Protection from httpd.conf and .htaccess is not detected properly.
541 * @uses INSECURE_DATAROOT_WARNING
542 * @uses INSECURE_DATAROOT_ERROR
543 * @param bool $fetchtest try to test public access by fetching file, default false
544 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
546 function is_dataroot_insecure($fetchtest=false) {
547 global $CFG;
549 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
551 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
552 $rp = strrev(trim($rp, '/'));
553 $rp = explode('/', $rp);
554 foreach($rp as $r) {
555 if (strpos($siteroot, '/'.$r.'/') === 0) {
556 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
557 } else {
558 break; // probably alias root
562 $siteroot = strrev($siteroot);
563 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
565 if (strpos($dataroot, $siteroot) !== 0) {
566 return false;
569 if (!$fetchtest) {
570 return INSECURE_DATAROOT_WARNING;
573 // now try all methods to fetch a test file using http protocol
575 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
576 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
577 $httpdocroot = $matches[1];
578 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
579 make_upload_directory('diag');
580 $testfile = $CFG->dataroot.'/diag/public.txt';
581 if (!file_exists($testfile)) {
582 file_put_contents($testfile, 'test file, do not delete');
584 $teststr = trim(file_get_contents($testfile));
585 if (empty($teststr)) {
586 // hmm, strange
587 return INSECURE_DATAROOT_WARNING;
590 $testurl = $datarooturl.'/diag/public.txt';
591 if (extension_loaded('curl') and
592 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
593 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
594 ($ch = @curl_init($testurl)) !== false) {
595 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
596 curl_setopt($ch, CURLOPT_HEADER, false);
597 $data = curl_exec($ch);
598 if (!curl_errno($ch)) {
599 $data = trim($data);
600 if ($data === $teststr) {
601 curl_close($ch);
602 return INSECURE_DATAROOT_ERROR;
605 curl_close($ch);
608 if ($data = @file_get_contents($testurl)) {
609 $data = trim($data);
610 if ($data === $teststr) {
611 return INSECURE_DATAROOT_ERROR;
615 preg_match('|https?://([^/]+)|i', $testurl, $matches);
616 $sitename = $matches[1];
617 $error = 0;
618 if ($fp = @fsockopen($sitename, 80, $error)) {
619 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
620 $localurl = $matches[1];
621 $out = "GET $localurl HTTP/1.1\r\n";
622 $out .= "Host: $sitename\r\n";
623 $out .= "Connection: Close\r\n\r\n";
624 fwrite($fp, $out);
625 $data = '';
626 $incoming = false;
627 while (!feof($fp)) {
628 if ($incoming) {
629 $data .= fgets($fp, 1024);
630 } else if (@fgets($fp, 1024) === "\r\n") {
631 $incoming = true;
634 fclose($fp);
635 $data = trim($data);
636 if ($data === $teststr) {
637 return INSECURE_DATAROOT_ERROR;
641 return INSECURE_DATAROOT_WARNING;
644 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
648 * Interface for anything appearing in the admin tree
650 * The interface that is implemented by anything that appears in the admin tree
651 * block. It forces inheriting classes to define a method for checking user permissions
652 * and methods for finding something in the admin tree.
654 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
656 interface part_of_admin_tree {
659 * Finds a named part_of_admin_tree.
661 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
662 * and not parentable_part_of_admin_tree, then this function should only check if
663 * $this->name matches $name. If it does, it should return a reference to $this,
664 * otherwise, it should return a reference to NULL.
666 * If a class inherits parentable_part_of_admin_tree, this method should be called
667 * recursively on all child objects (assuming, of course, the parent object's name
668 * doesn't match the search criterion).
670 * @param string $name The internal name of the part_of_admin_tree we're searching for.
671 * @return mixed An object reference or a NULL reference.
673 public function locate($name);
676 * Removes named part_of_admin_tree.
678 * @param string $name The internal name of the part_of_admin_tree we want to remove.
679 * @return bool success.
681 public function prune($name);
684 * Search using query
685 * @param string $query
686 * @return mixed array-object structure of found settings and pages
688 public function search($query);
691 * Verifies current user's access to this part_of_admin_tree.
693 * Used to check if the current user has access to this part of the admin tree or
694 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
695 * then this method is usually just a call to has_capability() in the site context.
697 * If a class inherits parentable_part_of_admin_tree, this method should return the
698 * logical OR of the return of check_access() on all child objects.
700 * @return bool True if the user has access, false if she doesn't.
702 public function check_access();
705 * Mostly useful for removing of some parts of the tree in admin tree block.
707 * @return True is hidden from normal list view
709 public function is_hidden();
712 * Show we display Save button at the page bottom?
713 * @return bool
715 public function show_save();
720 * Interface implemented by any part_of_admin_tree that has children.
722 * The interface implemented by any part_of_admin_tree that can be a parent
723 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
724 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
725 * include an add method for adding other part_of_admin_tree objects as children.
727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
729 interface parentable_part_of_admin_tree extends part_of_admin_tree {
732 * Adds a part_of_admin_tree object to the admin tree.
734 * Used to add a part_of_admin_tree object to this object or a child of this
735 * object. $something should only be added if $destinationname matches
736 * $this->name. If it doesn't, add should be called on child objects that are
737 * also parentable_part_of_admin_tree's.
739 * @param string $destinationname The internal name of the new parent for $something.
740 * @param part_of_admin_tree $something The object to be added.
741 * @return bool True on success, false on failure.
743 public function add($destinationname, $something);
749 * The object used to represent folders (a.k.a. categories) in the admin tree block.
751 * Each admin_category object contains a number of part_of_admin_tree objects.
753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
755 class admin_category implements parentable_part_of_admin_tree {
757 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
758 public $children;
759 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
760 public $name;
761 /** @var string The displayed name for this category. Usually obtained through get_string() */
762 public $visiblename;
763 /** @var bool Should this category be hidden in admin tree block? */
764 public $hidden;
765 /** @var mixed Either a string or an array or strings */
766 public $path;
767 /** @var mixed Either a string or an array or strings */
768 public $visiblepath;
770 /** @var array fast lookup category cache, all categories of one tree point to one cache */
771 protected $category_cache;
774 * Constructor for an empty admin category
776 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
777 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
778 * @param bool $hidden hide category in admin tree block, defaults to false
780 public function __construct($name, $visiblename, $hidden=false) {
781 $this->children = array();
782 $this->name = $name;
783 $this->visiblename = $visiblename;
784 $this->hidden = $hidden;
788 * Returns a reference to the part_of_admin_tree object with internal name $name.
790 * @param string $name The internal name of the object we want.
791 * @param bool $findpath initialize path and visiblepath arrays
792 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
793 * defaults to false
795 public function locate($name, $findpath=false) {
796 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
797 // somebody much have purged the cache
798 $this->category_cache[$this->name] = $this;
801 if ($this->name == $name) {
802 if ($findpath) {
803 $this->visiblepath[] = $this->visiblename;
804 $this->path[] = $this->name;
806 return $this;
809 // quick category lookup
810 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
811 return $this->category_cache[$name];
814 $return = NULL;
815 foreach($this->children as $childid=>$unused) {
816 if ($return = $this->children[$childid]->locate($name, $findpath)) {
817 break;
821 if (!is_null($return) and $findpath) {
822 $return->visiblepath[] = $this->visiblename;
823 $return->path[] = $this->name;
826 return $return;
830 * Search using query
832 * @param string query
833 * @return mixed array-object structure of found settings and pages
835 public function search($query) {
836 $result = array();
837 foreach ($this->children as $child) {
838 $subsearch = $child->search($query);
839 if (!is_array($subsearch)) {
840 debugging('Incorrect search result from '.$child->name);
841 continue;
843 $result = array_merge($result, $subsearch);
845 return $result;
849 * Removes part_of_admin_tree object with internal name $name.
851 * @param string $name The internal name of the object we want to remove.
852 * @return bool success
854 public function prune($name) {
856 if ($this->name == $name) {
857 return false; //can not remove itself
860 foreach($this->children as $precedence => $child) {
861 if ($child->name == $name) {
862 // clear cache and delete self
863 if (is_array($this->category_cache)) {
864 while($this->category_cache) {
865 // delete the cache, but keep the original array address
866 array_pop($this->category_cache);
869 unset($this->children[$precedence]);
870 return true;
871 } else if ($this->children[$precedence]->prune($name)) {
872 return true;
875 return false;
879 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
881 * @param string $destinationame The internal name of the immediate parent that we want for $something.
882 * @param mixed $something A part_of_admin_tree or setting instance to be added.
883 * @return bool True if successfully added, false if $something can not be added.
885 public function add($parentname, $something) {
886 $parent = $this->locate($parentname);
887 if (is_null($parent)) {
888 debugging('parent does not exist!');
889 return false;
892 if ($something instanceof part_of_admin_tree) {
893 if (!($parent instanceof parentable_part_of_admin_tree)) {
894 debugging('error - parts of tree can be inserted only into parentable parts');
895 return false;
897 $parent->children[] = $something;
898 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
899 if (isset($this->category_cache[$something->name])) {
900 debugging('Duplicate admin category name: '.$something->name);
901 } else {
902 $this->category_cache[$something->name] = $something;
903 $something->category_cache =& $this->category_cache;
904 foreach ($something->children as $child) {
905 // just in case somebody already added subcategories
906 if ($child instanceof admin_category) {
907 if (isset($this->category_cache[$child->name])) {
908 debugging('Duplicate admin category name: '.$child->name);
909 } else {
910 $this->category_cache[$child->name] = $child;
911 $child->category_cache =& $this->category_cache;
917 return true;
919 } else {
920 debugging('error - can not add this element');
921 return false;
927 * Checks if the user has access to anything in this category.
929 * @return bool True if the user has access to at least one child in this category, false otherwise.
931 public function check_access() {
932 foreach ($this->children as $child) {
933 if ($child->check_access()) {
934 return true;
937 return false;
941 * Is this category hidden in admin tree block?
943 * @return bool True if hidden
945 public function is_hidden() {
946 return $this->hidden;
950 * Show we display Save button at the page bottom?
951 * @return bool
953 public function show_save() {
954 foreach ($this->children as $child) {
955 if ($child->show_save()) {
956 return true;
959 return false;
965 * Root of admin settings tree, does not have any parent.
967 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
969 class admin_root extends admin_category {
970 /** @var array List of errors */
971 public $errors;
972 /** @var string search query */
973 public $search;
974 /** @var bool full tree flag - true means all settings required, false only pages required */
975 public $fulltree;
976 /** @var bool flag indicating loaded tree */
977 public $loaded;
978 /** @var mixed site custom defaults overriding defaults in settings files*/
979 public $custom_defaults;
982 * @param bool $fulltree true means all settings required,
983 * false only pages required
985 public function __construct($fulltree) {
986 global $CFG;
988 parent::__construct('root', get_string('administration'), false);
989 $this->errors = array();
990 $this->search = '';
991 $this->fulltree = $fulltree;
992 $this->loaded = false;
994 $this->category_cache = array();
996 // load custom defaults if found
997 $this->custom_defaults = null;
998 $defaultsfile = "$CFG->dirroot/local/defaults.php";
999 if (is_readable($defaultsfile)) {
1000 $defaults = array();
1001 include($defaultsfile);
1002 if (is_array($defaults) and count($defaults)) {
1003 $this->custom_defaults = $defaults;
1009 * Empties children array, and sets loaded to false
1011 * @param bool $requirefulltree
1013 public function purge_children($requirefulltree) {
1014 $this->children = array();
1015 $this->fulltree = ($requirefulltree || $this->fulltree);
1016 $this->loaded = false;
1017 //break circular dependencies - this helps PHP 5.2
1018 while($this->category_cache) {
1019 array_pop($this->category_cache);
1021 $this->category_cache = array();
1027 * Links external PHP pages into the admin tree.
1029 * See detailed usage example at the top of this document (adminlib.php)
1031 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1033 class admin_externalpage implements part_of_admin_tree {
1035 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1036 public $name;
1038 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1039 public $visiblename;
1041 /** @var string The external URL that we should link to when someone requests this external page. */
1042 public $url;
1044 /** @var string The role capability/permission a user must have to access this external page. */
1045 public $req_capability;
1047 /** @var object The context in which capability/permission should be checked, default is site context. */
1048 public $context;
1050 /** @var bool hidden in admin tree block. */
1051 public $hidden;
1053 /** @var mixed either string or array of string */
1054 public $path;
1056 /** @var array list of visible names of page parents */
1057 public $visiblepath;
1060 * Constructor for adding an external page into the admin tree.
1062 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1063 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1064 * @param string $url The external URL that we should link to when someone requests this external page.
1065 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1066 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1067 * @param stdClass $context The context the page relates to. Not sure what happens
1068 * if you specify something other than system or front page. Defaults to system.
1070 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1071 $this->name = $name;
1072 $this->visiblename = $visiblename;
1073 $this->url = $url;
1074 if (is_array($req_capability)) {
1075 $this->req_capability = $req_capability;
1076 } else {
1077 $this->req_capability = array($req_capability);
1079 $this->hidden = $hidden;
1080 $this->context = $context;
1084 * Returns a reference to the part_of_admin_tree object with internal name $name.
1086 * @param string $name The internal name of the object we want.
1087 * @param bool $findpath defaults to false
1088 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1090 public function locate($name, $findpath=false) {
1091 if ($this->name == $name) {
1092 if ($findpath) {
1093 $this->visiblepath = array($this->visiblename);
1094 $this->path = array($this->name);
1096 return $this;
1097 } else {
1098 $return = NULL;
1099 return $return;
1104 * This function always returns false, required function by interface
1106 * @param string $name
1107 * @return false
1109 public function prune($name) {
1110 return false;
1114 * Search using query
1116 * @param string $query
1117 * @return mixed array-object structure of found settings and pages
1119 public function search($query) {
1120 $textlib = textlib_get_instance();
1122 $found = false;
1123 if (strpos(strtolower($this->name), $query) !== false) {
1124 $found = true;
1125 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1126 $found = true;
1128 if ($found) {
1129 $result = new stdClass();
1130 $result->page = $this;
1131 $result->settings = array();
1132 return array($this->name => $result);
1133 } else {
1134 return array();
1139 * Determines if the current user has access to this external page based on $this->req_capability.
1141 * @return bool True if user has access, false otherwise.
1143 public function check_access() {
1144 global $CFG;
1145 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1146 foreach($this->req_capability as $cap) {
1147 if (has_capability($cap, $context)) {
1148 return true;
1151 return false;
1155 * Is this external page hidden in admin tree block?
1157 * @return bool True if hidden
1159 public function is_hidden() {
1160 return $this->hidden;
1164 * Show we display Save button at the page bottom?
1165 * @return bool
1167 public function show_save() {
1168 return false;
1174 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1176 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1178 class admin_settingpage implements part_of_admin_tree {
1180 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1181 public $name;
1183 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1184 public $visiblename;
1186 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1187 public $settings;
1189 /** @var string The role capability/permission a user must have to access this external page. */
1190 public $req_capability;
1192 /** @var object The context in which capability/permission should be checked, default is site context. */
1193 public $context;
1195 /** @var bool hidden in admin tree block. */
1196 public $hidden;
1198 /** @var mixed string of paths or array of strings of paths */
1199 public $path;
1201 /** @var array list of visible names of page parents */
1202 public $visiblepath;
1205 * see admin_settingpage for details of this function
1207 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1208 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1209 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1210 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1211 * @param stdClass $context The context the page relates to. Not sure what happens
1212 * if you specify something other than system or front page. Defaults to system.
1214 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1215 $this->settings = new stdClass();
1216 $this->name = $name;
1217 $this->visiblename = $visiblename;
1218 if (is_array($req_capability)) {
1219 $this->req_capability = $req_capability;
1220 } else {
1221 $this->req_capability = array($req_capability);
1223 $this->hidden = $hidden;
1224 $this->context = $context;
1228 * see admin_category
1230 * @param string $name
1231 * @param bool $findpath
1232 * @return mixed Object (this) if name == this->name, else returns null
1234 public function locate($name, $findpath=false) {
1235 if ($this->name == $name) {
1236 if ($findpath) {
1237 $this->visiblepath = array($this->visiblename);
1238 $this->path = array($this->name);
1240 return $this;
1241 } else {
1242 $return = NULL;
1243 return $return;
1248 * Search string in settings page.
1250 * @param string $query
1251 * @return array
1253 public function search($query) {
1254 $found = array();
1256 foreach ($this->settings as $setting) {
1257 if ($setting->is_related($query)) {
1258 $found[] = $setting;
1262 if ($found) {
1263 $result = new stdClass();
1264 $result->page = $this;
1265 $result->settings = $found;
1266 return array($this->name => $result);
1269 $textlib = textlib_get_instance();
1271 $found = false;
1272 if (strpos(strtolower($this->name), $query) !== false) {
1273 $found = true;
1274 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1275 $found = true;
1277 if ($found) {
1278 $result = new stdClass();
1279 $result->page = $this;
1280 $result->settings = array();
1281 return array($this->name => $result);
1282 } else {
1283 return array();
1288 * This function always returns false, required by interface
1290 * @param string $name
1291 * @return bool Always false
1293 public function prune($name) {
1294 return false;
1298 * adds an admin_setting to this admin_settingpage
1300 * 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
1301 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1303 * @param object $setting is the admin_setting object you want to add
1304 * @return bool true if successful, false if not
1306 public function add($setting) {
1307 if (!($setting instanceof admin_setting)) {
1308 debugging('error - not a setting instance');
1309 return false;
1312 $this->settings->{$setting->name} = $setting;
1313 return true;
1317 * see admin_externalpage
1319 * @return bool Returns true for yes false for no
1321 public function check_access() {
1322 global $CFG;
1323 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1324 foreach($this->req_capability as $cap) {
1325 if (has_capability($cap, $context)) {
1326 return true;
1329 return false;
1333 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1334 * @return string Returns an XHTML string
1336 public function output_html() {
1337 $adminroot = admin_get_root();
1338 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1339 foreach($this->settings as $setting) {
1340 $fullname = $setting->get_full_name();
1341 if (array_key_exists($fullname, $adminroot->errors)) {
1342 $data = $adminroot->errors[$fullname]->data;
1343 } else {
1344 $data = $setting->get_setting();
1345 // do not use defaults if settings not available - upgrade settings handles the defaults!
1347 $return .= $setting->output_html($data);
1349 $return .= '</fieldset>';
1350 return $return;
1354 * Is this settings page hidden in admin tree block?
1356 * @return bool True if hidden
1358 public function is_hidden() {
1359 return $this->hidden;
1363 * Show we display Save button at the page bottom?
1364 * @return bool
1366 public function show_save() {
1367 foreach($this->settings as $setting) {
1368 if (empty($setting->nosave)) {
1369 return true;
1372 return false;
1378 * Admin settings class. Only exists on setting pages.
1379 * Read & write happens at this level; no authentication.
1381 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1383 abstract class admin_setting {
1384 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1385 public $name;
1386 /** @var string localised name */
1387 public $visiblename;
1388 /** @var string localised long description in Markdown format */
1389 public $description;
1390 /** @var mixed Can be string or array of string */
1391 public $defaultsetting;
1392 /** @var string */
1393 public $updatedcallback;
1394 /** @var mixed can be String or Null. Null means main config table */
1395 public $plugin; // null means main config table
1396 /** @var bool true indicates this setting does not actually save anything, just information */
1397 public $nosave = false;
1398 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1399 public $affectsmodinfo = false;
1402 * Constructor
1403 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1404 * or 'myplugin/mysetting' for ones in config_plugins.
1405 * @param string $visiblename localised name
1406 * @param string $description localised long description
1407 * @param mixed $defaultsetting string or array depending on implementation
1409 public function __construct($name, $visiblename, $description, $defaultsetting) {
1410 $this->parse_setting_name($name);
1411 $this->visiblename = $visiblename;
1412 $this->description = $description;
1413 $this->defaultsetting = $defaultsetting;
1417 * Set up $this->name and potentially $this->plugin
1419 * Set up $this->name and possibly $this->plugin based on whether $name looks
1420 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1421 * on the names, that is, output a developer debug warning if the name
1422 * contains anything other than [a-zA-Z0-9_]+.
1424 * @param string $name the setting name passed in to the constructor.
1426 private function parse_setting_name($name) {
1427 $bits = explode('/', $name);
1428 if (count($bits) > 2) {
1429 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1431 $this->name = array_pop($bits);
1432 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1433 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1435 if (!empty($bits)) {
1436 $this->plugin = array_pop($bits);
1437 if ($this->plugin === 'moodle') {
1438 $this->plugin = null;
1439 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1440 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1446 * Returns the fullname prefixed by the plugin
1447 * @return string
1449 public function get_full_name() {
1450 return 's_'.$this->plugin.'_'.$this->name;
1454 * Returns the ID string based on plugin and name
1455 * @return string
1457 public function get_id() {
1458 return 'id_s_'.$this->plugin.'_'.$this->name;
1462 * @param bool $affectsmodinfo If true, changes to this setting will
1463 * cause the course cache to be rebuilt
1465 public function set_affects_modinfo($affectsmodinfo) {
1466 $this->affectsmodinfo = $affectsmodinfo;
1470 * Returns the config if possible
1472 * @return mixed returns config if successful else null
1474 public function config_read($name) {
1475 global $CFG;
1476 if (!empty($this->plugin)) {
1477 $value = get_config($this->plugin, $name);
1478 return $value === false ? NULL : $value;
1480 } else {
1481 if (isset($CFG->$name)) {
1482 return $CFG->$name;
1483 } else {
1484 return NULL;
1490 * Used to set a config pair and log change
1492 * @param string $name
1493 * @param mixed $value Gets converted to string if not null
1494 * @return bool Write setting to config table
1496 public function config_write($name, $value) {
1497 global $DB, $USER, $CFG;
1499 if ($this->nosave) {
1500 return true;
1503 // make sure it is a real change
1504 $oldvalue = get_config($this->plugin, $name);
1505 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1506 $value = is_null($value) ? null : (string)$value;
1508 if ($oldvalue === $value) {
1509 return true;
1512 // store change
1513 set_config($name, $value, $this->plugin);
1515 // Some admin settings affect course modinfo
1516 if ($this->affectsmodinfo) {
1517 // Clear course cache for all courses
1518 rebuild_course_cache(0, true);
1521 // log change
1522 $log = new stdClass();
1523 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1524 $log->timemodified = time();
1525 $log->plugin = $this->plugin;
1526 $log->name = $name;
1527 $log->value = $value;
1528 $log->oldvalue = $oldvalue;
1529 $DB->insert_record('config_log', $log);
1531 return true; // BC only
1535 * Returns current value of this setting
1536 * @return mixed array or string depending on instance, NULL means not set yet
1538 public abstract function get_setting();
1541 * Returns default setting if exists
1542 * @return mixed array or string depending on instance; NULL means no default, user must supply
1544 public function get_defaultsetting() {
1545 $adminroot = admin_get_root(false, false);
1546 if (!empty($adminroot->custom_defaults)) {
1547 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1548 if (isset($adminroot->custom_defaults[$plugin])) {
1549 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1550 return $adminroot->custom_defaults[$plugin][$this->name];
1554 return $this->defaultsetting;
1558 * Store new setting
1560 * @param mixed $data string or array, must not be NULL
1561 * @return string empty string if ok, string error message otherwise
1563 public abstract function write_setting($data);
1566 * Return part of form with setting
1567 * This function should always be overwritten
1569 * @param mixed $data array or string depending on setting
1570 * @param string $query
1571 * @return string
1573 public function output_html($data, $query='') {
1574 // should be overridden
1575 return;
1579 * Function called if setting updated - cleanup, cache reset, etc.
1580 * @param string $functionname Sets the function name
1581 * @return void
1583 public function set_updatedcallback($functionname) {
1584 $this->updatedcallback = $functionname;
1588 * Is setting related to query text - used when searching
1589 * @param string $query
1590 * @return bool
1592 public function is_related($query) {
1593 if (strpos(strtolower($this->name), $query) !== false) {
1594 return true;
1596 $textlib = textlib_get_instance();
1597 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1598 return true;
1600 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1601 return true;
1603 $current = $this->get_setting();
1604 if (!is_null($current)) {
1605 if (is_string($current)) {
1606 if (strpos($textlib->strtolower($current), $query) !== false) {
1607 return true;
1611 $default = $this->get_defaultsetting();
1612 if (!is_null($default)) {
1613 if (is_string($default)) {
1614 if (strpos($textlib->strtolower($default), $query) !== false) {
1615 return true;
1619 return false;
1625 * No setting - just heading and text.
1627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1629 class admin_setting_heading extends admin_setting {
1632 * not a setting, just text
1633 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1634 * @param string $heading heading
1635 * @param string $information text in box
1637 public function __construct($name, $heading, $information) {
1638 $this->nosave = true;
1639 parent::__construct($name, $heading, $information, '');
1643 * Always returns true
1644 * @return bool Always returns true
1646 public function get_setting() {
1647 return true;
1651 * Always returns true
1652 * @return bool Always returns true
1654 public function get_defaultsetting() {
1655 return true;
1659 * Never write settings
1660 * @return string Always returns an empty string
1662 public function write_setting($data) {
1663 // do not write any setting
1664 return '';
1668 * Returns an HTML string
1669 * @return string Returns an HTML string
1671 public function output_html($data, $query='') {
1672 global $OUTPUT;
1673 $return = '';
1674 if ($this->visiblename != '') {
1675 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1677 if ($this->description != '') {
1678 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1680 return $return;
1686 * The most flexibly setting, user is typing text
1688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1690 class admin_setting_configtext extends admin_setting {
1692 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1693 public $paramtype;
1694 /** @var int default field size */
1695 public $size;
1698 * Config text constructor
1700 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1701 * @param string $visiblename localised
1702 * @param string $description long localised info
1703 * @param string $defaultsetting
1704 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1705 * @param int $size default field size
1707 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1708 $this->paramtype = $paramtype;
1709 if (!is_null($size)) {
1710 $this->size = $size;
1711 } else {
1712 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1714 parent::__construct($name, $visiblename, $description, $defaultsetting);
1718 * Return the setting
1720 * @return mixed returns config if successful else null
1722 public function get_setting() {
1723 return $this->config_read($this->name);
1726 public function write_setting($data) {
1727 if ($this->paramtype === PARAM_INT and $data === '') {
1728 // do not complain if '' used instead of 0
1729 $data = 0;
1731 // $data is a string
1732 $validated = $this->validate($data);
1733 if ($validated !== true) {
1734 return $validated;
1736 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1740 * Validate data before storage
1741 * @param string data
1742 * @return mixed true if ok string if error found
1744 public function validate($data) {
1745 // allow paramtype to be a custom regex if it is the form of /pattern/
1746 if (preg_match('#^/.*/$#', $this->paramtype)) {
1747 if (preg_match($this->paramtype, $data)) {
1748 return true;
1749 } else {
1750 return get_string('validateerror', 'admin');
1753 } else if ($this->paramtype === PARAM_RAW) {
1754 return true;
1756 } else {
1757 $cleaned = clean_param($data, $this->paramtype);
1758 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1759 return true;
1760 } else {
1761 return get_string('validateerror', 'admin');
1767 * Return an XHTML string for the setting
1768 * @return string Returns an XHTML string
1770 public function output_html($data, $query='') {
1771 $default = $this->get_defaultsetting();
1773 return format_admin_setting($this, $this->visiblename,
1774 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1775 $this->description, true, '', $default, $query);
1781 * General text area without html editor.
1783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1785 class admin_setting_configtextarea extends admin_setting_configtext {
1786 private $rows;
1787 private $cols;
1790 * @param string $name
1791 * @param string $visiblename
1792 * @param string $description
1793 * @param mixed $defaultsetting string or array
1794 * @param mixed $paramtype
1795 * @param string $cols The number of columns to make the editor
1796 * @param string $rows The number of rows to make the editor
1798 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1799 $this->rows = $rows;
1800 $this->cols = $cols;
1801 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1805 * Returns an XHTML string for the editor
1807 * @param string $data
1808 * @param string $query
1809 * @return string XHTML string for the editor
1811 public function output_html($data, $query='') {
1812 $default = $this->get_defaultsetting();
1814 $defaultinfo = $default;
1815 if (!is_null($default) and $default !== '') {
1816 $defaultinfo = "\n".$default;
1819 return format_admin_setting($this, $this->visiblename,
1820 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1821 $this->description, true, '', $defaultinfo, $query);
1827 * General text area with html editor.
1829 class admin_setting_confightmleditor extends admin_setting_configtext {
1830 private $rows;
1831 private $cols;
1834 * @param string $name
1835 * @param string $visiblename
1836 * @param string $description
1837 * @param mixed $defaultsetting string or array
1838 * @param mixed $paramtype
1840 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1841 $this->rows = $rows;
1842 $this->cols = $cols;
1843 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1844 editors_head_setup();
1848 * Returns an XHTML string for the editor
1850 * @param string $data
1851 * @param string $query
1852 * @return string XHTML string for the editor
1854 public function output_html($data, $query='') {
1855 $default = $this->get_defaultsetting();
1857 $defaultinfo = $default;
1858 if (!is_null($default) and $default !== '') {
1859 $defaultinfo = "\n".$default;
1862 $editor = editors_get_preferred_editor(FORMAT_HTML);
1863 $editor->use_editor($this->get_id(), array('noclean'=>true));
1865 return format_admin_setting($this, $this->visiblename,
1866 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1867 $this->description, true, '', $defaultinfo, $query);
1873 * Password field, allows unmasking of password
1875 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1877 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1879 * Constructor
1880 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1881 * @param string $visiblename localised
1882 * @param string $description long localised info
1883 * @param string $defaultsetting default password
1885 public function __construct($name, $visiblename, $description, $defaultsetting) {
1886 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1890 * Returns XHTML for the field
1891 * Writes Javascript into the HTML below right before the last div
1893 * @todo Make javascript available through newer methods if possible
1894 * @param string $data Value for the field
1895 * @param string $query Passed as final argument for format_admin_setting
1896 * @return string XHTML field
1898 public function output_html($data, $query='') {
1899 $id = $this->get_id();
1900 $unmask = get_string('unmaskpassword', 'form');
1901 $unmaskjs = '<script type="text/javascript">
1902 //<![CDATA[
1903 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1905 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1907 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1909 var unmaskchb = document.createElement("input");
1910 unmaskchb.setAttribute("type", "checkbox");
1911 unmaskchb.setAttribute("id", "'.$id.'unmask");
1912 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1913 unmaskdiv.appendChild(unmaskchb);
1915 var unmasklbl = document.createElement("label");
1916 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1917 if (is_ie) {
1918 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1919 } else {
1920 unmasklbl.setAttribute("for", "'.$id.'unmask");
1922 unmaskdiv.appendChild(unmasklbl);
1924 if (is_ie) {
1925 // ugly hack to work around the famous onchange IE bug
1926 unmaskchb.onclick = function() {this.blur();};
1927 unmaskdiv.onclick = function() {this.blur();};
1929 //]]>
1930 </script>';
1931 return format_admin_setting($this, $this->visiblename,
1932 '<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>',
1933 $this->description, true, '', NULL, $query);
1939 * Path to directory
1941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1943 class admin_setting_configfile extends admin_setting_configtext {
1945 * Constructor
1946 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1947 * @param string $visiblename localised
1948 * @param string $description long localised info
1949 * @param string $defaultdirectory default directory location
1951 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1952 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1956 * Returns XHTML for the field
1958 * Returns XHTML for the field and also checks whether the file
1959 * specified in $data exists using file_exists()
1961 * @param string $data File name and path to use in value attr
1962 * @param string $query
1963 * @return string XHTML field
1965 public function output_html($data, $query='') {
1966 $default = $this->get_defaultsetting();
1968 if ($data) {
1969 if (file_exists($data)) {
1970 $executable = '<span class="pathok">&#x2714;</span>';
1971 } else {
1972 $executable = '<span class="patherror">&#x2718;</span>';
1974 } else {
1975 $executable = '';
1978 return format_admin_setting($this, $this->visiblename,
1979 '<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>',
1980 $this->description, true, '', $default, $query);
1986 * Path to executable file
1988 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1990 class admin_setting_configexecutable extends admin_setting_configfile {
1993 * Returns an XHTML field
1995 * @param string $data This is the value for the field
1996 * @param string $query
1997 * @return string XHTML field
1999 public function output_html($data, $query='') {
2000 $default = $this->get_defaultsetting();
2002 if ($data) {
2003 if (file_exists($data) and is_executable($data)) {
2004 $executable = '<span class="pathok">&#x2714;</span>';
2005 } else {
2006 $executable = '<span class="patherror">&#x2718;</span>';
2008 } else {
2009 $executable = '';
2012 return format_admin_setting($this, $this->visiblename,
2013 '<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>',
2014 $this->description, true, '', $default, $query);
2020 * Path to directory
2022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2024 class admin_setting_configdirectory extends admin_setting_configfile {
2027 * Returns an XHTML field
2029 * @param string $data This is the value for the field
2030 * @param string $query
2031 * @return string XHTML
2033 public function output_html($data, $query='') {
2034 $default = $this->get_defaultsetting();
2036 if ($data) {
2037 if (file_exists($data) and is_dir($data)) {
2038 $executable = '<span class="pathok">&#x2714;</span>';
2039 } else {
2040 $executable = '<span class="patherror">&#x2718;</span>';
2042 } else {
2043 $executable = '';
2046 return format_admin_setting($this, $this->visiblename,
2047 '<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>',
2048 $this->description, true, '', $default, $query);
2054 * Checkbox
2056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2058 class admin_setting_configcheckbox extends admin_setting {
2059 /** @var string Value used when checked */
2060 public $yes;
2061 /** @var string Value used when not checked */
2062 public $no;
2065 * Constructor
2066 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2067 * @param string $visiblename localised
2068 * @param string $description long localised info
2069 * @param string $defaultsetting
2070 * @param string $yes value used when checked
2071 * @param string $no value used when not checked
2073 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2074 parent::__construct($name, $visiblename, $description, $defaultsetting);
2075 $this->yes = (string)$yes;
2076 $this->no = (string)$no;
2080 * Retrieves the current setting using the objects name
2082 * @return string
2084 public function get_setting() {
2085 return $this->config_read($this->name);
2089 * Sets the value for the setting
2091 * Sets the value for the setting to either the yes or no values
2092 * of the object by comparing $data to yes
2094 * @param mixed $data Gets converted to str for comparison against yes value
2095 * @return string empty string or error
2097 public function write_setting($data) {
2098 if ((string)$data === $this->yes) { // convert to strings before comparison
2099 $data = $this->yes;
2100 } else {
2101 $data = $this->no;
2103 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2107 * Returns an XHTML checkbox field
2109 * @param string $data If $data matches yes then checkbox is checked
2110 * @param string $query
2111 * @return string XHTML field
2113 public function output_html($data, $query='') {
2114 $default = $this->get_defaultsetting();
2116 if (!is_null($default)) {
2117 if ((string)$default === $this->yes) {
2118 $defaultinfo = get_string('checkboxyes', 'admin');
2119 } else {
2120 $defaultinfo = get_string('checkboxno', 'admin');
2122 } else {
2123 $defaultinfo = NULL;
2126 if ((string)$data === $this->yes) { // convert to strings before comparison
2127 $checked = 'checked="checked"';
2128 } else {
2129 $checked = '';
2132 return format_admin_setting($this, $this->visiblename,
2133 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2134 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2135 $this->description, true, '', $defaultinfo, $query);
2141 * Multiple checkboxes, each represents different value, stored in csv format
2143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2145 class admin_setting_configmulticheckbox extends admin_setting {
2146 /** @var array Array of choices value=>label */
2147 public $choices;
2150 * Constructor: uses parent::__construct
2152 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2153 * @param string $visiblename localised
2154 * @param string $description long localised info
2155 * @param array $defaultsetting array of selected
2156 * @param array $choices array of $value=>$label for each checkbox
2158 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2159 $this->choices = $choices;
2160 parent::__construct($name, $visiblename, $description, $defaultsetting);
2164 * This public function may be used in ancestors for lazy loading of choices
2166 * @todo Check if this function is still required content commented out only returns true
2167 * @return bool true if loaded, false if error
2169 public function load_choices() {
2171 if (is_array($this->choices)) {
2172 return true;
2174 .... load choices here
2176 return true;
2180 * Is setting related to query text - used when searching
2182 * @param string $query
2183 * @return bool true on related, false on not or failure
2185 public function is_related($query) {
2186 if (!$this->load_choices() or empty($this->choices)) {
2187 return false;
2189 if (parent::is_related($query)) {
2190 return true;
2193 $textlib = textlib_get_instance();
2194 foreach ($this->choices as $desc) {
2195 if (strpos($textlib->strtolower($desc), $query) !== false) {
2196 return true;
2199 return false;
2203 * Returns the current setting if it is set
2205 * @return mixed null if null, else an array
2207 public function get_setting() {
2208 $result = $this->config_read($this->name);
2210 if (is_null($result)) {
2211 return NULL;
2213 if ($result === '') {
2214 return array();
2216 $enabled = explode(',', $result);
2217 $setting = array();
2218 foreach ($enabled as $option) {
2219 $setting[$option] = 1;
2221 return $setting;
2225 * Saves the setting(s) provided in $data
2227 * @param array $data An array of data, if not array returns empty str
2228 * @return mixed empty string on useless data or bool true=success, false=failed
2230 public function write_setting($data) {
2231 if (!is_array($data)) {
2232 return ''; // ignore it
2234 if (!$this->load_choices() or empty($this->choices)) {
2235 return '';
2237 unset($data['xxxxx']);
2238 $result = array();
2239 foreach ($data as $key => $value) {
2240 if ($value and array_key_exists($key, $this->choices)) {
2241 $result[] = $key;
2244 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2248 * Returns XHTML field(s) as required by choices
2250 * Relies on data being an array should data ever be another valid vartype with
2251 * acceptable value this may cause a warning/error
2252 * if (!is_array($data)) would fix the problem
2254 * @todo Add vartype handling to ensure $data is an array
2256 * @param array $data An array of checked values
2257 * @param string $query
2258 * @return string XHTML field
2260 public function output_html($data, $query='') {
2261 if (!$this->load_choices() or empty($this->choices)) {
2262 return '';
2264 $default = $this->get_defaultsetting();
2265 if (is_null($default)) {
2266 $default = array();
2268 if (is_null($data)) {
2269 $data = array();
2271 $options = array();
2272 $defaults = array();
2273 foreach ($this->choices as $key=>$description) {
2274 if (!empty($data[$key])) {
2275 $checked = 'checked="checked"';
2276 } else {
2277 $checked = '';
2279 if (!empty($default[$key])) {
2280 $defaults[] = $description;
2283 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2284 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2287 if (is_null($default)) {
2288 $defaultinfo = NULL;
2289 } else if (!empty($defaults)) {
2290 $defaultinfo = implode(', ', $defaults);
2291 } else {
2292 $defaultinfo = get_string('none');
2295 $return = '<div class="form-multicheckbox">';
2296 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2297 if ($options) {
2298 $return .= '<ul>';
2299 foreach ($options as $option) {
2300 $return .= '<li>'.$option.'</li>';
2302 $return .= '</ul>';
2304 $return .= '</div>';
2306 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2313 * Multiple checkboxes 2, value stored as string 00101011
2315 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2317 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2320 * Returns the setting if set
2322 * @return mixed null if not set, else an array of set settings
2324 public function get_setting() {
2325 $result = $this->config_read($this->name);
2326 if (is_null($result)) {
2327 return NULL;
2329 if (!$this->load_choices()) {
2330 return NULL;
2332 $result = str_pad($result, count($this->choices), '0');
2333 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2334 $setting = array();
2335 foreach ($this->choices as $key=>$unused) {
2336 $value = array_shift($result);
2337 if ($value) {
2338 $setting[$key] = 1;
2341 return $setting;
2345 * Save setting(s) provided in $data param
2347 * @param array $data An array of settings to save
2348 * @return mixed empty string for bad data or bool true=>success, false=>error
2350 public function write_setting($data) {
2351 if (!is_array($data)) {
2352 return ''; // ignore it
2354 if (!$this->load_choices() or empty($this->choices)) {
2355 return '';
2357 $result = '';
2358 foreach ($this->choices as $key=>$unused) {
2359 if (!empty($data[$key])) {
2360 $result .= '1';
2361 } else {
2362 $result .= '0';
2365 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2371 * Select one value from list
2373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2375 class admin_setting_configselect extends admin_setting {
2376 /** @var array Array of choices value=>label */
2377 public $choices;
2380 * Constructor
2381 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2382 * @param string $visiblename localised
2383 * @param string $description long localised info
2384 * @param string|int $defaultsetting
2385 * @param array $choices array of $value=>$label for each selection
2387 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2388 $this->choices = $choices;
2389 parent::__construct($name, $visiblename, $description, $defaultsetting);
2393 * This function may be used in ancestors for lazy loading of choices
2395 * Override this method if loading of choices is expensive, such
2396 * as when it requires multiple db requests.
2398 * @return bool true if loaded, false if error
2400 public function load_choices() {
2402 if (is_array($this->choices)) {
2403 return true;
2405 .... load choices here
2407 return true;
2411 * Check if this is $query is related to a choice
2413 * @param string $query
2414 * @return bool true if related, false if not
2416 public function is_related($query) {
2417 if (parent::is_related($query)) {
2418 return true;
2420 if (!$this->load_choices()) {
2421 return false;
2423 $textlib = textlib_get_instance();
2424 foreach ($this->choices as $key=>$value) {
2425 if (strpos($textlib->strtolower($key), $query) !== false) {
2426 return true;
2428 if (strpos($textlib->strtolower($value), $query) !== false) {
2429 return true;
2432 return false;
2436 * Return the setting
2438 * @return mixed returns config if successful else null
2440 public function get_setting() {
2441 return $this->config_read($this->name);
2445 * Save a setting
2447 * @param string $data
2448 * @return string empty of error string
2450 public function write_setting($data) {
2451 if (!$this->load_choices() or empty($this->choices)) {
2452 return '';
2454 if (!array_key_exists($data, $this->choices)) {
2455 return ''; // ignore it
2458 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2462 * Returns XHTML select field
2464 * Ensure the options are loaded, and generate the XHTML for the select
2465 * element and any warning message. Separating this out from output_html
2466 * makes it easier to subclass this class.
2468 * @param string $data the option to show as selected.
2469 * @param string $current the currently selected option in the database, null if none.
2470 * @param string $default the default selected option.
2471 * @return array the HTML for the select element, and a warning message.
2473 public function output_select_html($data, $current, $default, $extraname = '') {
2474 if (!$this->load_choices() or empty($this->choices)) {
2475 return array('', '');
2478 $warning = '';
2479 if (is_null($current)) {
2480 // first run
2481 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2482 // no warning
2483 } else if (!array_key_exists($current, $this->choices)) {
2484 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2485 if (!is_null($default) and $data == $current) {
2486 $data = $default; // use default instead of first value when showing the form
2490 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2491 foreach ($this->choices as $key => $value) {
2492 // the string cast is needed because key may be integer - 0 is equal to most strings!
2493 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2495 $selecthtml .= '</select>';
2496 return array($selecthtml, $warning);
2500 * Returns XHTML select field and wrapping div(s)
2502 * @see output_select_html()
2504 * @param string $data the option to show as selected
2505 * @param string $query
2506 * @return string XHTML field and wrapping div
2508 public function output_html($data, $query='') {
2509 $default = $this->get_defaultsetting();
2510 $current = $this->get_setting();
2512 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2513 if (!$selecthtml) {
2514 return '';
2517 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2518 $defaultinfo = $this->choices[$default];
2519 } else {
2520 $defaultinfo = NULL;
2523 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2525 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2531 * Select multiple items from list
2533 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2535 class admin_setting_configmultiselect extends admin_setting_configselect {
2537 * Constructor
2538 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2539 * @param string $visiblename localised
2540 * @param string $description long localised info
2541 * @param array $defaultsetting array of selected items
2542 * @param array $choices array of $value=>$label for each list item
2544 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2545 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2549 * Returns the select setting(s)
2551 * @return mixed null or array. Null if no settings else array of setting(s)
2553 public function get_setting() {
2554 $result = $this->config_read($this->name);
2555 if (is_null($result)) {
2556 return NULL;
2558 if ($result === '') {
2559 return array();
2561 return explode(',', $result);
2565 * Saves setting(s) provided through $data
2567 * Potential bug in the works should anyone call with this function
2568 * using a vartype that is not an array
2570 * @param array $data
2572 public function write_setting($data) {
2573 if (!is_array($data)) {
2574 return ''; //ignore it
2576 if (!$this->load_choices() or empty($this->choices)) {
2577 return '';
2580 unset($data['xxxxx']);
2582 $save = array();
2583 foreach ($data as $value) {
2584 if (!array_key_exists($value, $this->choices)) {
2585 continue; // ignore it
2587 $save[] = $value;
2590 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2594 * Is setting related to query text - used when searching
2596 * @param string $query
2597 * @return bool true if related, false if not
2599 public function is_related($query) {
2600 if (!$this->load_choices() or empty($this->choices)) {
2601 return false;
2603 if (parent::is_related($query)) {
2604 return true;
2607 $textlib = textlib_get_instance();
2608 foreach ($this->choices as $desc) {
2609 if (strpos($textlib->strtolower($desc), $query) !== false) {
2610 return true;
2613 return false;
2617 * Returns XHTML multi-select field
2619 * @todo Add vartype handling to ensure $data is an array
2620 * @param array $data Array of values to select by default
2621 * @param string $query
2622 * @return string XHTML multi-select field
2624 public function output_html($data, $query='') {
2625 if (!$this->load_choices() or empty($this->choices)) {
2626 return '';
2628 $choices = $this->choices;
2629 $default = $this->get_defaultsetting();
2630 if (is_null($default)) {
2631 $default = array();
2633 if (is_null($data)) {
2634 $data = array();
2637 $defaults = array();
2638 $size = min(10, count($this->choices));
2639 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2640 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2641 foreach ($this->choices as $key => $description) {
2642 if (in_array($key, $data)) {
2643 $selected = 'selected="selected"';
2644 } else {
2645 $selected = '';
2647 if (in_array($key, $default)) {
2648 $defaults[] = $description;
2651 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2654 if (is_null($default)) {
2655 $defaultinfo = NULL;
2656 } if (!empty($defaults)) {
2657 $defaultinfo = implode(', ', $defaults);
2658 } else {
2659 $defaultinfo = get_string('none');
2662 $return .= '</select></div>';
2663 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2668 * Time selector
2670 * This is a liiitle bit messy. we're using two selects, but we're returning
2671 * them as an array named after $name (so we only use $name2 internally for the setting)
2673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2675 class admin_setting_configtime extends admin_setting {
2676 /** @var string Used for setting second select (minutes) */
2677 public $name2;
2680 * Constructor
2681 * @param string $hoursname setting for hours
2682 * @param string $minutesname setting for hours
2683 * @param string $visiblename localised
2684 * @param string $description long localised info
2685 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2687 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2688 $this->name2 = $minutesname;
2689 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2693 * Get the selected time
2695 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2697 public function get_setting() {
2698 $result1 = $this->config_read($this->name);
2699 $result2 = $this->config_read($this->name2);
2700 if (is_null($result1) or is_null($result2)) {
2701 return NULL;
2704 return array('h' => $result1, 'm' => $result2);
2708 * Store the time (hours and minutes)
2710 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2711 * @return bool true if success, false if not
2713 public function write_setting($data) {
2714 if (!is_array($data)) {
2715 return '';
2718 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2719 return ($result ? '' : get_string('errorsetting', 'admin'));
2723 * Returns XHTML time select fields
2725 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2726 * @param string $query
2727 * @return string XHTML time select fields and wrapping div(s)
2729 public function output_html($data, $query='') {
2730 $default = $this->get_defaultsetting();
2732 if (is_array($default)) {
2733 $defaultinfo = $default['h'].':'.$default['m'];
2734 } else {
2735 $defaultinfo = NULL;
2738 $return = '<div class="form-time defaultsnext">'.
2739 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2740 for ($i = 0; $i < 24; $i++) {
2741 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2743 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2744 for ($i = 0; $i < 60; $i += 5) {
2745 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2747 $return .= '</select></div>';
2748 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2755 * Used to validate a textarea used for ip addresses
2757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2759 class admin_setting_configiplist extends admin_setting_configtextarea {
2762 * Validate the contents of the textarea as IP addresses
2764 * Used to validate a new line separated list of IP addresses collected from
2765 * a textarea control
2767 * @param string $data A list of IP Addresses separated by new lines
2768 * @return mixed bool true for success or string:error on failure
2770 public function validate($data) {
2771 if(!empty($data)) {
2772 $ips = explode("\n", $data);
2773 } else {
2774 return true;
2776 $result = true;
2777 foreach($ips as $ip) {
2778 $ip = trim($ip);
2779 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2780 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2781 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2782 $result = true;
2783 } else {
2784 $result = false;
2785 break;
2788 if($result) {
2789 return true;
2790 } else {
2791 return get_string('validateerror', 'admin');
2798 * An admin setting for selecting one or more users who have a capability
2799 * in the system context
2801 * An admin setting for selecting one or more users, who have a particular capability
2802 * in the system context. Warning, make sure the list will never be too long. There is
2803 * no paging or searching of this list.
2805 * To correctly get a list of users from this config setting, you need to call the
2806 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2810 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2811 /** @var string The capabilities name */
2812 protected $capability;
2813 /** @var int include admin users too */
2814 protected $includeadmins;
2817 * Constructor.
2819 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2820 * @param string $visiblename localised name
2821 * @param string $description localised long description
2822 * @param array $defaultsetting array of usernames
2823 * @param string $capability string capability name.
2824 * @param bool $includeadmins include administrators
2826 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2827 $this->capability = $capability;
2828 $this->includeadmins = $includeadmins;
2829 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2833 * Load all of the uses who have the capability into choice array
2835 * @return bool Always returns true
2837 function load_choices() {
2838 if (is_array($this->choices)) {
2839 return true;
2841 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2842 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2843 $this->choices = array(
2844 '$@NONE@$' => get_string('nobody'),
2845 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2847 if ($this->includeadmins) {
2848 $admins = get_admins();
2849 foreach ($admins as $user) {
2850 $this->choices[$user->id] = fullname($user);
2853 if (is_array($users)) {
2854 foreach ($users as $user) {
2855 $this->choices[$user->id] = fullname($user);
2858 return true;
2862 * Returns the default setting for class
2864 * @return mixed Array, or string. Empty string if no default
2866 public function get_defaultsetting() {
2867 $this->load_choices();
2868 $defaultsetting = parent::get_defaultsetting();
2869 if (empty($defaultsetting)) {
2870 return array('$@NONE@$');
2871 } else if (array_key_exists($defaultsetting, $this->choices)) {
2872 return $defaultsetting;
2873 } else {
2874 return '';
2879 * Returns the current setting
2881 * @return mixed array or string
2883 public function get_setting() {
2884 $result = parent::get_setting();
2885 if ($result === null) {
2886 // this is necessary for settings upgrade
2887 return null;
2889 if (empty($result)) {
2890 $result = array('$@NONE@$');
2892 return $result;
2896 * Save the chosen setting provided as $data
2898 * @param array $data
2899 * @return mixed string or array
2901 public function write_setting($data) {
2902 // If all is selected, remove any explicit options.
2903 if (in_array('$@ALL@$', $data)) {
2904 $data = array('$@ALL@$');
2906 // None never needs to be written to the DB.
2907 if (in_array('$@NONE@$', $data)) {
2908 unset($data[array_search('$@NONE@$', $data)]);
2910 return parent::write_setting($data);
2916 * Special checkbox for calendar - resets SESSION vars.
2918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2920 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2922 * Calls the parent::__construct with default values
2924 * name => calendar_adminseesall
2925 * visiblename => get_string('adminseesall', 'admin')
2926 * description => get_string('helpadminseesall', 'admin')
2927 * defaultsetting => 0
2929 public function __construct() {
2930 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2931 get_string('helpadminseesall', 'admin'), '0');
2935 * Stores the setting passed in $data
2937 * @param mixed gets converted to string for comparison
2938 * @return string empty string or error message
2940 public function write_setting($data) {
2941 global $SESSION;
2942 return parent::write_setting($data);
2947 * Special select for settings that are altered in setup.php and can not be altered on the fly
2949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2951 class admin_setting_special_selectsetup extends admin_setting_configselect {
2953 * Reads the setting directly from the database
2955 * @return mixed
2957 public function get_setting() {
2958 // read directly from db!
2959 return get_config(NULL, $this->name);
2963 * Save the setting passed in $data
2965 * @param string $data The setting to save
2966 * @return string empty or error message
2968 public function write_setting($data) {
2969 global $CFG;
2970 // do not change active CFG setting!
2971 $current = $CFG->{$this->name};
2972 $result = parent::write_setting($data);
2973 $CFG->{$this->name} = $current;
2974 return $result;
2980 * Special select for frontpage - stores data in course table
2982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2984 class admin_setting_sitesetselect extends admin_setting_configselect {
2986 * Returns the site name for the selected site
2988 * @see get_site()
2989 * @return string The site name of the selected site
2991 public function get_setting() {
2992 $site = get_site();
2993 return $site->{$this->name};
2997 * Updates the database and save the setting
2999 * @param string data
3000 * @return string empty or error message
3002 public function write_setting($data) {
3003 global $DB, $SITE;
3004 if (!in_array($data, array_keys($this->choices))) {
3005 return get_string('errorsetting', 'admin');
3007 $record = new stdClass();
3008 $record->id = SITEID;
3009 $temp = $this->name;
3010 $record->$temp = $data;
3011 $record->timemodified = time();
3012 // update $SITE
3013 $SITE->{$this->name} = $data;
3014 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3020 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3021 * block to hidden.
3023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3025 class admin_setting_bloglevel extends admin_setting_configselect {
3027 * Updates the database and save the setting
3029 * @param string data
3030 * @return string empty or error message
3032 public function write_setting($data) {
3033 global $DB, $CFG;
3034 if ($data == 0) {
3035 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3036 foreach ($blogblocks as $block) {
3037 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3039 } else {
3040 // reenable all blocks only when switching from disabled blogs
3041 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3042 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3043 foreach ($blogblocks as $block) {
3044 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3048 return parent::write_setting($data);
3054 * Special select - lists on the frontpage - hacky
3056 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3058 class admin_setting_courselist_frontpage extends admin_setting {
3059 /** @var array Array of choices value=>label */
3060 public $choices;
3063 * Construct override, requires one param
3065 * @param bool $loggedin Is the user logged in
3067 public function __construct($loggedin) {
3068 global $CFG;
3069 require_once($CFG->dirroot.'/course/lib.php');
3070 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3071 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3072 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3073 $defaults = array(FRONTPAGECOURSELIST);
3074 parent::__construct($name, $visiblename, $description, $defaults);
3078 * Loads the choices available
3080 * @return bool always returns true
3082 public function load_choices() {
3083 global $DB;
3084 if (is_array($this->choices)) {
3085 return true;
3087 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3088 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3089 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3090 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3091 'none' => get_string('none'));
3092 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3093 unset($this->choices[FRONTPAGECOURSELIST]);
3095 return true;
3099 * Returns the selected settings
3101 * @param mixed array or setting or null
3103 public function get_setting() {
3104 $result = $this->config_read($this->name);
3105 if (is_null($result)) {
3106 return NULL;
3108 if ($result === '') {
3109 return array();
3111 return explode(',', $result);
3115 * Save the selected options
3117 * @param array $data
3118 * @return mixed empty string (data is not an array) or bool true=success false=failure
3120 public function write_setting($data) {
3121 if (!is_array($data)) {
3122 return '';
3124 $this->load_choices();
3125 $save = array();
3126 foreach($data as $datum) {
3127 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3128 continue;
3130 $save[$datum] = $datum; // no duplicates
3132 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3136 * Return XHTML select field and wrapping div
3138 * @todo Add vartype handling to make sure $data is an array
3139 * @param array $data Array of elements to select by default
3140 * @return string XHTML select field and wrapping div
3142 public function output_html($data, $query='') {
3143 $this->load_choices();
3144 $currentsetting = array();
3145 foreach ($data as $key) {
3146 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3147 $currentsetting[] = $key; // already selected first
3151 $return = '<div class="form-group">';
3152 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3153 if (!array_key_exists($i, $currentsetting)) {
3154 $currentsetting[$i] = 'none'; //none
3156 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3157 foreach ($this->choices as $key => $value) {
3158 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3160 $return .= '</select>';
3161 if ($i !== count($this->choices) - 2) {
3162 $return .= '<br />';
3165 $return .= '</div>';
3167 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3173 * Special checkbox for frontpage - stores data in course table
3175 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3177 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3179 * Returns the current sites name
3181 * @return string
3183 public function get_setting() {
3184 $site = get_site();
3185 return $site->{$this->name};
3189 * Save the selected setting
3191 * @param string $data The selected site
3192 * @return string empty string or error message
3194 public function write_setting($data) {
3195 global $DB, $SITE;
3196 $record = new stdClass();
3197 $record->id = SITEID;
3198 $record->{$this->name} = ($data == '1' ? 1 : 0);
3199 $record->timemodified = time();
3200 // update $SITE
3201 $SITE->{$this->name} = $data;
3202 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3207 * Special text for frontpage - stores data in course table.
3208 * Empty string means not set here. Manual setting is required.
3210 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3212 class admin_setting_sitesettext extends admin_setting_configtext {
3214 * Return the current setting
3216 * @return mixed string or null
3218 public function get_setting() {
3219 $site = get_site();
3220 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3224 * Validate the selected data
3226 * @param string $data The selected value to validate
3227 * @return mixed true or message string
3229 public function validate($data) {
3230 $cleaned = clean_param($data, PARAM_MULTILANG);
3231 if ($cleaned === '') {
3232 return get_string('required');
3234 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3235 return true;
3236 } else {
3237 return get_string('validateerror', 'admin');
3242 * Save the selected setting
3244 * @param string $data The selected value
3245 * @return string empty or error message
3247 public function write_setting($data) {
3248 global $DB, $SITE;
3249 $data = trim($data);
3250 $validated = $this->validate($data);
3251 if ($validated !== true) {
3252 return $validated;
3255 $record = new stdClass();
3256 $record->id = SITEID;
3257 $record->{$this->name} = $data;
3258 $record->timemodified = time();
3259 // update $SITE
3260 $SITE->{$this->name} = $data;
3261 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3267 * Special text editor for site description.
3269 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3271 class admin_setting_special_frontpagedesc extends admin_setting {
3273 * Calls parent::__construct with specific arguments
3275 public function __construct() {
3276 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3277 editors_head_setup();
3281 * Return the current setting
3282 * @return string The current setting
3284 public function get_setting() {
3285 $site = get_site();
3286 return $site->{$this->name};
3290 * Save the new setting
3292 * @param string $data The new value to save
3293 * @return string empty or error message
3295 public function write_setting($data) {
3296 global $DB, $SITE;
3297 $record = new stdClass();
3298 $record->id = SITEID;
3299 $record->{$this->name} = $data;
3300 $record->timemodified = time();
3301 $SITE->{$this->name} = $data;
3302 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3306 * Returns XHTML for the field plus wrapping div
3308 * @param string $data The current value
3309 * @param string $query
3310 * @return string The XHTML output
3312 public function output_html($data, $query='') {
3313 global $CFG;
3315 $CFG->adminusehtmleditor = can_use_html_editor();
3316 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3318 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3324 * Administration interface for emoticon_manager settings.
3326 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3328 class admin_setting_emoticons extends admin_setting {
3331 * Calls parent::__construct with specific args
3333 public function __construct() {
3334 global $CFG;
3336 $manager = get_emoticon_manager();
3337 $defaults = $this->prepare_form_data($manager->default_emoticons());
3338 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3342 * Return the current setting(s)
3344 * @return array Current settings array
3346 public function get_setting() {
3347 global $CFG;
3349 $manager = get_emoticon_manager();
3351 $config = $this->config_read($this->name);
3352 if (is_null($config)) {
3353 return null;
3356 $config = $manager->decode_stored_config($config);
3357 if (is_null($config)) {
3358 return null;
3361 return $this->prepare_form_data($config);
3365 * Save selected settings
3367 * @param array $data Array of settings to save
3368 * @return bool
3370 public function write_setting($data) {
3372 $manager = get_emoticon_manager();
3373 $emoticons = $this->process_form_data($data);
3375 if ($emoticons === false) {
3376 return false;
3379 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3380 return ''; // success
3381 } else {
3382 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3387 * Return XHTML field(s) for options
3389 * @param array $data Array of options to set in HTML
3390 * @return string XHTML string for the fields and wrapping div(s)
3392 public function output_html($data, $query='') {
3393 global $OUTPUT;
3395 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3396 $out .= html_writer::start_tag('thead');
3397 $out .= html_writer::start_tag('tr');
3398 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3399 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3400 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3401 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3402 $out .= html_writer::tag('th', '');
3403 $out .= html_writer::end_tag('tr');
3404 $out .= html_writer::end_tag('thead');
3405 $out .= html_writer::start_tag('tbody');
3406 $i = 0;
3407 foreach($data as $field => $value) {
3408 switch ($i) {
3409 case 0:
3410 $out .= html_writer::start_tag('tr');
3411 $current_text = $value;
3412 $current_filename = '';
3413 $current_imagecomponent = '';
3414 $current_altidentifier = '';
3415 $current_altcomponent = '';
3416 case 1:
3417 $current_filename = $value;
3418 case 2:
3419 $current_imagecomponent = $value;
3420 case 3:
3421 $current_altidentifier = $value;
3422 case 4:
3423 $current_altcomponent = $value;
3426 $out .= html_writer::tag('td',
3427 html_writer::empty_tag('input',
3428 array(
3429 'type' => 'text',
3430 'class' => 'form-text',
3431 'name' => $this->get_full_name().'['.$field.']',
3432 'value' => $value,
3434 ), array('class' => 'c'.$i)
3437 if ($i == 4) {
3438 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3439 $alt = get_string($current_altidentifier, $current_altcomponent);
3440 } else {
3441 $alt = $current_text;
3443 if ($current_filename) {
3444 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3445 } else {
3446 $out .= html_writer::tag('td', '');
3448 $out .= html_writer::end_tag('tr');
3449 $i = 0;
3450 } else {
3451 $i++;
3455 $out .= html_writer::end_tag('tbody');
3456 $out .= html_writer::end_tag('table');
3457 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3458 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3460 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3464 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3466 * @see self::process_form_data()
3467 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3468 * @return array of form fields and their values
3470 protected function prepare_form_data(array $emoticons) {
3472 $form = array();
3473 $i = 0;
3474 foreach ($emoticons as $emoticon) {
3475 $form['text'.$i] = $emoticon->text;
3476 $form['imagename'.$i] = $emoticon->imagename;
3477 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3478 $form['altidentifier'.$i] = $emoticon->altidentifier;
3479 $form['altcomponent'.$i] = $emoticon->altcomponent;
3480 $i++;
3482 // add one more blank field set for new object
3483 $form['text'.$i] = '';
3484 $form['imagename'.$i] = '';
3485 $form['imagecomponent'.$i] = '';
3486 $form['altidentifier'.$i] = '';
3487 $form['altcomponent'.$i] = '';
3489 return $form;
3493 * Converts the data from admin settings form into an array of emoticon objects
3495 * @see self::prepare_form_data()
3496 * @param array $data array of admin form fields and values
3497 * @return false|array of emoticon objects
3499 protected function process_form_data(array $form) {
3501 $count = count($form); // number of form field values
3503 if ($count % 5) {
3504 // we must get five fields per emoticon object
3505 return false;
3508 $emoticons = array();
3509 for ($i = 0; $i < $count / 5; $i++) {
3510 $emoticon = new stdClass();
3511 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3512 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3513 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_SAFEDIR);
3514 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3515 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_SAFEDIR);
3517 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3518 // prevent from breaking http://url.addresses by accident
3519 $emoticon->text = '';
3522 if (strlen($emoticon->text) < 2) {
3523 // do not allow single character emoticons
3524 $emoticon->text = '';
3527 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3528 // emoticon text must contain some non-alphanumeric character to prevent
3529 // breaking HTML tags
3530 $emoticon->text = '';
3533 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3534 $emoticons[] = $emoticon;
3537 return $emoticons;
3543 * Special setting for limiting of the list of available languages.
3545 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3547 class admin_setting_langlist extends admin_setting_configtext {
3549 * Calls parent::__construct with specific arguments
3551 public function __construct() {
3552 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3556 * Save the new setting
3558 * @param string $data The new setting
3559 * @return bool
3561 public function write_setting($data) {
3562 $return = parent::write_setting($data);
3563 get_string_manager()->reset_caches();
3564 return $return;
3570 * Selection of one of the recognised countries using the list
3571 * returned by {@link get_list_of_countries()}.
3573 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3575 class admin_settings_country_select extends admin_setting_configselect {
3576 protected $includeall;
3577 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3578 $this->includeall = $includeall;
3579 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3583 * Lazy-load the available choices for the select box
3585 public function load_choices() {
3586 global $CFG;
3587 if (is_array($this->choices)) {
3588 return true;
3590 $this->choices = array_merge(
3591 array('0' => get_string('choosedots')),
3592 get_string_manager()->get_list_of_countries($this->includeall));
3593 return true;
3599 * admin_setting_configselect for the default number of sections in a course,
3600 * simply so we can lazy-load the choices.
3602 * @copyright 2011 The Open University
3603 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3605 class admin_settings_num_course_sections extends admin_setting_configselect {
3606 public function __construct($name, $visiblename, $description, $defaultsetting) {
3607 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3610 /** Lazy-load the available choices for the select box */
3611 public function load_choices() {
3612 $max = get_config('moodlecourse', 'maxsections');
3613 if (empty($max)) {
3614 $max = 52;
3616 for ($i = 0; $i <= $max; $i++) {
3617 $this->choices[$i] = "$i";
3619 return true;
3625 * Course category selection
3627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3629 class admin_settings_coursecat_select extends admin_setting_configselect {
3631 * Calls parent::__construct with specific arguments
3633 public function __construct($name, $visiblename, $description, $defaultsetting) {
3634 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3638 * Load the available choices for the select box
3640 * @return bool
3642 public function load_choices() {
3643 global $CFG;
3644 require_once($CFG->dirroot.'/course/lib.php');
3645 if (is_array($this->choices)) {
3646 return true;
3648 $this->choices = make_categories_options();
3649 return true;
3655 * Special control for selecting days to backup
3657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3659 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3661 * Calls parent::__construct with specific arguments
3663 public function __construct() {
3664 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3665 $this->plugin = 'backup';
3669 * Load the available choices for the select box
3671 * @return bool Always returns true
3673 public function load_choices() {
3674 if (is_array($this->choices)) {
3675 return true;
3677 $this->choices = array();
3678 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3679 foreach ($days as $day) {
3680 $this->choices[$day] = get_string($day, 'calendar');
3682 return true;
3688 * Special debug setting
3690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3692 class admin_setting_special_debug extends admin_setting_configselect {
3694 * Calls parent::__construct with specific arguments
3696 public function __construct() {
3697 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3701 * Load the available choices for the select box
3703 * @return bool
3705 public function load_choices() {
3706 if (is_array($this->choices)) {
3707 return true;
3709 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3710 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3711 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3712 DEBUG_ALL => get_string('debugall', 'admin'),
3713 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3714 return true;
3720 * Special admin control
3722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3724 class admin_setting_special_calendar_weekend extends admin_setting {
3726 * Calls parent::__construct with specific arguments
3728 public function __construct() {
3729 $name = 'calendar_weekend';
3730 $visiblename = get_string('calendar_weekend', 'admin');
3731 $description = get_string('helpweekenddays', 'admin');
3732 $default = array ('0', '6'); // Saturdays and Sundays
3733 parent::__construct($name, $visiblename, $description, $default);
3737 * Gets the current settings as an array
3739 * @return mixed Null if none, else array of settings
3741 public function get_setting() {
3742 $result = $this->config_read($this->name);
3743 if (is_null($result)) {
3744 return NULL;
3746 if ($result === '') {
3747 return array();
3749 $settings = array();
3750 for ($i=0; $i<7; $i++) {
3751 if ($result & (1 << $i)) {
3752 $settings[] = $i;
3755 return $settings;
3759 * Save the new settings
3761 * @param array $data Array of new settings
3762 * @return bool
3764 public function write_setting($data) {
3765 if (!is_array($data)) {
3766 return '';
3768 unset($data['xxxxx']);
3769 $result = 0;
3770 foreach($data as $index) {
3771 $result |= 1 << $index;
3773 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3777 * Return XHTML to display the control
3779 * @param array $data array of selected days
3780 * @param string $query
3781 * @return string XHTML for display (field + wrapping div(s)
3783 public function output_html($data, $query='') {
3784 // The order matters very much because of the implied numeric keys
3785 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3786 $return = '<table><thead><tr>';
3787 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3788 foreach($days as $index => $day) {
3789 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3791 $return .= '</tr></thead><tbody><tr>';
3792 foreach($days as $index => $day) {
3793 $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>';
3795 $return .= '</tr></tbody></table>';
3797 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3804 * Admin setting that allows a user to pick a behaviour.
3806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3808 class admin_setting_question_behaviour extends admin_setting_configselect {
3810 * @param string $name name of config variable
3811 * @param string $visiblename display name
3812 * @param string $description description
3813 * @param string $default default.
3815 public function __construct($name, $visiblename, $description, $default) {
3816 parent::__construct($name, $visiblename, $description, $default, NULL);
3820 * Load list of behaviours as choices
3821 * @return bool true => success, false => error.
3823 public function load_choices() {
3824 global $CFG;
3825 require_once($CFG->dirroot . '/question/engine/lib.php');
3826 $this->choices = question_engine::get_archetypal_behaviours();
3827 return true;
3833 * Admin setting that allows a user to pick appropriate roles for something.
3835 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3837 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
3838 /** @var array Array of capabilities which identify roles */
3839 private $types;
3842 * @param string $name Name of config variable
3843 * @param string $visiblename Display name
3844 * @param string $description Description
3845 * @param array $types Array of archetypes which identify
3846 * roles that will be enabled by default.
3848 public function __construct($name, $visiblename, $description, $types) {
3849 parent::__construct($name, $visiblename, $description, NULL, NULL);
3850 $this->types = $types;
3854 * Load roles as choices
3856 * @return bool true=>success, false=>error
3858 public function load_choices() {
3859 global $CFG, $DB;
3860 if (during_initial_install()) {
3861 return false;
3863 if (is_array($this->choices)) {
3864 return true;
3866 if ($roles = get_all_roles()) {
3867 $this->choices = array();
3868 foreach($roles as $role) {
3869 $this->choices[$role->id] = format_string($role->name);
3871 return true;
3872 } else {
3873 return false;
3878 * Return the default setting for this control
3880 * @return array Array of default settings
3882 public function get_defaultsetting() {
3883 global $CFG;
3885 if (during_initial_install()) {
3886 return null;
3888 $result = array();
3889 foreach($this->types as $archetype) {
3890 if ($caproles = get_archetype_roles($archetype)) {
3891 foreach ($caproles as $caprole) {
3892 $result[$caprole->id] = 1;
3896 return $result;
3902 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
3904 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3906 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
3908 * Constructor
3909 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3910 * @param string $visiblename localised
3911 * @param string $description long localised info
3912 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
3913 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
3914 * @param int $size default field size
3916 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
3917 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
3921 * Loads the current setting and returns array
3923 * @return array Returns array value=>xx, __construct=>xx
3925 public function get_setting() {
3926 $value = parent::get_setting();
3927 $adv = $this->config_read($this->name.'_adv');
3928 if (is_null($value) or is_null($adv)) {
3929 return NULL;
3931 return array('value' => $value, 'adv' => $adv);
3935 * Saves the new settings passed in $data
3937 * @todo Add vartype handling to ensure $data is an array
3938 * @param array $data
3939 * @return mixed string or Array
3941 public function write_setting($data) {
3942 $error = parent::write_setting($data['value']);
3943 if (!$error) {
3944 $value = empty($data['adv']) ? 0 : 1;
3945 $this->config_write($this->name.'_adv', $value);
3947 return $error;
3951 * Return XHTML for the control
3953 * @param array $data Default data array
3954 * @param string $query
3955 * @return string XHTML to display control
3957 public function output_html($data, $query='') {
3958 $default = $this->get_defaultsetting();
3959 $defaultinfo = array();
3960 if (isset($default['value'])) {
3961 if ($default['value'] === '') {
3962 $defaultinfo[] = "''";
3963 } else {
3964 $defaultinfo[] = $default['value'];
3967 if (!empty($default['adv'])) {
3968 $defaultinfo[] = get_string('advanced');
3970 $defaultinfo = implode(', ', $defaultinfo);
3972 $adv = !empty($data['adv']);
3973 $return = '<div class="form-text defaultsnext">' .
3974 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
3975 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
3976 ' <input type="checkbox" class="form-checkbox" id="' .
3977 $this->get_id() . '_adv" name="' . $this->get_full_name() .
3978 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
3979 ' <label for="' . $this->get_id() . '_adv">' .
3980 get_string('advanced') . '</label></div>';
3982 return format_admin_setting($this, $this->visiblename, $return,
3983 $this->description, true, '', $defaultinfo, $query);
3989 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
3991 * @copyright 2009 Petr Skoda (http://skodak.org)
3992 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3994 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
3997 * Constructor
3998 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3999 * @param string $visiblename localised
4000 * @param string $description long localised info
4001 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4002 * @param string $yes value used when checked
4003 * @param string $no value used when not checked
4005 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4006 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4010 * Loads the current setting and returns array
4012 * @return array Returns array value=>xx, adv=>xx
4014 public function get_setting() {
4015 $value = parent::get_setting();
4016 $adv = $this->config_read($this->name.'_adv');
4017 if (is_null($value) or is_null($adv)) {
4018 return NULL;
4020 return array('value' => $value, 'adv' => $adv);
4024 * Sets the value for the setting
4026 * Sets the value for the setting to either the yes or no values
4027 * of the object by comparing $data to yes
4029 * @param mixed $data Gets converted to str for comparison against yes value
4030 * @return string empty string or error
4032 public function write_setting($data) {
4033 $error = parent::write_setting($data['value']);
4034 if (!$error) {
4035 $value = empty($data['adv']) ? 0 : 1;
4036 $this->config_write($this->name.'_adv', $value);
4038 return $error;
4042 * Returns an XHTML checkbox field and with extra advanced cehckbox
4044 * @param string $data If $data matches yes then checkbox is checked
4045 * @param string $query
4046 * @return string XHTML field
4048 public function output_html($data, $query='') {
4049 $defaults = $this->get_defaultsetting();
4050 $defaultinfo = array();
4051 if (!is_null($defaults)) {
4052 if ((string)$defaults['value'] === $this->yes) {
4053 $defaultinfo[] = get_string('checkboxyes', 'admin');
4054 } else {
4055 $defaultinfo[] = get_string('checkboxno', 'admin');
4057 if (!empty($defaults['adv'])) {
4058 $defaultinfo[] = get_string('advanced');
4061 $defaultinfo = implode(', ', $defaultinfo);
4063 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4064 $checked = 'checked="checked"';
4065 } else {
4066 $checked = '';
4068 if (!empty($data['adv'])) {
4069 $advanced = 'checked="checked"';
4070 } else {
4071 $advanced = '';
4074 $fullname = $this->get_full_name();
4075 $novalue = s($this->no);
4076 $yesvalue = s($this->yes);
4077 $id = $this->get_id();
4078 $stradvanced = get_string('advanced');
4079 $return = <<<EOT
4080 <div class="form-checkbox defaultsnext" >
4081 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4082 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4083 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4084 <label for="{$id}_adv">$stradvanced</label>
4085 </div>
4086 EOT;
4087 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4088 true, '', $defaultinfo, $query);
4094 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4096 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4098 * @copyright 2010 Sam Hemelryk
4099 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4101 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4103 * Constructor
4104 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4105 * @param string $visiblename localised
4106 * @param string $description long localised info
4107 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4108 * @param string $yes value used when checked
4109 * @param string $no value used when not checked
4111 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4112 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4116 * Loads the current setting and returns array
4118 * @return array Returns array value=>xx, adv=>xx
4120 public function get_setting() {
4121 $value = parent::get_setting();
4122 $locked = $this->config_read($this->name.'_locked');
4123 if (is_null($value) or is_null($locked)) {
4124 return NULL;
4126 return array('value' => $value, 'locked' => $locked);
4130 * Sets the value for the setting
4132 * Sets the value for the setting to either the yes or no values
4133 * of the object by comparing $data to yes
4135 * @param mixed $data Gets converted to str for comparison against yes value
4136 * @return string empty string or error
4138 public function write_setting($data) {
4139 $error = parent::write_setting($data['value']);
4140 if (!$error) {
4141 $value = empty($data['locked']) ? 0 : 1;
4142 $this->config_write($this->name.'_locked', $value);
4144 return $error;
4148 * Returns an XHTML checkbox field and with extra locked checkbox
4150 * @param string $data If $data matches yes then checkbox is checked
4151 * @param string $query
4152 * @return string XHTML field
4154 public function output_html($data, $query='') {
4155 $defaults = $this->get_defaultsetting();
4156 $defaultinfo = array();
4157 if (!is_null($defaults)) {
4158 if ((string)$defaults['value'] === $this->yes) {
4159 $defaultinfo[] = get_string('checkboxyes', 'admin');
4160 } else {
4161 $defaultinfo[] = get_string('checkboxno', 'admin');
4163 if (!empty($defaults['locked'])) {
4164 $defaultinfo[] = get_string('locked', 'admin');
4167 $defaultinfo = implode(', ', $defaultinfo);
4169 $fullname = $this->get_full_name();
4170 $novalue = s($this->no);
4171 $yesvalue = s($this->yes);
4172 $id = $this->get_id();
4174 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4175 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4176 $checkboxparams['checked'] = 'checked';
4179 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4180 if (!empty($data['locked'])) { // convert to strings before comparison
4181 $lockcheckboxparams['checked'] = 'checked';
4184 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4185 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4186 $return .= html_writer::empty_tag('input', $checkboxparams);
4187 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4188 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4189 $return .= html_writer::end_tag('div');
4190 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4196 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4200 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4202 * Calls parent::__construct with specific arguments
4204 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4205 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4209 * Loads the current setting and returns array
4211 * @return array Returns array value=>xx, adv=>xx
4213 public function get_setting() {
4214 $value = parent::get_setting();
4215 $adv = $this->config_read($this->name.'_adv');
4216 if (is_null($value) or is_null($adv)) {
4217 return NULL;
4219 return array('value' => $value, 'adv' => $adv);
4223 * Saves the new settings passed in $data
4225 * @todo Add vartype handling to ensure $data is an array
4226 * @param array $data
4227 * @return mixed string or Array
4229 public function write_setting($data) {
4230 $error = parent::write_setting($data['value']);
4231 if (!$error) {
4232 $value = empty($data['adv']) ? 0 : 1;
4233 $this->config_write($this->name.'_adv', $value);
4235 return $error;
4239 * Return XHTML for the control
4241 * @param array $data Default data array
4242 * @param string $query
4243 * @return string XHTML to display control
4245 public function output_html($data, $query='') {
4246 $default = $this->get_defaultsetting();
4247 $current = $this->get_setting();
4249 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4250 $current['value'], $default['value'], '[value]');
4251 if (!$selecthtml) {
4252 return '';
4255 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4256 $defaultinfo = array();
4257 if (isset($this->choices[$default['value']])) {
4258 $defaultinfo[] = $this->choices[$default['value']];
4260 if (!empty($default['adv'])) {
4261 $defaultinfo[] = get_string('advanced');
4263 $defaultinfo = implode(', ', $defaultinfo);
4264 } else {
4265 $defaultinfo = '';
4268 $adv = !empty($data['adv']);
4269 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4270 ' <input type="checkbox" class="form-checkbox" id="' .
4271 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4272 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4273 ' <label for="' . $this->get_id() . '_adv">' .
4274 get_string('advanced') . '</label></div>';
4276 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4282 * Graded roles in gradebook
4284 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4286 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4288 * Calls parent::__construct with specific arguments
4290 public function __construct() {
4291 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4292 get_string('configgradebookroles', 'admin'),
4293 array('student'));
4300 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4302 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4304 * Saves the new settings passed in $data
4306 * @param string $data
4307 * @return mixed string or Array
4309 public function write_setting($data) {
4310 global $CFG, $DB;
4312 $oldvalue = $this->config_read($this->name);
4313 $return = parent::write_setting($data);
4314 $newvalue = $this->config_read($this->name);
4316 if ($oldvalue !== $newvalue) {
4317 // force full regrading
4318 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4321 return $return;
4327 * Which roles to show on course description page
4329 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4331 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4333 * Calls parent::__construct with specific arguments
4335 public function __construct() {
4336 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4337 get_string('coursecontact_desc', 'admin'),
4338 array('editingteacher'));
4345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4347 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4349 * Calls parent::__construct with specific arguments
4351 function admin_setting_special_gradelimiting() {
4352 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4353 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4357 * Force site regrading
4359 function regrade_all() {
4360 global $CFG;
4361 require_once("$CFG->libdir/gradelib.php");
4362 grade_force_site_regrading();
4366 * Saves the new settings
4368 * @param mixed $data
4369 * @return string empty string or error message
4371 function write_setting($data) {
4372 $previous = $this->get_setting();
4374 if ($previous === null) {
4375 if ($data) {
4376 $this->regrade_all();
4378 } else {
4379 if ($data != $previous) {
4380 $this->regrade_all();
4383 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4390 * Primary grade export plugin - has state tracking.
4392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4394 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4396 * Calls parent::__construct with specific arguments
4398 public function __construct() {
4399 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4400 get_string('configgradeexport', 'admin'), array(), NULL);
4404 * Load the available choices for the multicheckbox
4406 * @return bool always returns true
4408 public function load_choices() {
4409 if (is_array($this->choices)) {
4410 return true;
4412 $this->choices = array();
4414 if ($plugins = get_plugin_list('gradeexport')) {
4415 foreach($plugins as $plugin => $unused) {
4416 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4419 return true;
4425 * Grade category settings
4427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4429 class admin_setting_gradecat_combo extends admin_setting {
4430 /** @var array Array of choices */
4431 public $choices;
4434 * Sets choices and calls parent::__construct with passed arguments
4435 * @param string $name
4436 * @param string $visiblename
4437 * @param string $description
4438 * @param mixed $defaultsetting string or array depending on implementation
4439 * @param array $choices An array of choices for the control
4441 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4442 $this->choices = $choices;
4443 parent::__construct($name, $visiblename, $description, $defaultsetting);
4447 * Return the current setting(s) array
4449 * @return array Array of value=>xx, forced=>xx, adv=>xx
4451 public function get_setting() {
4452 global $CFG;
4454 $value = $this->config_read($this->name);
4455 $flag = $this->config_read($this->name.'_flag');
4457 if (is_null($value) or is_null($flag)) {
4458 return NULL;
4461 $flag = (int)$flag;
4462 $forced = (boolean)(1 & $flag); // first bit
4463 $adv = (boolean)(2 & $flag); // second bit
4465 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4469 * Save the new settings passed in $data
4471 * @todo Add vartype handling to ensure $data is array
4472 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4473 * @return string empty or error message
4475 public function write_setting($data) {
4476 global $CFG;
4478 $value = $data['value'];
4479 $forced = empty($data['forced']) ? 0 : 1;
4480 $adv = empty($data['adv']) ? 0 : 2;
4481 $flag = ($forced | $adv); //bitwise or
4483 if (!in_array($value, array_keys($this->choices))) {
4484 return 'Error setting ';
4487 $oldvalue = $this->config_read($this->name);
4488 $oldflag = (int)$this->config_read($this->name.'_flag');
4489 $oldforced = (1 & $oldflag); // first bit
4491 $result1 = $this->config_write($this->name, $value);
4492 $result2 = $this->config_write($this->name.'_flag', $flag);
4494 // force regrade if needed
4495 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4496 require_once($CFG->libdir.'/gradelib.php');
4497 grade_category::updated_forced_settings();
4500 if ($result1 and $result2) {
4501 return '';
4502 } else {
4503 return get_string('errorsetting', 'admin');
4508 * Return XHTML to display the field and wrapping div
4510 * @todo Add vartype handling to ensure $data is array
4511 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4512 * @param string $query
4513 * @return string XHTML to display control
4515 public function output_html($data, $query='') {
4516 $value = $data['value'];
4517 $forced = !empty($data['forced']);
4518 $adv = !empty($data['adv']);
4520 $default = $this->get_defaultsetting();
4521 if (!is_null($default)) {
4522 $defaultinfo = array();
4523 if (isset($this->choices[$default['value']])) {
4524 $defaultinfo[] = $this->choices[$default['value']];
4526 if (!empty($default['forced'])) {
4527 $defaultinfo[] = get_string('force');
4529 if (!empty($default['adv'])) {
4530 $defaultinfo[] = get_string('advanced');
4532 $defaultinfo = implode(', ', $defaultinfo);
4534 } else {
4535 $defaultinfo = NULL;
4539 $return = '<div class="form-group">';
4540 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4541 foreach ($this->choices as $key => $val) {
4542 // the string cast is needed because key may be integer - 0 is equal to most strings!
4543 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4545 $return .= '</select>';
4546 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4547 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4548 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4549 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4550 $return .= '</div>';
4552 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4558 * Selection of grade report in user profiles
4560 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4562 class admin_setting_grade_profilereport extends admin_setting_configselect {
4564 * Calls parent::__construct with specific arguments
4566 public function __construct() {
4567 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4571 * Loads an array of choices for the configselect control
4573 * @return bool always return true
4575 public function load_choices() {
4576 if (is_array($this->choices)) {
4577 return true;
4579 $this->choices = array();
4581 global $CFG;
4582 require_once($CFG->libdir.'/gradelib.php');
4584 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4585 if (file_exists($plugindir.'/lib.php')) {
4586 require_once($plugindir.'/lib.php');
4587 $functionname = 'grade_report_'.$plugin.'_profilereport';
4588 if (function_exists($functionname)) {
4589 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4593 return true;
4599 * Special class for register auth selection
4601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4603 class admin_setting_special_registerauth extends admin_setting_configselect {
4605 * Calls parent::__construct with specific arguments
4607 public function __construct() {
4608 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4612 * Returns the default option
4614 * @return string empty or default option
4616 public function get_defaultsetting() {
4617 $this->load_choices();
4618 $defaultsetting = parent::get_defaultsetting();
4619 if (array_key_exists($defaultsetting, $this->choices)) {
4620 return $defaultsetting;
4621 } else {
4622 return '';
4627 * Loads the possible choices for the array
4629 * @return bool always returns true
4631 public function load_choices() {
4632 global $CFG;
4634 if (is_array($this->choices)) {
4635 return true;
4637 $this->choices = array();
4638 $this->choices[''] = get_string('disable');
4640 $authsenabled = get_enabled_auth_plugins(true);
4642 foreach ($authsenabled as $auth) {
4643 $authplugin = get_auth_plugin($auth);
4644 if (!$authplugin->can_signup()) {
4645 continue;
4647 // Get the auth title (from core or own auth lang files)
4648 $authtitle = $authplugin->get_title();
4649 $this->choices[$auth] = $authtitle;
4651 return true;
4657 * General plugins manager
4659 class admin_page_pluginsoverview extends admin_externalpage {
4662 * Sets basic information about the external page
4664 public function __construct() {
4665 global $CFG;
4666 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4667 "$CFG->wwwroot/$CFG->admin/plugins.php");
4672 * Module manage page
4674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4676 class admin_page_managemods extends admin_externalpage {
4678 * Calls parent::__construct with specific arguments
4680 public function __construct() {
4681 global $CFG;
4682 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4686 * Try to find the specified module
4688 * @param string $query The module to search for
4689 * @return array
4691 public function search($query) {
4692 global $CFG, $DB;
4693 if ($result = parent::search($query)) {
4694 return $result;
4697 $found = false;
4698 if ($modules = $DB->get_records('modules')) {
4699 $textlib = textlib_get_instance();
4700 foreach ($modules as $module) {
4701 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4702 continue;
4704 if (strpos($module->name, $query) !== false) {
4705 $found = true;
4706 break;
4708 $strmodulename = get_string('modulename', $module->name);
4709 if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
4710 $found = true;
4711 break;
4715 if ($found) {
4716 $result = new stdClass();
4717 $result->page = $this;
4718 $result->settings = array();
4719 return array($this->name => $result);
4720 } else {
4721 return array();
4728 * Special class for enrol plugins management.
4730 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4731 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4733 class admin_setting_manageenrols extends admin_setting {
4735 * Calls parent::__construct with specific arguments
4737 public function __construct() {
4738 $this->nosave = true;
4739 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4743 * Always returns true, does nothing
4745 * @return true
4747 public function get_setting() {
4748 return true;
4752 * Always returns true, does nothing
4754 * @return true
4756 public function get_defaultsetting() {
4757 return true;
4761 * Always returns '', does not write anything
4763 * @return string Always returns ''
4765 public function write_setting($data) {
4766 // do not write any setting
4767 return '';
4771 * Checks if $query is one of the available enrol plugins
4773 * @param string $query The string to search for
4774 * @return bool Returns true if found, false if not
4776 public function is_related($query) {
4777 if (parent::is_related($query)) {
4778 return true;
4781 $textlib = textlib_get_instance();
4782 $query = $textlib->strtolower($query);
4783 $enrols = enrol_get_plugins(false);
4784 foreach ($enrols as $name=>$enrol) {
4785 $localised = get_string('pluginname', 'enrol_'.$name);
4786 if (strpos($textlib->strtolower($name), $query) !== false) {
4787 return true;
4789 if (strpos($textlib->strtolower($localised), $query) !== false) {
4790 return true;
4793 return false;
4797 * Builds the XHTML to display the control
4799 * @param string $data Unused
4800 * @param string $query
4801 * @return string
4803 public function output_html($data, $query='') {
4804 global $CFG, $OUTPUT, $DB;
4806 // display strings
4807 $strup = get_string('up');
4808 $strdown = get_string('down');
4809 $strsettings = get_string('settings');
4810 $strenable = get_string('enable');
4811 $strdisable = get_string('disable');
4812 $struninstall = get_string('uninstallplugin', 'admin');
4813 $strusage = get_string('enrolusage', 'enrol');
4815 $enrols_available = enrol_get_plugins(false);
4816 $active_enrols = enrol_get_plugins(true);
4818 $allenrols = array();
4819 foreach ($active_enrols as $key=>$enrol) {
4820 $allenrols[$key] = true;
4822 foreach ($enrols_available as $key=>$enrol) {
4823 $allenrols[$key] = true;
4825 // now find all borked plugins and at least allow then to uninstall
4826 $borked = array();
4827 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
4828 foreach ($condidates as $candidate) {
4829 if (empty($allenrols[$candidate])) {
4830 $allenrols[$candidate] = true;
4834 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
4835 $return .= $OUTPUT->box_start('generalbox enrolsui');
4837 $table = new html_table();
4838 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
4839 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
4840 $table->width = '90%';
4841 $table->data = array();
4843 // iterate through enrol plugins and add to the display table
4844 $updowncount = 1;
4845 $enrolcount = count($active_enrols);
4846 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
4847 $printed = array();
4848 foreach($allenrols as $enrol => $unused) {
4849 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
4850 $name = get_string('pluginname', 'enrol_'.$enrol);
4851 } else {
4852 $name = $enrol;
4854 //usage
4855 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
4856 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
4857 $usage = "$ci / $cp";
4859 // hide/show link
4860 if (isset($active_enrols[$enrol])) {
4861 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
4862 $hideshow = "<a href=\"$aurl\">";
4863 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
4864 $enabled = true;
4865 $displayname = "<span>$name</span>";
4866 } else if (isset($enrols_available[$enrol])) {
4867 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
4868 $hideshow = "<a href=\"$aurl\">";
4869 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
4870 $enabled = false;
4871 $displayname = "<span class=\"dimmed_text\">$name</span>";
4872 } else {
4873 $hideshow = '';
4874 $enabled = false;
4875 $displayname = '<span class="notifyproblem">'.$name.'</span>';
4878 // up/down link (only if enrol is enabled)
4879 $updown = '';
4880 if ($enabled) {
4881 if ($updowncount > 1) {
4882 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
4883 $updown .= "<a href=\"$aurl\">";
4884 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
4885 } else {
4886 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
4888 if ($updowncount < $enrolcount) {
4889 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
4890 $updown .= "<a href=\"$aurl\">";
4891 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
4892 } else {
4893 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
4895 ++$updowncount;
4898 // settings link
4899 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
4900 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
4901 $settings = "<a href=\"$surl\">$strsettings</a>";
4902 } else {
4903 $settings = '';
4906 // uninstall
4907 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
4908 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
4910 // add a row to the table
4911 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
4913 $printed[$enrol] = true;
4916 $return .= html_writer::table($table);
4917 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
4918 $return .= $OUTPUT->box_end();
4919 return highlight($query, $return);
4925 * Blocks manage page
4927 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4929 class admin_page_manageblocks extends admin_externalpage {
4931 * Calls parent::__construct with specific arguments
4933 public function __construct() {
4934 global $CFG;
4935 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
4939 * Search for a specific block
4941 * @param string $query The string to search for
4942 * @return array
4944 public function search($query) {
4945 global $CFG, $DB;
4946 if ($result = parent::search($query)) {
4947 return $result;
4950 $found = false;
4951 if ($blocks = $DB->get_records('block')) {
4952 $textlib = textlib_get_instance();
4953 foreach ($blocks as $block) {
4954 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
4955 continue;
4957 if (strpos($block->name, $query) !== false) {
4958 $found = true;
4959 break;
4961 $strblockname = get_string('pluginname', 'block_'.$block->name);
4962 if (strpos($textlib->strtolower($strblockname), $query) !== false) {
4963 $found = true;
4964 break;
4968 if ($found) {
4969 $result = new stdClass();
4970 $result->page = $this;
4971 $result->settings = array();
4972 return array($this->name => $result);
4973 } else {
4974 return array();
4980 * Message outputs configuration
4982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4984 class admin_page_managemessageoutputs extends admin_externalpage {
4986 * Calls parent::__construct with specific arguments
4988 public function __construct() {
4989 global $CFG;
4990 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
4994 * Search for a specific message processor
4996 * @param string $query The string to search for
4997 * @return array
4999 public function search($query) {
5000 global $CFG, $DB;
5001 if ($result = parent::search($query)) {
5002 return $result;
5005 $found = false;
5006 if ($processors = get_message_processors()) {
5007 $textlib = textlib_get_instance();
5008 foreach ($processors as $processor) {
5009 if (!$processor->available) {
5010 continue;
5012 if (strpos($processor->name, $query) !== false) {
5013 $found = true;
5014 break;
5016 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5017 if (strpos($textlib->strtolower($strprocessorname), $query) !== false) {
5018 $found = true;
5019 break;
5023 if ($found) {
5024 $result = new stdClass();
5025 $result->page = $this;
5026 $result->settings = array();
5027 return array($this->name => $result);
5028 } else {
5029 return array();
5035 * Default message outputs configuration
5037 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5039 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5041 * Calls parent::__construct with specific arguments
5043 public function __construct() {
5044 global $CFG;
5045 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5051 * Manage question behaviours page
5053 * @copyright 2011 The Open University
5054 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5056 class admin_page_manageqbehaviours extends admin_externalpage {
5058 * Constructor
5060 public function __construct() {
5061 global $CFG;
5062 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5063 new moodle_url('/admin/qbehaviours.php'));
5067 * Search question behaviours for the specified string
5069 * @param string $query The string to search for in question behaviours
5070 * @return array
5072 public function search($query) {
5073 global $CFG;
5074 if ($result = parent::search($query)) {
5075 return $result;
5078 $found = false;
5079 $textlib = textlib_get_instance();
5080 require_once($CFG->dirroot . '/question/engine/lib.php');
5081 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5082 if (strpos($textlib->strtolower(question_engine::get_behaviour_name($behaviour)),
5083 $query) !== false) {
5084 $found = true;
5085 break;
5088 if ($found) {
5089 $result = new stdClass();
5090 $result->page = $this;
5091 $result->settings = array();
5092 return array($this->name => $result);
5093 } else {
5094 return array();
5101 * Question type manage page
5103 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5105 class admin_page_manageqtypes extends admin_externalpage {
5107 * Calls parent::__construct with specific arguments
5109 public function __construct() {
5110 global $CFG;
5111 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5115 * Search question types for the specified string
5117 * @param string $query The string to search for in question types
5118 * @return array
5120 public function search($query) {
5121 global $CFG;
5122 if ($result = parent::search($query)) {
5123 return $result;
5126 $found = false;
5127 $textlib = textlib_get_instance();
5128 require_once($CFG->dirroot . '/question/engine/bank.php');
5129 foreach (question_bank::get_all_qtypes() as $qtype) {
5130 if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
5131 $found = true;
5132 break;
5135 if ($found) {
5136 $result = new stdClass();
5137 $result->page = $this;
5138 $result->settings = array();
5139 return array($this->name => $result);
5140 } else {
5141 return array();
5147 class admin_page_manageportfolios extends admin_externalpage {
5149 * Calls parent::__construct with specific arguments
5151 public function __construct() {
5152 global $CFG;
5153 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5154 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5158 * Searches page for the specified string.
5159 * @param string $query The string to search for
5160 * @return bool True if it is found on this page
5162 public function search($query) {
5163 global $CFG;
5164 if ($result = parent::search($query)) {
5165 return $result;
5168 $found = false;
5169 $textlib = textlib_get_instance();
5170 $portfolios = get_plugin_list('portfolio');
5171 foreach ($portfolios as $p => $dir) {
5172 if (strpos($p, $query) !== false) {
5173 $found = true;
5174 break;
5177 if (!$found) {
5178 foreach (portfolio_instances(false, false) as $instance) {
5179 $title = $instance->get('name');
5180 if (strpos($textlib->strtolower($title), $query) !== false) {
5181 $found = true;
5182 break;
5187 if ($found) {
5188 $result = new stdClass();
5189 $result->page = $this;
5190 $result->settings = array();
5191 return array($this->name => $result);
5192 } else {
5193 return array();
5199 class admin_page_managerepositories extends admin_externalpage {
5201 * Calls parent::__construct with specific arguments
5203 public function __construct() {
5204 global $CFG;
5205 parent::__construct('managerepositories', get_string('manage',
5206 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5210 * Searches page for the specified string.
5211 * @param string $query The string to search for
5212 * @return bool True if it is found on this page
5214 public function search($query) {
5215 global $CFG;
5216 if ($result = parent::search($query)) {
5217 return $result;
5220 $found = false;
5221 $textlib = textlib_get_instance();
5222 $repositories= get_plugin_list('repository');
5223 foreach ($repositories as $p => $dir) {
5224 if (strpos($p, $query) !== false) {
5225 $found = true;
5226 break;
5229 if (!$found) {
5230 foreach (repository::get_types() as $instance) {
5231 $title = $instance->get_typename();
5232 if (strpos($textlib->strtolower($title), $query) !== false) {
5233 $found = true;
5234 break;
5239 if ($found) {
5240 $result = new stdClass();
5241 $result->page = $this;
5242 $result->settings = array();
5243 return array($this->name => $result);
5244 } else {
5245 return array();
5252 * Special class for authentication administration.
5254 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5256 class admin_setting_manageauths extends admin_setting {
5258 * Calls parent::__construct with specific arguments
5260 public function __construct() {
5261 $this->nosave = true;
5262 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5266 * Always returns true
5268 * @return true
5270 public function get_setting() {
5271 return true;
5275 * Always returns true
5277 * @return true
5279 public function get_defaultsetting() {
5280 return true;
5284 * Always returns '' and doesn't write anything
5286 * @return string Always returns ''
5288 public function write_setting($data) {
5289 // do not write any setting
5290 return '';
5294 * Search to find if Query is related to auth plugin
5296 * @param string $query The string to search for
5297 * @return bool true for related false for not
5299 public function is_related($query) {
5300 if (parent::is_related($query)) {
5301 return true;
5304 $textlib = textlib_get_instance();
5305 $authsavailable = get_plugin_list('auth');
5306 foreach ($authsavailable as $auth => $dir) {
5307 if (strpos($auth, $query) !== false) {
5308 return true;
5310 $authplugin = get_auth_plugin($auth);
5311 $authtitle = $authplugin->get_title();
5312 if (strpos($textlib->strtolower($authtitle), $query) !== false) {
5313 return true;
5316 return false;
5320 * Return XHTML to display control
5322 * @param mixed $data Unused
5323 * @param string $query
5324 * @return string highlight
5326 public function output_html($data, $query='') {
5327 global $CFG, $OUTPUT;
5330 // display strings
5331 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5332 'settings', 'edit', 'name', 'enable', 'disable',
5333 'up', 'down', 'none'));
5334 $txt->updown = "$txt->up/$txt->down";
5336 $authsavailable = get_plugin_list('auth');
5337 get_enabled_auth_plugins(true); // fix the list of enabled auths
5338 if (empty($CFG->auth)) {
5339 $authsenabled = array();
5340 } else {
5341 $authsenabled = explode(',', $CFG->auth);
5344 // construct the display array, with enabled auth plugins at the top, in order
5345 $displayauths = array();
5346 $registrationauths = array();
5347 $registrationauths[''] = $txt->disable;
5348 foreach ($authsenabled as $auth) {
5349 $authplugin = get_auth_plugin($auth);
5350 /// Get the auth title (from core or own auth lang files)
5351 $authtitle = $authplugin->get_title();
5352 /// Apply titles
5353 $displayauths[$auth] = $authtitle;
5354 if ($authplugin->can_signup()) {
5355 $registrationauths[$auth] = $authtitle;
5359 foreach ($authsavailable as $auth => $dir) {
5360 if (array_key_exists($auth, $displayauths)) {
5361 continue; //already in the list
5363 $authplugin = get_auth_plugin($auth);
5364 /// Get the auth title (from core or own auth lang files)
5365 $authtitle = $authplugin->get_title();
5366 /// Apply titles
5367 $displayauths[$auth] = $authtitle;
5368 if ($authplugin->can_signup()) {
5369 $registrationauths[$auth] = $authtitle;
5373 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5374 $return .= $OUTPUT->box_start('generalbox authsui');
5376 $table = new html_table();
5377 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5378 $table->align = array('left', 'center', 'center', 'center');
5379 $table->data = array();
5380 $table->attributes['class'] = 'manageauthtable generaltable';
5382 //add always enabled plugins first
5383 $displayname = "<span>".$displayauths['manual']."</span>";
5384 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5385 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5386 $table->data[] = array($displayname, '', '', $settings);
5387 $displayname = "<span>".$displayauths['nologin']."</span>";
5388 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5389 $table->data[] = array($displayname, '', '', $settings);
5392 // iterate through auth plugins and add to the display table
5393 $updowncount = 1;
5394 $authcount = count($authsenabled);
5395 $url = "auth.php?sesskey=" . sesskey();
5396 foreach ($displayauths as $auth => $name) {
5397 if ($auth == 'manual' or $auth == 'nologin') {
5398 continue;
5400 // hide/show link
5401 if (in_array($auth, $authsenabled)) {
5402 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5403 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5404 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5405 $enabled = true;
5406 $displayname = "<span>$name</span>";
5408 else {
5409 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5410 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5411 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5412 $enabled = false;
5413 $displayname = "<span class=\"dimmed_text\">$name</span>";
5416 // up/down link (only if auth is enabled)
5417 $updown = '';
5418 if ($enabled) {
5419 if ($updowncount > 1) {
5420 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5421 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5423 else {
5424 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5426 if ($updowncount < $authcount) {
5427 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5428 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5430 else {
5431 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5433 ++ $updowncount;
5436 // settings link
5437 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5438 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5439 } else {
5440 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5443 // add a row to the table
5444 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5446 $return .= html_writer::table($table);
5447 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5448 $return .= $OUTPUT->box_end();
5449 return highlight($query, $return);
5455 * Special class for authentication administration.
5457 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5459 class admin_setting_manageeditors extends admin_setting {
5461 * Calls parent::__construct with specific arguments
5463 public function __construct() {
5464 $this->nosave = true;
5465 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5469 * Always returns true, does nothing
5471 * @return true
5473 public function get_setting() {
5474 return true;
5478 * Always returns true, does nothing
5480 * @return true
5482 public function get_defaultsetting() {
5483 return true;
5487 * Always returns '', does not write anything
5489 * @return string Always returns ''
5491 public function write_setting($data) {
5492 // do not write any setting
5493 return '';
5497 * Checks if $query is one of the available editors
5499 * @param string $query The string to search for
5500 * @return bool Returns true if found, false if not
5502 public function is_related($query) {
5503 if (parent::is_related($query)) {
5504 return true;
5507 $textlib = textlib_get_instance();
5508 $editors_available = editors_get_available();
5509 foreach ($editors_available as $editor=>$editorstr) {
5510 if (strpos($editor, $query) !== false) {
5511 return true;
5513 if (strpos($textlib->strtolower($editorstr), $query) !== false) {
5514 return true;
5517 return false;
5521 * Builds the XHTML to display the control
5523 * @param string $data Unused
5524 * @param string $query
5525 * @return string
5527 public function output_html($data, $query='') {
5528 global $CFG, $OUTPUT;
5530 // display strings
5531 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5532 'up', 'down', 'none'));
5533 $txt->updown = "$txt->up/$txt->down";
5535 $editors_available = editors_get_available();
5536 $active_editors = explode(',', $CFG->texteditors);
5538 $active_editors = array_reverse($active_editors);
5539 foreach ($active_editors as $key=>$editor) {
5540 if (empty($editors_available[$editor])) {
5541 unset($active_editors[$key]);
5542 } else {
5543 $name = $editors_available[$editor];
5544 unset($editors_available[$editor]);
5545 $editors_available[$editor] = $name;
5548 if (empty($active_editors)) {
5549 //$active_editors = array('textarea');
5551 $editors_available = array_reverse($editors_available, true);
5552 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5553 $return .= $OUTPUT->box_start('generalbox editorsui');
5555 $table = new html_table();
5556 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5557 $table->align = array('left', 'center', 'center', 'center');
5558 $table->width = '90%';
5559 $table->data = array();
5561 // iterate through auth plugins and add to the display table
5562 $updowncount = 1;
5563 $editorcount = count($active_editors);
5564 $url = "editors.php?sesskey=" . sesskey();
5565 foreach ($editors_available as $editor => $name) {
5566 // hide/show link
5567 if (in_array($editor, $active_editors)) {
5568 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5569 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5570 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5571 $enabled = true;
5572 $displayname = "<span>$name</span>";
5574 else {
5575 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5576 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5577 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5578 $enabled = false;
5579 $displayname = "<span class=\"dimmed_text\">$name</span>";
5582 // up/down link (only if auth is enabled)
5583 $updown = '';
5584 if ($enabled) {
5585 if ($updowncount > 1) {
5586 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5587 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5589 else {
5590 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5592 if ($updowncount < $editorcount) {
5593 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5594 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5596 else {
5597 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5599 ++ $updowncount;
5602 // settings link
5603 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5604 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5605 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5606 } else {
5607 $settings = '';
5610 // add a row to the table
5611 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5613 $return .= html_writer::table($table);
5614 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5615 $return .= $OUTPUT->box_end();
5616 return highlight($query, $return);
5622 * Special class for license administration.
5624 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5626 class admin_setting_managelicenses extends admin_setting {
5628 * Calls parent::__construct with specific arguments
5630 public function __construct() {
5631 $this->nosave = true;
5632 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5636 * Always returns true, does nothing
5638 * @return true
5640 public function get_setting() {
5641 return true;
5645 * Always returns true, does nothing
5647 * @return true
5649 public function get_defaultsetting() {
5650 return true;
5654 * Always returns '', does not write anything
5656 * @return string Always returns ''
5658 public function write_setting($data) {
5659 // do not write any setting
5660 return '';
5664 * Builds the XHTML to display the control
5666 * @param string $data Unused
5667 * @param string $query
5668 * @return string
5670 public function output_html($data, $query='') {
5671 global $CFG, $OUTPUT;
5672 require_once($CFG->libdir . '/licenselib.php');
5673 $url = "licenses.php?sesskey=" . sesskey();
5675 // display strings
5676 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5677 $licenses = license_manager::get_licenses();
5679 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5681 $return .= $OUTPUT->box_start('generalbox editorsui');
5683 $table = new html_table();
5684 $table->head = array($txt->name, $txt->enable);
5685 $table->align = array('left', 'center');
5686 $table->width = '100%';
5687 $table->data = array();
5689 foreach ($licenses as $value) {
5690 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5692 if ($value->enabled == 1) {
5693 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5694 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5695 } else {
5696 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5697 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5700 if ($value->shortname == $CFG->sitedefaultlicense) {
5701 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5702 $hideshow = '';
5705 $enabled = true;
5707 $table->data[] =array($displayname, $hideshow);
5709 $return .= html_writer::table($table);
5710 $return .= $OUTPUT->box_end();
5711 return highlight($query, $return);
5717 * Special class for filter administration.
5719 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5721 class admin_page_managefilters extends admin_externalpage {
5723 * Calls parent::__construct with specific arguments
5725 public function __construct() {
5726 global $CFG;
5727 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5731 * Searches all installed filters for specified filter
5733 * @param string $query The filter(string) to search for
5734 * @param string $query
5736 public function search($query) {
5737 global $CFG;
5738 if ($result = parent::search($query)) {
5739 return $result;
5742 $found = false;
5743 $filternames = filter_get_all_installed();
5744 $textlib = textlib_get_instance();
5745 foreach ($filternames as $path => $strfiltername) {
5746 if (strpos($textlib->strtolower($strfiltername), $query) !== false) {
5747 $found = true;
5748 break;
5750 list($type, $filter) = explode('/', $path);
5751 if (strpos($filter, $query) !== false) {
5752 $found = true;
5753 break;
5757 if ($found) {
5758 $result = new stdClass;
5759 $result->page = $this;
5760 $result->settings = array();
5761 return array($this->name => $result);
5762 } else {
5763 return array();
5770 * Initialise admin page - this function does require login and permission
5771 * checks specified in page definition.
5773 * This function must be called on each admin page before other code.
5775 * @global moodle_page $PAGE
5777 * @param string $section name of page
5778 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5779 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5780 * added to the turn blocks editing on/off form, so this page reloads correctly.
5781 * @param string $actualurl if the actual page being viewed is not the normal one for this
5782 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5783 * @param array $options Additional options that can be specified for page setup.
5784 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5786 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5787 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5789 $PAGE->set_context(null); // hack - set context to something, by default to system context
5791 $site = get_site();
5792 require_login();
5794 if (!empty($options['pagelayout'])) {
5795 // A specific page layout has been requested.
5796 $PAGE->set_pagelayout($options['pagelayout']);
5797 } else if ($section === 'upgradesettings') {
5798 $PAGE->set_pagelayout('maintenance');
5799 } else {
5800 $PAGE->set_pagelayout('admin');
5803 $adminroot = admin_get_root(false, false); // settings not required for external pages
5804 $extpage = $adminroot->locate($section, true);
5806 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5807 // The requested section isn't in the admin tree
5808 // It could be because the user has inadequate capapbilities or because the section doesn't exist
5809 if (!has_capability('moodle/site:config', get_system_context())) {
5810 // The requested section could depend on a different capability
5811 // but most likely the user has inadequate capabilities
5812 print_error('accessdenied', 'admin');
5813 } else {
5814 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5818 // this eliminates our need to authenticate on the actual pages
5819 if (!$extpage->check_access()) {
5820 print_error('accessdenied', 'admin');
5821 die;
5824 // $PAGE->set_extra_button($extrabutton); TODO
5826 if (!$actualurl) {
5827 $actualurl = $extpage->url;
5830 $PAGE->set_url($actualurl, $extraurlparams);
5831 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5832 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
5835 if (empty($SITE->fullname) || empty($SITE->shortname)) {
5836 // During initial install.
5837 $strinstallation = get_string('installation', 'install');
5838 $strsettings = get_string('settings');
5839 $PAGE->navbar->add($strsettings);
5840 $PAGE->set_title($strinstallation);
5841 $PAGE->set_heading($strinstallation);
5842 $PAGE->set_cacheable(false);
5843 return;
5846 // Locate the current item on the navigation and make it active when found.
5847 $path = $extpage->path;
5848 $node = $PAGE->settingsnav;
5849 while ($node && count($path) > 0) {
5850 $node = $node->get(array_pop($path));
5852 if ($node) {
5853 $node->make_active();
5856 // Normal case.
5857 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
5858 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
5859 $USER->editing = $adminediting;
5862 $visiblepathtosection = array_reverse($extpage->visiblepath);
5864 if ($PAGE->user_allowed_editing()) {
5865 if ($PAGE->user_is_editing()) {
5866 $caption = get_string('blockseditoff');
5867 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
5868 } else {
5869 $caption = get_string('blocksediton');
5870 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
5872 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
5875 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
5876 $PAGE->set_heading($SITE->fullname);
5878 // prevent caching in nav block
5879 $PAGE->navigation->clear_cache();
5883 * Returns the reference to admin tree root
5885 * @return object admin_root object
5887 function admin_get_root($reload=false, $requirefulltree=true) {
5888 global $CFG, $DB, $OUTPUT;
5890 static $ADMIN = NULL;
5892 if (is_null($ADMIN)) {
5893 // create the admin tree!
5894 $ADMIN = new admin_root($requirefulltree);
5897 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
5898 $ADMIN->purge_children($requirefulltree);
5901 if (!$ADMIN->loaded) {
5902 // we process this file first to create categories first and in correct order
5903 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
5905 // now we process all other files in admin/settings to build the admin tree
5906 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
5907 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
5908 continue;
5910 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
5911 // plugins are loaded last - they may insert pages anywhere
5912 continue;
5914 require($file);
5916 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
5918 $ADMIN->loaded = true;
5921 return $ADMIN;
5924 /// settings utility functions
5927 * This function applies default settings.
5929 * @param object $node, NULL means complete tree, null by default
5930 * @param bool $unconditional if true overrides all values with defaults, null buy default
5932 function admin_apply_default_settings($node=NULL, $unconditional=true) {
5933 global $CFG;
5935 if (is_null($node)) {
5936 $node = admin_get_root(true, true);
5939 if ($node instanceof admin_category) {
5940 $entries = array_keys($node->children);
5941 foreach ($entries as $entry) {
5942 admin_apply_default_settings($node->children[$entry], $unconditional);
5945 } else if ($node instanceof admin_settingpage) {
5946 foreach ($node->settings as $setting) {
5947 if (!$unconditional and !is_null($setting->get_setting())) {
5948 //do not override existing defaults
5949 continue;
5951 $defaultsetting = $setting->get_defaultsetting();
5952 if (is_null($defaultsetting)) {
5953 // no value yet - default maybe applied after admin user creation or in upgradesettings
5954 continue;
5956 $setting->write_setting($defaultsetting);
5962 * Store changed settings, this function updates the errors variable in $ADMIN
5964 * @param object $formdata from form
5965 * @return int number of changed settings
5967 function admin_write_settings($formdata) {
5968 global $CFG, $SITE, $DB;
5970 $olddbsessions = !empty($CFG->dbsessions);
5971 $formdata = (array)$formdata;
5973 $data = array();
5974 foreach ($formdata as $fullname=>$value) {
5975 if (strpos($fullname, 's_') !== 0) {
5976 continue; // not a config value
5978 $data[$fullname] = $value;
5981 $adminroot = admin_get_root();
5982 $settings = admin_find_write_settings($adminroot, $data);
5984 $count = 0;
5985 foreach ($settings as $fullname=>$setting) {
5986 $original = serialize($setting->get_setting()); // comparison must work for arrays too
5987 $error = $setting->write_setting($data[$fullname]);
5988 if ($error !== '') {
5989 $adminroot->errors[$fullname] = new stdClass();
5990 $adminroot->errors[$fullname]->data = $data[$fullname];
5991 $adminroot->errors[$fullname]->id = $setting->get_id();
5992 $adminroot->errors[$fullname]->error = $error;
5994 if ($original !== serialize($setting->get_setting())) {
5995 $count++;
5996 $callbackfunction = $setting->updatedcallback;
5997 if (function_exists($callbackfunction)) {
5998 $callbackfunction($fullname);
6003 if ($olddbsessions != !empty($CFG->dbsessions)) {
6004 require_logout();
6007 // Now update $SITE - just update the fields, in case other people have a
6008 // a reference to it (e.g. $PAGE, $COURSE).
6009 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6010 foreach (get_object_vars($newsite) as $field => $value) {
6011 $SITE->$field = $value;
6014 // now reload all settings - some of them might depend on the changed
6015 admin_get_root(true);
6016 return $count;
6020 * Internal recursive function - finds all settings from submitted form
6022 * @param object $node Instance of admin_category, or admin_settingpage
6023 * @param array $data
6024 * @return array
6026 function admin_find_write_settings($node, $data) {
6027 $return = array();
6029 if (empty($data)) {
6030 return $return;
6033 if ($node instanceof admin_category) {
6034 $entries = array_keys($node->children);
6035 foreach ($entries as $entry) {
6036 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6039 } else if ($node instanceof admin_settingpage) {
6040 foreach ($node->settings as $setting) {
6041 $fullname = $setting->get_full_name();
6042 if (array_key_exists($fullname, $data)) {
6043 $return[$fullname] = $setting;
6049 return $return;
6053 * Internal function - prints the search results
6055 * @param string $query String to search for
6056 * @return string empty or XHTML
6058 function admin_search_settings_html($query) {
6059 global $CFG, $OUTPUT;
6061 $textlib = textlib_get_instance();
6062 if ($textlib->strlen($query) < 2) {
6063 return '';
6065 $query = $textlib->strtolower($query);
6067 $adminroot = admin_get_root();
6068 $findings = $adminroot->search($query);
6069 $return = '';
6070 $savebutton = false;
6072 foreach ($findings as $found) {
6073 $page = $found->page;
6074 $settings = $found->settings;
6075 if ($page->is_hidden()) {
6076 // hidden pages are not displayed in search results
6077 continue;
6079 if ($page instanceof admin_externalpage) {
6080 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6081 } else if ($page instanceof admin_settingpage) {
6082 $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');
6083 } else {
6084 continue;
6086 if (!empty($settings)) {
6087 $return .= '<fieldset class="adminsettings">'."\n";
6088 foreach ($settings as $setting) {
6089 if (empty($setting->nosave)) {
6090 $savebutton = true;
6092 $return .= '<div class="clearer"><!-- --></div>'."\n";
6093 $fullname = $setting->get_full_name();
6094 if (array_key_exists($fullname, $adminroot->errors)) {
6095 $data = $adminroot->errors[$fullname]->data;
6096 } else {
6097 $data = $setting->get_setting();
6098 // do not use defaults if settings not available - upgradesettings handles the defaults!
6100 $return .= $setting->output_html($data, $query);
6102 $return .= '</fieldset>';
6106 if ($savebutton) {
6107 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6110 return $return;
6114 * Internal function - returns arrays of html pages with uninitialised settings
6116 * @param object $node Instance of admin_category or admin_settingpage
6117 * @return array
6119 function admin_output_new_settings_by_page($node) {
6120 global $OUTPUT;
6121 $return = array();
6123 if ($node instanceof admin_category) {
6124 $entries = array_keys($node->children);
6125 foreach ($entries as $entry) {
6126 $return += admin_output_new_settings_by_page($node->children[$entry]);
6129 } else if ($node instanceof admin_settingpage) {
6130 $newsettings = array();
6131 foreach ($node->settings as $setting) {
6132 if (is_null($setting->get_setting())) {
6133 $newsettings[] = $setting;
6136 if (count($newsettings) > 0) {
6137 $adminroot = admin_get_root();
6138 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6139 $page .= '<fieldset class="adminsettings">'."\n";
6140 foreach ($newsettings as $setting) {
6141 $fullname = $setting->get_full_name();
6142 if (array_key_exists($fullname, $adminroot->errors)) {
6143 $data = $adminroot->errors[$fullname]->data;
6144 } else {
6145 $data = $setting->get_setting();
6146 if (is_null($data)) {
6147 $data = $setting->get_defaultsetting();
6150 $page .= '<div class="clearer"><!-- --></div>'."\n";
6151 $page .= $setting->output_html($data);
6153 $page .= '</fieldset>';
6154 $return[$node->name] = $page;
6158 return $return;
6162 * Format admin settings
6164 * @param object $setting
6165 * @param string $title label element
6166 * @param string $form form fragment, html code - not highlighted automatically
6167 * @param string $description
6168 * @param bool $label link label to id, true by default
6169 * @param string $warning warning text
6170 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6171 * @param string $query search query to be highlighted
6172 * @return string XHTML
6174 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6175 global $CFG;
6177 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6178 $fullname = $setting->get_full_name();
6180 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6181 if ($label) {
6182 $labelfor = 'for = "'.$setting->get_id().'"';
6183 } else {
6184 $labelfor = '';
6187 $override = '';
6188 if (empty($setting->plugin)) {
6189 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6190 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6192 } else {
6193 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6194 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6198 if ($warning !== '') {
6199 $warning = '<div class="form-warning">'.$warning.'</div>';
6202 if (is_null($defaultinfo)) {
6203 $defaultinfo = '';
6204 } else {
6205 if ($defaultinfo === '') {
6206 $defaultinfo = get_string('emptysettingvalue', 'admin');
6208 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6209 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6213 $str = '
6214 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6215 <div class="form-label">
6216 <label '.$labelfor.'>'.highlightfast($query, $title).'<span class="form-shortname">'.highlightfast($query, $name).'</span>
6217 '.$override.$warning.'
6218 </label>
6219 </div>
6220 <div class="form-setting">'.$form.$defaultinfo.'</div>
6221 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6222 </div>';
6224 $adminroot = admin_get_root();
6225 if (array_key_exists($fullname, $adminroot->errors)) {
6226 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6229 return $str;
6233 * Based on find_new_settings{@link ()} in upgradesettings.php
6234 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6236 * @param object $node Instance of admin_category, or admin_settingpage
6237 * @return boolean true if any settings haven't been initialised, false if they all have
6239 function any_new_admin_settings($node) {
6241 if ($node instanceof admin_category) {
6242 $entries = array_keys($node->children);
6243 foreach ($entries as $entry) {
6244 if (any_new_admin_settings($node->children[$entry])) {
6245 return true;
6249 } else if ($node instanceof admin_settingpage) {
6250 foreach ($node->settings as $setting) {
6251 if ($setting->get_setting() === NULL) {
6252 return true;
6257 return false;
6261 * Moved from admin/replace.php so that we can use this in cron
6263 * @param string $search string to look for
6264 * @param string $replace string to replace
6265 * @return bool success or fail
6267 function db_replace($search, $replace) {
6268 global $DB, $CFG, $OUTPUT;
6270 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6271 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6272 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6273 'block_instances', 'block_pinned_old', 'block_instance_old', '');
6275 // Turn off time limits, sometimes upgrades can be slow.
6276 @set_time_limit(0);
6278 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6279 return false;
6281 foreach ($tables as $table) {
6283 if (in_array($table, $skiptables)) { // Don't process these
6284 continue;
6287 if ($columns = $DB->get_columns($table)) {
6288 $DB->set_debug(true);
6289 foreach ($columns as $column => $data) {
6290 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6291 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6292 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6295 $DB->set_debug(false);
6299 // delete modinfo caches
6300 rebuild_course_cache(0, true);
6302 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6303 $blocks = get_plugin_list('block');
6304 foreach ($blocks as $blockname=>$fullblock) {
6305 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6306 continue;
6309 if (!is_readable($fullblock.'/lib.php')) {
6310 continue;
6313 $function = 'block_'.$blockname.'_global_db_replace';
6314 include_once($fullblock.'/lib.php');
6315 if (!function_exists($function)) {
6316 continue;
6319 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6320 $function($search, $replace);
6321 echo $OUTPUT->notification("...finished", 'notifysuccess');
6324 return true;
6328 * Manage repository settings
6330 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6332 class admin_setting_managerepository extends admin_setting {
6333 /** @var string */
6334 private $baseurl;
6337 * calls parent::__construct with specific arguments
6339 public function __construct() {
6340 global $CFG;
6341 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6342 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6346 * Always returns true, does nothing
6348 * @return true
6350 public function get_setting() {
6351 return true;
6355 * Always returns true does nothing
6357 * @return true
6359 public function get_defaultsetting() {
6360 return true;
6364 * Always returns s_managerepository
6366 * @return string Always return 's_managerepository'
6368 public function get_full_name() {
6369 return 's_managerepository';
6373 * Always returns '' doesn't do anything
6375 public function write_setting($data) {
6376 $url = $this->baseurl . '&amp;new=' . $data;
6377 return '';
6378 // TODO
6379 // Should not use redirect and exit here
6380 // Find a better way to do this.
6381 // redirect($url);
6382 // exit;
6386 * Searches repository plugins for one that matches $query
6388 * @param string $query The string to search for
6389 * @return bool true if found, false if not
6391 public function is_related($query) {
6392 if (parent::is_related($query)) {
6393 return true;
6396 $textlib = textlib_get_instance();
6397 $repositories= get_plugin_list('repository');
6398 foreach ($repositories as $p => $dir) {
6399 if (strpos($p, $query) !== false) {
6400 return true;
6403 foreach (repository::get_types() as $instance) {
6404 $title = $instance->get_typename();
6405 if (strpos($textlib->strtolower($title), $query) !== false) {
6406 return true;
6409 return false;
6413 * Helper function that generates a moodle_url object
6414 * relevant to the repository
6417 function repository_action_url($repository) {
6418 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6422 * Builds XHTML to display the control
6424 * @param string $data Unused
6425 * @param string $query
6426 * @return string XHTML
6428 public function output_html($data, $query='') {
6429 global $CFG, $USER, $OUTPUT;
6431 // Get strings that are used
6432 $strshow = get_string('on', 'repository');
6433 $strhide = get_string('off', 'repository');
6434 $strdelete = get_string('disabled', 'repository');
6436 $actionchoicesforexisting = array(
6437 'show' => $strshow,
6438 'hide' => $strhide,
6439 'delete' => $strdelete
6442 $actionchoicesfornew = array(
6443 'newon' => $strshow,
6444 'newoff' => $strhide,
6445 'delete' => $strdelete
6448 $return = '';
6449 $return .= $OUTPUT->box_start('generalbox');
6451 // Set strings that are used multiple times
6452 $settingsstr = get_string('settings');
6453 $disablestr = get_string('disable');
6455 // Table to list plug-ins
6456 $table = new html_table();
6457 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6458 $table->align = array('left', 'center', 'center', 'center', 'center');
6459 $table->data = array();
6461 // Get list of used plug-ins
6462 $instances = repository::get_types();
6463 if (!empty($instances)) {
6464 // Array to store plugins being used
6465 $alreadyplugins = array();
6466 $totalinstances = count($instances);
6467 $updowncount = 1;
6468 foreach ($instances as $i) {
6469 $settings = '';
6470 $typename = $i->get_typename();
6471 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6472 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6473 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6475 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6476 // Calculate number of instances in order to display them for the Moodle administrator
6477 if (!empty($instanceoptionnames)) {
6478 $params = array();
6479 $params['context'] = array(get_system_context());
6480 $params['onlyvisible'] = false;
6481 $params['type'] = $typename;
6482 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6483 // site instances
6484 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6485 $params['context'] = array();
6486 $instances = repository::static_function($typename, 'get_instances', $params);
6487 $courseinstances = array();
6488 $userinstances = array();
6490 foreach ($instances as $instance) {
6491 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6492 $courseinstances[] = $instance;
6493 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6494 $userinstances[] = $instance;
6497 // course instances
6498 $instancenumber = count($courseinstances);
6499 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6501 // user private instances
6502 $instancenumber = count($userinstances);
6503 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6504 } else {
6505 $admininstancenumbertext = "";
6506 $courseinstancenumbertext = "";
6507 $userinstancenumbertext = "";
6510 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6512 $settings .= $OUTPUT->container_start('mdl-left');
6513 $settings .= '<br/>';
6514 $settings .= $admininstancenumbertext;
6515 $settings .= '<br/>';
6516 $settings .= $courseinstancenumbertext;
6517 $settings .= '<br/>';
6518 $settings .= $userinstancenumbertext;
6519 $settings .= $OUTPUT->container_end();
6521 // Get the current visibility
6522 if ($i->get_visible()) {
6523 $currentaction = 'show';
6524 } else {
6525 $currentaction = 'hide';
6528 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6530 // Display up/down link
6531 $updown = '';
6532 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6534 if ($updowncount > 1) {
6535 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6536 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6538 else {
6539 $updown .= $spacer;
6541 if ($updowncount < $totalinstances) {
6542 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6543 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6545 else {
6546 $updown .= $spacer;
6549 $updowncount++;
6551 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6553 if (!in_array($typename, $alreadyplugins)) {
6554 $alreadyplugins[] = $typename;
6559 // Get all the plugins that exist on disk
6560 $plugins = get_plugin_list('repository');
6561 if (!empty($plugins)) {
6562 foreach ($plugins as $plugin => $dir) {
6563 // Check that it has not already been listed
6564 if (!in_array($plugin, $alreadyplugins)) {
6565 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6566 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6571 $return .= html_writer::table($table);
6572 $return .= $OUTPUT->box_end();
6573 return highlight($query, $return);
6578 * Special checkbox for enable mobile web service
6579 * If enable then we store the service id of the mobile service into config table
6580 * If disable then we unstore the service id from the config table
6582 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6584 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6587 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6588 * @return boolean
6590 private function is_xmlrpc_cap_allowed() {
6591 global $DB, $CFG;
6593 //if the $this->xmlrpcuse variable is not set, it needs to be set
6594 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6595 $params = array();
6596 $params['permission'] = CAP_ALLOW;
6597 $params['roleid'] = $CFG->defaultuserroleid;
6598 $params['capability'] = 'webservice/xmlrpc:use';
6599 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6602 return $this->xmlrpcuse;
6606 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6607 * @param type $status true to allow, false to not set
6609 private function set_xmlrpc_cap($status) {
6610 global $CFG;
6611 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6612 //need to allow the cap
6613 $permission = CAP_ALLOW;
6614 $assign = true;
6615 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6616 //need to disallow the cap
6617 $permission = CAP_INHERIT;
6618 $assign = true;
6620 if (!empty($assign)) {
6621 $systemcontext = get_system_context();
6622 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6627 * Builds XHTML to display the control.
6628 * The main purpose of this overloading is to display a warning when https
6629 * is not supported by the server
6630 * @param string $data Unused
6631 * @param string $query
6632 * @return string XHTML
6634 public function output_html($data, $query='') {
6635 global $CFG, $OUTPUT;
6636 $html = parent::output_html($data, $query);
6638 if ((string)$data === $this->yes) {
6639 require_once($CFG->dirroot . "/lib/filelib.php");
6640 $curl = new curl();
6641 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6642 $curl->head($httpswwwroot . "/login/index.php");
6643 $info = $curl->get_info();
6644 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6645 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6649 return $html;
6653 * Retrieves the current setting using the objects name
6655 * @return string
6657 public function get_setting() {
6658 global $CFG;
6660 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6661 // Or if web services aren't enabled this can't be,
6662 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6663 return 0;
6666 require_once($CFG->dirroot . '/webservice/lib.php');
6667 $webservicemanager = new webservice();
6668 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6669 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6670 return $this->config_read($this->name); //same as returning 1
6671 } else {
6672 return 0;
6677 * Save the selected setting
6679 * @param string $data The selected site
6680 * @return string empty string or error message
6682 public function write_setting($data) {
6683 global $DB, $CFG;
6685 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6686 if (empty($CFG->defaultuserroleid)) {
6687 return '';
6690 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6692 require_once($CFG->dirroot . '/webservice/lib.php');
6693 $webservicemanager = new webservice();
6695 if ((string)$data === $this->yes) {
6696 //code run when enable mobile web service
6697 //enable web service systeme if necessary
6698 set_config('enablewebservices', true);
6700 //enable mobile service
6701 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6702 $mobileservice->enabled = 1;
6703 $webservicemanager->update_external_service($mobileservice);
6705 //enable xml-rpc server
6706 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6708 if (!in_array('xmlrpc', $activeprotocols)) {
6709 $activeprotocols[] = 'xmlrpc';
6710 set_config('webserviceprotocols', implode(',', $activeprotocols));
6713 //allow xml-rpc:use capability for authenticated user
6714 $this->set_xmlrpc_cap(true);
6716 } else {
6717 //disable web service system if no other services are enabled
6718 $otherenabledservices = $DB->get_records_select('external_services',
6719 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6720 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6721 if (empty($otherenabledservices)) {
6722 set_config('enablewebservices', false);
6724 //also disable xml-rpc server
6725 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6726 $protocolkey = array_search('xmlrpc', $activeprotocols);
6727 if ($protocolkey !== false) {
6728 unset($activeprotocols[$protocolkey]);
6729 set_config('webserviceprotocols', implode(',', $activeprotocols));
6732 //disallow xml-rpc:use capability for authenticated user
6733 $this->set_xmlrpc_cap(false);
6736 //disable the mobile service
6737 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6738 $mobileservice->enabled = 0;
6739 $webservicemanager->update_external_service($mobileservice);
6742 return (parent::write_setting($data));
6747 * Special class for management of external services
6749 * @author Petr Skoda (skodak)
6751 class admin_setting_manageexternalservices extends admin_setting {
6753 * Calls parent::__construct with specific arguments
6755 public function __construct() {
6756 $this->nosave = true;
6757 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6761 * Always returns true, does nothing
6763 * @return true
6765 public function get_setting() {
6766 return true;
6770 * Always returns true, does nothing
6772 * @return true
6774 public function get_defaultsetting() {
6775 return true;
6779 * Always returns '', does not write anything
6781 * @return string Always returns ''
6783 public function write_setting($data) {
6784 // do not write any setting
6785 return '';
6789 * Checks if $query is one of the available external services
6791 * @param string $query The string to search for
6792 * @return bool Returns true if found, false if not
6794 public function is_related($query) {
6795 global $DB;
6797 if (parent::is_related($query)) {
6798 return true;
6801 $textlib = textlib_get_instance();
6802 $services = $DB->get_records('external_services', array(), 'id, name');
6803 foreach ($services as $service) {
6804 if (strpos($textlib->strtolower($service->name), $query) !== false) {
6805 return true;
6808 return false;
6812 * Builds the XHTML to display the control
6814 * @param string $data Unused
6815 * @param string $query
6816 * @return string
6818 public function output_html($data, $query='') {
6819 global $CFG, $OUTPUT, $DB;
6821 // display strings
6822 $stradministration = get_string('administration');
6823 $stredit = get_string('edit');
6824 $strservice = get_string('externalservice', 'webservice');
6825 $strdelete = get_string('delete');
6826 $strplugin = get_string('plugin', 'admin');
6827 $stradd = get_string('add');
6828 $strfunctions = get_string('functions', 'webservice');
6829 $strusers = get_string('users');
6830 $strserviceusers = get_string('serviceusers', 'webservice');
6832 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6833 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6834 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6836 // built in services
6837 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6838 $return = "";
6839 if (!empty($services)) {
6840 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
6844 $table = new html_table();
6845 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
6846 $table->align = array('left', 'left', 'center', 'center', 'center');
6847 $table->size = array('30%', '20%', '20%', '20%', '10%');
6848 $table->width = '100%';
6849 $table->data = array();
6851 // iterate through auth plugins and add to the display table
6852 foreach ($services as $service) {
6853 $name = $service->name;
6855 // hide/show link
6856 if ($service->enabled) {
6857 $displayname = "<span>$name</span>";
6858 } else {
6859 $displayname = "<span class=\"dimmed_text\">$name</span>";
6862 $plugin = $service->component;
6864 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6866 if ($service->restrictedusers) {
6867 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6868 } else {
6869 $users = get_string('allusers', 'webservice');
6872 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6874 // add a row to the table
6875 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
6877 $return .= html_writer::table($table);
6880 // Custom services
6881 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
6882 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
6884 $table = new html_table();
6885 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
6886 $table->align = array('left', 'center', 'center', 'center', 'center');
6887 $table->size = array('30%', '20%', '20%', '20%', '10%');
6888 $table->width = '100%';
6889 $table->data = array();
6891 // iterate through auth plugins and add to the display table
6892 foreach ($services as $service) {
6893 $name = $service->name;
6895 // hide/show link
6896 if ($service->enabled) {
6897 $displayname = "<span>$name</span>";
6898 } else {
6899 $displayname = "<span class=\"dimmed_text\">$name</span>";
6902 // delete link
6903 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
6905 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6907 if ($service->restrictedusers) {
6908 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6909 } else {
6910 $users = get_string('allusers', 'webservice');
6913 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6915 // add a row to the table
6916 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
6918 // add new custom service option
6919 $return .= html_writer::table($table);
6921 $return .= '<br />';
6922 // add a token to the table
6923 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
6925 return highlight($query, $return);
6931 * Special class for plagiarism administration.
6933 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6935 class admin_setting_manageplagiarism extends admin_setting {
6937 * Calls parent::__construct with specific arguments
6939 public function __construct() {
6940 $this->nosave = true;
6941 parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
6945 * Always returns true
6947 * @return true
6949 public function get_setting() {
6950 return true;
6954 * Always returns true
6956 * @return true
6958 public function get_defaultsetting() {
6959 return true;
6963 * Always returns '' and doesn't write anything
6965 * @return string Always returns ''
6967 public function write_setting($data) {
6968 // do not write any setting
6969 return '';
6973 * Return XHTML to display control
6975 * @param mixed $data Unused
6976 * @param string $query
6977 * @return string highlight
6979 public function output_html($data, $query='') {
6980 global $CFG, $OUTPUT;
6982 // display strings
6983 $txt = get_strings(array('settings', 'name'));
6985 $plagiarismplugins = get_plugin_list('plagiarism');
6986 if (empty($plagiarismplugins)) {
6987 return get_string('nopluginsinstalled', 'plagiarism');
6990 $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
6991 $return .= $OUTPUT->box_start('generalbox authsui');
6993 $table = new html_table();
6994 $table->head = array($txt->name, $txt->settings);
6995 $table->align = array('left', 'center');
6996 $table->data = array();
6997 $table->attributes['class'] = 'manageplagiarismtable generaltable';
6999 // iterate through auth plugins and add to the display table
7000 $authcount = count($plagiarismplugins);
7001 foreach ($plagiarismplugins as $plugin => $dir) {
7002 if (file_exists($dir.'/settings.php')) {
7003 $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
7004 // settings link
7005 $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
7006 // add a row to the table
7007 $table->data[] =array($displayname, $settings);
7010 $return .= html_writer::table($table);
7011 $return .= get_string('configplagiarismplugins', 'plagiarism');
7012 $return .= $OUTPUT->box_end();
7013 return highlight($query, $return);
7019 * Special class for overview of external services
7021 * @author Jerome Mouneyrac
7023 class admin_setting_webservicesoverview extends admin_setting {
7026 * Calls parent::__construct with specific arguments
7028 public function __construct() {
7029 $this->nosave = true;
7030 parent::__construct('webservicesoverviewui',
7031 get_string('webservicesoverview', 'webservice'), '', '');
7035 * Always returns true, does nothing
7037 * @return true
7039 public function get_setting() {
7040 return true;
7044 * Always returns true, does nothing
7046 * @return true
7048 public function get_defaultsetting() {
7049 return true;
7053 * Always returns '', does not write anything
7055 * @return string Always returns ''
7057 public function write_setting($data) {
7058 // do not write any setting
7059 return '';
7063 * Builds the XHTML to display the control
7065 * @param string $data Unused
7066 * @param string $query
7067 * @return string
7069 public function output_html($data, $query='') {
7070 global $CFG, $OUTPUT;
7072 $return = "";
7073 $brtag = html_writer::empty_tag('br');
7075 // Enable mobile web service
7076 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7077 get_string('enablemobilewebservice', 'admin'),
7078 get_string('configenablemobilewebservice',
7079 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7080 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7081 $wsmobileparam = new stdClass();
7082 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7083 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7084 get_string('externalservices', 'webservice'));
7085 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7086 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7087 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7088 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7089 . $brtag . $brtag;
7091 /// One system controlling Moodle with Token
7092 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7093 $table = new html_table();
7094 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7095 get_string('description'));
7096 $table->size = array('30%', '10%', '60%');
7097 $table->align = array('left', 'left', 'left');
7098 $table->width = '90%';
7099 $table->data = array();
7101 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7102 . $brtag . $brtag;
7104 /// 1. Enable Web Services
7105 $row = array();
7106 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7107 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7108 array('href' => $url));
7109 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7110 if ($CFG->enablewebservices) {
7111 $status = get_string('yes');
7113 $row[1] = $status;
7114 $row[2] = get_string('enablewsdescription', 'webservice');
7115 $table->data[] = $row;
7117 /// 2. Enable protocols
7118 $row = array();
7119 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7120 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7121 array('href' => $url));
7122 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7123 //retrieve activated protocol
7124 $active_protocols = empty($CFG->webserviceprotocols) ?
7125 array() : explode(',', $CFG->webserviceprotocols);
7126 if (!empty($active_protocols)) {
7127 $status = "";
7128 foreach ($active_protocols as $protocol) {
7129 $status .= $protocol . $brtag;
7132 $row[1] = $status;
7133 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7134 $table->data[] = $row;
7136 /// 3. Create user account
7137 $row = array();
7138 $url = new moodle_url("/user/editadvanced.php?id=-1");
7139 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7140 array('href' => $url));
7141 $row[1] = "";
7142 $row[2] = get_string('createuserdescription', 'webservice');
7143 $table->data[] = $row;
7145 /// 4. Add capability to users
7146 $row = array();
7147 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7148 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7149 array('href' => $url));
7150 $row[1] = "";
7151 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7152 $table->data[] = $row;
7154 /// 5. Select a web service
7155 $row = array();
7156 $url = new moodle_url("/admin/settings.php?section=externalservices");
7157 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7158 array('href' => $url));
7159 $row[1] = "";
7160 $row[2] = get_string('createservicedescription', 'webservice');
7161 $table->data[] = $row;
7163 /// 6. Add functions
7164 $row = array();
7165 $url = new moodle_url("/admin/settings.php?section=externalservices");
7166 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7167 array('href' => $url));
7168 $row[1] = "";
7169 $row[2] = get_string('addfunctionsdescription', 'webservice');
7170 $table->data[] = $row;
7172 /// 7. Add the specific user
7173 $row = array();
7174 $url = new moodle_url("/admin/settings.php?section=externalservices");
7175 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7176 array('href' => $url));
7177 $row[1] = "";
7178 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7179 $table->data[] = $row;
7181 /// 8. Create token for the specific user
7182 $row = array();
7183 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7184 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7185 array('href' => $url));
7186 $row[1] = "";
7187 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7188 $table->data[] = $row;
7190 /// 9. Enable the documentation
7191 $row = array();
7192 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7193 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7194 array('href' => $url));
7195 $status = '<span class="warning">' . get_string('no') . '</span>';
7196 if ($CFG->enablewsdocumentation) {
7197 $status = get_string('yes');
7199 $row[1] = $status;
7200 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7201 $table->data[] = $row;
7203 /// 10. Test the service
7204 $row = array();
7205 $url = new moodle_url("/admin/webservice/testclient.php");
7206 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7207 array('href' => $url));
7208 $row[1] = "";
7209 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7210 $table->data[] = $row;
7212 $return .= html_writer::table($table);
7214 /// Users as clients with token
7215 $return .= $brtag . $brtag . $brtag;
7216 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7217 $table = new html_table();
7218 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7219 get_string('description'));
7220 $table->size = array('30%', '10%', '60%');
7221 $table->align = array('left', 'left', 'left');
7222 $table->width = '90%';
7223 $table->data = array();
7225 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7226 $brtag . $brtag;
7228 /// 1. Enable Web Services
7229 $row = array();
7230 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7231 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7232 array('href' => $url));
7233 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7234 if ($CFG->enablewebservices) {
7235 $status = get_string('yes');
7237 $row[1] = $status;
7238 $row[2] = get_string('enablewsdescription', 'webservice');
7239 $table->data[] = $row;
7241 /// 2. Enable protocols
7242 $row = array();
7243 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7244 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7245 array('href' => $url));
7246 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7247 //retrieve activated protocol
7248 $active_protocols = empty($CFG->webserviceprotocols) ?
7249 array() : explode(',', $CFG->webserviceprotocols);
7250 if (!empty($active_protocols)) {
7251 $status = "";
7252 foreach ($active_protocols as $protocol) {
7253 $status .= $protocol . $brtag;
7256 $row[1] = $status;
7257 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7258 $table->data[] = $row;
7261 /// 3. Select a web service
7262 $row = array();
7263 $url = new moodle_url("/admin/settings.php?section=externalservices");
7264 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7265 array('href' => $url));
7266 $row[1] = "";
7267 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7268 $table->data[] = $row;
7270 /// 4. Add functions
7271 $row = array();
7272 $url = new moodle_url("/admin/settings.php?section=externalservices");
7273 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7274 array('href' => $url));
7275 $row[1] = "";
7276 $row[2] = get_string('addfunctionsdescription', 'webservice');
7277 $table->data[] = $row;
7279 /// 5. Add capability to users
7280 $row = array();
7281 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7282 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7283 array('href' => $url));
7284 $row[1] = "";
7285 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7286 $table->data[] = $row;
7288 /// 6. Test the service
7289 $row = array();
7290 $url = new moodle_url("/admin/webservice/testclient.php");
7291 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7292 array('href' => $url));
7293 $row[1] = "";
7294 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7295 $table->data[] = $row;
7297 $return .= html_writer::table($table);
7299 return highlight($query, $return);
7306 * Special class for web service protocol administration.
7308 * @author Petr Skoda (skodak)
7310 class admin_setting_managewebserviceprotocols extends admin_setting {
7313 * Calls parent::__construct with specific arguments
7315 public function __construct() {
7316 $this->nosave = true;
7317 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7321 * Always returns true, does nothing
7323 * @return true
7325 public function get_setting() {
7326 return true;
7330 * Always returns true, does nothing
7332 * @return true
7334 public function get_defaultsetting() {
7335 return true;
7339 * Always returns '', does not write anything
7341 * @return string Always returns ''
7343 public function write_setting($data) {
7344 // do not write any setting
7345 return '';
7349 * Checks if $query is one of the available webservices
7351 * @param string $query The string to search for
7352 * @return bool Returns true if found, false if not
7354 public function is_related($query) {
7355 if (parent::is_related($query)) {
7356 return true;
7359 $textlib = textlib_get_instance();
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 {
7887 * Calls parent::__construct - note array $choices is not required
7889 * @param string $name setting name
7890 * @param string $visiblename localised setting name
7891 * @param string $description setting description
7892 * @param array $defaultsetting a plain array of default module ids
7894 public function __construct($name, $visiblename, $description, $defaultsetting = array()) {
7895 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
7899 * Loads an array of current module choices
7901 * @return bool always return true
7903 public function load_choices() {
7904 if (is_array($this->choices)) {
7905 return true;
7907 $this->choices = array();
7909 global $CFG, $DB;
7910 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7911 foreach ($records as $record) {
7912 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7913 $this->choices[$record->id] = $record->name;
7916 return true;