MDL-30007 standardise repository version files
[moodle.git] / lib / adminlib.php
blob4eaaecb4ad79d686d7ce57075a69494be5c0f22e
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions and classes used during installation, upgrades and for admin settings.
20 * ADMIN SETTINGS TREE INTRODUCTION
22 * This file performs the following tasks:
23 * -it defines the necessary objects and interfaces to build the Moodle
24 * admin hierarchy
25 * -it defines the admin_externalpage_setup()
27 * ADMIN_SETTING OBJECTS
29 * Moodle settings are represented by objects that inherit from the admin_setting
30 * class. These objects encapsulate how to read a setting, how to write a new value
31 * to a setting, and how to appropriately display the HTML to modify the setting.
33 * ADMIN_SETTINGPAGE OBJECTS
35 * The admin_setting objects are then grouped into admin_settingpages. The latter
36 * appear in the Moodle admin tree block. All interaction with admin_settingpage
37 * objects is handled by the admin/settings.php file.
39 * ADMIN_EXTERNALPAGE OBJECTS
41 * There are some settings in Moodle that are too complex to (efficiently) handle
42 * with admin_settingpages. (Consider, for example, user management and displaying
43 * lists of users.) In this case, we use the admin_externalpage object. This object
44 * places a link to an external PHP file in the admin tree block.
46 * If you're using an admin_externalpage object for some settings, you can take
47 * advantage of the admin_externalpage_* functions. For example, suppose you wanted
48 * to add a foo.php file into admin. First off, you add the following line to
49 * admin/settings/first.php (at the end of the file) or to some other file in
50 * admin/settings:
51 * <code>
52 * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
53 * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
54 * </code>
56 * Next, in foo.php, your file structure would resemble the following:
57 * <code>
58 * require(dirname(dirname(dirname(__FILE__))).'/config.php');
59 * require_once($CFG->libdir.'/adminlib.php');
60 * admin_externalpage_setup('foo');
61 * // functionality like processing form submissions goes here
62 * echo $OUTPUT->header();
63 * // your HTML goes here
64 * echo $OUTPUT->footer();
65 * </code>
67 * The admin_externalpage_setup() function call ensures the user is logged in,
68 * and makes sure that they have the proper role permission to access the page.
69 * It also configures all $PAGE properties needed for navigation.
71 * ADMIN_CATEGORY OBJECTS
73 * Above and beyond all this, we have admin_category objects. These objects
74 * appear as folders in the admin tree block. They contain admin_settingpage's,
75 * admin_externalpage's, and other admin_category's.
77 * OTHER NOTES
79 * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
80 * from part_of_admin_tree (a pseudointerface). This interface insists that
81 * a class has a check_access method for access permissions, a locate method
82 * used to find a specific node in the admin tree and find parent path.
84 * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
85 * interface ensures that the class implements a recursive add function which
86 * accepts a part_of_admin_tree object and searches for the proper place to
87 * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
89 * Please note that the $this->name field of any part_of_admin_tree must be
90 * UNIQUE throughout the ENTIRE admin tree.
92 * The $this->name field of an admin_setting object (which is *not* part_of_
93 * admin_tree) must be unique on the respective admin_settingpage where it is
94 * used.
96 * Original author: Vincenzo K. Marcovecchio
97 * Maintainer: Petr Skoda
99 * @package core
100 * @subpackage admin
101 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
105 defined('MOODLE_INTERNAL') || die();
107 /// Add libraries
108 require_once($CFG->libdir.'/ddllib.php');
109 require_once($CFG->libdir.'/xmlize.php');
110 require_once($CFG->libdir.'/messagelib.php');
112 define('INSECURE_DATAROOT_WARNING', 1);
113 define('INSECURE_DATAROOT_ERROR', 2);
116 * Automatically clean-up all plugin data and remove the plugin DB tables
118 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
119 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
120 * @uses global $OUTPUT to produce notices and other messages
121 * @return void
123 function uninstall_plugin($type, $name) {
124 global $CFG, $DB, $OUTPUT;
126 // recursively uninstall all module subplugins first
127 if ($type === 'mod') {
128 if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
129 $subplugins = array();
130 include("$CFG->dirroot/mod/$name/db/subplugins.php");
131 foreach ($subplugins as $subplugintype=>$dir) {
132 $instances = get_plugin_list($subplugintype);
133 foreach ($instances as $subpluginname => $notusedpluginpath) {
134 uninstall_plugin($subplugintype, $subpluginname);
141 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
143 if ($type === 'mod') {
144 $pluginname = $name; // eg. 'forum'
145 if (get_string_manager()->string_exists('modulename', $component)) {
146 $strpluginname = get_string('modulename', $component);
147 } else {
148 $strpluginname = $component;
151 } else {
152 $pluginname = $component;
153 if (get_string_manager()->string_exists('pluginname', $component)) {
154 $strpluginname = get_string('pluginname', $component);
155 } else {
156 $strpluginname = $component;
160 echo $OUTPUT->heading($pluginname);
162 $plugindirectory = get_plugin_directory($type, $name);
163 $uninstalllib = $plugindirectory . '/db/uninstall.php';
164 if (file_exists($uninstalllib)) {
165 require_once($uninstalllib);
166 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
167 if (function_exists($uninstallfunction)) {
168 if (!$uninstallfunction()) {
169 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
174 if ($type === 'mod') {
175 // perform cleanup tasks specific for activity modules
177 if (!$module = $DB->get_record('modules', array('name' => $name))) {
178 print_error('moduledoesnotexist', 'error');
181 // delete all the relevant instances from all course sections
182 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
183 foreach ($coursemods as $coursemod) {
184 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
185 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
190 // clear course.modinfo for courses that used this module
191 $sql = "UPDATE {course}
192 SET modinfo=''
193 WHERE id IN (SELECT DISTINCT course
194 FROM {course_modules}
195 WHERE module=?)";
196 $DB->execute($sql, array($module->id));
198 // delete all the course module records
199 $DB->delete_records('course_modules', array('module' => $module->id));
201 // delete module contexts
202 if ($coursemods) {
203 foreach ($coursemods as $coursemod) {
204 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
205 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
210 // delete the module entry itself
211 $DB->delete_records('modules', array('name' => $module->name));
213 // cleanup the gradebook
214 require_once($CFG->libdir.'/gradelib.php');
215 grade_uninstalled_module($module->name);
217 // Perform any custom uninstall tasks
218 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
219 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
220 $uninstallfunction = $module->name . '_uninstall';
221 if (function_exists($uninstallfunction)) {
222 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
223 if (!$uninstallfunction()) {
224 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
229 } else if ($type === 'enrol') {
230 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
231 // nuke all role assignments
232 role_unassign_all(array('component'=>$component));
233 // purge participants
234 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
235 // purge enrol instances
236 $DB->delete_records('enrol', array('enrol'=>$name));
237 // tweak enrol settings
238 if (!empty($CFG->enrol_plugins_enabled)) {
239 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
240 $enabledenrols = array_unique($enabledenrols);
241 $enabledenrols = array_flip($enabledenrols);
242 unset($enabledenrols[$name]);
243 $enabledenrols = array_flip($enabledenrols);
244 if (is_array($enabledenrols)) {
245 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
249 } else if ($type === 'block') {
250 if ($block = $DB->get_record('block', array('name'=>$name))) {
251 // Inform block it's about to be deleted
252 if (file_exists("$CFG->dirroot/blocks/$block->name/block_$block->name.php")) {
253 $blockobject = block_instance($block->name);
254 if ($blockobject) {
255 $blockobject->before_delete(); //only if we can create instance, block might have been already removed
259 // First delete instances and related contexts
260 $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
261 foreach($instances as $instance) {
262 blocks_delete_instance($instance);
265 // Delete block
266 $DB->delete_records('block', array('id'=>$block->id));
270 // perform clean-up task common for all the plugin/subplugin types
272 // delete calendar events
273 $DB->delete_records('event', array('modulename' => $pluginname));
275 // delete all the logs
276 $DB->delete_records('log', array('module' => $pluginname));
278 // delete log_display information
279 $DB->delete_records('log_display', array('component' => $component));
281 // delete the module configuration records
282 unset_all_config_for_plugin($pluginname);
284 // delete message provider
285 message_provider_uninstall($component);
287 // delete message processor
288 if ($type === 'message') {
289 message_processor_uninstall($name);
292 // delete the plugin tables
293 $xmldbfilepath = $plugindirectory . '/db/install.xml';
294 drop_plugin_tables($component, $xmldbfilepath, false);
295 if ($type === 'mod' or $type === 'block') {
296 // non-frankenstyle table prefixes
297 drop_plugin_tables($name, $xmldbfilepath, false);
300 // delete the capabilities that were defined by this module
301 capabilities_cleanup($component);
303 // remove event handlers and dequeue pending events
304 events_uninstall($component);
306 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
310 * Returns the version of installed component
312 * @param string $component component name
313 * @param string $source either 'disk' or 'installed' - where to get the version information from
314 * @return string|bool version number or false if the component is not found
316 function get_component_version($component, $source='installed') {
317 global $CFG, $DB;
319 list($type, $name) = normalize_component($component);
321 // moodle core or a core subsystem
322 if ($type === 'core') {
323 if ($source === 'installed') {
324 if (empty($CFG->version)) {
325 return false;
326 } else {
327 return $CFG->version;
329 } else {
330 if (!is_readable($CFG->dirroot.'/version.php')) {
331 return false;
332 } else {
333 $version = null; //initialize variable for IDEs
334 include($CFG->dirroot.'/version.php');
335 return $version;
340 // activity module
341 if ($type === 'mod') {
342 if ($source === 'installed') {
343 return $DB->get_field('modules', 'version', array('name'=>$name));
344 } else {
345 $mods = get_plugin_list('mod');
346 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
347 return false;
348 } else {
349 $module = new stdclass();
350 include($mods[$name].'/version.php');
351 return $module->version;
356 // block
357 if ($type === 'block') {
358 if ($source === 'installed') {
359 return $DB->get_field('block', 'version', array('name'=>$name));
360 } else {
361 $blocks = get_plugin_list('block');
362 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
363 return false;
364 } else {
365 $plugin = new stdclass();
366 include($blocks[$name].'/version.php');
367 return $plugin->version;
372 // all other plugin types
373 if ($source === 'installed') {
374 return get_config($type.'_'.$name, 'version');
375 } else {
376 $plugins = get_plugin_list($type);
377 if (empty($plugins[$name])) {
378 return false;
379 } else {
380 $plugin = new stdclass();
381 include($plugins[$name].'/version.php');
382 return $plugin->version;
388 * Delete all plugin tables
390 * @param string $name Name of plugin, used as table prefix
391 * @param string $file Path to install.xml file
392 * @param bool $feedback defaults to true
393 * @return bool Always returns true
395 function drop_plugin_tables($name, $file, $feedback=true) {
396 global $CFG, $DB;
398 // first try normal delete
399 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
400 return true;
403 // then try to find all tables that start with name and are not in any xml file
404 $used_tables = get_used_table_names();
406 $tables = $DB->get_tables();
408 /// Iterate over, fixing id fields as necessary
409 foreach ($tables as $table) {
410 if (in_array($table, $used_tables)) {
411 continue;
414 if (strpos($table, $name) !== 0) {
415 continue;
418 // found orphan table --> delete it
419 if ($DB->get_manager()->table_exists($table)) {
420 $xmldb_table = new xmldb_table($table);
421 $DB->get_manager()->drop_table($xmldb_table);
425 return true;
429 * Returns names of all known tables == tables that moodle knows about.
431 * @return array Array of lowercase table names
433 function get_used_table_names() {
434 $table_names = array();
435 $dbdirs = get_db_directories();
437 foreach ($dbdirs as $dbdir) {
438 $file = $dbdir.'/install.xml';
440 $xmldb_file = new xmldb_file($file);
442 if (!$xmldb_file->fileExists()) {
443 continue;
446 $loaded = $xmldb_file->loadXMLStructure();
447 $structure = $xmldb_file->getStructure();
449 if ($loaded and $tables = $structure->getTables()) {
450 foreach($tables as $table) {
451 $table_names[] = strtolower($table->name);
456 return $table_names;
460 * Returns list of all directories where we expect install.xml files
461 * @return array Array of paths
463 function get_db_directories() {
464 global $CFG;
466 $dbdirs = array();
468 /// First, the main one (lib/db)
469 $dbdirs[] = $CFG->libdir.'/db';
471 /// Then, all the ones defined by get_plugin_types()
472 $plugintypes = get_plugin_types();
473 foreach ($plugintypes as $plugintype => $pluginbasedir) {
474 if ($plugins = get_plugin_list($plugintype)) {
475 foreach ($plugins as $plugin => $plugindir) {
476 $dbdirs[] = $plugindir.'/db';
481 return $dbdirs;
485 * Try to obtain or release the cron lock.
486 * @param string $name name of lock
487 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
488 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
489 * @return bool true if lock obtained
491 function set_cron_lock($name, $until, $ignorecurrent=false) {
492 global $DB;
493 if (empty($name)) {
494 debugging("Tried to get a cron lock for a null fieldname");
495 return false;
498 // remove lock by force == remove from config table
499 if (is_null($until)) {
500 set_config($name, null);
501 return true;
504 if (!$ignorecurrent) {
505 // read value from db - other processes might have changed it
506 $value = $DB->get_field('config', 'value', array('name'=>$name));
508 if ($value and $value > time()) {
509 //lock active
510 return false;
514 set_config($name, $until);
515 return true;
519 * Test if and critical warnings are present
520 * @return bool
522 function admin_critical_warnings_present() {
523 global $SESSION;
525 if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
526 return 0;
529 if (!isset($SESSION->admin_critical_warning)) {
530 $SESSION->admin_critical_warning = 0;
531 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
532 $SESSION->admin_critical_warning = 1;
536 return $SESSION->admin_critical_warning;
540 * Detects if float supports at least 10 decimal digits
542 * Detects if float supports at least 10 decimal digits
543 * and also if float-->string conversion works as expected.
545 * @return bool true if problem found
547 function is_float_problem() {
548 $num1 = 2009010200.01;
549 $num2 = 2009010200.02;
551 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
555 * Try to verify that dataroot is not accessible from web.
557 * Try to verify that dataroot is not accessible from web.
558 * It is not 100% correct but might help to reduce number of vulnerable sites.
559 * Protection from httpd.conf and .htaccess is not detected properly.
561 * @uses INSECURE_DATAROOT_WARNING
562 * @uses INSECURE_DATAROOT_ERROR
563 * @param bool $fetchtest try to test public access by fetching file, default false
564 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
566 function is_dataroot_insecure($fetchtest=false) {
567 global $CFG;
569 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
571 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
572 $rp = strrev(trim($rp, '/'));
573 $rp = explode('/', $rp);
574 foreach($rp as $r) {
575 if (strpos($siteroot, '/'.$r.'/') === 0) {
576 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
577 } else {
578 break; // probably alias root
582 $siteroot = strrev($siteroot);
583 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
585 if (strpos($dataroot, $siteroot) !== 0) {
586 return false;
589 if (!$fetchtest) {
590 return INSECURE_DATAROOT_WARNING;
593 // now try all methods to fetch a test file using http protocol
595 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
596 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
597 $httpdocroot = $matches[1];
598 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
599 make_upload_directory('diag');
600 $testfile = $CFG->dataroot.'/diag/public.txt';
601 if (!file_exists($testfile)) {
602 file_put_contents($testfile, 'test file, do not delete');
604 $teststr = trim(file_get_contents($testfile));
605 if (empty($teststr)) {
606 // hmm, strange
607 return INSECURE_DATAROOT_WARNING;
610 $testurl = $datarooturl.'/diag/public.txt';
611 if (extension_loaded('curl') and
612 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
613 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
614 ($ch = @curl_init($testurl)) !== false) {
615 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
616 curl_setopt($ch, CURLOPT_HEADER, false);
617 $data = curl_exec($ch);
618 if (!curl_errno($ch)) {
619 $data = trim($data);
620 if ($data === $teststr) {
621 curl_close($ch);
622 return INSECURE_DATAROOT_ERROR;
625 curl_close($ch);
628 if ($data = @file_get_contents($testurl)) {
629 $data = trim($data);
630 if ($data === $teststr) {
631 return INSECURE_DATAROOT_ERROR;
635 preg_match('|https?://([^/]+)|i', $testurl, $matches);
636 $sitename = $matches[1];
637 $error = 0;
638 if ($fp = @fsockopen($sitename, 80, $error)) {
639 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
640 $localurl = $matches[1];
641 $out = "GET $localurl HTTP/1.1\r\n";
642 $out .= "Host: $sitename\r\n";
643 $out .= "Connection: Close\r\n\r\n";
644 fwrite($fp, $out);
645 $data = '';
646 $incoming = false;
647 while (!feof($fp)) {
648 if ($incoming) {
649 $data .= fgets($fp, 1024);
650 } else if (@fgets($fp, 1024) === "\r\n") {
651 $incoming = true;
654 fclose($fp);
655 $data = trim($data);
656 if ($data === $teststr) {
657 return INSECURE_DATAROOT_ERROR;
661 return INSECURE_DATAROOT_WARNING;
664 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
668 * Interface for anything appearing in the admin tree
670 * The interface that is implemented by anything that appears in the admin tree
671 * block. It forces inheriting classes to define a method for checking user permissions
672 * and methods for finding something in the admin tree.
674 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676 interface part_of_admin_tree {
679 * Finds a named part_of_admin_tree.
681 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
682 * and not parentable_part_of_admin_tree, then this function should only check if
683 * $this->name matches $name. If it does, it should return a reference to $this,
684 * otherwise, it should return a reference to NULL.
686 * If a class inherits parentable_part_of_admin_tree, this method should be called
687 * recursively on all child objects (assuming, of course, the parent object's name
688 * doesn't match the search criterion).
690 * @param string $name The internal name of the part_of_admin_tree we're searching for.
691 * @return mixed An object reference or a NULL reference.
693 public function locate($name);
696 * Removes named part_of_admin_tree.
698 * @param string $name The internal name of the part_of_admin_tree we want to remove.
699 * @return bool success.
701 public function prune($name);
704 * Search using query
705 * @param string $query
706 * @return mixed array-object structure of found settings and pages
708 public function search($query);
711 * Verifies current user's access to this part_of_admin_tree.
713 * Used to check if the current user has access to this part of the admin tree or
714 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
715 * then this method is usually just a call to has_capability() in the site context.
717 * If a class inherits parentable_part_of_admin_tree, this method should return the
718 * logical OR of the return of check_access() on all child objects.
720 * @return bool True if the user has access, false if she doesn't.
722 public function check_access();
725 * Mostly useful for removing of some parts of the tree in admin tree block.
727 * @return True is hidden from normal list view
729 public function is_hidden();
732 * Show we display Save button at the page bottom?
733 * @return bool
735 public function show_save();
740 * Interface implemented by any part_of_admin_tree that has children.
742 * The interface implemented by any part_of_admin_tree that can be a parent
743 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
744 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
745 * include an add method for adding other part_of_admin_tree objects as children.
747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
749 interface parentable_part_of_admin_tree extends part_of_admin_tree {
752 * Adds a part_of_admin_tree object to the admin tree.
754 * Used to add a part_of_admin_tree object to this object or a child of this
755 * object. $something should only be added if $destinationname matches
756 * $this->name. If it doesn't, add should be called on child objects that are
757 * also parentable_part_of_admin_tree's.
759 * @param string $destinationname The internal name of the new parent for $something.
760 * @param part_of_admin_tree $something The object to be added.
761 * @return bool True on success, false on failure.
763 public function add($destinationname, $something);
769 * The object used to represent folders (a.k.a. categories) in the admin tree block.
771 * Each admin_category object contains a number of part_of_admin_tree objects.
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 class admin_category implements parentable_part_of_admin_tree {
777 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
778 public $children;
779 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
780 public $name;
781 /** @var string The displayed name for this category. Usually obtained through get_string() */
782 public $visiblename;
783 /** @var bool Should this category be hidden in admin tree block? */
784 public $hidden;
785 /** @var mixed Either a string or an array or strings */
786 public $path;
787 /** @var mixed Either a string or an array or strings */
788 public $visiblepath;
790 /** @var array fast lookup category cache, all categories of one tree point to one cache */
791 protected $category_cache;
794 * Constructor for an empty admin category
796 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
797 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
798 * @param bool $hidden hide category in admin tree block, defaults to false
800 public function __construct($name, $visiblename, $hidden=false) {
801 $this->children = array();
802 $this->name = $name;
803 $this->visiblename = $visiblename;
804 $this->hidden = $hidden;
808 * Returns a reference to the part_of_admin_tree object with internal name $name.
810 * @param string $name The internal name of the object we want.
811 * @param bool $findpath initialize path and visiblepath arrays
812 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
813 * defaults to false
815 public function locate($name, $findpath=false) {
816 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
817 // somebody much have purged the cache
818 $this->category_cache[$this->name] = $this;
821 if ($this->name == $name) {
822 if ($findpath) {
823 $this->visiblepath[] = $this->visiblename;
824 $this->path[] = $this->name;
826 return $this;
829 // quick category lookup
830 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
831 return $this->category_cache[$name];
834 $return = NULL;
835 foreach($this->children as $childid=>$unused) {
836 if ($return = $this->children[$childid]->locate($name, $findpath)) {
837 break;
841 if (!is_null($return) and $findpath) {
842 $return->visiblepath[] = $this->visiblename;
843 $return->path[] = $this->name;
846 return $return;
850 * Search using query
852 * @param string query
853 * @return mixed array-object structure of found settings and pages
855 public function search($query) {
856 $result = array();
857 foreach ($this->children as $child) {
858 $subsearch = $child->search($query);
859 if (!is_array($subsearch)) {
860 debugging('Incorrect search result from '.$child->name);
861 continue;
863 $result = array_merge($result, $subsearch);
865 return $result;
869 * Removes part_of_admin_tree object with internal name $name.
871 * @param string $name The internal name of the object we want to remove.
872 * @return bool success
874 public function prune($name) {
876 if ($this->name == $name) {
877 return false; //can not remove itself
880 foreach($this->children as $precedence => $child) {
881 if ($child->name == $name) {
882 // clear cache and delete self
883 if (is_array($this->category_cache)) {
884 while($this->category_cache) {
885 // delete the cache, but keep the original array address
886 array_pop($this->category_cache);
889 unset($this->children[$precedence]);
890 return true;
891 } else if ($this->children[$precedence]->prune($name)) {
892 return true;
895 return false;
899 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
901 * @param string $destinationame The internal name of the immediate parent that we want for $something.
902 * @param mixed $something A part_of_admin_tree or setting instance to be added.
903 * @return bool True if successfully added, false if $something can not be added.
905 public function add($parentname, $something) {
906 $parent = $this->locate($parentname);
907 if (is_null($parent)) {
908 debugging('parent does not exist!');
909 return false;
912 if ($something instanceof part_of_admin_tree) {
913 if (!($parent instanceof parentable_part_of_admin_tree)) {
914 debugging('error - parts of tree can be inserted only into parentable parts');
915 return false;
917 $parent->children[] = $something;
918 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
919 if (isset($this->category_cache[$something->name])) {
920 debugging('Duplicate admin category name: '.$something->name);
921 } else {
922 $this->category_cache[$something->name] = $something;
923 $something->category_cache =& $this->category_cache;
924 foreach ($something->children as $child) {
925 // just in case somebody already added subcategories
926 if ($child instanceof admin_category) {
927 if (isset($this->category_cache[$child->name])) {
928 debugging('Duplicate admin category name: '.$child->name);
929 } else {
930 $this->category_cache[$child->name] = $child;
931 $child->category_cache =& $this->category_cache;
937 return true;
939 } else {
940 debugging('error - can not add this element');
941 return false;
947 * Checks if the user has access to anything in this category.
949 * @return bool True if the user has access to at least one child in this category, false otherwise.
951 public function check_access() {
952 foreach ($this->children as $child) {
953 if ($child->check_access()) {
954 return true;
957 return false;
961 * Is this category hidden in admin tree block?
963 * @return bool True if hidden
965 public function is_hidden() {
966 return $this->hidden;
970 * Show we display Save button at the page bottom?
971 * @return bool
973 public function show_save() {
974 foreach ($this->children as $child) {
975 if ($child->show_save()) {
976 return true;
979 return false;
985 * Root of admin settings tree, does not have any parent.
987 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
989 class admin_root extends admin_category {
990 /** @var array List of errors */
991 public $errors;
992 /** @var string search query */
993 public $search;
994 /** @var bool full tree flag - true means all settings required, false only pages required */
995 public $fulltree;
996 /** @var bool flag indicating loaded tree */
997 public $loaded;
998 /** @var mixed site custom defaults overriding defaults in settings files*/
999 public $custom_defaults;
1002 * @param bool $fulltree true means all settings required,
1003 * false only pages required
1005 public function __construct($fulltree) {
1006 global $CFG;
1008 parent::__construct('root', get_string('administration'), false);
1009 $this->errors = array();
1010 $this->search = '';
1011 $this->fulltree = $fulltree;
1012 $this->loaded = false;
1014 $this->category_cache = array();
1016 // load custom defaults if found
1017 $this->custom_defaults = null;
1018 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1019 if (is_readable($defaultsfile)) {
1020 $defaults = array();
1021 include($defaultsfile);
1022 if (is_array($defaults) and count($defaults)) {
1023 $this->custom_defaults = $defaults;
1029 * Empties children array, and sets loaded to false
1031 * @param bool $requirefulltree
1033 public function purge_children($requirefulltree) {
1034 $this->children = array();
1035 $this->fulltree = ($requirefulltree || $this->fulltree);
1036 $this->loaded = false;
1037 //break circular dependencies - this helps PHP 5.2
1038 while($this->category_cache) {
1039 array_pop($this->category_cache);
1041 $this->category_cache = array();
1047 * Links external PHP pages into the admin tree.
1049 * See detailed usage example at the top of this document (adminlib.php)
1051 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1053 class admin_externalpage implements part_of_admin_tree {
1055 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1056 public $name;
1058 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1059 public $visiblename;
1061 /** @var string The external URL that we should link to when someone requests this external page. */
1062 public $url;
1064 /** @var string The role capability/permission a user must have to access this external page. */
1065 public $req_capability;
1067 /** @var object The context in which capability/permission should be checked, default is site context. */
1068 public $context;
1070 /** @var bool hidden in admin tree block. */
1071 public $hidden;
1073 /** @var mixed either string or array of string */
1074 public $path;
1076 /** @var array list of visible names of page parents */
1077 public $visiblepath;
1080 * Constructor for adding an external page into the admin tree.
1082 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1083 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1084 * @param string $url The external URL that we should link to when someone requests this external page.
1085 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1086 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1087 * @param stdClass $context The context the page relates to. Not sure what happens
1088 * if you specify something other than system or front page. Defaults to system.
1090 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1091 $this->name = $name;
1092 $this->visiblename = $visiblename;
1093 $this->url = $url;
1094 if (is_array($req_capability)) {
1095 $this->req_capability = $req_capability;
1096 } else {
1097 $this->req_capability = array($req_capability);
1099 $this->hidden = $hidden;
1100 $this->context = $context;
1104 * Returns a reference to the part_of_admin_tree object with internal name $name.
1106 * @param string $name The internal name of the object we want.
1107 * @param bool $findpath defaults to false
1108 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1110 public function locate($name, $findpath=false) {
1111 if ($this->name == $name) {
1112 if ($findpath) {
1113 $this->visiblepath = array($this->visiblename);
1114 $this->path = array($this->name);
1116 return $this;
1117 } else {
1118 $return = NULL;
1119 return $return;
1124 * This function always returns false, required function by interface
1126 * @param string $name
1127 * @return false
1129 public function prune($name) {
1130 return false;
1134 * Search using query
1136 * @param string $query
1137 * @return mixed array-object structure of found settings and pages
1139 public function search($query) {
1140 $textlib = textlib_get_instance();
1142 $found = false;
1143 if (strpos(strtolower($this->name), $query) !== false) {
1144 $found = true;
1145 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1146 $found = true;
1148 if ($found) {
1149 $result = new stdClass();
1150 $result->page = $this;
1151 $result->settings = array();
1152 return array($this->name => $result);
1153 } else {
1154 return array();
1159 * Determines if the current user has access to this external page based on $this->req_capability.
1161 * @return bool True if user has access, false otherwise.
1163 public function check_access() {
1164 global $CFG;
1165 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1166 foreach($this->req_capability as $cap) {
1167 if (has_capability($cap, $context)) {
1168 return true;
1171 return false;
1175 * Is this external page hidden in admin tree block?
1177 * @return bool True if hidden
1179 public function is_hidden() {
1180 return $this->hidden;
1184 * Show we display Save button at the page bottom?
1185 * @return bool
1187 public function show_save() {
1188 return false;
1194 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1196 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1198 class admin_settingpage implements part_of_admin_tree {
1200 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1201 public $name;
1203 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1204 public $visiblename;
1206 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1207 public $settings;
1209 /** @var string The role capability/permission a user must have to access this external page. */
1210 public $req_capability;
1212 /** @var object The context in which capability/permission should be checked, default is site context. */
1213 public $context;
1215 /** @var bool hidden in admin tree block. */
1216 public $hidden;
1218 /** @var mixed string of paths or array of strings of paths */
1219 public $path;
1221 /** @var array list of visible names of page parents */
1222 public $visiblepath;
1225 * see admin_settingpage for details of this function
1227 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1228 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1229 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1230 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1231 * @param stdClass $context The context the page relates to. Not sure what happens
1232 * if you specify something other than system or front page. Defaults to system.
1234 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1235 $this->settings = new stdClass();
1236 $this->name = $name;
1237 $this->visiblename = $visiblename;
1238 if (is_array($req_capability)) {
1239 $this->req_capability = $req_capability;
1240 } else {
1241 $this->req_capability = array($req_capability);
1243 $this->hidden = $hidden;
1244 $this->context = $context;
1248 * see admin_category
1250 * @param string $name
1251 * @param bool $findpath
1252 * @return mixed Object (this) if name == this->name, else returns null
1254 public function locate($name, $findpath=false) {
1255 if ($this->name == $name) {
1256 if ($findpath) {
1257 $this->visiblepath = array($this->visiblename);
1258 $this->path = array($this->name);
1260 return $this;
1261 } else {
1262 $return = NULL;
1263 return $return;
1268 * Search string in settings page.
1270 * @param string $query
1271 * @return array
1273 public function search($query) {
1274 $found = array();
1276 foreach ($this->settings as $setting) {
1277 if ($setting->is_related($query)) {
1278 $found[] = $setting;
1282 if ($found) {
1283 $result = new stdClass();
1284 $result->page = $this;
1285 $result->settings = $found;
1286 return array($this->name => $result);
1289 $textlib = textlib_get_instance();
1291 $found = false;
1292 if (strpos(strtolower($this->name), $query) !== false) {
1293 $found = true;
1294 } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1295 $found = true;
1297 if ($found) {
1298 $result = new stdClass();
1299 $result->page = $this;
1300 $result->settings = array();
1301 return array($this->name => $result);
1302 } else {
1303 return array();
1308 * This function always returns false, required by interface
1310 * @param string $name
1311 * @return bool Always false
1313 public function prune($name) {
1314 return false;
1318 * adds an admin_setting to this admin_settingpage
1320 * not the same as add for admin_category. adds an admin_setting to this admin_settingpage. settings appear (on the settingpage) in the order in which they're added
1321 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1323 * @param object $setting is the admin_setting object you want to add
1324 * @return bool true if successful, false if not
1326 public function add($setting) {
1327 if (!($setting instanceof admin_setting)) {
1328 debugging('error - not a setting instance');
1329 return false;
1332 $this->settings->{$setting->name} = $setting;
1333 return true;
1337 * see admin_externalpage
1339 * @return bool Returns true for yes false for no
1341 public function check_access() {
1342 global $CFG;
1343 $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
1344 foreach($this->req_capability as $cap) {
1345 if (has_capability($cap, $context)) {
1346 return true;
1349 return false;
1353 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1354 * @return string Returns an XHTML string
1356 public function output_html() {
1357 $adminroot = admin_get_root();
1358 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1359 foreach($this->settings as $setting) {
1360 $fullname = $setting->get_full_name();
1361 if (array_key_exists($fullname, $adminroot->errors)) {
1362 $data = $adminroot->errors[$fullname]->data;
1363 } else {
1364 $data = $setting->get_setting();
1365 // do not use defaults if settings not available - upgrade settings handles the defaults!
1367 $return .= $setting->output_html($data);
1369 $return .= '</fieldset>';
1370 return $return;
1374 * Is this settings page hidden in admin tree block?
1376 * @return bool True if hidden
1378 public function is_hidden() {
1379 return $this->hidden;
1383 * Show we display Save button at the page bottom?
1384 * @return bool
1386 public function show_save() {
1387 foreach($this->settings as $setting) {
1388 if (empty($setting->nosave)) {
1389 return true;
1392 return false;
1398 * Admin settings class. Only exists on setting pages.
1399 * Read & write happens at this level; no authentication.
1401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1403 abstract class admin_setting {
1404 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1405 public $name;
1406 /** @var string localised name */
1407 public $visiblename;
1408 /** @var string localised long description in Markdown format */
1409 public $description;
1410 /** @var mixed Can be string or array of string */
1411 public $defaultsetting;
1412 /** @var string */
1413 public $updatedcallback;
1414 /** @var mixed can be String or Null. Null means main config table */
1415 public $plugin; // null means main config table
1416 /** @var bool true indicates this setting does not actually save anything, just information */
1417 public $nosave = false;
1418 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1419 public $affectsmodinfo = false;
1422 * Constructor
1423 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1424 * or 'myplugin/mysetting' for ones in config_plugins.
1425 * @param string $visiblename localised name
1426 * @param string $description localised long description
1427 * @param mixed $defaultsetting string or array depending on implementation
1429 public function __construct($name, $visiblename, $description, $defaultsetting) {
1430 $this->parse_setting_name($name);
1431 $this->visiblename = $visiblename;
1432 $this->description = $description;
1433 $this->defaultsetting = $defaultsetting;
1437 * Set up $this->name and potentially $this->plugin
1439 * Set up $this->name and possibly $this->plugin based on whether $name looks
1440 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1441 * on the names, that is, output a developer debug warning if the name
1442 * contains anything other than [a-zA-Z0-9_]+.
1444 * @param string $name the setting name passed in to the constructor.
1446 private function parse_setting_name($name) {
1447 $bits = explode('/', $name);
1448 if (count($bits) > 2) {
1449 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1451 $this->name = array_pop($bits);
1452 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1453 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1455 if (!empty($bits)) {
1456 $this->plugin = array_pop($bits);
1457 if ($this->plugin === 'moodle') {
1458 $this->plugin = null;
1459 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1460 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1466 * Returns the fullname prefixed by the plugin
1467 * @return string
1469 public function get_full_name() {
1470 return 's_'.$this->plugin.'_'.$this->name;
1474 * Returns the ID string based on plugin and name
1475 * @return string
1477 public function get_id() {
1478 return 'id_s_'.$this->plugin.'_'.$this->name;
1482 * @param bool $affectsmodinfo If true, changes to this setting will
1483 * cause the course cache to be rebuilt
1485 public function set_affects_modinfo($affectsmodinfo) {
1486 $this->affectsmodinfo = $affectsmodinfo;
1490 * Returns the config if possible
1492 * @return mixed returns config if successful else null
1494 public function config_read($name) {
1495 global $CFG;
1496 if (!empty($this->plugin)) {
1497 $value = get_config($this->plugin, $name);
1498 return $value === false ? NULL : $value;
1500 } else {
1501 if (isset($CFG->$name)) {
1502 return $CFG->$name;
1503 } else {
1504 return NULL;
1510 * Used to set a config pair and log change
1512 * @param string $name
1513 * @param mixed $value Gets converted to string if not null
1514 * @return bool Write setting to config table
1516 public function config_write($name, $value) {
1517 global $DB, $USER, $CFG;
1519 if ($this->nosave) {
1520 return true;
1523 // make sure it is a real change
1524 $oldvalue = get_config($this->plugin, $name);
1525 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1526 $value = is_null($value) ? null : (string)$value;
1528 if ($oldvalue === $value) {
1529 return true;
1532 // store change
1533 set_config($name, $value, $this->plugin);
1535 // Some admin settings affect course modinfo
1536 if ($this->affectsmodinfo) {
1537 // Clear course cache for all courses
1538 rebuild_course_cache(0, true);
1541 // log change
1542 $log = new stdClass();
1543 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1544 $log->timemodified = time();
1545 $log->plugin = $this->plugin;
1546 $log->name = $name;
1547 $log->value = $value;
1548 $log->oldvalue = $oldvalue;
1549 $DB->insert_record('config_log', $log);
1551 return true; // BC only
1555 * Returns current value of this setting
1556 * @return mixed array or string depending on instance, NULL means not set yet
1558 public abstract function get_setting();
1561 * Returns default setting if exists
1562 * @return mixed array or string depending on instance; NULL means no default, user must supply
1564 public function get_defaultsetting() {
1565 $adminroot = admin_get_root(false, false);
1566 if (!empty($adminroot->custom_defaults)) {
1567 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1568 if (isset($adminroot->custom_defaults[$plugin])) {
1569 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1570 return $adminroot->custom_defaults[$plugin][$this->name];
1574 return $this->defaultsetting;
1578 * Store new setting
1580 * @param mixed $data string or array, must not be NULL
1581 * @return string empty string if ok, string error message otherwise
1583 public abstract function write_setting($data);
1586 * Return part of form with setting
1587 * This function should always be overwritten
1589 * @param mixed $data array or string depending on setting
1590 * @param string $query
1591 * @return string
1593 public function output_html($data, $query='') {
1594 // should be overridden
1595 return;
1599 * Function called if setting updated - cleanup, cache reset, etc.
1600 * @param string $functionname Sets the function name
1601 * @return void
1603 public function set_updatedcallback($functionname) {
1604 $this->updatedcallback = $functionname;
1608 * Is setting related to query text - used when searching
1609 * @param string $query
1610 * @return bool
1612 public function is_related($query) {
1613 if (strpos(strtolower($this->name), $query) !== false) {
1614 return true;
1616 $textlib = textlib_get_instance();
1617 if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
1618 return true;
1620 if (strpos($textlib->strtolower($this->description), $query) !== false) {
1621 return true;
1623 $current = $this->get_setting();
1624 if (!is_null($current)) {
1625 if (is_string($current)) {
1626 if (strpos($textlib->strtolower($current), $query) !== false) {
1627 return true;
1631 $default = $this->get_defaultsetting();
1632 if (!is_null($default)) {
1633 if (is_string($default)) {
1634 if (strpos($textlib->strtolower($default), $query) !== false) {
1635 return true;
1639 return false;
1645 * No setting - just heading and text.
1647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1649 class admin_setting_heading extends admin_setting {
1652 * not a setting, just text
1653 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1654 * @param string $heading heading
1655 * @param string $information text in box
1657 public function __construct($name, $heading, $information) {
1658 $this->nosave = true;
1659 parent::__construct($name, $heading, $information, '');
1663 * Always returns true
1664 * @return bool Always returns true
1666 public function get_setting() {
1667 return true;
1671 * Always returns true
1672 * @return bool Always returns true
1674 public function get_defaultsetting() {
1675 return true;
1679 * Never write settings
1680 * @return string Always returns an empty string
1682 public function write_setting($data) {
1683 // do not write any setting
1684 return '';
1688 * Returns an HTML string
1689 * @return string Returns an HTML string
1691 public function output_html($data, $query='') {
1692 global $OUTPUT;
1693 $return = '';
1694 if ($this->visiblename != '') {
1695 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1697 if ($this->description != '') {
1698 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1700 return $return;
1706 * The most flexibly setting, user is typing text
1708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1710 class admin_setting_configtext extends admin_setting {
1712 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1713 public $paramtype;
1714 /** @var int default field size */
1715 public $size;
1718 * Config text constructor
1720 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1721 * @param string $visiblename localised
1722 * @param string $description long localised info
1723 * @param string $defaultsetting
1724 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1725 * @param int $size default field size
1727 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1728 $this->paramtype = $paramtype;
1729 if (!is_null($size)) {
1730 $this->size = $size;
1731 } else {
1732 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1734 parent::__construct($name, $visiblename, $description, $defaultsetting);
1738 * Return the setting
1740 * @return mixed returns config if successful else null
1742 public function get_setting() {
1743 return $this->config_read($this->name);
1746 public function write_setting($data) {
1747 if ($this->paramtype === PARAM_INT and $data === '') {
1748 // do not complain if '' used instead of 0
1749 $data = 0;
1751 // $data is a string
1752 $validated = $this->validate($data);
1753 if ($validated !== true) {
1754 return $validated;
1756 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1760 * Validate data before storage
1761 * @param string data
1762 * @return mixed true if ok string if error found
1764 public function validate($data) {
1765 // allow paramtype to be a custom regex if it is the form of /pattern/
1766 if (preg_match('#^/.*/$#', $this->paramtype)) {
1767 if (preg_match($this->paramtype, $data)) {
1768 return true;
1769 } else {
1770 return get_string('validateerror', 'admin');
1773 } else if ($this->paramtype === PARAM_RAW) {
1774 return true;
1776 } else {
1777 $cleaned = clean_param($data, $this->paramtype);
1778 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1779 return true;
1780 } else {
1781 return get_string('validateerror', 'admin');
1787 * Return an XHTML string for the setting
1788 * @return string Returns an XHTML string
1790 public function output_html($data, $query='') {
1791 $default = $this->get_defaultsetting();
1793 return format_admin_setting($this, $this->visiblename,
1794 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1795 $this->description, true, '', $default, $query);
1801 * General text area without html editor.
1803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1805 class admin_setting_configtextarea extends admin_setting_configtext {
1806 private $rows;
1807 private $cols;
1810 * @param string $name
1811 * @param string $visiblename
1812 * @param string $description
1813 * @param mixed $defaultsetting string or array
1814 * @param mixed $paramtype
1815 * @param string $cols The number of columns to make the editor
1816 * @param string $rows The number of rows to make the editor
1818 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1819 $this->rows = $rows;
1820 $this->cols = $cols;
1821 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1825 * Returns an XHTML string for the editor
1827 * @param string $data
1828 * @param string $query
1829 * @return string XHTML string for the editor
1831 public function output_html($data, $query='') {
1832 $default = $this->get_defaultsetting();
1834 $defaultinfo = $default;
1835 if (!is_null($default) and $default !== '') {
1836 $defaultinfo = "\n".$default;
1839 return format_admin_setting($this, $this->visiblename,
1840 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1841 $this->description, true, '', $defaultinfo, $query);
1847 * General text area with html editor.
1849 class admin_setting_confightmleditor extends admin_setting_configtext {
1850 private $rows;
1851 private $cols;
1854 * @param string $name
1855 * @param string $visiblename
1856 * @param string $description
1857 * @param mixed $defaultsetting string or array
1858 * @param mixed $paramtype
1860 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1861 $this->rows = $rows;
1862 $this->cols = $cols;
1863 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1864 editors_head_setup();
1868 * Returns an XHTML string for the editor
1870 * @param string $data
1871 * @param string $query
1872 * @return string XHTML string for the editor
1874 public function output_html($data, $query='') {
1875 $default = $this->get_defaultsetting();
1877 $defaultinfo = $default;
1878 if (!is_null($default) and $default !== '') {
1879 $defaultinfo = "\n".$default;
1882 $editor = editors_get_preferred_editor(FORMAT_HTML);
1883 $editor->use_editor($this->get_id(), array('noclean'=>true));
1885 return format_admin_setting($this, $this->visiblename,
1886 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1887 $this->description, true, '', $defaultinfo, $query);
1893 * Password field, allows unmasking of password
1895 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1897 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1899 * Constructor
1900 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1901 * @param string $visiblename localised
1902 * @param string $description long localised info
1903 * @param string $defaultsetting default password
1905 public function __construct($name, $visiblename, $description, $defaultsetting) {
1906 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1910 * Returns XHTML for the field
1911 * Writes Javascript into the HTML below right before the last div
1913 * @todo Make javascript available through newer methods if possible
1914 * @param string $data Value for the field
1915 * @param string $query Passed as final argument for format_admin_setting
1916 * @return string XHTML field
1918 public function output_html($data, $query='') {
1919 $id = $this->get_id();
1920 $unmask = get_string('unmaskpassword', 'form');
1921 $unmaskjs = '<script type="text/javascript">
1922 //<![CDATA[
1923 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1925 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1927 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1929 var unmaskchb = document.createElement("input");
1930 unmaskchb.setAttribute("type", "checkbox");
1931 unmaskchb.setAttribute("id", "'.$id.'unmask");
1932 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1933 unmaskdiv.appendChild(unmaskchb);
1935 var unmasklbl = document.createElement("label");
1936 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1937 if (is_ie) {
1938 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1939 } else {
1940 unmasklbl.setAttribute("for", "'.$id.'unmask");
1942 unmaskdiv.appendChild(unmasklbl);
1944 if (is_ie) {
1945 // ugly hack to work around the famous onchange IE bug
1946 unmaskchb.onclick = function() {this.blur();};
1947 unmaskdiv.onclick = function() {this.blur();};
1949 //]]>
1950 </script>';
1951 return format_admin_setting($this, $this->visiblename,
1952 '<div class="form-password"><input type="password" size="'.$this->size.'" id="'.$id.'" name="'.$this->get_full_name().'" value="'.s($data).'" /><div class="unmask" id="'.$id.'unmaskdiv"></div>'.$unmaskjs.'</div>',
1953 $this->description, true, '', NULL, $query);
1959 * Path to directory
1961 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1963 class admin_setting_configfile extends admin_setting_configtext {
1965 * Constructor
1966 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1967 * @param string $visiblename localised
1968 * @param string $description long localised info
1969 * @param string $defaultdirectory default directory location
1971 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1972 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1976 * Returns XHTML for the field
1978 * Returns XHTML for the field and also checks whether the file
1979 * specified in $data exists using file_exists()
1981 * @param string $data File name and path to use in value attr
1982 * @param string $query
1983 * @return string XHTML field
1985 public function output_html($data, $query='') {
1986 $default = $this->get_defaultsetting();
1988 if ($data) {
1989 if (file_exists($data)) {
1990 $executable = '<span class="pathok">&#x2714;</span>';
1991 } else {
1992 $executable = '<span class="patherror">&#x2718;</span>';
1994 } else {
1995 $executable = '';
1998 return format_admin_setting($this, $this->visiblename,
1999 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2000 $this->description, true, '', $default, $query);
2006 * Path to executable file
2008 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2010 class admin_setting_configexecutable extends admin_setting_configfile {
2013 * Returns an XHTML field
2015 * @param string $data This is the value for the field
2016 * @param string $query
2017 * @return string XHTML field
2019 public function output_html($data, $query='') {
2020 $default = $this->get_defaultsetting();
2022 if ($data) {
2023 if (file_exists($data) and is_executable($data)) {
2024 $executable = '<span class="pathok">&#x2714;</span>';
2025 } else {
2026 $executable = '<span class="patherror">&#x2718;</span>';
2028 } else {
2029 $executable = '';
2032 return format_admin_setting($this, $this->visiblename,
2033 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2034 $this->description, true, '', $default, $query);
2040 * Path to directory
2042 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2044 class admin_setting_configdirectory extends admin_setting_configfile {
2047 * Returns an XHTML field
2049 * @param string $data This is the value for the field
2050 * @param string $query
2051 * @return string XHTML
2053 public function output_html($data, $query='') {
2054 $default = $this->get_defaultsetting();
2056 if ($data) {
2057 if (file_exists($data) and is_dir($data)) {
2058 $executable = '<span class="pathok">&#x2714;</span>';
2059 } else {
2060 $executable = '<span class="patherror">&#x2718;</span>';
2062 } else {
2063 $executable = '';
2066 return format_admin_setting($this, $this->visiblename,
2067 '<div class="form-file defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" />'.$executable.'</div>',
2068 $this->description, true, '', $default, $query);
2074 * Checkbox
2076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2078 class admin_setting_configcheckbox extends admin_setting {
2079 /** @var string Value used when checked */
2080 public $yes;
2081 /** @var string Value used when not checked */
2082 public $no;
2085 * Constructor
2086 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2087 * @param string $visiblename localised
2088 * @param string $description long localised info
2089 * @param string $defaultsetting
2090 * @param string $yes value used when checked
2091 * @param string $no value used when not checked
2093 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2094 parent::__construct($name, $visiblename, $description, $defaultsetting);
2095 $this->yes = (string)$yes;
2096 $this->no = (string)$no;
2100 * Retrieves the current setting using the objects name
2102 * @return string
2104 public function get_setting() {
2105 return $this->config_read($this->name);
2109 * Sets the value for the setting
2111 * Sets the value for the setting to either the yes or no values
2112 * of the object by comparing $data to yes
2114 * @param mixed $data Gets converted to str for comparison against yes value
2115 * @return string empty string or error
2117 public function write_setting($data) {
2118 if ((string)$data === $this->yes) { // convert to strings before comparison
2119 $data = $this->yes;
2120 } else {
2121 $data = $this->no;
2123 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2127 * Returns an XHTML checkbox field
2129 * @param string $data If $data matches yes then checkbox is checked
2130 * @param string $query
2131 * @return string XHTML field
2133 public function output_html($data, $query='') {
2134 $default = $this->get_defaultsetting();
2136 if (!is_null($default)) {
2137 if ((string)$default === $this->yes) {
2138 $defaultinfo = get_string('checkboxyes', 'admin');
2139 } else {
2140 $defaultinfo = get_string('checkboxno', 'admin');
2142 } else {
2143 $defaultinfo = NULL;
2146 if ((string)$data === $this->yes) { // convert to strings before comparison
2147 $checked = 'checked="checked"';
2148 } else {
2149 $checked = '';
2152 return format_admin_setting($this, $this->visiblename,
2153 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2154 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2155 $this->description, true, '', $defaultinfo, $query);
2161 * Multiple checkboxes, each represents different value, stored in csv format
2163 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2165 class admin_setting_configmulticheckbox extends admin_setting {
2166 /** @var array Array of choices value=>label */
2167 public $choices;
2170 * Constructor: uses parent::__construct
2172 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2173 * @param string $visiblename localised
2174 * @param string $description long localised info
2175 * @param array $defaultsetting array of selected
2176 * @param array $choices array of $value=>$label for each checkbox
2178 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2179 $this->choices = $choices;
2180 parent::__construct($name, $visiblename, $description, $defaultsetting);
2184 * This public function may be used in ancestors for lazy loading of choices
2186 * @todo Check if this function is still required content commented out only returns true
2187 * @return bool true if loaded, false if error
2189 public function load_choices() {
2191 if (is_array($this->choices)) {
2192 return true;
2194 .... load choices here
2196 return true;
2200 * Is setting related to query text - used when searching
2202 * @param string $query
2203 * @return bool true on related, false on not or failure
2205 public function is_related($query) {
2206 if (!$this->load_choices() or empty($this->choices)) {
2207 return false;
2209 if (parent::is_related($query)) {
2210 return true;
2213 $textlib = textlib_get_instance();
2214 foreach ($this->choices as $desc) {
2215 if (strpos($textlib->strtolower($desc), $query) !== false) {
2216 return true;
2219 return false;
2223 * Returns the current setting if it is set
2225 * @return mixed null if null, else an array
2227 public function get_setting() {
2228 $result = $this->config_read($this->name);
2230 if (is_null($result)) {
2231 return NULL;
2233 if ($result === '') {
2234 return array();
2236 $enabled = explode(',', $result);
2237 $setting = array();
2238 foreach ($enabled as $option) {
2239 $setting[$option] = 1;
2241 return $setting;
2245 * Saves the setting(s) provided in $data
2247 * @param array $data An array of data, if not array returns empty str
2248 * @return mixed empty string on useless data or bool true=success, false=failed
2250 public function write_setting($data) {
2251 if (!is_array($data)) {
2252 return ''; // ignore it
2254 if (!$this->load_choices() or empty($this->choices)) {
2255 return '';
2257 unset($data['xxxxx']);
2258 $result = array();
2259 foreach ($data as $key => $value) {
2260 if ($value and array_key_exists($key, $this->choices)) {
2261 $result[] = $key;
2264 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2268 * Returns XHTML field(s) as required by choices
2270 * Relies on data being an array should data ever be another valid vartype with
2271 * acceptable value this may cause a warning/error
2272 * if (!is_array($data)) would fix the problem
2274 * @todo Add vartype handling to ensure $data is an array
2276 * @param array $data An array of checked values
2277 * @param string $query
2278 * @return string XHTML field
2280 public function output_html($data, $query='') {
2281 if (!$this->load_choices() or empty($this->choices)) {
2282 return '';
2284 $default = $this->get_defaultsetting();
2285 if (is_null($default)) {
2286 $default = array();
2288 if (is_null($data)) {
2289 $data = array();
2291 $options = array();
2292 $defaults = array();
2293 foreach ($this->choices as $key=>$description) {
2294 if (!empty($data[$key])) {
2295 $checked = 'checked="checked"';
2296 } else {
2297 $checked = '';
2299 if (!empty($default[$key])) {
2300 $defaults[] = $description;
2303 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2304 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2307 if (is_null($default)) {
2308 $defaultinfo = NULL;
2309 } else if (!empty($defaults)) {
2310 $defaultinfo = implode(', ', $defaults);
2311 } else {
2312 $defaultinfo = get_string('none');
2315 $return = '<div class="form-multicheckbox">';
2316 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2317 if ($options) {
2318 $return .= '<ul>';
2319 foreach ($options as $option) {
2320 $return .= '<li>'.$option.'</li>';
2322 $return .= '</ul>';
2324 $return .= '</div>';
2326 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2333 * Multiple checkboxes 2, value stored as string 00101011
2335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2337 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2340 * Returns the setting if set
2342 * @return mixed null if not set, else an array of set settings
2344 public function get_setting() {
2345 $result = $this->config_read($this->name);
2346 if (is_null($result)) {
2347 return NULL;
2349 if (!$this->load_choices()) {
2350 return NULL;
2352 $result = str_pad($result, count($this->choices), '0');
2353 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2354 $setting = array();
2355 foreach ($this->choices as $key=>$unused) {
2356 $value = array_shift($result);
2357 if ($value) {
2358 $setting[$key] = 1;
2361 return $setting;
2365 * Save setting(s) provided in $data param
2367 * @param array $data An array of settings to save
2368 * @return mixed empty string for bad data or bool true=>success, false=>error
2370 public function write_setting($data) {
2371 if (!is_array($data)) {
2372 return ''; // ignore it
2374 if (!$this->load_choices() or empty($this->choices)) {
2375 return '';
2377 $result = '';
2378 foreach ($this->choices as $key=>$unused) {
2379 if (!empty($data[$key])) {
2380 $result .= '1';
2381 } else {
2382 $result .= '0';
2385 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2391 * Select one value from list
2393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2395 class admin_setting_configselect extends admin_setting {
2396 /** @var array Array of choices value=>label */
2397 public $choices;
2400 * Constructor
2401 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2402 * @param string $visiblename localised
2403 * @param string $description long localised info
2404 * @param string|int $defaultsetting
2405 * @param array $choices array of $value=>$label for each selection
2407 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2408 $this->choices = $choices;
2409 parent::__construct($name, $visiblename, $description, $defaultsetting);
2413 * This function may be used in ancestors for lazy loading of choices
2415 * Override this method if loading of choices is expensive, such
2416 * as when it requires multiple db requests.
2418 * @return bool true if loaded, false if error
2420 public function load_choices() {
2422 if (is_array($this->choices)) {
2423 return true;
2425 .... load choices here
2427 return true;
2431 * Check if this is $query is related to a choice
2433 * @param string $query
2434 * @return bool true if related, false if not
2436 public function is_related($query) {
2437 if (parent::is_related($query)) {
2438 return true;
2440 if (!$this->load_choices()) {
2441 return false;
2443 $textlib = textlib_get_instance();
2444 foreach ($this->choices as $key=>$value) {
2445 if (strpos($textlib->strtolower($key), $query) !== false) {
2446 return true;
2448 if (strpos($textlib->strtolower($value), $query) !== false) {
2449 return true;
2452 return false;
2456 * Return the setting
2458 * @return mixed returns config if successful else null
2460 public function get_setting() {
2461 return $this->config_read($this->name);
2465 * Save a setting
2467 * @param string $data
2468 * @return string empty of error string
2470 public function write_setting($data) {
2471 if (!$this->load_choices() or empty($this->choices)) {
2472 return '';
2474 if (!array_key_exists($data, $this->choices)) {
2475 return ''; // ignore it
2478 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2482 * Returns XHTML select field
2484 * Ensure the options are loaded, and generate the XHTML for the select
2485 * element and any warning message. Separating this out from output_html
2486 * makes it easier to subclass this class.
2488 * @param string $data the option to show as selected.
2489 * @param string $current the currently selected option in the database, null if none.
2490 * @param string $default the default selected option.
2491 * @return array the HTML for the select element, and a warning message.
2493 public function output_select_html($data, $current, $default, $extraname = '') {
2494 if (!$this->load_choices() or empty($this->choices)) {
2495 return array('', '');
2498 $warning = '';
2499 if (is_null($current)) {
2500 // first run
2501 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2502 // no warning
2503 } else if (!array_key_exists($current, $this->choices)) {
2504 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2505 if (!is_null($default) and $data == $current) {
2506 $data = $default; // use default instead of first value when showing the form
2510 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2511 foreach ($this->choices as $key => $value) {
2512 // the string cast is needed because key may be integer - 0 is equal to most strings!
2513 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2515 $selecthtml .= '</select>';
2516 return array($selecthtml, $warning);
2520 * Returns XHTML select field and wrapping div(s)
2522 * @see output_select_html()
2524 * @param string $data the option to show as selected
2525 * @param string $query
2526 * @return string XHTML field and wrapping div
2528 public function output_html($data, $query='') {
2529 $default = $this->get_defaultsetting();
2530 $current = $this->get_setting();
2532 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2533 if (!$selecthtml) {
2534 return '';
2537 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2538 $defaultinfo = $this->choices[$default];
2539 } else {
2540 $defaultinfo = NULL;
2543 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2545 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2551 * Select multiple items from list
2553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2555 class admin_setting_configmultiselect extends admin_setting_configselect {
2557 * Constructor
2558 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2559 * @param string $visiblename localised
2560 * @param string $description long localised info
2561 * @param array $defaultsetting array of selected items
2562 * @param array $choices array of $value=>$label for each list item
2564 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2565 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2569 * Returns the select setting(s)
2571 * @return mixed null or array. Null if no settings else array of setting(s)
2573 public function get_setting() {
2574 $result = $this->config_read($this->name);
2575 if (is_null($result)) {
2576 return NULL;
2578 if ($result === '') {
2579 return array();
2581 return explode(',', $result);
2585 * Saves setting(s) provided through $data
2587 * Potential bug in the works should anyone call with this function
2588 * using a vartype that is not an array
2590 * @param array $data
2592 public function write_setting($data) {
2593 if (!is_array($data)) {
2594 return ''; //ignore it
2596 if (!$this->load_choices() or empty($this->choices)) {
2597 return '';
2600 unset($data['xxxxx']);
2602 $save = array();
2603 foreach ($data as $value) {
2604 if (!array_key_exists($value, $this->choices)) {
2605 continue; // ignore it
2607 $save[] = $value;
2610 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2614 * Is setting related to query text - used when searching
2616 * @param string $query
2617 * @return bool true if related, false if not
2619 public function is_related($query) {
2620 if (!$this->load_choices() or empty($this->choices)) {
2621 return false;
2623 if (parent::is_related($query)) {
2624 return true;
2627 $textlib = textlib_get_instance();
2628 foreach ($this->choices as $desc) {
2629 if (strpos($textlib->strtolower($desc), $query) !== false) {
2630 return true;
2633 return false;
2637 * Returns XHTML multi-select field
2639 * @todo Add vartype handling to ensure $data is an array
2640 * @param array $data Array of values to select by default
2641 * @param string $query
2642 * @return string XHTML multi-select field
2644 public function output_html($data, $query='') {
2645 if (!$this->load_choices() or empty($this->choices)) {
2646 return '';
2648 $choices = $this->choices;
2649 $default = $this->get_defaultsetting();
2650 if (is_null($default)) {
2651 $default = array();
2653 if (is_null($data)) {
2654 $data = array();
2657 $defaults = array();
2658 $size = min(10, count($this->choices));
2659 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2660 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2661 foreach ($this->choices as $key => $description) {
2662 if (in_array($key, $data)) {
2663 $selected = 'selected="selected"';
2664 } else {
2665 $selected = '';
2667 if (in_array($key, $default)) {
2668 $defaults[] = $description;
2671 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2674 if (is_null($default)) {
2675 $defaultinfo = NULL;
2676 } if (!empty($defaults)) {
2677 $defaultinfo = implode(', ', $defaults);
2678 } else {
2679 $defaultinfo = get_string('none');
2682 $return .= '</select></div>';
2683 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2688 * Time selector
2690 * This is a liiitle bit messy. we're using two selects, but we're returning
2691 * them as an array named after $name (so we only use $name2 internally for the setting)
2693 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2695 class admin_setting_configtime extends admin_setting {
2696 /** @var string Used for setting second select (minutes) */
2697 public $name2;
2700 * Constructor
2701 * @param string $hoursname setting for hours
2702 * @param string $minutesname setting for hours
2703 * @param string $visiblename localised
2704 * @param string $description long localised info
2705 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2707 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2708 $this->name2 = $minutesname;
2709 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2713 * Get the selected time
2715 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2717 public function get_setting() {
2718 $result1 = $this->config_read($this->name);
2719 $result2 = $this->config_read($this->name2);
2720 if (is_null($result1) or is_null($result2)) {
2721 return NULL;
2724 return array('h' => $result1, 'm' => $result2);
2728 * Store the time (hours and minutes)
2730 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2731 * @return bool true if success, false if not
2733 public function write_setting($data) {
2734 if (!is_array($data)) {
2735 return '';
2738 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2739 return ($result ? '' : get_string('errorsetting', 'admin'));
2743 * Returns XHTML time select fields
2745 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2746 * @param string $query
2747 * @return string XHTML time select fields and wrapping div(s)
2749 public function output_html($data, $query='') {
2750 $default = $this->get_defaultsetting();
2752 if (is_array($default)) {
2753 $defaultinfo = $default['h'].':'.$default['m'];
2754 } else {
2755 $defaultinfo = NULL;
2758 $return = '<div class="form-time defaultsnext">'.
2759 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2760 for ($i = 0; $i < 24; $i++) {
2761 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2763 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2764 for ($i = 0; $i < 60; $i += 5) {
2765 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2767 $return .= '</select></div>';
2768 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2775 * Used to validate a textarea used for ip addresses
2777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2779 class admin_setting_configiplist extends admin_setting_configtextarea {
2782 * Validate the contents of the textarea as IP addresses
2784 * Used to validate a new line separated list of IP addresses collected from
2785 * a textarea control
2787 * @param string $data A list of IP Addresses separated by new lines
2788 * @return mixed bool true for success or string:error on failure
2790 public function validate($data) {
2791 if(!empty($data)) {
2792 $ips = explode("\n", $data);
2793 } else {
2794 return true;
2796 $result = true;
2797 foreach($ips as $ip) {
2798 $ip = trim($ip);
2799 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2800 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2801 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2802 $result = true;
2803 } else {
2804 $result = false;
2805 break;
2808 if($result) {
2809 return true;
2810 } else {
2811 return get_string('validateerror', 'admin');
2818 * An admin setting for selecting one or more users who have a capability
2819 * in the system context
2821 * An admin setting for selecting one or more users, who have a particular capability
2822 * in the system context. Warning, make sure the list will never be too long. There is
2823 * no paging or searching of this list.
2825 * To correctly get a list of users from this config setting, you need to call the
2826 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
2828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2830 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
2831 /** @var string The capabilities name */
2832 protected $capability;
2833 /** @var int include admin users too */
2834 protected $includeadmins;
2837 * Constructor.
2839 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2840 * @param string $visiblename localised name
2841 * @param string $description localised long description
2842 * @param array $defaultsetting array of usernames
2843 * @param string $capability string capability name.
2844 * @param bool $includeadmins include administrators
2846 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
2847 $this->capability = $capability;
2848 $this->includeadmins = $includeadmins;
2849 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
2853 * Load all of the uses who have the capability into choice array
2855 * @return bool Always returns true
2857 function load_choices() {
2858 if (is_array($this->choices)) {
2859 return true;
2861 $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
2862 $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
2863 $this->choices = array(
2864 '$@NONE@$' => get_string('nobody'),
2865 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
2867 if ($this->includeadmins) {
2868 $admins = get_admins();
2869 foreach ($admins as $user) {
2870 $this->choices[$user->id] = fullname($user);
2873 if (is_array($users)) {
2874 foreach ($users as $user) {
2875 $this->choices[$user->id] = fullname($user);
2878 return true;
2882 * Returns the default setting for class
2884 * @return mixed Array, or string. Empty string if no default
2886 public function get_defaultsetting() {
2887 $this->load_choices();
2888 $defaultsetting = parent::get_defaultsetting();
2889 if (empty($defaultsetting)) {
2890 return array('$@NONE@$');
2891 } else if (array_key_exists($defaultsetting, $this->choices)) {
2892 return $defaultsetting;
2893 } else {
2894 return '';
2899 * Returns the current setting
2901 * @return mixed array or string
2903 public function get_setting() {
2904 $result = parent::get_setting();
2905 if ($result === null) {
2906 // this is necessary for settings upgrade
2907 return null;
2909 if (empty($result)) {
2910 $result = array('$@NONE@$');
2912 return $result;
2916 * Save the chosen setting provided as $data
2918 * @param array $data
2919 * @return mixed string or array
2921 public function write_setting($data) {
2922 // If all is selected, remove any explicit options.
2923 if (in_array('$@ALL@$', $data)) {
2924 $data = array('$@ALL@$');
2926 // None never needs to be written to the DB.
2927 if (in_array('$@NONE@$', $data)) {
2928 unset($data[array_search('$@NONE@$', $data)]);
2930 return parent::write_setting($data);
2936 * Special checkbox for calendar - resets SESSION vars.
2938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2940 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
2942 * Calls the parent::__construct with default values
2944 * name => calendar_adminseesall
2945 * visiblename => get_string('adminseesall', 'admin')
2946 * description => get_string('helpadminseesall', 'admin')
2947 * defaultsetting => 0
2949 public function __construct() {
2950 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
2951 get_string('helpadminseesall', 'admin'), '0');
2955 * Stores the setting passed in $data
2957 * @param mixed gets converted to string for comparison
2958 * @return string empty string or error message
2960 public function write_setting($data) {
2961 global $SESSION;
2962 return parent::write_setting($data);
2967 * Special select for settings that are altered in setup.php and can not be altered on the fly
2969 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2971 class admin_setting_special_selectsetup extends admin_setting_configselect {
2973 * Reads the setting directly from the database
2975 * @return mixed
2977 public function get_setting() {
2978 // read directly from db!
2979 return get_config(NULL, $this->name);
2983 * Save the setting passed in $data
2985 * @param string $data The setting to save
2986 * @return string empty or error message
2988 public function write_setting($data) {
2989 global $CFG;
2990 // do not change active CFG setting!
2991 $current = $CFG->{$this->name};
2992 $result = parent::write_setting($data);
2993 $CFG->{$this->name} = $current;
2994 return $result;
3000 * Special select for frontpage - stores data in course table
3002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3004 class admin_setting_sitesetselect extends admin_setting_configselect {
3006 * Returns the site name for the selected site
3008 * @see get_site()
3009 * @return string The site name of the selected site
3011 public function get_setting() {
3012 $site = get_site();
3013 return $site->{$this->name};
3017 * Updates the database and save the setting
3019 * @param string data
3020 * @return string empty or error message
3022 public function write_setting($data) {
3023 global $DB, $SITE;
3024 if (!in_array($data, array_keys($this->choices))) {
3025 return get_string('errorsetting', 'admin');
3027 $record = new stdClass();
3028 $record->id = SITEID;
3029 $temp = $this->name;
3030 $record->$temp = $data;
3031 $record->timemodified = time();
3032 // update $SITE
3033 $SITE->{$this->name} = $data;
3034 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3040 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3041 * block to hidden.
3043 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3045 class admin_setting_bloglevel extends admin_setting_configselect {
3047 * Updates the database and save the setting
3049 * @param string data
3050 * @return string empty or error message
3052 public function write_setting($data) {
3053 global $DB, $CFG;
3054 if ($data['bloglevel'] == 0) {
3055 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3056 foreach ($blogblocks as $block) {
3057 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3059 } else {
3060 // reenable all blocks only when switching from disabled blogs
3061 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3062 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3063 foreach ($blogblocks as $block) {
3064 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3068 return parent::write_setting($data);
3074 * Special select - lists on the frontpage - hacky
3076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3078 class admin_setting_courselist_frontpage extends admin_setting {
3079 /** @var array Array of choices value=>label */
3080 public $choices;
3083 * Construct override, requires one param
3085 * @param bool $loggedin Is the user logged in
3087 public function __construct($loggedin) {
3088 global $CFG;
3089 require_once($CFG->dirroot.'/course/lib.php');
3090 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3091 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3092 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3093 $defaults = array(FRONTPAGECOURSELIST);
3094 parent::__construct($name, $visiblename, $description, $defaults);
3098 * Loads the choices available
3100 * @return bool always returns true
3102 public function load_choices() {
3103 global $DB;
3104 if (is_array($this->choices)) {
3105 return true;
3107 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3108 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3109 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3110 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3111 'none' => get_string('none'));
3112 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3113 unset($this->choices[FRONTPAGECOURSELIST]);
3115 return true;
3119 * Returns the selected settings
3121 * @param mixed array or setting or null
3123 public function get_setting() {
3124 $result = $this->config_read($this->name);
3125 if (is_null($result)) {
3126 return NULL;
3128 if ($result === '') {
3129 return array();
3131 return explode(',', $result);
3135 * Save the selected options
3137 * @param array $data
3138 * @return mixed empty string (data is not an array) or bool true=success false=failure
3140 public function write_setting($data) {
3141 if (!is_array($data)) {
3142 return '';
3144 $this->load_choices();
3145 $save = array();
3146 foreach($data as $datum) {
3147 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3148 continue;
3150 $save[$datum] = $datum; // no duplicates
3152 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3156 * Return XHTML select field and wrapping div
3158 * @todo Add vartype handling to make sure $data is an array
3159 * @param array $data Array of elements to select by default
3160 * @return string XHTML select field and wrapping div
3162 public function output_html($data, $query='') {
3163 $this->load_choices();
3164 $currentsetting = array();
3165 foreach ($data as $key) {
3166 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3167 $currentsetting[] = $key; // already selected first
3171 $return = '<div class="form-group">';
3172 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3173 if (!array_key_exists($i, $currentsetting)) {
3174 $currentsetting[$i] = 'none'; //none
3176 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3177 foreach ($this->choices as $key => $value) {
3178 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3180 $return .= '</select>';
3181 if ($i !== count($this->choices) - 2) {
3182 $return .= '<br />';
3185 $return .= '</div>';
3187 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3193 * Special checkbox for frontpage - stores data in course table
3195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3197 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3199 * Returns the current sites name
3201 * @return string
3203 public function get_setting() {
3204 $site = get_site();
3205 return $site->{$this->name};
3209 * Save the selected setting
3211 * @param string $data The selected site
3212 * @return string empty string or error message
3214 public function write_setting($data) {
3215 global $DB, $SITE;
3216 $record = new stdClass();
3217 $record->id = SITEID;
3218 $record->{$this->name} = ($data == '1' ? 1 : 0);
3219 $record->timemodified = time();
3220 // update $SITE
3221 $SITE->{$this->name} = $data;
3222 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3227 * Special text for frontpage - stores data in course table.
3228 * Empty string means not set here. Manual setting is required.
3230 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3232 class admin_setting_sitesettext extends admin_setting_configtext {
3234 * Return the current setting
3236 * @return mixed string or null
3238 public function get_setting() {
3239 $site = get_site();
3240 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3244 * Validate the selected data
3246 * @param string $data The selected value to validate
3247 * @return mixed true or message string
3249 public function validate($data) {
3250 $cleaned = clean_param($data, PARAM_MULTILANG);
3251 if ($cleaned === '') {
3252 return get_string('required');
3254 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3255 return true;
3256 } else {
3257 return get_string('validateerror', 'admin');
3262 * Save the selected setting
3264 * @param string $data The selected value
3265 * @return string empty or error message
3267 public function write_setting($data) {
3268 global $DB, $SITE;
3269 $data = trim($data);
3270 $validated = $this->validate($data);
3271 if ($validated !== true) {
3272 return $validated;
3275 $record = new stdClass();
3276 $record->id = SITEID;
3277 $record->{$this->name} = $data;
3278 $record->timemodified = time();
3279 // update $SITE
3280 $SITE->{$this->name} = $data;
3281 return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
3287 * Special text editor for site description.
3289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3291 class admin_setting_special_frontpagedesc extends admin_setting {
3293 * Calls parent::__construct with specific arguments
3295 public function __construct() {
3296 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3297 editors_head_setup();
3301 * Return the current setting
3302 * @return string The current setting
3304 public function get_setting() {
3305 $site = get_site();
3306 return $site->{$this->name};
3310 * Save the new setting
3312 * @param string $data The new value to save
3313 * @return string empty or error message
3315 public function write_setting($data) {
3316 global $DB, $SITE;
3317 $record = new stdClass();
3318 $record->id = SITEID;
3319 $record->{$this->name} = $data;
3320 $record->timemodified = time();
3321 $SITE->{$this->name} = $data;
3322 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3326 * Returns XHTML for the field plus wrapping div
3328 * @param string $data The current value
3329 * @param string $query
3330 * @return string The XHTML output
3332 public function output_html($data, $query='') {
3333 global $CFG;
3335 $CFG->adminusehtmleditor = can_use_html_editor();
3336 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3338 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3344 * Administration interface for emoticon_manager settings.
3346 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3348 class admin_setting_emoticons extends admin_setting {
3351 * Calls parent::__construct with specific args
3353 public function __construct() {
3354 global $CFG;
3356 $manager = get_emoticon_manager();
3357 $defaults = $this->prepare_form_data($manager->default_emoticons());
3358 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3362 * Return the current setting(s)
3364 * @return array Current settings array
3366 public function get_setting() {
3367 global $CFG;
3369 $manager = get_emoticon_manager();
3371 $config = $this->config_read($this->name);
3372 if (is_null($config)) {
3373 return null;
3376 $config = $manager->decode_stored_config($config);
3377 if (is_null($config)) {
3378 return null;
3381 return $this->prepare_form_data($config);
3385 * Save selected settings
3387 * @param array $data Array of settings to save
3388 * @return bool
3390 public function write_setting($data) {
3392 $manager = get_emoticon_manager();
3393 $emoticons = $this->process_form_data($data);
3395 if ($emoticons === false) {
3396 return false;
3399 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3400 return ''; // success
3401 } else {
3402 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3407 * Return XHTML field(s) for options
3409 * @param array $data Array of options to set in HTML
3410 * @return string XHTML string for the fields and wrapping div(s)
3412 public function output_html($data, $query='') {
3413 global $OUTPUT;
3415 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3416 $out .= html_writer::start_tag('thead');
3417 $out .= html_writer::start_tag('tr');
3418 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3419 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3420 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3421 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3422 $out .= html_writer::tag('th', '');
3423 $out .= html_writer::end_tag('tr');
3424 $out .= html_writer::end_tag('thead');
3425 $out .= html_writer::start_tag('tbody');
3426 $i = 0;
3427 foreach($data as $field => $value) {
3428 switch ($i) {
3429 case 0:
3430 $out .= html_writer::start_tag('tr');
3431 $current_text = $value;
3432 $current_filename = '';
3433 $current_imagecomponent = '';
3434 $current_altidentifier = '';
3435 $current_altcomponent = '';
3436 case 1:
3437 $current_filename = $value;
3438 case 2:
3439 $current_imagecomponent = $value;
3440 case 3:
3441 $current_altidentifier = $value;
3442 case 4:
3443 $current_altcomponent = $value;
3446 $out .= html_writer::tag('td',
3447 html_writer::empty_tag('input',
3448 array(
3449 'type' => 'text',
3450 'class' => 'form-text',
3451 'name' => $this->get_full_name().'['.$field.']',
3452 'value' => $value,
3454 ), array('class' => 'c'.$i)
3457 if ($i == 4) {
3458 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3459 $alt = get_string($current_altidentifier, $current_altcomponent);
3460 } else {
3461 $alt = $current_text;
3463 if ($current_filename) {
3464 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3465 } else {
3466 $out .= html_writer::tag('td', '');
3468 $out .= html_writer::end_tag('tr');
3469 $i = 0;
3470 } else {
3471 $i++;
3475 $out .= html_writer::end_tag('tbody');
3476 $out .= html_writer::end_tag('table');
3477 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3478 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3480 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3484 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3486 * @see self::process_form_data()
3487 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3488 * @return array of form fields and their values
3490 protected function prepare_form_data(array $emoticons) {
3492 $form = array();
3493 $i = 0;
3494 foreach ($emoticons as $emoticon) {
3495 $form['text'.$i] = $emoticon->text;
3496 $form['imagename'.$i] = $emoticon->imagename;
3497 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3498 $form['altidentifier'.$i] = $emoticon->altidentifier;
3499 $form['altcomponent'.$i] = $emoticon->altcomponent;
3500 $i++;
3502 // add one more blank field set for new object
3503 $form['text'.$i] = '';
3504 $form['imagename'.$i] = '';
3505 $form['imagecomponent'.$i] = '';
3506 $form['altidentifier'.$i] = '';
3507 $form['altcomponent'.$i] = '';
3509 return $form;
3513 * Converts the data from admin settings form into an array of emoticon objects
3515 * @see self::prepare_form_data()
3516 * @param array $data array of admin form fields and values
3517 * @return false|array of emoticon objects
3519 protected function process_form_data(array $form) {
3521 $count = count($form); // number of form field values
3523 if ($count % 5) {
3524 // we must get five fields per emoticon object
3525 return false;
3528 $emoticons = array();
3529 for ($i = 0; $i < $count / 5; $i++) {
3530 $emoticon = new stdClass();
3531 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3532 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3533 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3534 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3535 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3537 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3538 // prevent from breaking http://url.addresses by accident
3539 $emoticon->text = '';
3542 if (strlen($emoticon->text) < 2) {
3543 // do not allow single character emoticons
3544 $emoticon->text = '';
3547 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3548 // emoticon text must contain some non-alphanumeric character to prevent
3549 // breaking HTML tags
3550 $emoticon->text = '';
3553 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3554 $emoticons[] = $emoticon;
3557 return $emoticons;
3563 * Special setting for limiting of the list of available languages.
3565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3567 class admin_setting_langlist extends admin_setting_configtext {
3569 * Calls parent::__construct with specific arguments
3571 public function __construct() {
3572 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3576 * Save the new setting
3578 * @param string $data The new setting
3579 * @return bool
3581 public function write_setting($data) {
3582 $return = parent::write_setting($data);
3583 get_string_manager()->reset_caches();
3584 return $return;
3590 * Selection of one of the recognised countries using the list
3591 * returned by {@link get_list_of_countries()}.
3593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3595 class admin_settings_country_select extends admin_setting_configselect {
3596 protected $includeall;
3597 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3598 $this->includeall = $includeall;
3599 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3603 * Lazy-load the available choices for the select box
3605 public function load_choices() {
3606 global $CFG;
3607 if (is_array($this->choices)) {
3608 return true;
3610 $this->choices = array_merge(
3611 array('0' => get_string('choosedots')),
3612 get_string_manager()->get_list_of_countries($this->includeall));
3613 return true;
3619 * admin_setting_configselect for the default number of sections in a course,
3620 * simply so we can lazy-load the choices.
3622 * @copyright 2011 The Open University
3623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3625 class admin_settings_num_course_sections extends admin_setting_configselect {
3626 public function __construct($name, $visiblename, $description, $defaultsetting) {
3627 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3630 /** Lazy-load the available choices for the select box */
3631 public function load_choices() {
3632 $max = get_config('moodlecourse', 'maxsections');
3633 if (empty($max)) {
3634 $max = 52;
3636 for ($i = 0; $i <= $max; $i++) {
3637 $this->choices[$i] = "$i";
3639 return true;
3645 * Course category selection
3647 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3649 class admin_settings_coursecat_select extends admin_setting_configselect {
3651 * Calls parent::__construct with specific arguments
3653 public function __construct($name, $visiblename, $description, $defaultsetting) {
3654 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3658 * Load the available choices for the select box
3660 * @return bool
3662 public function load_choices() {
3663 global $CFG;
3664 require_once($CFG->dirroot.'/course/lib.php');
3665 if (is_array($this->choices)) {
3666 return true;
3668 $this->choices = make_categories_options();
3669 return true;
3675 * Special control for selecting days to backup
3677 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3679 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3681 * Calls parent::__construct with specific arguments
3683 public function __construct() {
3684 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3685 $this->plugin = 'backup';
3689 * Load the available choices for the select box
3691 * @return bool Always returns true
3693 public function load_choices() {
3694 if (is_array($this->choices)) {
3695 return true;
3697 $this->choices = array();
3698 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3699 foreach ($days as $day) {
3700 $this->choices[$day] = get_string($day, 'calendar');
3702 return true;
3708 * Special debug setting
3710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3712 class admin_setting_special_debug extends admin_setting_configselect {
3714 * Calls parent::__construct with specific arguments
3716 public function __construct() {
3717 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3721 * Load the available choices for the select box
3723 * @return bool
3725 public function load_choices() {
3726 if (is_array($this->choices)) {
3727 return true;
3729 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3730 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3731 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3732 DEBUG_ALL => get_string('debugall', 'admin'),
3733 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3734 return true;
3740 * Special admin control
3742 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3744 class admin_setting_special_calendar_weekend extends admin_setting {
3746 * Calls parent::__construct with specific arguments
3748 public function __construct() {
3749 $name = 'calendar_weekend';
3750 $visiblename = get_string('calendar_weekend', 'admin');
3751 $description = get_string('helpweekenddays', 'admin');
3752 $default = array ('0', '6'); // Saturdays and Sundays
3753 parent::__construct($name, $visiblename, $description, $default);
3757 * Gets the current settings as an array
3759 * @return mixed Null if none, else array of settings
3761 public function get_setting() {
3762 $result = $this->config_read($this->name);
3763 if (is_null($result)) {
3764 return NULL;
3766 if ($result === '') {
3767 return array();
3769 $settings = array();
3770 for ($i=0; $i<7; $i++) {
3771 if ($result & (1 << $i)) {
3772 $settings[] = $i;
3775 return $settings;
3779 * Save the new settings
3781 * @param array $data Array of new settings
3782 * @return bool
3784 public function write_setting($data) {
3785 if (!is_array($data)) {
3786 return '';
3788 unset($data['xxxxx']);
3789 $result = 0;
3790 foreach($data as $index) {
3791 $result |= 1 << $index;
3793 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3797 * Return XHTML to display the control
3799 * @param array $data array of selected days
3800 * @param string $query
3801 * @return string XHTML for display (field + wrapping div(s)
3803 public function output_html($data, $query='') {
3804 // The order matters very much because of the implied numeric keys
3805 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3806 $return = '<table><thead><tr>';
3807 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3808 foreach($days as $index => $day) {
3809 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
3811 $return .= '</tr></thead><tbody><tr>';
3812 foreach($days as $index => $day) {
3813 $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>';
3815 $return .= '</tr></tbody></table>';
3817 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3824 * Admin setting that allows a user to pick a behaviour.
3826 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3828 class admin_setting_question_behaviour extends admin_setting_configselect {
3830 * @param string $name name of config variable
3831 * @param string $visiblename display name
3832 * @param string $description description
3833 * @param string $default default.
3835 public function __construct($name, $visiblename, $description, $default) {
3836 parent::__construct($name, $visiblename, $description, $default, NULL);
3840 * Load list of behaviours as choices
3841 * @return bool true => success, false => error.
3843 public function load_choices() {
3844 global $CFG;
3845 require_once($CFG->dirroot . '/question/engine/lib.php');
3846 $this->choices = question_engine::get_archetypal_behaviours();
3847 return true;
3853 * Admin setting that allows a user to pick appropriate roles for something.
3855 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3857 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
3858 /** @var array Array of capabilities which identify roles */
3859 private $types;
3862 * @param string $name Name of config variable
3863 * @param string $visiblename Display name
3864 * @param string $description Description
3865 * @param array $types Array of archetypes which identify
3866 * roles that will be enabled by default.
3868 public function __construct($name, $visiblename, $description, $types) {
3869 parent::__construct($name, $visiblename, $description, NULL, NULL);
3870 $this->types = $types;
3874 * Load roles as choices
3876 * @return bool true=>success, false=>error
3878 public function load_choices() {
3879 global $CFG, $DB;
3880 if (during_initial_install()) {
3881 return false;
3883 if (is_array($this->choices)) {
3884 return true;
3886 if ($roles = get_all_roles()) {
3887 $this->choices = array();
3888 foreach($roles as $role) {
3889 $this->choices[$role->id] = format_string($role->name);
3891 return true;
3892 } else {
3893 return false;
3898 * Return the default setting for this control
3900 * @return array Array of default settings
3902 public function get_defaultsetting() {
3903 global $CFG;
3905 if (during_initial_install()) {
3906 return null;
3908 $result = array();
3909 foreach($this->types as $archetype) {
3910 if ($caproles = get_archetype_roles($archetype)) {
3911 foreach ($caproles as $caprole) {
3912 $result[$caprole->id] = 1;
3916 return $result;
3922 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
3924 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3926 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
3928 * Constructor
3929 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3930 * @param string $visiblename localised
3931 * @param string $description long localised info
3932 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
3933 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
3934 * @param int $size default field size
3936 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
3937 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
3941 * Loads the current setting and returns array
3943 * @return array Returns array value=>xx, __construct=>xx
3945 public function get_setting() {
3946 $value = parent::get_setting();
3947 $adv = $this->config_read($this->name.'_adv');
3948 if (is_null($value) or is_null($adv)) {
3949 return NULL;
3951 return array('value' => $value, 'adv' => $adv);
3955 * Saves the new settings passed in $data
3957 * @todo Add vartype handling to ensure $data is an array
3958 * @param array $data
3959 * @return mixed string or Array
3961 public function write_setting($data) {
3962 $error = parent::write_setting($data['value']);
3963 if (!$error) {
3964 $value = empty($data['adv']) ? 0 : 1;
3965 $this->config_write($this->name.'_adv', $value);
3967 return $error;
3971 * Return XHTML for the control
3973 * @param array $data Default data array
3974 * @param string $query
3975 * @return string XHTML to display control
3977 public function output_html($data, $query='') {
3978 $default = $this->get_defaultsetting();
3979 $defaultinfo = array();
3980 if (isset($default['value'])) {
3981 if ($default['value'] === '') {
3982 $defaultinfo[] = "''";
3983 } else {
3984 $defaultinfo[] = $default['value'];
3987 if (!empty($default['adv'])) {
3988 $defaultinfo[] = get_string('advanced');
3990 $defaultinfo = implode(', ', $defaultinfo);
3992 $adv = !empty($data['adv']);
3993 $return = '<div class="form-text defaultsnext">' .
3994 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
3995 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
3996 ' <input type="checkbox" class="form-checkbox" id="' .
3997 $this->get_id() . '_adv" name="' . $this->get_full_name() .
3998 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
3999 ' <label for="' . $this->get_id() . '_adv">' .
4000 get_string('advanced') . '</label></div>';
4002 return format_admin_setting($this, $this->visiblename, $return,
4003 $this->description, true, '', $defaultinfo, $query);
4009 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4011 * @copyright 2009 Petr Skoda (http://skodak.org)
4012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4014 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4017 * Constructor
4018 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4019 * @param string $visiblename localised
4020 * @param string $description long localised info
4021 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4022 * @param string $yes value used when checked
4023 * @param string $no value used when not checked
4025 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4026 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4030 * Loads the current setting and returns array
4032 * @return array Returns array value=>xx, adv=>xx
4034 public function get_setting() {
4035 $value = parent::get_setting();
4036 $adv = $this->config_read($this->name.'_adv');
4037 if (is_null($value) or is_null($adv)) {
4038 return NULL;
4040 return array('value' => $value, 'adv' => $adv);
4044 * Sets the value for the setting
4046 * Sets the value for the setting to either the yes or no values
4047 * of the object by comparing $data to yes
4049 * @param mixed $data Gets converted to str for comparison against yes value
4050 * @return string empty string or error
4052 public function write_setting($data) {
4053 $error = parent::write_setting($data['value']);
4054 if (!$error) {
4055 $value = empty($data['adv']) ? 0 : 1;
4056 $this->config_write($this->name.'_adv', $value);
4058 return $error;
4062 * Returns an XHTML checkbox field and with extra advanced cehckbox
4064 * @param string $data If $data matches yes then checkbox is checked
4065 * @param string $query
4066 * @return string XHTML field
4068 public function output_html($data, $query='') {
4069 $defaults = $this->get_defaultsetting();
4070 $defaultinfo = array();
4071 if (!is_null($defaults)) {
4072 if ((string)$defaults['value'] === $this->yes) {
4073 $defaultinfo[] = get_string('checkboxyes', 'admin');
4074 } else {
4075 $defaultinfo[] = get_string('checkboxno', 'admin');
4077 if (!empty($defaults['adv'])) {
4078 $defaultinfo[] = get_string('advanced');
4081 $defaultinfo = implode(', ', $defaultinfo);
4083 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4084 $checked = 'checked="checked"';
4085 } else {
4086 $checked = '';
4088 if (!empty($data['adv'])) {
4089 $advanced = 'checked="checked"';
4090 } else {
4091 $advanced = '';
4094 $fullname = $this->get_full_name();
4095 $novalue = s($this->no);
4096 $yesvalue = s($this->yes);
4097 $id = $this->get_id();
4098 $stradvanced = get_string('advanced');
4099 $return = <<<EOT
4100 <div class="form-checkbox defaultsnext" >
4101 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4102 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4103 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4104 <label for="{$id}_adv">$stradvanced</label>
4105 </div>
4106 EOT;
4107 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4108 true, '', $defaultinfo, $query);
4114 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4116 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4118 * @copyright 2010 Sam Hemelryk
4119 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4121 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4123 * Constructor
4124 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4125 * @param string $visiblename localised
4126 * @param string $description long localised info
4127 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4128 * @param string $yes value used when checked
4129 * @param string $no value used when not checked
4131 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4132 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4136 * Loads the current setting and returns array
4138 * @return array Returns array value=>xx, adv=>xx
4140 public function get_setting() {
4141 $value = parent::get_setting();
4142 $locked = $this->config_read($this->name.'_locked');
4143 if (is_null($value) or is_null($locked)) {
4144 return NULL;
4146 return array('value' => $value, 'locked' => $locked);
4150 * Sets the value for the setting
4152 * Sets the value for the setting to either the yes or no values
4153 * of the object by comparing $data to yes
4155 * @param mixed $data Gets converted to str for comparison against yes value
4156 * @return string empty string or error
4158 public function write_setting($data) {
4159 $error = parent::write_setting($data['value']);
4160 if (!$error) {
4161 $value = empty($data['locked']) ? 0 : 1;
4162 $this->config_write($this->name.'_locked', $value);
4164 return $error;
4168 * Returns an XHTML checkbox field and with extra locked checkbox
4170 * @param string $data If $data matches yes then checkbox is checked
4171 * @param string $query
4172 * @return string XHTML field
4174 public function output_html($data, $query='') {
4175 $defaults = $this->get_defaultsetting();
4176 $defaultinfo = array();
4177 if (!is_null($defaults)) {
4178 if ((string)$defaults['value'] === $this->yes) {
4179 $defaultinfo[] = get_string('checkboxyes', 'admin');
4180 } else {
4181 $defaultinfo[] = get_string('checkboxno', 'admin');
4183 if (!empty($defaults['locked'])) {
4184 $defaultinfo[] = get_string('locked', 'admin');
4187 $defaultinfo = implode(', ', $defaultinfo);
4189 $fullname = $this->get_full_name();
4190 $novalue = s($this->no);
4191 $yesvalue = s($this->yes);
4192 $id = $this->get_id();
4194 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4195 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4196 $checkboxparams['checked'] = 'checked';
4199 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4200 if (!empty($data['locked'])) { // convert to strings before comparison
4201 $lockcheckboxparams['checked'] = 'checked';
4204 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4205 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4206 $return .= html_writer::empty_tag('input', $checkboxparams);
4207 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4208 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4209 $return .= html_writer::end_tag('div');
4210 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4216 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4218 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4220 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4222 * Calls parent::__construct with specific arguments
4224 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4225 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4229 * Loads the current setting and returns array
4231 * @return array Returns array value=>xx, adv=>xx
4233 public function get_setting() {
4234 $value = parent::get_setting();
4235 $adv = $this->config_read($this->name.'_adv');
4236 if (is_null($value) or is_null($adv)) {
4237 return NULL;
4239 return array('value' => $value, 'adv' => $adv);
4243 * Saves the new settings passed in $data
4245 * @todo Add vartype handling to ensure $data is an array
4246 * @param array $data
4247 * @return mixed string or Array
4249 public function write_setting($data) {
4250 $error = parent::write_setting($data['value']);
4251 if (!$error) {
4252 $value = empty($data['adv']) ? 0 : 1;
4253 $this->config_write($this->name.'_adv', $value);
4255 return $error;
4259 * Return XHTML for the control
4261 * @param array $data Default data array
4262 * @param string $query
4263 * @return string XHTML to display control
4265 public function output_html($data, $query='') {
4266 $default = $this->get_defaultsetting();
4267 $current = $this->get_setting();
4269 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4270 $current['value'], $default['value'], '[value]');
4271 if (!$selecthtml) {
4272 return '';
4275 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4276 $defaultinfo = array();
4277 if (isset($this->choices[$default['value']])) {
4278 $defaultinfo[] = $this->choices[$default['value']];
4280 if (!empty($default['adv'])) {
4281 $defaultinfo[] = get_string('advanced');
4283 $defaultinfo = implode(', ', $defaultinfo);
4284 } else {
4285 $defaultinfo = '';
4288 $adv = !empty($data['adv']);
4289 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4290 ' <input type="checkbox" class="form-checkbox" id="' .
4291 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4292 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4293 ' <label for="' . $this->get_id() . '_adv">' .
4294 get_string('advanced') . '</label></div>';
4296 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4302 * Graded roles in gradebook
4304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4306 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4308 * Calls parent::__construct with specific arguments
4310 public function __construct() {
4311 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4312 get_string('configgradebookroles', 'admin'),
4313 array('student'));
4320 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4322 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4324 * Saves the new settings passed in $data
4326 * @param string $data
4327 * @return mixed string or Array
4329 public function write_setting($data) {
4330 global $CFG, $DB;
4332 $oldvalue = $this->config_read($this->name);
4333 $return = parent::write_setting($data);
4334 $newvalue = $this->config_read($this->name);
4336 if ($oldvalue !== $newvalue) {
4337 // force full regrading
4338 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4341 return $return;
4347 * Which roles to show on course description page
4349 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4351 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4353 * Calls parent::__construct with specific arguments
4355 public function __construct() {
4356 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4357 get_string('coursecontact_desc', 'admin'),
4358 array('editingteacher'));
4365 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4367 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4369 * Calls parent::__construct with specific arguments
4371 function admin_setting_special_gradelimiting() {
4372 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4373 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4377 * Force site regrading
4379 function regrade_all() {
4380 global $CFG;
4381 require_once("$CFG->libdir/gradelib.php");
4382 grade_force_site_regrading();
4386 * Saves the new settings
4388 * @param mixed $data
4389 * @return string empty string or error message
4391 function write_setting($data) {
4392 $previous = $this->get_setting();
4394 if ($previous === null) {
4395 if ($data) {
4396 $this->regrade_all();
4398 } else {
4399 if ($data != $previous) {
4400 $this->regrade_all();
4403 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4410 * Primary grade export plugin - has state tracking.
4412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4414 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4416 * Calls parent::__construct with specific arguments
4418 public function __construct() {
4419 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4420 get_string('configgradeexport', 'admin'), array(), NULL);
4424 * Load the available choices for the multicheckbox
4426 * @return bool always returns true
4428 public function load_choices() {
4429 if (is_array($this->choices)) {
4430 return true;
4432 $this->choices = array();
4434 if ($plugins = get_plugin_list('gradeexport')) {
4435 foreach($plugins as $plugin => $unused) {
4436 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4439 return true;
4445 * Grade category settings
4447 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4449 class admin_setting_gradecat_combo extends admin_setting {
4450 /** @var array Array of choices */
4451 public $choices;
4454 * Sets choices and calls parent::__construct with passed arguments
4455 * @param string $name
4456 * @param string $visiblename
4457 * @param string $description
4458 * @param mixed $defaultsetting string or array depending on implementation
4459 * @param array $choices An array of choices for the control
4461 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4462 $this->choices = $choices;
4463 parent::__construct($name, $visiblename, $description, $defaultsetting);
4467 * Return the current setting(s) array
4469 * @return array Array of value=>xx, forced=>xx, adv=>xx
4471 public function get_setting() {
4472 global $CFG;
4474 $value = $this->config_read($this->name);
4475 $flag = $this->config_read($this->name.'_flag');
4477 if (is_null($value) or is_null($flag)) {
4478 return NULL;
4481 $flag = (int)$flag;
4482 $forced = (boolean)(1 & $flag); // first bit
4483 $adv = (boolean)(2 & $flag); // second bit
4485 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4489 * Save the new settings passed in $data
4491 * @todo Add vartype handling to ensure $data is array
4492 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4493 * @return string empty or error message
4495 public function write_setting($data) {
4496 global $CFG;
4498 $value = $data['value'];
4499 $forced = empty($data['forced']) ? 0 : 1;
4500 $adv = empty($data['adv']) ? 0 : 2;
4501 $flag = ($forced | $adv); //bitwise or
4503 if (!in_array($value, array_keys($this->choices))) {
4504 return 'Error setting ';
4507 $oldvalue = $this->config_read($this->name);
4508 $oldflag = (int)$this->config_read($this->name.'_flag');
4509 $oldforced = (1 & $oldflag); // first bit
4511 $result1 = $this->config_write($this->name, $value);
4512 $result2 = $this->config_write($this->name.'_flag', $flag);
4514 // force regrade if needed
4515 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4516 require_once($CFG->libdir.'/gradelib.php');
4517 grade_category::updated_forced_settings();
4520 if ($result1 and $result2) {
4521 return '';
4522 } else {
4523 return get_string('errorsetting', 'admin');
4528 * Return XHTML to display the field and wrapping div
4530 * @todo Add vartype handling to ensure $data is array
4531 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4532 * @param string $query
4533 * @return string XHTML to display control
4535 public function output_html($data, $query='') {
4536 $value = $data['value'];
4537 $forced = !empty($data['forced']);
4538 $adv = !empty($data['adv']);
4540 $default = $this->get_defaultsetting();
4541 if (!is_null($default)) {
4542 $defaultinfo = array();
4543 if (isset($this->choices[$default['value']])) {
4544 $defaultinfo[] = $this->choices[$default['value']];
4546 if (!empty($default['forced'])) {
4547 $defaultinfo[] = get_string('force');
4549 if (!empty($default['adv'])) {
4550 $defaultinfo[] = get_string('advanced');
4552 $defaultinfo = implode(', ', $defaultinfo);
4554 } else {
4555 $defaultinfo = NULL;
4559 $return = '<div class="form-group">';
4560 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4561 foreach ($this->choices as $key => $val) {
4562 // the string cast is needed because key may be integer - 0 is equal to most strings!
4563 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4565 $return .= '</select>';
4566 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4567 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4568 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4569 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4570 $return .= '</div>';
4572 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4578 * Selection of grade report in user profiles
4580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4582 class admin_setting_grade_profilereport extends admin_setting_configselect {
4584 * Calls parent::__construct with specific arguments
4586 public function __construct() {
4587 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4591 * Loads an array of choices for the configselect control
4593 * @return bool always return true
4595 public function load_choices() {
4596 if (is_array($this->choices)) {
4597 return true;
4599 $this->choices = array();
4601 global $CFG;
4602 require_once($CFG->libdir.'/gradelib.php');
4604 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4605 if (file_exists($plugindir.'/lib.php')) {
4606 require_once($plugindir.'/lib.php');
4607 $functionname = 'grade_report_'.$plugin.'_profilereport';
4608 if (function_exists($functionname)) {
4609 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4613 return true;
4619 * Special class for register auth selection
4621 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4623 class admin_setting_special_registerauth extends admin_setting_configselect {
4625 * Calls parent::__construct with specific arguments
4627 public function __construct() {
4628 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4632 * Returns the default option
4634 * @return string empty or default option
4636 public function get_defaultsetting() {
4637 $this->load_choices();
4638 $defaultsetting = parent::get_defaultsetting();
4639 if (array_key_exists($defaultsetting, $this->choices)) {
4640 return $defaultsetting;
4641 } else {
4642 return '';
4647 * Loads the possible choices for the array
4649 * @return bool always returns true
4651 public function load_choices() {
4652 global $CFG;
4654 if (is_array($this->choices)) {
4655 return true;
4657 $this->choices = array();
4658 $this->choices[''] = get_string('disable');
4660 $authsenabled = get_enabled_auth_plugins(true);
4662 foreach ($authsenabled as $auth) {
4663 $authplugin = get_auth_plugin($auth);
4664 if (!$authplugin->can_signup()) {
4665 continue;
4667 // Get the auth title (from core or own auth lang files)
4668 $authtitle = $authplugin->get_title();
4669 $this->choices[$auth] = $authtitle;
4671 return true;
4677 * General plugins manager
4679 class admin_page_pluginsoverview extends admin_externalpage {
4682 * Sets basic information about the external page
4684 public function __construct() {
4685 global $CFG;
4686 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4687 "$CFG->wwwroot/$CFG->admin/plugins.php");
4692 * Module manage page
4694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4696 class admin_page_managemods extends admin_externalpage {
4698 * Calls parent::__construct with specific arguments
4700 public function __construct() {
4701 global $CFG;
4702 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4706 * Try to find the specified module
4708 * @param string $query The module to search for
4709 * @return array
4711 public function search($query) {
4712 global $CFG, $DB;
4713 if ($result = parent::search($query)) {
4714 return $result;
4717 $found = false;
4718 if ($modules = $DB->get_records('modules')) {
4719 $textlib = textlib_get_instance();
4720 foreach ($modules as $module) {
4721 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4722 continue;
4724 if (strpos($module->name, $query) !== false) {
4725 $found = true;
4726 break;
4728 $strmodulename = get_string('modulename', $module->name);
4729 if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
4730 $found = true;
4731 break;
4735 if ($found) {
4736 $result = new stdClass();
4737 $result->page = $this;
4738 $result->settings = array();
4739 return array($this->name => $result);
4740 } else {
4741 return array();
4748 * Special class for enrol plugins management.
4750 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4753 class admin_setting_manageenrols extends admin_setting {
4755 * Calls parent::__construct with specific arguments
4757 public function __construct() {
4758 $this->nosave = true;
4759 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4763 * Always returns true, does nothing
4765 * @return true
4767 public function get_setting() {
4768 return true;
4772 * Always returns true, does nothing
4774 * @return true
4776 public function get_defaultsetting() {
4777 return true;
4781 * Always returns '', does not write anything
4783 * @return string Always returns ''
4785 public function write_setting($data) {
4786 // do not write any setting
4787 return '';
4791 * Checks if $query is one of the available enrol plugins
4793 * @param string $query The string to search for
4794 * @return bool Returns true if found, false if not
4796 public function is_related($query) {
4797 if (parent::is_related($query)) {
4798 return true;
4801 $textlib = textlib_get_instance();
4802 $query = $textlib->strtolower($query);
4803 $enrols = enrol_get_plugins(false);
4804 foreach ($enrols as $name=>$enrol) {
4805 $localised = get_string('pluginname', 'enrol_'.$name);
4806 if (strpos($textlib->strtolower($name), $query) !== false) {
4807 return true;
4809 if (strpos($textlib->strtolower($localised), $query) !== false) {
4810 return true;
4813 return false;
4817 * Builds the XHTML to display the control
4819 * @param string $data Unused
4820 * @param string $query
4821 * @return string
4823 public function output_html($data, $query='') {
4824 global $CFG, $OUTPUT, $DB;
4826 // display strings
4827 $strup = get_string('up');
4828 $strdown = get_string('down');
4829 $strsettings = get_string('settings');
4830 $strenable = get_string('enable');
4831 $strdisable = get_string('disable');
4832 $struninstall = get_string('uninstallplugin', 'admin');
4833 $strusage = get_string('enrolusage', 'enrol');
4835 $enrols_available = enrol_get_plugins(false);
4836 $active_enrols = enrol_get_plugins(true);
4838 $allenrols = array();
4839 foreach ($active_enrols as $key=>$enrol) {
4840 $allenrols[$key] = true;
4842 foreach ($enrols_available as $key=>$enrol) {
4843 $allenrols[$key] = true;
4845 // now find all borked plugins and at least allow then to uninstall
4846 $borked = array();
4847 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
4848 foreach ($condidates as $candidate) {
4849 if (empty($allenrols[$candidate])) {
4850 $allenrols[$candidate] = true;
4854 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
4855 $return .= $OUTPUT->box_start('generalbox enrolsui');
4857 $table = new html_table();
4858 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
4859 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
4860 $table->width = '90%';
4861 $table->data = array();
4863 // iterate through enrol plugins and add to the display table
4864 $updowncount = 1;
4865 $enrolcount = count($active_enrols);
4866 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
4867 $printed = array();
4868 foreach($allenrols as $enrol => $unused) {
4869 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
4870 $name = get_string('pluginname', 'enrol_'.$enrol);
4871 } else {
4872 $name = $enrol;
4874 //usage
4875 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
4876 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
4877 $usage = "$ci / $cp";
4879 // hide/show link
4880 if (isset($active_enrols[$enrol])) {
4881 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
4882 $hideshow = "<a href=\"$aurl\">";
4883 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
4884 $enabled = true;
4885 $displayname = "<span>$name</span>";
4886 } else if (isset($enrols_available[$enrol])) {
4887 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
4888 $hideshow = "<a href=\"$aurl\">";
4889 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
4890 $enabled = false;
4891 $displayname = "<span class=\"dimmed_text\">$name</span>";
4892 } else {
4893 $hideshow = '';
4894 $enabled = false;
4895 $displayname = '<span class="notifyproblem">'.$name.'</span>';
4898 // up/down link (only if enrol is enabled)
4899 $updown = '';
4900 if ($enabled) {
4901 if ($updowncount > 1) {
4902 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
4903 $updown .= "<a href=\"$aurl\">";
4904 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
4905 } else {
4906 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
4908 if ($updowncount < $enrolcount) {
4909 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
4910 $updown .= "<a href=\"$aurl\">";
4911 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
4912 } else {
4913 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
4915 ++$updowncount;
4918 // settings link
4919 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
4920 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
4921 $settings = "<a href=\"$surl\">$strsettings</a>";
4922 } else {
4923 $settings = '';
4926 // uninstall
4927 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
4928 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
4930 // add a row to the table
4931 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
4933 $printed[$enrol] = true;
4936 $return .= html_writer::table($table);
4937 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
4938 $return .= $OUTPUT->box_end();
4939 return highlight($query, $return);
4945 * Blocks manage page
4947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4949 class admin_page_manageblocks extends admin_externalpage {
4951 * Calls parent::__construct with specific arguments
4953 public function __construct() {
4954 global $CFG;
4955 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
4959 * Search for a specific block
4961 * @param string $query The string to search for
4962 * @return array
4964 public function search($query) {
4965 global $CFG, $DB;
4966 if ($result = parent::search($query)) {
4967 return $result;
4970 $found = false;
4971 if ($blocks = $DB->get_records('block')) {
4972 $textlib = textlib_get_instance();
4973 foreach ($blocks as $block) {
4974 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
4975 continue;
4977 if (strpos($block->name, $query) !== false) {
4978 $found = true;
4979 break;
4981 $strblockname = get_string('pluginname', 'block_'.$block->name);
4982 if (strpos($textlib->strtolower($strblockname), $query) !== false) {
4983 $found = true;
4984 break;
4988 if ($found) {
4989 $result = new stdClass();
4990 $result->page = $this;
4991 $result->settings = array();
4992 return array($this->name => $result);
4993 } else {
4994 return array();
5000 * Message outputs configuration
5002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5004 class admin_page_managemessageoutputs extends admin_externalpage {
5006 * Calls parent::__construct with specific arguments
5008 public function __construct() {
5009 global $CFG;
5010 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5014 * Search for a specific message processor
5016 * @param string $query The string to search for
5017 * @return array
5019 public function search($query) {
5020 global $CFG, $DB;
5021 if ($result = parent::search($query)) {
5022 return $result;
5025 $found = false;
5026 if ($processors = get_message_processors()) {
5027 $textlib = textlib_get_instance();
5028 foreach ($processors as $processor) {
5029 if (!$processor->available) {
5030 continue;
5032 if (strpos($processor->name, $query) !== false) {
5033 $found = true;
5034 break;
5036 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5037 if (strpos($textlib->strtolower($strprocessorname), $query) !== false) {
5038 $found = true;
5039 break;
5043 if ($found) {
5044 $result = new stdClass();
5045 $result->page = $this;
5046 $result->settings = array();
5047 return array($this->name => $result);
5048 } else {
5049 return array();
5055 * Default message outputs configuration
5057 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5059 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5061 * Calls parent::__construct with specific arguments
5063 public function __construct() {
5064 global $CFG;
5065 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5071 * Manage question behaviours page
5073 * @copyright 2011 The Open University
5074 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5076 class admin_page_manageqbehaviours extends admin_externalpage {
5078 * Constructor
5080 public function __construct() {
5081 global $CFG;
5082 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5083 new moodle_url('/admin/qbehaviours.php'));
5087 * Search question behaviours for the specified string
5089 * @param string $query The string to search for in question behaviours
5090 * @return array
5092 public function search($query) {
5093 global $CFG;
5094 if ($result = parent::search($query)) {
5095 return $result;
5098 $found = false;
5099 $textlib = textlib_get_instance();
5100 require_once($CFG->dirroot . '/question/engine/lib.php');
5101 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5102 if (strpos($textlib->strtolower(question_engine::get_behaviour_name($behaviour)),
5103 $query) !== false) {
5104 $found = true;
5105 break;
5108 if ($found) {
5109 $result = new stdClass();
5110 $result->page = $this;
5111 $result->settings = array();
5112 return array($this->name => $result);
5113 } else {
5114 return array();
5121 * Question type manage page
5123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5125 class admin_page_manageqtypes extends admin_externalpage {
5127 * Calls parent::__construct with specific arguments
5129 public function __construct() {
5130 global $CFG;
5131 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
5135 * Search question types for the specified string
5137 * @param string $query The string to search for in question types
5138 * @return array
5140 public function search($query) {
5141 global $CFG;
5142 if ($result = parent::search($query)) {
5143 return $result;
5146 $found = false;
5147 $textlib = textlib_get_instance();
5148 require_once($CFG->dirroot . '/question/engine/bank.php');
5149 foreach (question_bank::get_all_qtypes() as $qtype) {
5150 if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
5151 $found = true;
5152 break;
5155 if ($found) {
5156 $result = new stdClass();
5157 $result->page = $this;
5158 $result->settings = array();
5159 return array($this->name => $result);
5160 } else {
5161 return array();
5167 class admin_page_manageportfolios extends admin_externalpage {
5169 * Calls parent::__construct with specific arguments
5171 public function __construct() {
5172 global $CFG;
5173 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5174 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5178 * Searches page for the specified string.
5179 * @param string $query The string to search for
5180 * @return bool True if it is found on this page
5182 public function search($query) {
5183 global $CFG;
5184 if ($result = parent::search($query)) {
5185 return $result;
5188 $found = false;
5189 $textlib = textlib_get_instance();
5190 $portfolios = get_plugin_list('portfolio');
5191 foreach ($portfolios as $p => $dir) {
5192 if (strpos($p, $query) !== false) {
5193 $found = true;
5194 break;
5197 if (!$found) {
5198 foreach (portfolio_instances(false, false) as $instance) {
5199 $title = $instance->get('name');
5200 if (strpos($textlib->strtolower($title), $query) !== false) {
5201 $found = true;
5202 break;
5207 if ($found) {
5208 $result = new stdClass();
5209 $result->page = $this;
5210 $result->settings = array();
5211 return array($this->name => $result);
5212 } else {
5213 return array();
5219 class admin_page_managerepositories extends admin_externalpage {
5221 * Calls parent::__construct with specific arguments
5223 public function __construct() {
5224 global $CFG;
5225 parent::__construct('managerepositories', get_string('manage',
5226 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5230 * Searches page for the specified string.
5231 * @param string $query The string to search for
5232 * @return bool True if it is found on this page
5234 public function search($query) {
5235 global $CFG;
5236 if ($result = parent::search($query)) {
5237 return $result;
5240 $found = false;
5241 $textlib = textlib_get_instance();
5242 $repositories= get_plugin_list('repository');
5243 foreach ($repositories as $p => $dir) {
5244 if (strpos($p, $query) !== false) {
5245 $found = true;
5246 break;
5249 if (!$found) {
5250 foreach (repository::get_types() as $instance) {
5251 $title = $instance->get_typename();
5252 if (strpos($textlib->strtolower($title), $query) !== false) {
5253 $found = true;
5254 break;
5259 if ($found) {
5260 $result = new stdClass();
5261 $result->page = $this;
5262 $result->settings = array();
5263 return array($this->name => $result);
5264 } else {
5265 return array();
5272 * Special class for authentication administration.
5274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5276 class admin_setting_manageauths extends admin_setting {
5278 * Calls parent::__construct with specific arguments
5280 public function __construct() {
5281 $this->nosave = true;
5282 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5286 * Always returns true
5288 * @return true
5290 public function get_setting() {
5291 return true;
5295 * Always returns true
5297 * @return true
5299 public function get_defaultsetting() {
5300 return true;
5304 * Always returns '' and doesn't write anything
5306 * @return string Always returns ''
5308 public function write_setting($data) {
5309 // do not write any setting
5310 return '';
5314 * Search to find if Query is related to auth plugin
5316 * @param string $query The string to search for
5317 * @return bool true for related false for not
5319 public function is_related($query) {
5320 if (parent::is_related($query)) {
5321 return true;
5324 $textlib = textlib_get_instance();
5325 $authsavailable = get_plugin_list('auth');
5326 foreach ($authsavailable as $auth => $dir) {
5327 if (strpos($auth, $query) !== false) {
5328 return true;
5330 $authplugin = get_auth_plugin($auth);
5331 $authtitle = $authplugin->get_title();
5332 if (strpos($textlib->strtolower($authtitle), $query) !== false) {
5333 return true;
5336 return false;
5340 * Return XHTML to display control
5342 * @param mixed $data Unused
5343 * @param string $query
5344 * @return string highlight
5346 public function output_html($data, $query='') {
5347 global $CFG, $OUTPUT;
5350 // display strings
5351 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5352 'settings', 'edit', 'name', 'enable', 'disable',
5353 'up', 'down', 'none'));
5354 $txt->updown = "$txt->up/$txt->down";
5356 $authsavailable = get_plugin_list('auth');
5357 get_enabled_auth_plugins(true); // fix the list of enabled auths
5358 if (empty($CFG->auth)) {
5359 $authsenabled = array();
5360 } else {
5361 $authsenabled = explode(',', $CFG->auth);
5364 // construct the display array, with enabled auth plugins at the top, in order
5365 $displayauths = array();
5366 $registrationauths = array();
5367 $registrationauths[''] = $txt->disable;
5368 foreach ($authsenabled as $auth) {
5369 $authplugin = get_auth_plugin($auth);
5370 /// Get the auth title (from core or own auth lang files)
5371 $authtitle = $authplugin->get_title();
5372 /// Apply titles
5373 $displayauths[$auth] = $authtitle;
5374 if ($authplugin->can_signup()) {
5375 $registrationauths[$auth] = $authtitle;
5379 foreach ($authsavailable as $auth => $dir) {
5380 if (array_key_exists($auth, $displayauths)) {
5381 continue; //already in the list
5383 $authplugin = get_auth_plugin($auth);
5384 /// Get the auth title (from core or own auth lang files)
5385 $authtitle = $authplugin->get_title();
5386 /// Apply titles
5387 $displayauths[$auth] = $authtitle;
5388 if ($authplugin->can_signup()) {
5389 $registrationauths[$auth] = $authtitle;
5393 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5394 $return .= $OUTPUT->box_start('generalbox authsui');
5396 $table = new html_table();
5397 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5398 $table->align = array('left', 'center', 'center', 'center');
5399 $table->data = array();
5400 $table->attributes['class'] = 'manageauthtable generaltable';
5402 //add always enabled plugins first
5403 $displayname = "<span>".$displayauths['manual']."</span>";
5404 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5405 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5406 $table->data[] = array($displayname, '', '', $settings);
5407 $displayname = "<span>".$displayauths['nologin']."</span>";
5408 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5409 $table->data[] = array($displayname, '', '', $settings);
5412 // iterate through auth plugins and add to the display table
5413 $updowncount = 1;
5414 $authcount = count($authsenabled);
5415 $url = "auth.php?sesskey=" . sesskey();
5416 foreach ($displayauths as $auth => $name) {
5417 if ($auth == 'manual' or $auth == 'nologin') {
5418 continue;
5420 // hide/show link
5421 if (in_array($auth, $authsenabled)) {
5422 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5423 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5424 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5425 $enabled = true;
5426 $displayname = "<span>$name</span>";
5428 else {
5429 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5430 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5431 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5432 $enabled = false;
5433 $displayname = "<span class=\"dimmed_text\">$name</span>";
5436 // up/down link (only if auth is enabled)
5437 $updown = '';
5438 if ($enabled) {
5439 if ($updowncount > 1) {
5440 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5441 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5443 else {
5444 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5446 if ($updowncount < $authcount) {
5447 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5448 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5450 else {
5451 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5453 ++ $updowncount;
5456 // settings link
5457 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5458 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5459 } else {
5460 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5463 // add a row to the table
5464 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5466 $return .= html_writer::table($table);
5467 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5468 $return .= $OUTPUT->box_end();
5469 return highlight($query, $return);
5475 * Special class for authentication administration.
5477 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5479 class admin_setting_manageeditors extends admin_setting {
5481 * Calls parent::__construct with specific arguments
5483 public function __construct() {
5484 $this->nosave = true;
5485 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5489 * Always returns true, does nothing
5491 * @return true
5493 public function get_setting() {
5494 return true;
5498 * Always returns true, does nothing
5500 * @return true
5502 public function get_defaultsetting() {
5503 return true;
5507 * Always returns '', does not write anything
5509 * @return string Always returns ''
5511 public function write_setting($data) {
5512 // do not write any setting
5513 return '';
5517 * Checks if $query is one of the available editors
5519 * @param string $query The string to search for
5520 * @return bool Returns true if found, false if not
5522 public function is_related($query) {
5523 if (parent::is_related($query)) {
5524 return true;
5527 $textlib = textlib_get_instance();
5528 $editors_available = editors_get_available();
5529 foreach ($editors_available as $editor=>$editorstr) {
5530 if (strpos($editor, $query) !== false) {
5531 return true;
5533 if (strpos($textlib->strtolower($editorstr), $query) !== false) {
5534 return true;
5537 return false;
5541 * Builds the XHTML to display the control
5543 * @param string $data Unused
5544 * @param string $query
5545 * @return string
5547 public function output_html($data, $query='') {
5548 global $CFG, $OUTPUT;
5550 // display strings
5551 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5552 'up', 'down', 'none'));
5553 $txt->updown = "$txt->up/$txt->down";
5555 $editors_available = editors_get_available();
5556 $active_editors = explode(',', $CFG->texteditors);
5558 $active_editors = array_reverse($active_editors);
5559 foreach ($active_editors as $key=>$editor) {
5560 if (empty($editors_available[$editor])) {
5561 unset($active_editors[$key]);
5562 } else {
5563 $name = $editors_available[$editor];
5564 unset($editors_available[$editor]);
5565 $editors_available[$editor] = $name;
5568 if (empty($active_editors)) {
5569 //$active_editors = array('textarea');
5571 $editors_available = array_reverse($editors_available, true);
5572 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5573 $return .= $OUTPUT->box_start('generalbox editorsui');
5575 $table = new html_table();
5576 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5577 $table->align = array('left', 'center', 'center', 'center');
5578 $table->width = '90%';
5579 $table->data = array();
5581 // iterate through auth plugins and add to the display table
5582 $updowncount = 1;
5583 $editorcount = count($active_editors);
5584 $url = "editors.php?sesskey=" . sesskey();
5585 foreach ($editors_available as $editor => $name) {
5586 // hide/show link
5587 if (in_array($editor, $active_editors)) {
5588 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5589 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
5590 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5591 $enabled = true;
5592 $displayname = "<span>$name</span>";
5594 else {
5595 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5596 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
5597 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5598 $enabled = false;
5599 $displayname = "<span class=\"dimmed_text\">$name</span>";
5602 // up/down link (only if auth is enabled)
5603 $updown = '';
5604 if ($enabled) {
5605 if ($updowncount > 1) {
5606 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5607 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
5609 else {
5610 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
5612 if ($updowncount < $editorcount) {
5613 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5614 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
5616 else {
5617 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
5619 ++ $updowncount;
5622 // settings link
5623 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5624 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5625 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5626 } else {
5627 $settings = '';
5630 // add a row to the table
5631 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5633 $return .= html_writer::table($table);
5634 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5635 $return .= $OUTPUT->box_end();
5636 return highlight($query, $return);
5642 * Special class for license administration.
5644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5646 class admin_setting_managelicenses extends admin_setting {
5648 * Calls parent::__construct with specific arguments
5650 public function __construct() {
5651 $this->nosave = true;
5652 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5656 * Always returns true, does nothing
5658 * @return true
5660 public function get_setting() {
5661 return true;
5665 * Always returns true, does nothing
5667 * @return true
5669 public function get_defaultsetting() {
5670 return true;
5674 * Always returns '', does not write anything
5676 * @return string Always returns ''
5678 public function write_setting($data) {
5679 // do not write any setting
5680 return '';
5684 * Builds the XHTML to display the control
5686 * @param string $data Unused
5687 * @param string $query
5688 * @return string
5690 public function output_html($data, $query='') {
5691 global $CFG, $OUTPUT;
5692 require_once($CFG->libdir . '/licenselib.php');
5693 $url = "licenses.php?sesskey=" . sesskey();
5695 // display strings
5696 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5697 $licenses = license_manager::get_licenses();
5699 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5701 $return .= $OUTPUT->box_start('generalbox editorsui');
5703 $table = new html_table();
5704 $table->head = array($txt->name, $txt->enable);
5705 $table->align = array('left', 'center');
5706 $table->width = '100%';
5707 $table->data = array();
5709 foreach ($licenses as $value) {
5710 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5712 if ($value->enabled == 1) {
5713 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5714 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
5715 } else {
5716 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5717 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
5720 if ($value->shortname == $CFG->sitedefaultlicense) {
5721 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5722 $hideshow = '';
5725 $enabled = true;
5727 $table->data[] =array($displayname, $hideshow);
5729 $return .= html_writer::table($table);
5730 $return .= $OUTPUT->box_end();
5731 return highlight($query, $return);
5737 * Special class for filter administration.
5739 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5741 class admin_page_managefilters extends admin_externalpage {
5743 * Calls parent::__construct with specific arguments
5745 public function __construct() {
5746 global $CFG;
5747 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
5751 * Searches all installed filters for specified filter
5753 * @param string $query The filter(string) to search for
5754 * @param string $query
5756 public function search($query) {
5757 global $CFG;
5758 if ($result = parent::search($query)) {
5759 return $result;
5762 $found = false;
5763 $filternames = filter_get_all_installed();
5764 $textlib = textlib_get_instance();
5765 foreach ($filternames as $path => $strfiltername) {
5766 if (strpos($textlib->strtolower($strfiltername), $query) !== false) {
5767 $found = true;
5768 break;
5770 list($type, $filter) = explode('/', $path);
5771 if (strpos($filter, $query) !== false) {
5772 $found = true;
5773 break;
5777 if ($found) {
5778 $result = new stdClass;
5779 $result->page = $this;
5780 $result->settings = array();
5781 return array($this->name => $result);
5782 } else {
5783 return array();
5790 * Initialise admin page - this function does require login and permission
5791 * checks specified in page definition.
5793 * This function must be called on each admin page before other code.
5795 * @global moodle_page $PAGE
5797 * @param string $section name of page
5798 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
5799 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
5800 * added to the turn blocks editing on/off form, so this page reloads correctly.
5801 * @param string $actualurl if the actual page being viewed is not the normal one for this
5802 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
5803 * @param array $options Additional options that can be specified for page setup.
5804 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
5806 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
5807 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
5809 $PAGE->set_context(null); // hack - set context to something, by default to system context
5811 $site = get_site();
5812 require_login();
5814 $adminroot = admin_get_root(false, false); // settings not required for external pages
5815 $extpage = $adminroot->locate($section, true);
5817 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
5818 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
5819 die;
5822 // this eliminates our need to authenticate on the actual pages
5823 if (!$extpage->check_access()) {
5824 print_error('accessdenied', 'admin');
5825 die;
5828 if (!empty($options['pagelayout'])) {
5829 // A specific page layout has been requested.
5830 $PAGE->set_pagelayout($options['pagelayout']);
5831 } else if ($section === 'upgradesettings') {
5832 $PAGE->set_pagelayout('maintenance');
5833 } else {
5834 $PAGE->set_pagelayout('admin');
5837 // $PAGE->set_extra_button($extrabutton); TODO
5839 if (!$actualurl) {
5840 $actualurl = $extpage->url;
5843 $PAGE->set_url($actualurl, $extraurlparams);
5844 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
5845 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
5848 if (empty($SITE->fullname) || empty($SITE->shortname)) {
5849 // During initial install.
5850 $strinstallation = get_string('installation', 'install');
5851 $strsettings = get_string('settings');
5852 $PAGE->navbar->add($strsettings);
5853 $PAGE->set_title($strinstallation);
5854 $PAGE->set_heading($strinstallation);
5855 $PAGE->set_cacheable(false);
5856 return;
5859 // Locate the current item on the navigation and make it active when found.
5860 $path = $extpage->path;
5861 $node = $PAGE->settingsnav;
5862 while ($node && count($path) > 0) {
5863 $node = $node->get(array_pop($path));
5865 if ($node) {
5866 $node->make_active();
5869 // Normal case.
5870 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
5871 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
5872 $USER->editing = $adminediting;
5875 $visiblepathtosection = array_reverse($extpage->visiblepath);
5877 if ($PAGE->user_allowed_editing()) {
5878 if ($PAGE->user_is_editing()) {
5879 $caption = get_string('blockseditoff');
5880 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
5881 } else {
5882 $caption = get_string('blocksediton');
5883 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
5885 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
5888 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
5889 $PAGE->set_heading($SITE->fullname);
5891 // prevent caching in nav block
5892 $PAGE->navigation->clear_cache();
5896 * Returns the reference to admin tree root
5898 * @return object admin_root object
5900 function admin_get_root($reload=false, $requirefulltree=true) {
5901 global $CFG, $DB, $OUTPUT;
5903 static $ADMIN = NULL;
5905 if (is_null($ADMIN)) {
5906 // create the admin tree!
5907 $ADMIN = new admin_root($requirefulltree);
5910 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
5911 $ADMIN->purge_children($requirefulltree);
5914 if (!$ADMIN->loaded) {
5915 // we process this file first to create categories first and in correct order
5916 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
5918 // now we process all other files in admin/settings to build the admin tree
5919 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
5920 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
5921 continue;
5923 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
5924 // plugins are loaded last - they may insert pages anywhere
5925 continue;
5927 require($file);
5929 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
5931 $ADMIN->loaded = true;
5934 return $ADMIN;
5937 /// settings utility functions
5940 * This function applies default settings.
5942 * @param object $node, NULL means complete tree, null by default
5943 * @param bool $unconditional if true overrides all values with defaults, null buy default
5945 function admin_apply_default_settings($node=NULL, $unconditional=true) {
5946 global $CFG;
5948 if (is_null($node)) {
5949 $node = admin_get_root(true, true);
5952 if ($node instanceof admin_category) {
5953 $entries = array_keys($node->children);
5954 foreach ($entries as $entry) {
5955 admin_apply_default_settings($node->children[$entry], $unconditional);
5958 } else if ($node instanceof admin_settingpage) {
5959 foreach ($node->settings as $setting) {
5960 if (!$unconditional and !is_null($setting->get_setting())) {
5961 //do not override existing defaults
5962 continue;
5964 $defaultsetting = $setting->get_defaultsetting();
5965 if (is_null($defaultsetting)) {
5966 // no value yet - default maybe applied after admin user creation or in upgradesettings
5967 continue;
5969 $setting->write_setting($defaultsetting);
5975 * Store changed settings, this function updates the errors variable in $ADMIN
5977 * @param object $formdata from form
5978 * @return int number of changed settings
5980 function admin_write_settings($formdata) {
5981 global $CFG, $SITE, $DB;
5983 $olddbsessions = !empty($CFG->dbsessions);
5984 $formdata = (array)$formdata;
5986 $data = array();
5987 foreach ($formdata as $fullname=>$value) {
5988 if (strpos($fullname, 's_') !== 0) {
5989 continue; // not a config value
5991 $data[$fullname] = $value;
5994 $adminroot = admin_get_root();
5995 $settings = admin_find_write_settings($adminroot, $data);
5997 $count = 0;
5998 foreach ($settings as $fullname=>$setting) {
5999 $original = serialize($setting->get_setting()); // comparison must work for arrays too
6000 $error = $setting->write_setting($data[$fullname]);
6001 if ($error !== '') {
6002 $adminroot->errors[$fullname] = new stdClass();
6003 $adminroot->errors[$fullname]->data = $data[$fullname];
6004 $adminroot->errors[$fullname]->id = $setting->get_id();
6005 $adminroot->errors[$fullname]->error = $error;
6007 if ($original !== serialize($setting->get_setting())) {
6008 $count++;
6009 $callbackfunction = $setting->updatedcallback;
6010 if (function_exists($callbackfunction)) {
6011 $callbackfunction($fullname);
6016 if ($olddbsessions != !empty($CFG->dbsessions)) {
6017 require_logout();
6020 // Now update $SITE - just update the fields, in case other people have a
6021 // a reference to it (e.g. $PAGE, $COURSE).
6022 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6023 foreach (get_object_vars($newsite) as $field => $value) {
6024 $SITE->$field = $value;
6027 // now reload all settings - some of them might depend on the changed
6028 admin_get_root(true);
6029 return $count;
6033 * Internal recursive function - finds all settings from submitted form
6035 * @param object $node Instance of admin_category, or admin_settingpage
6036 * @param array $data
6037 * @return array
6039 function admin_find_write_settings($node, $data) {
6040 $return = array();
6042 if (empty($data)) {
6043 return $return;
6046 if ($node instanceof admin_category) {
6047 $entries = array_keys($node->children);
6048 foreach ($entries as $entry) {
6049 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6052 } else if ($node instanceof admin_settingpage) {
6053 foreach ($node->settings as $setting) {
6054 $fullname = $setting->get_full_name();
6055 if (array_key_exists($fullname, $data)) {
6056 $return[$fullname] = $setting;
6062 return $return;
6066 * Internal function - prints the search results
6068 * @param string $query String to search for
6069 * @return string empty or XHTML
6071 function admin_search_settings_html($query) {
6072 global $CFG, $OUTPUT;
6074 $textlib = textlib_get_instance();
6075 if ($textlib->strlen($query) < 2) {
6076 return '';
6078 $query = $textlib->strtolower($query);
6080 $adminroot = admin_get_root();
6081 $findings = $adminroot->search($query);
6082 $return = '';
6083 $savebutton = false;
6085 foreach ($findings as $found) {
6086 $page = $found->page;
6087 $settings = $found->settings;
6088 if ($page->is_hidden()) {
6089 // hidden pages are not displayed in search results
6090 continue;
6092 if ($page instanceof admin_externalpage) {
6093 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6094 } else if ($page instanceof admin_settingpage) {
6095 $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');
6096 } else {
6097 continue;
6099 if (!empty($settings)) {
6100 $return .= '<fieldset class="adminsettings">'."\n";
6101 foreach ($settings as $setting) {
6102 if (empty($setting->nosave)) {
6103 $savebutton = true;
6105 $return .= '<div class="clearer"><!-- --></div>'."\n";
6106 $fullname = $setting->get_full_name();
6107 if (array_key_exists($fullname, $adminroot->errors)) {
6108 $data = $adminroot->errors[$fullname]->data;
6109 } else {
6110 $data = $setting->get_setting();
6111 // do not use defaults if settings not available - upgradesettings handles the defaults!
6113 $return .= $setting->output_html($data, $query);
6115 $return .= '</fieldset>';
6119 if ($savebutton) {
6120 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6123 return $return;
6127 * Internal function - returns arrays of html pages with uninitialised settings
6129 * @param object $node Instance of admin_category or admin_settingpage
6130 * @return array
6132 function admin_output_new_settings_by_page($node) {
6133 global $OUTPUT;
6134 $return = array();
6136 if ($node instanceof admin_category) {
6137 $entries = array_keys($node->children);
6138 foreach ($entries as $entry) {
6139 $return += admin_output_new_settings_by_page($node->children[$entry]);
6142 } else if ($node instanceof admin_settingpage) {
6143 $newsettings = array();
6144 foreach ($node->settings as $setting) {
6145 if (is_null($setting->get_setting())) {
6146 $newsettings[] = $setting;
6149 if (count($newsettings) > 0) {
6150 $adminroot = admin_get_root();
6151 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6152 $page .= '<fieldset class="adminsettings">'."\n";
6153 foreach ($newsettings as $setting) {
6154 $fullname = $setting->get_full_name();
6155 if (array_key_exists($fullname, $adminroot->errors)) {
6156 $data = $adminroot->errors[$fullname]->data;
6157 } else {
6158 $data = $setting->get_setting();
6159 if (is_null($data)) {
6160 $data = $setting->get_defaultsetting();
6163 $page .= '<div class="clearer"><!-- --></div>'."\n";
6164 $page .= $setting->output_html($data);
6166 $page .= '</fieldset>';
6167 $return[$node->name] = $page;
6171 return $return;
6175 * Format admin settings
6177 * @param object $setting
6178 * @param string $title label element
6179 * @param string $form form fragment, html code - not highlighted automatically
6180 * @param string $description
6181 * @param bool $label link label to id, true by default
6182 * @param string $warning warning text
6183 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6184 * @param string $query search query to be highlighted
6185 * @return string XHTML
6187 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6188 global $CFG;
6190 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6191 $fullname = $setting->get_full_name();
6193 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6194 if ($label) {
6195 $labelfor = 'for = "'.$setting->get_id().'"';
6196 } else {
6197 $labelfor = '';
6200 $override = '';
6201 if (empty($setting->plugin)) {
6202 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6203 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6205 } else {
6206 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6207 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6211 if ($warning !== '') {
6212 $warning = '<div class="form-warning">'.$warning.'</div>';
6215 if (is_null($defaultinfo)) {
6216 $defaultinfo = '';
6217 } else {
6218 if ($defaultinfo === '') {
6219 $defaultinfo = get_string('emptysettingvalue', 'admin');
6221 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6222 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6226 $str = '
6227 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6228 <div class="form-label">
6229 <label '.$labelfor.'>'.highlightfast($query, $title).'<span class="form-shortname">'.highlightfast($query, $name).'</span>
6230 '.$override.$warning.'
6231 </label>
6232 </div>
6233 <div class="form-setting">'.$form.$defaultinfo.'</div>
6234 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6235 </div>';
6237 $adminroot = admin_get_root();
6238 if (array_key_exists($fullname, $adminroot->errors)) {
6239 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6242 return $str;
6246 * Based on find_new_settings{@link ()} in upgradesettings.php
6247 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6249 * @param object $node Instance of admin_category, or admin_settingpage
6250 * @return boolean true if any settings haven't been initialised, false if they all have
6252 function any_new_admin_settings($node) {
6254 if ($node instanceof admin_category) {
6255 $entries = array_keys($node->children);
6256 foreach ($entries as $entry) {
6257 if (any_new_admin_settings($node->children[$entry])) {
6258 return true;
6262 } else if ($node instanceof admin_settingpage) {
6263 foreach ($node->settings as $setting) {
6264 if ($setting->get_setting() === NULL) {
6265 return true;
6270 return false;
6274 * Moved from admin/replace.php so that we can use this in cron
6276 * @param string $search string to look for
6277 * @param string $replace string to replace
6278 * @return bool success or fail
6280 function db_replace($search, $replace) {
6281 global $DB, $CFG, $OUTPUT;
6283 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6284 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6285 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6286 'block_instances', '');
6288 // Turn off time limits, sometimes upgrades can be slow.
6289 @set_time_limit(0);
6291 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6292 return false;
6294 foreach ($tables as $table) {
6296 if (in_array($table, $skiptables)) { // Don't process these
6297 continue;
6300 if ($columns = $DB->get_columns($table)) {
6301 $DB->set_debug(true);
6302 foreach ($columns as $column => $data) {
6303 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6304 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6305 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6308 $DB->set_debug(false);
6312 // delete modinfo caches
6313 rebuild_course_cache(0, true);
6315 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6316 $blocks = get_plugin_list('block');
6317 foreach ($blocks as $blockname=>$fullblock) {
6318 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6319 continue;
6322 if (!is_readable($fullblock.'/lib.php')) {
6323 continue;
6326 $function = 'block_'.$blockname.'_global_db_replace';
6327 include_once($fullblock.'/lib.php');
6328 if (!function_exists($function)) {
6329 continue;
6332 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6333 $function($search, $replace);
6334 echo $OUTPUT->notification("...finished", 'notifysuccess');
6337 return true;
6341 * Manage repository settings
6343 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6345 class admin_setting_managerepository extends admin_setting {
6346 /** @var string */
6347 private $baseurl;
6350 * calls parent::__construct with specific arguments
6352 public function __construct() {
6353 global $CFG;
6354 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6355 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6359 * Always returns true, does nothing
6361 * @return true
6363 public function get_setting() {
6364 return true;
6368 * Always returns true does nothing
6370 * @return true
6372 public function get_defaultsetting() {
6373 return true;
6377 * Always returns s_managerepository
6379 * @return string Always return 's_managerepository'
6381 public function get_full_name() {
6382 return 's_managerepository';
6386 * Always returns '' doesn't do anything
6388 public function write_setting($data) {
6389 $url = $this->baseurl . '&amp;new=' . $data;
6390 return '';
6391 // TODO
6392 // Should not use redirect and exit here
6393 // Find a better way to do this.
6394 // redirect($url);
6395 // exit;
6399 * Searches repository plugins for one that matches $query
6401 * @param string $query The string to search for
6402 * @return bool true if found, false if not
6404 public function is_related($query) {
6405 if (parent::is_related($query)) {
6406 return true;
6409 $textlib = textlib_get_instance();
6410 $repositories= get_plugin_list('repository');
6411 foreach ($repositories as $p => $dir) {
6412 if (strpos($p, $query) !== false) {
6413 return true;
6416 foreach (repository::get_types() as $instance) {
6417 $title = $instance->get_typename();
6418 if (strpos($textlib->strtolower($title), $query) !== false) {
6419 return true;
6422 return false;
6426 * Helper function that generates a moodle_url object
6427 * relevant to the repository
6430 function repository_action_url($repository) {
6431 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6435 * Builds XHTML to display the control
6437 * @param string $data Unused
6438 * @param string $query
6439 * @return string XHTML
6441 public function output_html($data, $query='') {
6442 global $CFG, $USER, $OUTPUT;
6444 // Get strings that are used
6445 $strshow = get_string('on', 'repository');
6446 $strhide = get_string('off', 'repository');
6447 $strdelete = get_string('disabled', 'repository');
6449 $actionchoicesforexisting = array(
6450 'show' => $strshow,
6451 'hide' => $strhide,
6452 'delete' => $strdelete
6455 $actionchoicesfornew = array(
6456 'newon' => $strshow,
6457 'newoff' => $strhide,
6458 'delete' => $strdelete
6461 $return = '';
6462 $return .= $OUTPUT->box_start('generalbox');
6464 // Set strings that are used multiple times
6465 $settingsstr = get_string('settings');
6466 $disablestr = get_string('disable');
6468 // Table to list plug-ins
6469 $table = new html_table();
6470 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6471 $table->align = array('left', 'center', 'center', 'center', 'center');
6472 $table->data = array();
6474 // Get list of used plug-ins
6475 $instances = repository::get_types();
6476 if (!empty($instances)) {
6477 // Array to store plugins being used
6478 $alreadyplugins = array();
6479 $totalinstances = count($instances);
6480 $updowncount = 1;
6481 foreach ($instances as $i) {
6482 $settings = '';
6483 $typename = $i->get_typename();
6484 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6485 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6486 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6488 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6489 // Calculate number of instances in order to display them for the Moodle administrator
6490 if (!empty($instanceoptionnames)) {
6491 $params = array();
6492 $params['context'] = array(get_system_context());
6493 $params['onlyvisible'] = false;
6494 $params['type'] = $typename;
6495 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6496 // site instances
6497 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6498 $params['context'] = array();
6499 $instances = repository::static_function($typename, 'get_instances', $params);
6500 $courseinstances = array();
6501 $userinstances = array();
6503 foreach ($instances as $instance) {
6504 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6505 $courseinstances[] = $instance;
6506 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6507 $userinstances[] = $instance;
6510 // course instances
6511 $instancenumber = count($courseinstances);
6512 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6514 // user private instances
6515 $instancenumber = count($userinstances);
6516 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6517 } else {
6518 $admininstancenumbertext = "";
6519 $courseinstancenumbertext = "";
6520 $userinstancenumbertext = "";
6523 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6525 $settings .= $OUTPUT->container_start('mdl-left');
6526 $settings .= '<br/>';
6527 $settings .= $admininstancenumbertext;
6528 $settings .= '<br/>';
6529 $settings .= $courseinstancenumbertext;
6530 $settings .= '<br/>';
6531 $settings .= $userinstancenumbertext;
6532 $settings .= $OUTPUT->container_end();
6534 // Get the current visibility
6535 if ($i->get_visible()) {
6536 $currentaction = 'show';
6537 } else {
6538 $currentaction = 'hide';
6541 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6543 // Display up/down link
6544 $updown = '';
6545 $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
6547 if ($updowncount > 1) {
6548 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6549 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
6551 else {
6552 $updown .= $spacer;
6554 if ($updowncount < $totalinstances) {
6555 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6556 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
6558 else {
6559 $updown .= $spacer;
6562 $updowncount++;
6564 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6566 if (!in_array($typename, $alreadyplugins)) {
6567 $alreadyplugins[] = $typename;
6572 // Get all the plugins that exist on disk
6573 $plugins = get_plugin_list('repository');
6574 if (!empty($plugins)) {
6575 foreach ($plugins as $plugin => $dir) {
6576 // Check that it has not already been listed
6577 if (!in_array($plugin, $alreadyplugins)) {
6578 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6579 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6584 $return .= html_writer::table($table);
6585 $return .= $OUTPUT->box_end();
6586 return highlight($query, $return);
6591 * Special checkbox for enable mobile web service
6592 * If enable then we store the service id of the mobile service into config table
6593 * If disable then we unstore the service id from the config table
6595 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6597 private $xmlrpcuse; //boolean: true => capability 'webservice/xmlrpc:use' is set for authenticated user role
6600 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use', otherwise false
6601 * @return boolean
6603 private function is_xmlrpc_cap_allowed() {
6604 global $DB, $CFG;
6606 //if the $this->xmlrpcuse variable is not set, it needs to be set
6607 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6608 $params = array();
6609 $params['permission'] = CAP_ALLOW;
6610 $params['roleid'] = $CFG->defaultuserroleid;
6611 $params['capability'] = 'webservice/xmlrpc:use';
6612 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6615 return $this->xmlrpcuse;
6619 * Set the 'webservice/xmlrpc:use' to the Authenticated user role (allow or not)
6620 * @param type $status true to allow, false to not set
6622 private function set_xmlrpc_cap($status) {
6623 global $CFG;
6624 if ($status and !$this->is_xmlrpc_cap_allowed()) {
6625 //need to allow the cap
6626 $permission = CAP_ALLOW;
6627 $assign = true;
6628 } else if (!$status and $this->is_xmlrpc_cap_allowed()){
6629 //need to disallow the cap
6630 $permission = CAP_INHERIT;
6631 $assign = true;
6633 if (!empty($assign)) {
6634 $systemcontext = get_system_context();
6635 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6640 * Builds XHTML to display the control.
6641 * The main purpose of this overloading is to display a warning when https
6642 * is not supported by the server
6643 * @param string $data Unused
6644 * @param string $query
6645 * @return string XHTML
6647 public function output_html($data, $query='') {
6648 global $CFG, $OUTPUT;
6649 $html = parent::output_html($data, $query);
6651 if ((string)$data === $this->yes) {
6652 require_once($CFG->dirroot . "/lib/filelib.php");
6653 $curl = new curl();
6654 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
6655 $curl->head($httpswwwroot . "/login/index.php");
6656 $info = $curl->get_info();
6657 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
6658 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
6662 return $html;
6666 * Retrieves the current setting using the objects name
6668 * @return string
6670 public function get_setting() {
6671 global $CFG;
6673 // For install cli script, $CFG->defaultuserroleid is not set so return 0
6674 // Or if web services aren't enabled this can't be,
6675 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
6676 return 0;
6679 require_once($CFG->dirroot . '/webservice/lib.php');
6680 $webservicemanager = new webservice();
6681 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6682 if ($mobileservice->enabled and $this->is_xmlrpc_cap_allowed()) {
6683 return $this->config_read($this->name); //same as returning 1
6684 } else {
6685 return 0;
6690 * Save the selected setting
6692 * @param string $data The selected site
6693 * @return string empty string or error message
6695 public function write_setting($data) {
6696 global $DB, $CFG;
6698 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
6699 if (empty($CFG->defaultuserroleid)) {
6700 return '';
6703 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
6705 require_once($CFG->dirroot . '/webservice/lib.php');
6706 $webservicemanager = new webservice();
6708 if ((string)$data === $this->yes) {
6709 //code run when enable mobile web service
6710 //enable web service systeme if necessary
6711 set_config('enablewebservices', true);
6713 //enable mobile service
6714 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6715 $mobileservice->enabled = 1;
6716 $webservicemanager->update_external_service($mobileservice);
6718 //enable xml-rpc server
6719 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6721 if (!in_array('xmlrpc', $activeprotocols)) {
6722 $activeprotocols[] = 'xmlrpc';
6723 set_config('webserviceprotocols', implode(',', $activeprotocols));
6726 //allow xml-rpc:use capability for authenticated user
6727 $this->set_xmlrpc_cap(true);
6729 } else {
6730 //disable web service system if no other services are enabled
6731 $otherenabledservices = $DB->get_records_select('external_services',
6732 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
6733 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
6734 if (empty($otherenabledservices)) {
6735 set_config('enablewebservices', false);
6737 //also disable xml-rpc server
6738 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
6739 $protocolkey = array_search('xmlrpc', $activeprotocols);
6740 if ($protocolkey !== false) {
6741 unset($activeprotocols[$protocolkey]);
6742 set_config('webserviceprotocols', implode(',', $activeprotocols));
6745 //disallow xml-rpc:use capability for authenticated user
6746 $this->set_xmlrpc_cap(false);
6749 //disable the mobile service
6750 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
6751 $mobileservice->enabled = 0;
6752 $webservicemanager->update_external_service($mobileservice);
6755 return (parent::write_setting($data));
6760 * Special class for management of external services
6762 * @author Petr Skoda (skodak)
6764 class admin_setting_manageexternalservices extends admin_setting {
6766 * Calls parent::__construct with specific arguments
6768 public function __construct() {
6769 $this->nosave = true;
6770 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
6774 * Always returns true, does nothing
6776 * @return true
6778 public function get_setting() {
6779 return true;
6783 * Always returns true, does nothing
6785 * @return true
6787 public function get_defaultsetting() {
6788 return true;
6792 * Always returns '', does not write anything
6794 * @return string Always returns ''
6796 public function write_setting($data) {
6797 // do not write any setting
6798 return '';
6802 * Checks if $query is one of the available external services
6804 * @param string $query The string to search for
6805 * @return bool Returns true if found, false if not
6807 public function is_related($query) {
6808 global $DB;
6810 if (parent::is_related($query)) {
6811 return true;
6814 $textlib = textlib_get_instance();
6815 $services = $DB->get_records('external_services', array(), 'id, name');
6816 foreach ($services as $service) {
6817 if (strpos($textlib->strtolower($service->name), $query) !== false) {
6818 return true;
6821 return false;
6825 * Builds the XHTML to display the control
6827 * @param string $data Unused
6828 * @param string $query
6829 * @return string
6831 public function output_html($data, $query='') {
6832 global $CFG, $OUTPUT, $DB;
6834 // display strings
6835 $stradministration = get_string('administration');
6836 $stredit = get_string('edit');
6837 $strservice = get_string('externalservice', 'webservice');
6838 $strdelete = get_string('delete');
6839 $strplugin = get_string('plugin', 'admin');
6840 $stradd = get_string('add');
6841 $strfunctions = get_string('functions', 'webservice');
6842 $strusers = get_string('users');
6843 $strserviceusers = get_string('serviceusers', 'webservice');
6845 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
6846 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
6847 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
6849 // built in services
6850 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
6851 $return = "";
6852 if (!empty($services)) {
6853 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
6857 $table = new html_table();
6858 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
6859 $table->align = array('left', 'left', 'center', 'center', 'center');
6860 $table->size = array('30%', '20%', '20%', '20%', '10%');
6861 $table->width = '100%';
6862 $table->data = array();
6864 // iterate through auth plugins and add to the display table
6865 foreach ($services as $service) {
6866 $name = $service->name;
6868 // hide/show link
6869 if ($service->enabled) {
6870 $displayname = "<span>$name</span>";
6871 } else {
6872 $displayname = "<span class=\"dimmed_text\">$name</span>";
6875 $plugin = $service->component;
6877 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6879 if ($service->restrictedusers) {
6880 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6881 } else {
6882 $users = get_string('allusers', 'webservice');
6885 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6887 // add a row to the table
6888 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
6890 $return .= html_writer::table($table);
6893 // Custom services
6894 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
6895 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
6897 $table = new html_table();
6898 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
6899 $table->align = array('left', 'center', 'center', 'center', 'center');
6900 $table->size = array('30%', '20%', '20%', '20%', '10%');
6901 $table->width = '100%';
6902 $table->data = array();
6904 // iterate through auth plugins and add to the display table
6905 foreach ($services as $service) {
6906 $name = $service->name;
6908 // hide/show link
6909 if ($service->enabled) {
6910 $displayname = "<span>$name</span>";
6911 } else {
6912 $displayname = "<span class=\"dimmed_text\">$name</span>";
6915 // delete link
6916 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
6918 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
6920 if ($service->restrictedusers) {
6921 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
6922 } else {
6923 $users = get_string('allusers', 'webservice');
6926 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
6928 // add a row to the table
6929 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
6931 // add new custom service option
6932 $return .= html_writer::table($table);
6934 $return .= '<br />';
6935 // add a token to the table
6936 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
6938 return highlight($query, $return);
6944 * Special class for plagiarism administration.
6946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6948 class admin_setting_manageplagiarism extends admin_setting {
6950 * Calls parent::__construct with specific arguments
6952 public function __construct() {
6953 $this->nosave = true;
6954 parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
6958 * Always returns true
6960 * @return true
6962 public function get_setting() {
6963 return true;
6967 * Always returns true
6969 * @return true
6971 public function get_defaultsetting() {
6972 return true;
6976 * Always returns '' and doesn't write anything
6978 * @return string Always returns ''
6980 public function write_setting($data) {
6981 // do not write any setting
6982 return '';
6986 * Return XHTML to display control
6988 * @param mixed $data Unused
6989 * @param string $query
6990 * @return string highlight
6992 public function output_html($data, $query='') {
6993 global $CFG, $OUTPUT;
6995 // display strings
6996 $txt = get_strings(array('settings', 'name'));
6998 $plagiarismplugins = get_plugin_list('plagiarism');
6999 if (empty($plagiarismplugins)) {
7000 return get_string('nopluginsinstalled', 'plagiarism');
7003 $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
7004 $return .= $OUTPUT->box_start('generalbox authsui');
7006 $table = new html_table();
7007 $table->head = array($txt->name, $txt->settings);
7008 $table->align = array('left', 'center');
7009 $table->data = array();
7010 $table->attributes['class'] = 'manageplagiarismtable generaltable';
7012 // iterate through auth plugins and add to the display table
7013 $authcount = count($plagiarismplugins);
7014 foreach ($plagiarismplugins as $plugin => $dir) {
7015 if (file_exists($dir.'/settings.php')) {
7016 $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
7017 // settings link
7018 $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
7019 // add a row to the table
7020 $table->data[] =array($displayname, $settings);
7023 $return .= html_writer::table($table);
7024 $return .= get_string('configplagiarismplugins', 'plagiarism');
7025 $return .= $OUTPUT->box_end();
7026 return highlight($query, $return);
7032 * Special class for overview of external services
7034 * @author Jerome Mouneyrac
7036 class admin_setting_webservicesoverview extends admin_setting {
7039 * Calls parent::__construct with specific arguments
7041 public function __construct() {
7042 $this->nosave = true;
7043 parent::__construct('webservicesoverviewui',
7044 get_string('webservicesoverview', 'webservice'), '', '');
7048 * Always returns true, does nothing
7050 * @return true
7052 public function get_setting() {
7053 return true;
7057 * Always returns true, does nothing
7059 * @return true
7061 public function get_defaultsetting() {
7062 return true;
7066 * Always returns '', does not write anything
7068 * @return string Always returns ''
7070 public function write_setting($data) {
7071 // do not write any setting
7072 return '';
7076 * Builds the XHTML to display the control
7078 * @param string $data Unused
7079 * @param string $query
7080 * @return string
7082 public function output_html($data, $query='') {
7083 global $CFG, $OUTPUT;
7085 $return = "";
7086 $brtag = html_writer::empty_tag('br');
7088 // Enable mobile web service
7089 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7090 get_string('enablemobilewebservice', 'admin'),
7091 get_string('configenablemobilewebservice',
7092 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7093 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7094 $wsmobileparam = new stdClass();
7095 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7096 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7097 get_string('externalservices', 'webservice'));
7098 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7099 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7100 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7101 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7102 . $brtag . $brtag;
7104 /// One system controlling Moodle with Token
7105 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7106 $table = new html_table();
7107 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7108 get_string('description'));
7109 $table->size = array('30%', '10%', '60%');
7110 $table->align = array('left', 'left', 'left');
7111 $table->width = '90%';
7112 $table->data = array();
7114 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7115 . $brtag . $brtag;
7117 /// 1. Enable Web Services
7118 $row = array();
7119 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7120 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7121 array('href' => $url));
7122 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7123 if ($CFG->enablewebservices) {
7124 $status = get_string('yes');
7126 $row[1] = $status;
7127 $row[2] = get_string('enablewsdescription', 'webservice');
7128 $table->data[] = $row;
7130 /// 2. Enable protocols
7131 $row = array();
7132 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7133 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7134 array('href' => $url));
7135 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7136 //retrieve activated protocol
7137 $active_protocols = empty($CFG->webserviceprotocols) ?
7138 array() : explode(',', $CFG->webserviceprotocols);
7139 if (!empty($active_protocols)) {
7140 $status = "";
7141 foreach ($active_protocols as $protocol) {
7142 $status .= $protocol . $brtag;
7145 $row[1] = $status;
7146 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7147 $table->data[] = $row;
7149 /// 3. Create user account
7150 $row = array();
7151 $url = new moodle_url("/user/editadvanced.php?id=-1");
7152 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7153 array('href' => $url));
7154 $row[1] = "";
7155 $row[2] = get_string('createuserdescription', 'webservice');
7156 $table->data[] = $row;
7158 /// 4. Add capability to users
7159 $row = array();
7160 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7161 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7162 array('href' => $url));
7163 $row[1] = "";
7164 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7165 $table->data[] = $row;
7167 /// 5. Select a web service
7168 $row = array();
7169 $url = new moodle_url("/admin/settings.php?section=externalservices");
7170 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7171 array('href' => $url));
7172 $row[1] = "";
7173 $row[2] = get_string('createservicedescription', 'webservice');
7174 $table->data[] = $row;
7176 /// 6. Add functions
7177 $row = array();
7178 $url = new moodle_url("/admin/settings.php?section=externalservices");
7179 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7180 array('href' => $url));
7181 $row[1] = "";
7182 $row[2] = get_string('addfunctionsdescription', 'webservice');
7183 $table->data[] = $row;
7185 /// 7. Add the specific user
7186 $row = array();
7187 $url = new moodle_url("/admin/settings.php?section=externalservices");
7188 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7189 array('href' => $url));
7190 $row[1] = "";
7191 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7192 $table->data[] = $row;
7194 /// 8. Create token for the specific user
7195 $row = array();
7196 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7197 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7198 array('href' => $url));
7199 $row[1] = "";
7200 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7201 $table->data[] = $row;
7203 /// 9. Enable the documentation
7204 $row = array();
7205 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7206 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7207 array('href' => $url));
7208 $status = '<span class="warning">' . get_string('no') . '</span>';
7209 if ($CFG->enablewsdocumentation) {
7210 $status = get_string('yes');
7212 $row[1] = $status;
7213 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7214 $table->data[] = $row;
7216 /// 10. Test the service
7217 $row = array();
7218 $url = new moodle_url("/admin/webservice/testclient.php");
7219 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7220 array('href' => $url));
7221 $row[1] = "";
7222 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7223 $table->data[] = $row;
7225 $return .= html_writer::table($table);
7227 /// Users as clients with token
7228 $return .= $brtag . $brtag . $brtag;
7229 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7230 $table = new html_table();
7231 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7232 get_string('description'));
7233 $table->size = array('30%', '10%', '60%');
7234 $table->align = array('left', 'left', 'left');
7235 $table->width = '90%';
7236 $table->data = array();
7238 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7239 $brtag . $brtag;
7241 /// 1. Enable Web Services
7242 $row = array();
7243 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7244 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7245 array('href' => $url));
7246 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7247 if ($CFG->enablewebservices) {
7248 $status = get_string('yes');
7250 $row[1] = $status;
7251 $row[2] = get_string('enablewsdescription', 'webservice');
7252 $table->data[] = $row;
7254 /// 2. Enable protocols
7255 $row = array();
7256 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7257 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7258 array('href' => $url));
7259 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7260 //retrieve activated protocol
7261 $active_protocols = empty($CFG->webserviceprotocols) ?
7262 array() : explode(',', $CFG->webserviceprotocols);
7263 if (!empty($active_protocols)) {
7264 $status = "";
7265 foreach ($active_protocols as $protocol) {
7266 $status .= $protocol . $brtag;
7269 $row[1] = $status;
7270 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7271 $table->data[] = $row;
7274 /// 3. Select a web service
7275 $row = array();
7276 $url = new moodle_url("/admin/settings.php?section=externalservices");
7277 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7278 array('href' => $url));
7279 $row[1] = "";
7280 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7281 $table->data[] = $row;
7283 /// 4. Add functions
7284 $row = array();
7285 $url = new moodle_url("/admin/settings.php?section=externalservices");
7286 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7287 array('href' => $url));
7288 $row[1] = "";
7289 $row[2] = get_string('addfunctionsdescription', 'webservice');
7290 $table->data[] = $row;
7292 /// 5. Add capability to users
7293 $row = array();
7294 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7295 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7296 array('href' => $url));
7297 $row[1] = "";
7298 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7299 $table->data[] = $row;
7301 /// 6. Test the service
7302 $row = array();
7303 $url = new moodle_url("/admin/webservice/testclient.php");
7304 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7305 array('href' => $url));
7306 $row[1] = "";
7307 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7308 $table->data[] = $row;
7310 $return .= html_writer::table($table);
7312 return highlight($query, $return);
7319 * Special class for web service protocol administration.
7321 * @author Petr Skoda (skodak)
7323 class admin_setting_managewebserviceprotocols extends admin_setting {
7326 * Calls parent::__construct with specific arguments
7328 public function __construct() {
7329 $this->nosave = true;
7330 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7334 * Always returns true, does nothing
7336 * @return true
7338 public function get_setting() {
7339 return true;
7343 * Always returns true, does nothing
7345 * @return true
7347 public function get_defaultsetting() {
7348 return true;
7352 * Always returns '', does not write anything
7354 * @return string Always returns ''
7356 public function write_setting($data) {
7357 // do not write any setting
7358 return '';
7362 * Checks if $query is one of the available webservices
7364 * @param string $query The string to search for
7365 * @return bool Returns true if found, false if not
7367 public function is_related($query) {
7368 if (parent::is_related($query)) {
7369 return true;
7372 $textlib = textlib_get_instance();
7373 $protocols = get_plugin_list('webservice');
7374 foreach ($protocols as $protocol=>$location) {
7375 if (strpos($protocol, $query) !== false) {
7376 return true;
7378 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7379 if (strpos($textlib->strtolower($protocolstr), $query) !== false) {
7380 return true;
7383 return false;
7387 * Builds the XHTML to display the control
7389 * @param string $data Unused
7390 * @param string $query
7391 * @return string
7393 public function output_html($data, $query='') {
7394 global $CFG, $OUTPUT;
7396 // display strings
7397 $stradministration = get_string('administration');
7398 $strsettings = get_string('settings');
7399 $stredit = get_string('edit');
7400 $strprotocol = get_string('protocol', 'webservice');
7401 $strenable = get_string('enable');
7402 $strdisable = get_string('disable');
7403 $strversion = get_string('version');
7404 $struninstall = get_string('uninstallplugin', 'admin');
7406 $protocols_available = get_plugin_list('webservice');
7407 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7408 ksort($protocols_available);
7410 foreach ($active_protocols as $key=>$protocol) {
7411 if (empty($protocols_available[$protocol])) {
7412 unset($active_protocols[$key]);
7416 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7417 $return .= $OUTPUT->box_start('generalbox webservicesui');
7419 $table = new html_table();
7420 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7421 $table->align = array('left', 'center', 'center', 'center', 'center');
7422 $table->width = '100%';
7423 $table->data = array();
7425 // iterate through auth plugins and add to the display table
7426 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7427 foreach ($protocols_available as $protocol => $location) {
7428 $name = get_string('pluginname', 'webservice_'.$protocol);
7430 $plugin = new stdClass();
7431 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7432 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7434 $version = isset($plugin->version) ? $plugin->version : '';
7436 // hide/show link
7437 if (in_array($protocol, $active_protocols)) {
7438 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7439 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
7440 $displayname = "<span>$name</span>";
7441 } else {
7442 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7443 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
7444 $displayname = "<span class=\"dimmed_text\">$name</span>";
7447 // delete link
7448 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7450 // settings link
7451 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7452 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7453 } else {
7454 $settings = '';
7457 // add a row to the table
7458 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7460 $return .= html_writer::table($table);
7461 $return .= get_string('configwebserviceplugins', 'webservice');
7462 $return .= $OUTPUT->box_end();
7464 return highlight($query, $return);
7470 * Special class for web service token administration.
7472 * @author Jerome Mouneyrac
7474 class admin_setting_managewebservicetokens extends admin_setting {
7477 * Calls parent::__construct with specific arguments
7479 public function __construct() {
7480 $this->nosave = true;
7481 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7485 * Always returns true, does nothing
7487 * @return true
7489 public function get_setting() {
7490 return true;
7494 * Always returns true, does nothing
7496 * @return true
7498 public function get_defaultsetting() {
7499 return true;
7503 * Always returns '', does not write anything
7505 * @return string Always returns ''
7507 public function write_setting($data) {
7508 // do not write any setting
7509 return '';
7513 * Builds the XHTML to display the control
7515 * @param string $data Unused
7516 * @param string $query
7517 * @return string
7519 public function output_html($data, $query='') {
7520 global $CFG, $OUTPUT, $DB, $USER;
7522 // display strings
7523 $stroperation = get_string('operation', 'webservice');
7524 $strtoken = get_string('token', 'webservice');
7525 $strservice = get_string('service', 'webservice');
7526 $struser = get_string('user');
7527 $strcontext = get_string('context', 'webservice');
7528 $strvaliduntil = get_string('validuntil', 'webservice');
7529 $striprestriction = get_string('iprestriction', 'webservice');
7531 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7533 $table = new html_table();
7534 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7535 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7536 $table->width = '100%';
7537 $table->data = array();
7539 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7541 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7543 //here retrieve token list (including linked users firstname/lastname and linked services name)
7544 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
7545 FROM {external_tokens} t, {user} u, {external_services} s
7546 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7547 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7548 if (!empty($tokens)) {
7549 foreach ($tokens as $token) {
7550 //TODO: retrieve context
7552 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7553 $delete .= get_string('delete')."</a>";
7555 $validuntil = '';
7556 if (!empty($token->validuntil)) {
7557 $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
7560 $iprestriction = '';
7561 if (!empty($token->iprestriction)) {
7562 $iprestriction = $token->iprestriction;
7565 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7566 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7567 $useratag .= $token->firstname." ".$token->lastname;
7568 $useratag .= html_writer::end_tag('a');
7570 //check user missing capabilities
7571 require_once($CFG->dirroot . '/webservice/lib.php');
7572 $webservicemanager = new webservice();
7573 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7574 array(array('id' => $token->userid)), $token->serviceid);
7576 if (!is_siteadmin($token->userid) and
7577 key_exists($token->userid, $usermissingcaps)) {
7578 $missingcapabilities = implode(',',
7579 $usermissingcaps[$token->userid]);
7580 if (!empty($missingcapabilities)) {
7581 $useratag .= html_writer::tag('div',
7582 get_string('usermissingcaps', 'webservice',
7583 $missingcapabilities)
7584 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7585 array('class' => 'missingcaps'));
7589 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7592 $return .= html_writer::table($table);
7593 } else {
7594 $return .= get_string('notoken', 'webservice');
7597 $return .= $OUTPUT->box_end();
7598 // add a token to the table
7599 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7600 $return .= get_string('add')."</a>";
7602 return highlight($query, $return);
7608 * Colour picker
7610 * @copyright 2010 Sam Hemelryk
7611 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7613 class admin_setting_configcolourpicker extends admin_setting {
7616 * Information for previewing the colour
7618 * @var array|null
7620 protected $previewconfig = null;
7624 * @param string $name
7625 * @param string $visiblename
7626 * @param string $description
7627 * @param string $defaultsetting
7628 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7630 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7631 $this->previewconfig = $previewconfig;
7632 parent::__construct($name, $visiblename, $description, $defaultsetting);
7636 * Return the setting
7638 * @return mixed returns config if successful else null
7640 public function get_setting() {
7641 return $this->config_read($this->name);
7645 * Saves the setting
7647 * @param string $data
7648 * @return bool
7650 public function write_setting($data) {
7651 $data = $this->validate($data);
7652 if ($data === false) {
7653 return get_string('validateerror', 'admin');
7655 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7659 * Validates the colour that was entered by the user
7661 * @param string $data
7662 * @return string|false
7664 protected function validate($data) {
7665 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7666 if (strpos($data, '#')!==0) {
7667 $data = '#'.$data;
7669 return $data;
7670 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7671 return $data;
7672 } else if (empty($data)) {
7673 return $this->defaultsetting;
7674 } else {
7675 return false;
7680 * Generates the HTML for the setting
7682 * @global moodle_page $PAGE
7683 * @global core_renderer $OUTPUT
7684 * @param string $data
7685 * @param string $query
7687 public function output_html($data, $query = '') {
7688 global $PAGE, $OUTPUT;
7689 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7690 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7691 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7692 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
7693 if (!empty($this->previewconfig)) {
7694 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7696 $content .= html_writer::end_tag('div');
7697 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7702 * Administration interface for user specified regular expressions for device detection.
7704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7706 class admin_setting_devicedetectregex extends admin_setting {
7709 * Calls parent::__construct with specific args
7711 * @param string $name
7712 * @param string $visiblename
7713 * @param string $description
7714 * @param mixed $defaultsetting
7716 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7717 global $CFG;
7718 parent::__construct($name, $visiblename, $description, $defaultsetting);
7722 * Return the current setting(s)
7724 * @return array Current settings array
7726 public function get_setting() {
7727 global $CFG;
7729 $config = $this->config_read($this->name);
7730 if (is_null($config)) {
7731 return null;
7734 return $this->prepare_form_data($config);
7738 * Save selected settings
7740 * @param array $data Array of settings to save
7741 * @return bool
7743 public function write_setting($data) {
7744 if (empty($data)) {
7745 $data = array();
7748 if ($this->config_write($this->name, $this->process_form_data($data))) {
7749 return ''; // success
7750 } else {
7751 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
7756 * Return XHTML field(s) for regexes
7758 * @param array $data Array of options to set in HTML
7759 * @return string XHTML string for the fields and wrapping div(s)
7761 public function output_html($data, $query='') {
7762 global $OUTPUT;
7764 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
7765 $out .= html_writer::start_tag('thead');
7766 $out .= html_writer::start_tag('tr');
7767 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
7768 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
7769 $out .= html_writer::end_tag('tr');
7770 $out .= html_writer::end_tag('thead');
7771 $out .= html_writer::start_tag('tbody');
7773 if (empty($data)) {
7774 $looplimit = 1;
7775 } else {
7776 $looplimit = (count($data)/2)+1;
7779 for ($i=0; $i<$looplimit; $i++) {
7780 $out .= html_writer::start_tag('tr');
7782 $expressionname = 'expression'.$i;
7784 if (!empty($data[$expressionname])){
7785 $expression = $data[$expressionname];
7786 } else {
7787 $expression = '';
7790 $out .= html_writer::tag('td',
7791 html_writer::empty_tag('input',
7792 array(
7793 'type' => 'text',
7794 'class' => 'form-text',
7795 'name' => $this->get_full_name().'[expression'.$i.']',
7796 'value' => $expression,
7798 ), array('class' => 'c'.$i)
7801 $valuename = 'value'.$i;
7803 if (!empty($data[$valuename])){
7804 $value = $data[$valuename];
7805 } else {
7806 $value= '';
7809 $out .= html_writer::tag('td',
7810 html_writer::empty_tag('input',
7811 array(
7812 'type' => 'text',
7813 'class' => 'form-text',
7814 'name' => $this->get_full_name().'[value'.$i.']',
7815 'value' => $value,
7817 ), array('class' => 'c'.$i)
7820 $out .= html_writer::end_tag('tr');
7823 $out .= html_writer::end_tag('tbody');
7824 $out .= html_writer::end_tag('table');
7826 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
7830 * Converts the string of regexes
7832 * @see self::process_form_data()
7833 * @param $regexes string of regexes
7834 * @return array of form fields and their values
7836 protected function prepare_form_data($regexes) {
7838 $regexes = json_decode($regexes);
7840 $form = array();
7842 $i = 0;
7844 foreach ($regexes as $value => $regex) {
7845 $expressionname = 'expression'.$i;
7846 $valuename = 'value'.$i;
7848 $form[$expressionname] = $regex;
7849 $form[$valuename] = $value;
7850 $i++;
7853 return $form;
7857 * Converts the data from admin settings form into a string of regexes
7859 * @see self::prepare_form_data()
7860 * @param array $data array of admin form fields and values
7861 * @return false|string of regexes
7863 protected function process_form_data(array $form) {
7865 $count = count($form); // number of form field values
7867 if ($count % 2) {
7868 // we must get five fields per expression
7869 return false;
7872 $regexes = array();
7873 for ($i = 0; $i < $count / 2; $i++) {
7874 $expressionname = "expression".$i;
7875 $valuename = "value".$i;
7877 $expression = trim($form['expression'.$i]);
7878 $value = trim($form['value'.$i]);
7880 if (empty($expression)){
7881 continue;
7884 $regexes[$value] = $expression;
7887 $regexes = json_encode($regexes);
7889 return $regexes;
7894 * Multiselect for current modules
7896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7898 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
7900 * Calls parent::__construct - note array $choices is not required
7902 * @param string $name setting name
7903 * @param string $visiblename localised setting name
7904 * @param string $description setting description
7905 * @param array $defaultsetting a plain array of default module ids
7907 public function __construct($name, $visiblename, $description, $defaultsetting = array()) {
7908 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
7912 * Loads an array of current module choices
7914 * @return bool always return true
7916 public function load_choices() {
7917 if (is_array($this->choices)) {
7918 return true;
7920 $this->choices = array();
7922 global $CFG, $DB;
7923 $records = $DB->get_records('modules', array('visible'=>1), 'name');
7924 foreach ($records as $record) {
7925 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
7926 $this->choices[$record->id] = $record->name;
7929 return true;