Merge branch 'MDL-39518-24' of git://github.com/damyon/moodle into MOODLE_24_STABLE
[moodle.git] / lib / adminlib.php
blob1d42162a9ae02a8e778e7206f45e9a3522d5f854
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 // This may take a long time.
127 @set_time_limit(0);
129 // recursively uninstall all module/editor subplugins first
130 if ($type === 'mod' || $type === 'editor') {
131 $base = get_component_directory($type . '_' . $name);
132 if (file_exists("$base/db/subplugins.php")) {
133 $subplugins = array();
134 include("$base/db/subplugins.php");
135 foreach ($subplugins as $subplugintype=>$dir) {
136 $instances = get_plugin_list($subplugintype);
137 foreach ($instances as $subpluginname => $notusedpluginpath) {
138 uninstall_plugin($subplugintype, $subpluginname);
145 $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
147 if ($type === 'mod') {
148 $pluginname = $name; // eg. 'forum'
149 if (get_string_manager()->string_exists('modulename', $component)) {
150 $strpluginname = get_string('modulename', $component);
151 } else {
152 $strpluginname = $component;
155 } else {
156 $pluginname = $component;
157 if (get_string_manager()->string_exists('pluginname', $component)) {
158 $strpluginname = get_string('pluginname', $component);
159 } else {
160 $strpluginname = $component;
164 echo $OUTPUT->heading($pluginname);
166 $plugindirectory = get_plugin_directory($type, $name);
167 $uninstalllib = $plugindirectory . '/db/uninstall.php';
168 if (file_exists($uninstalllib)) {
169 require_once($uninstalllib);
170 $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
171 if (function_exists($uninstallfunction)) {
172 if (!$uninstallfunction()) {
173 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
178 if ($type === 'mod') {
179 // perform cleanup tasks specific for activity modules
181 if (!$module = $DB->get_record('modules', array('name' => $name))) {
182 print_error('moduledoesnotexist', 'error');
185 // delete all the relevant instances from all course sections
186 if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
187 foreach ($coursemods as $coursemod) {
188 if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
189 echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
194 // clear course.modinfo for courses that used this module
195 $sql = "UPDATE {course}
196 SET modinfo=''
197 WHERE id IN (SELECT DISTINCT course
198 FROM {course_modules}
199 WHERE module=?)";
200 $DB->execute($sql, array($module->id));
202 // delete all the course module records
203 $DB->delete_records('course_modules', array('module' => $module->id));
205 // delete module contexts
206 if ($coursemods) {
207 foreach ($coursemods as $coursemod) {
208 if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
209 echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
214 // delete the module entry itself
215 $DB->delete_records('modules', array('name' => $module->name));
217 // cleanup the gradebook
218 require_once($CFG->libdir.'/gradelib.php');
219 grade_uninstalled_module($module->name);
221 // Perform any custom uninstall tasks
222 if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
223 require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
224 $uninstallfunction = $module->name . '_uninstall';
225 if (function_exists($uninstallfunction)) {
226 debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
227 if (!$uninstallfunction()) {
228 echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
233 } else if ($type === 'enrol') {
234 // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
235 // nuke all role assignments
236 role_unassign_all(array('component'=>$component));
237 // purge participants
238 $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
239 // purge enrol instances
240 $DB->delete_records('enrol', array('enrol'=>$name));
241 // tweak enrol settings
242 if (!empty($CFG->enrol_plugins_enabled)) {
243 $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
244 $enabledenrols = array_unique($enabledenrols);
245 $enabledenrols = array_flip($enabledenrols);
246 unset($enabledenrols[$name]);
247 $enabledenrols = array_flip($enabledenrols);
248 if (is_array($enabledenrols)) {
249 set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
253 } else if ($type === 'block') {
254 if ($block = $DB->get_record('block', array('name'=>$name))) {
255 // Inform block it's about to be deleted
256 if (file_exists("$CFG->dirroot/blocks/$block->name/block_$block->name.php")) {
257 $blockobject = block_instance($block->name);
258 if ($blockobject) {
259 $blockobject->before_delete(); //only if we can create instance, block might have been already removed
263 // First delete instances and related contexts
264 $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
265 foreach($instances as $instance) {
266 blocks_delete_instance($instance);
269 // Delete block
270 $DB->delete_records('block', array('id'=>$block->id));
272 } else if ($type === 'format') {
273 if (($defaultformat = get_config('moodlecourse', 'format')) && $defaultformat !== $name) {
274 $courses = $DB->get_records('course', array('format' => $name), 'id');
275 $data = (object)array('id' => null, 'format' => $defaultformat);
276 foreach ($courses as $record) {
277 $data->id = $record->id;
278 update_course($data);
281 $DB->delete_records('course_format_options', array('format' => $name));
284 // perform clean-up task common for all the plugin/subplugin types
286 //delete the web service functions and pre-built services
287 require_once($CFG->dirroot.'/lib/externallib.php');
288 external_delete_descriptions($component);
290 // delete calendar events
291 $DB->delete_records('event', array('modulename' => $pluginname));
293 // delete all the logs
294 $DB->delete_records('log', array('module' => $pluginname));
296 // delete log_display information
297 $DB->delete_records('log_display', array('component' => $component));
299 // delete the module configuration records
300 unset_all_config_for_plugin($pluginname);
302 // delete message provider
303 message_provider_uninstall($component);
305 // delete message processor
306 if ($type === 'message') {
307 message_processor_uninstall($name);
310 // delete the plugin tables
311 $xmldbfilepath = $plugindirectory . '/db/install.xml';
312 drop_plugin_tables($component, $xmldbfilepath, false);
313 if ($type === 'mod' or $type === 'block') {
314 // non-frankenstyle table prefixes
315 drop_plugin_tables($name, $xmldbfilepath, false);
318 // delete the capabilities that were defined by this module
319 capabilities_cleanup($component);
321 // remove event handlers and dequeue pending events
322 events_uninstall($component);
324 echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
328 * Returns the version of installed component
330 * @param string $component component name
331 * @param string $source either 'disk' or 'installed' - where to get the version information from
332 * @return string|bool version number or false if the component is not found
334 function get_component_version($component, $source='installed') {
335 global $CFG, $DB;
337 list($type, $name) = normalize_component($component);
339 // moodle core or a core subsystem
340 if ($type === 'core') {
341 if ($source === 'installed') {
342 if (empty($CFG->version)) {
343 return false;
344 } else {
345 return $CFG->version;
347 } else {
348 if (!is_readable($CFG->dirroot.'/version.php')) {
349 return false;
350 } else {
351 $version = null; //initialize variable for IDEs
352 include($CFG->dirroot.'/version.php');
353 return $version;
358 // activity module
359 if ($type === 'mod') {
360 if ($source === 'installed') {
361 return $DB->get_field('modules', 'version', array('name'=>$name));
362 } else {
363 $mods = get_plugin_list('mod');
364 if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
365 return false;
366 } else {
367 $module = new stdclass();
368 include($mods[$name].'/version.php');
369 return $module->version;
374 // block
375 if ($type === 'block') {
376 if ($source === 'installed') {
377 return $DB->get_field('block', 'version', array('name'=>$name));
378 } else {
379 $blocks = get_plugin_list('block');
380 if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
381 return false;
382 } else {
383 $plugin = new stdclass();
384 include($blocks[$name].'/version.php');
385 return $plugin->version;
390 // all other plugin types
391 if ($source === 'installed') {
392 return get_config($type.'_'.$name, 'version');
393 } else {
394 $plugins = get_plugin_list($type);
395 if (empty($plugins[$name])) {
396 return false;
397 } else {
398 $plugin = new stdclass();
399 include($plugins[$name].'/version.php');
400 return $plugin->version;
406 * Delete all plugin tables
408 * @param string $name Name of plugin, used as table prefix
409 * @param string $file Path to install.xml file
410 * @param bool $feedback defaults to true
411 * @return bool Always returns true
413 function drop_plugin_tables($name, $file, $feedback=true) {
414 global $CFG, $DB;
416 // first try normal delete
417 if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
418 return true;
421 // then try to find all tables that start with name and are not in any xml file
422 $used_tables = get_used_table_names();
424 $tables = $DB->get_tables();
426 /// Iterate over, fixing id fields as necessary
427 foreach ($tables as $table) {
428 if (in_array($table, $used_tables)) {
429 continue;
432 if (strpos($table, $name) !== 0) {
433 continue;
436 // found orphan table --> delete it
437 if ($DB->get_manager()->table_exists($table)) {
438 $xmldb_table = new xmldb_table($table);
439 $DB->get_manager()->drop_table($xmldb_table);
443 return true;
447 * Returns names of all known tables == tables that moodle knows about.
449 * @return array Array of lowercase table names
451 function get_used_table_names() {
452 $table_names = array();
453 $dbdirs = get_db_directories();
455 foreach ($dbdirs as $dbdir) {
456 $file = $dbdir.'/install.xml';
458 $xmldb_file = new xmldb_file($file);
460 if (!$xmldb_file->fileExists()) {
461 continue;
464 $loaded = $xmldb_file->loadXMLStructure();
465 $structure = $xmldb_file->getStructure();
467 if ($loaded and $tables = $structure->getTables()) {
468 foreach($tables as $table) {
469 $table_names[] = strtolower($table->getName());
474 return $table_names;
478 * Returns list of all directories where we expect install.xml files
479 * @return array Array of paths
481 function get_db_directories() {
482 global $CFG;
484 $dbdirs = array();
486 /// First, the main one (lib/db)
487 $dbdirs[] = $CFG->libdir.'/db';
489 /// Then, all the ones defined by get_plugin_types()
490 $plugintypes = get_plugin_types();
491 foreach ($plugintypes as $plugintype => $pluginbasedir) {
492 if ($plugins = get_plugin_list($plugintype)) {
493 foreach ($plugins as $plugin => $plugindir) {
494 $dbdirs[] = $plugindir.'/db';
499 return $dbdirs;
503 * Try to obtain or release the cron lock.
504 * @param string $name name of lock
505 * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
506 * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
507 * @return bool true if lock obtained
509 function set_cron_lock($name, $until, $ignorecurrent=false) {
510 global $DB;
511 if (empty($name)) {
512 debugging("Tried to get a cron lock for a null fieldname");
513 return false;
516 // remove lock by force == remove from config table
517 if (is_null($until)) {
518 set_config($name, null);
519 return true;
522 if (!$ignorecurrent) {
523 // read value from db - other processes might have changed it
524 $value = $DB->get_field('config', 'value', array('name'=>$name));
526 if ($value and $value > time()) {
527 //lock active
528 return false;
532 set_config($name, $until);
533 return true;
537 * Test if and critical warnings are present
538 * @return bool
540 function admin_critical_warnings_present() {
541 global $SESSION;
543 if (!has_capability('moodle/site:config', context_system::instance())) {
544 return 0;
547 if (!isset($SESSION->admin_critical_warning)) {
548 $SESSION->admin_critical_warning = 0;
549 if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
550 $SESSION->admin_critical_warning = 1;
554 return $SESSION->admin_critical_warning;
558 * Detects if float supports at least 10 decimal digits
560 * Detects if float supports at least 10 decimal digits
561 * and also if float-->string conversion works as expected.
563 * @return bool true if problem found
565 function is_float_problem() {
566 $num1 = 2009010200.01;
567 $num2 = 2009010200.02;
569 return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
573 * Try to verify that dataroot is not accessible from web.
575 * Try to verify that dataroot is not accessible from web.
576 * It is not 100% correct but might help to reduce number of vulnerable sites.
577 * Protection from httpd.conf and .htaccess is not detected properly.
579 * @uses INSECURE_DATAROOT_WARNING
580 * @uses INSECURE_DATAROOT_ERROR
581 * @param bool $fetchtest try to test public access by fetching file, default false
582 * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
584 function is_dataroot_insecure($fetchtest=false) {
585 global $CFG;
587 $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
589 $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
590 $rp = strrev(trim($rp, '/'));
591 $rp = explode('/', $rp);
592 foreach($rp as $r) {
593 if (strpos($siteroot, '/'.$r.'/') === 0) {
594 $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
595 } else {
596 break; // probably alias root
600 $siteroot = strrev($siteroot);
601 $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
603 if (strpos($dataroot, $siteroot) !== 0) {
604 return false;
607 if (!$fetchtest) {
608 return INSECURE_DATAROOT_WARNING;
611 // now try all methods to fetch a test file using http protocol
613 $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
614 preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
615 $httpdocroot = $matches[1];
616 $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
617 make_upload_directory('diag');
618 $testfile = $CFG->dataroot.'/diag/public.txt';
619 if (!file_exists($testfile)) {
620 file_put_contents($testfile, 'test file, do not delete');
622 $teststr = trim(file_get_contents($testfile));
623 if (empty($teststr)) {
624 // hmm, strange
625 return INSECURE_DATAROOT_WARNING;
628 $testurl = $datarooturl.'/diag/public.txt';
629 if (extension_loaded('curl') and
630 !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
631 !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
632 ($ch = @curl_init($testurl)) !== false) {
633 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
634 curl_setopt($ch, CURLOPT_HEADER, false);
635 $data = curl_exec($ch);
636 if (!curl_errno($ch)) {
637 $data = trim($data);
638 if ($data === $teststr) {
639 curl_close($ch);
640 return INSECURE_DATAROOT_ERROR;
643 curl_close($ch);
646 if ($data = @file_get_contents($testurl)) {
647 $data = trim($data);
648 if ($data === $teststr) {
649 return INSECURE_DATAROOT_ERROR;
653 preg_match('|https?://([^/]+)|i', $testurl, $matches);
654 $sitename = $matches[1];
655 $error = 0;
656 if ($fp = @fsockopen($sitename, 80, $error)) {
657 preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
658 $localurl = $matches[1];
659 $out = "GET $localurl HTTP/1.1\r\n";
660 $out .= "Host: $sitename\r\n";
661 $out .= "Connection: Close\r\n\r\n";
662 fwrite($fp, $out);
663 $data = '';
664 $incoming = false;
665 while (!feof($fp)) {
666 if ($incoming) {
667 $data .= fgets($fp, 1024);
668 } else if (@fgets($fp, 1024) === "\r\n") {
669 $incoming = true;
672 fclose($fp);
673 $data = trim($data);
674 if ($data === $teststr) {
675 return INSECURE_DATAROOT_ERROR;
679 return INSECURE_DATAROOT_WARNING;
682 /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
686 * Interface for anything appearing in the admin tree
688 * The interface that is implemented by anything that appears in the admin tree
689 * block. It forces inheriting classes to define a method for checking user permissions
690 * and methods for finding something in the admin tree.
692 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
694 interface part_of_admin_tree {
697 * Finds a named part_of_admin_tree.
699 * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
700 * and not parentable_part_of_admin_tree, then this function should only check if
701 * $this->name matches $name. If it does, it should return a reference to $this,
702 * otherwise, it should return a reference to NULL.
704 * If a class inherits parentable_part_of_admin_tree, this method should be called
705 * recursively on all child objects (assuming, of course, the parent object's name
706 * doesn't match the search criterion).
708 * @param string $name The internal name of the part_of_admin_tree we're searching for.
709 * @return mixed An object reference or a NULL reference.
711 public function locate($name);
714 * Removes named part_of_admin_tree.
716 * @param string $name The internal name of the part_of_admin_tree we want to remove.
717 * @return bool success.
719 public function prune($name);
722 * Search using query
723 * @param string $query
724 * @return mixed array-object structure of found settings and pages
726 public function search($query);
729 * Verifies current user's access to this part_of_admin_tree.
731 * Used to check if the current user has access to this part of the admin tree or
732 * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
733 * then this method is usually just a call to has_capability() in the site context.
735 * If a class inherits parentable_part_of_admin_tree, this method should return the
736 * logical OR of the return of check_access() on all child objects.
738 * @return bool True if the user has access, false if she doesn't.
740 public function check_access();
743 * Mostly useful for removing of some parts of the tree in admin tree block.
745 * @return True is hidden from normal list view
747 public function is_hidden();
750 * Show we display Save button at the page bottom?
751 * @return bool
753 public function show_save();
758 * Interface implemented by any part_of_admin_tree that has children.
760 * The interface implemented by any part_of_admin_tree that can be a parent
761 * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
762 * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
763 * include an add method for adding other part_of_admin_tree objects as children.
765 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
767 interface parentable_part_of_admin_tree extends part_of_admin_tree {
770 * Adds a part_of_admin_tree object to the admin tree.
772 * Used to add a part_of_admin_tree object to this object or a child of this
773 * object. $something should only be added if $destinationname matches
774 * $this->name. If it doesn't, add should be called on child objects that are
775 * also parentable_part_of_admin_tree's.
777 * @param string $destinationname The internal name of the new parent for $something.
778 * @param part_of_admin_tree $something The object to be added.
779 * @return bool True on success, false on failure.
781 public function add($destinationname, $something);
787 * The object used to represent folders (a.k.a. categories) in the admin tree block.
789 * Each admin_category object contains a number of part_of_admin_tree objects.
791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
793 class admin_category implements parentable_part_of_admin_tree {
795 /** @var mixed An array of part_of_admin_tree objects that are this object's children */
796 public $children;
797 /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
798 public $name;
799 /** @var string The displayed name for this category. Usually obtained through get_string() */
800 public $visiblename;
801 /** @var bool Should this category be hidden in admin tree block? */
802 public $hidden;
803 /** @var mixed Either a string or an array or strings */
804 public $path;
805 /** @var mixed Either a string or an array or strings */
806 public $visiblepath;
808 /** @var array fast lookup category cache, all categories of one tree point to one cache */
809 protected $category_cache;
812 * Constructor for an empty admin category
814 * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
815 * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
816 * @param bool $hidden hide category in admin tree block, defaults to false
818 public function __construct($name, $visiblename, $hidden=false) {
819 $this->children = array();
820 $this->name = $name;
821 $this->visiblename = $visiblename;
822 $this->hidden = $hidden;
826 * Returns a reference to the part_of_admin_tree object with internal name $name.
828 * @param string $name The internal name of the object we want.
829 * @param bool $findpath initialize path and visiblepath arrays
830 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
831 * defaults to false
833 public function locate($name, $findpath=false) {
834 if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
835 // somebody much have purged the cache
836 $this->category_cache[$this->name] = $this;
839 if ($this->name == $name) {
840 if ($findpath) {
841 $this->visiblepath[] = $this->visiblename;
842 $this->path[] = $this->name;
844 return $this;
847 // quick category lookup
848 if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
849 return $this->category_cache[$name];
852 $return = NULL;
853 foreach($this->children as $childid=>$unused) {
854 if ($return = $this->children[$childid]->locate($name, $findpath)) {
855 break;
859 if (!is_null($return) and $findpath) {
860 $return->visiblepath[] = $this->visiblename;
861 $return->path[] = $this->name;
864 return $return;
868 * Search using query
870 * @param string query
871 * @return mixed array-object structure of found settings and pages
873 public function search($query) {
874 $result = array();
875 foreach ($this->children as $child) {
876 $subsearch = $child->search($query);
877 if (!is_array($subsearch)) {
878 debugging('Incorrect search result from '.$child->name);
879 continue;
881 $result = array_merge($result, $subsearch);
883 return $result;
887 * Removes part_of_admin_tree object with internal name $name.
889 * @param string $name The internal name of the object we want to remove.
890 * @return bool success
892 public function prune($name) {
894 if ($this->name == $name) {
895 return false; //can not remove itself
898 foreach($this->children as $precedence => $child) {
899 if ($child->name == $name) {
900 // clear cache and delete self
901 if (is_array($this->category_cache)) {
902 while($this->category_cache) {
903 // delete the cache, but keep the original array address
904 array_pop($this->category_cache);
907 unset($this->children[$precedence]);
908 return true;
909 } else if ($this->children[$precedence]->prune($name)) {
910 return true;
913 return false;
917 * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
919 * @param string $destinationame The internal name of the immediate parent that we want for $something.
920 * @param mixed $something A part_of_admin_tree or setting instance to be added.
921 * @return bool True if successfully added, false if $something can not be added.
923 public function add($parentname, $something) {
924 $parent = $this->locate($parentname);
925 if (is_null($parent)) {
926 debugging('parent does not exist!');
927 return false;
930 if ($something instanceof part_of_admin_tree) {
931 if (!($parent instanceof parentable_part_of_admin_tree)) {
932 debugging('error - parts of tree can be inserted only into parentable parts');
933 return false;
935 $parent->children[] = $something;
936 if (is_array($this->category_cache) and ($something instanceof admin_category)) {
937 if (isset($this->category_cache[$something->name])) {
938 debugging('Duplicate admin category name: '.$something->name);
939 } else {
940 $this->category_cache[$something->name] = $something;
941 $something->category_cache =& $this->category_cache;
942 foreach ($something->children as $child) {
943 // just in case somebody already added subcategories
944 if ($child instanceof admin_category) {
945 if (isset($this->category_cache[$child->name])) {
946 debugging('Duplicate admin category name: '.$child->name);
947 } else {
948 $this->category_cache[$child->name] = $child;
949 $child->category_cache =& $this->category_cache;
955 return true;
957 } else {
958 debugging('error - can not add this element');
959 return false;
965 * Checks if the user has access to anything in this category.
967 * @return bool True if the user has access to at least one child in this category, false otherwise.
969 public function check_access() {
970 foreach ($this->children as $child) {
971 if ($child->check_access()) {
972 return true;
975 return false;
979 * Is this category hidden in admin tree block?
981 * @return bool True if hidden
983 public function is_hidden() {
984 return $this->hidden;
988 * Show we display Save button at the page bottom?
989 * @return bool
991 public function show_save() {
992 foreach ($this->children as $child) {
993 if ($child->show_save()) {
994 return true;
997 return false;
1003 * Root of admin settings tree, does not have any parent.
1005 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1007 class admin_root extends admin_category {
1008 /** @var array List of errors */
1009 public $errors;
1010 /** @var string search query */
1011 public $search;
1012 /** @var bool full tree flag - true means all settings required, false only pages required */
1013 public $fulltree;
1014 /** @var bool flag indicating loaded tree */
1015 public $loaded;
1016 /** @var mixed site custom defaults overriding defaults in settings files*/
1017 public $custom_defaults;
1020 * @param bool $fulltree true means all settings required,
1021 * false only pages required
1023 public function __construct($fulltree) {
1024 global $CFG;
1026 parent::__construct('root', get_string('administration'), false);
1027 $this->errors = array();
1028 $this->search = '';
1029 $this->fulltree = $fulltree;
1030 $this->loaded = false;
1032 $this->category_cache = array();
1034 // load custom defaults if found
1035 $this->custom_defaults = null;
1036 $defaultsfile = "$CFG->dirroot/local/defaults.php";
1037 if (is_readable($defaultsfile)) {
1038 $defaults = array();
1039 include($defaultsfile);
1040 if (is_array($defaults) and count($defaults)) {
1041 $this->custom_defaults = $defaults;
1047 * Empties children array, and sets loaded to false
1049 * @param bool $requirefulltree
1051 public function purge_children($requirefulltree) {
1052 $this->children = array();
1053 $this->fulltree = ($requirefulltree || $this->fulltree);
1054 $this->loaded = false;
1055 //break circular dependencies - this helps PHP 5.2
1056 while($this->category_cache) {
1057 array_pop($this->category_cache);
1059 $this->category_cache = array();
1065 * Links external PHP pages into the admin tree.
1067 * See detailed usage example at the top of this document (adminlib.php)
1069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1071 class admin_externalpage implements part_of_admin_tree {
1073 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1074 public $name;
1076 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1077 public $visiblename;
1079 /** @var string The external URL that we should link to when someone requests this external page. */
1080 public $url;
1082 /** @var string The role capability/permission a user must have to access this external page. */
1083 public $req_capability;
1085 /** @var object The context in which capability/permission should be checked, default is site context. */
1086 public $context;
1088 /** @var bool hidden in admin tree block. */
1089 public $hidden;
1091 /** @var mixed either string or array of string */
1092 public $path;
1094 /** @var array list of visible names of page parents */
1095 public $visiblepath;
1098 * Constructor for adding an external page into the admin tree.
1100 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1101 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1102 * @param string $url The external URL that we should link to when someone requests this external page.
1103 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1104 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1105 * @param stdClass $context The context the page relates to. Not sure what happens
1106 * if you specify something other than system or front page. Defaults to system.
1108 public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1109 $this->name = $name;
1110 $this->visiblename = $visiblename;
1111 $this->url = $url;
1112 if (is_array($req_capability)) {
1113 $this->req_capability = $req_capability;
1114 } else {
1115 $this->req_capability = array($req_capability);
1117 $this->hidden = $hidden;
1118 $this->context = $context;
1122 * Returns a reference to the part_of_admin_tree object with internal name $name.
1124 * @param string $name The internal name of the object we want.
1125 * @param bool $findpath defaults to false
1126 * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
1128 public function locate($name, $findpath=false) {
1129 if ($this->name == $name) {
1130 if ($findpath) {
1131 $this->visiblepath = array($this->visiblename);
1132 $this->path = array($this->name);
1134 return $this;
1135 } else {
1136 $return = NULL;
1137 return $return;
1142 * This function always returns false, required function by interface
1144 * @param string $name
1145 * @return false
1147 public function prune($name) {
1148 return false;
1152 * Search using query
1154 * @param string $query
1155 * @return mixed array-object structure of found settings and pages
1157 public function search($query) {
1158 $found = false;
1159 if (strpos(strtolower($this->name), $query) !== false) {
1160 $found = true;
1161 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1162 $found = true;
1164 if ($found) {
1165 $result = new stdClass();
1166 $result->page = $this;
1167 $result->settings = array();
1168 return array($this->name => $result);
1169 } else {
1170 return array();
1175 * Determines if the current user has access to this external page based on $this->req_capability.
1177 * @return bool True if user has access, false otherwise.
1179 public function check_access() {
1180 global $CFG;
1181 $context = empty($this->context) ? context_system::instance() : $this->context;
1182 foreach($this->req_capability as $cap) {
1183 if (has_capability($cap, $context)) {
1184 return true;
1187 return false;
1191 * Is this external page hidden in admin tree block?
1193 * @return bool True if hidden
1195 public function is_hidden() {
1196 return $this->hidden;
1200 * Show we display Save button at the page bottom?
1201 * @return bool
1203 public function show_save() {
1204 return false;
1210 * Used to group a number of admin_setting objects into a page and add them to the admin tree.
1212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1214 class admin_settingpage implements part_of_admin_tree {
1216 /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
1217 public $name;
1219 /** @var string The displayed name for this external page. Usually obtained through get_string(). */
1220 public $visiblename;
1222 /** @var mixed An array of admin_setting objects that are part of this setting page. */
1223 public $settings;
1225 /** @var string The role capability/permission a user must have to access this external page. */
1226 public $req_capability;
1228 /** @var object The context in which capability/permission should be checked, default is site context. */
1229 public $context;
1231 /** @var bool hidden in admin tree block. */
1232 public $hidden;
1234 /** @var mixed string of paths or array of strings of paths */
1235 public $path;
1237 /** @var array list of visible names of page parents */
1238 public $visiblepath;
1241 * see admin_settingpage for details of this function
1243 * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
1244 * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
1245 * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
1246 * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
1247 * @param stdClass $context The context the page relates to. Not sure what happens
1248 * if you specify something other than system or front page. Defaults to system.
1250 public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
1251 $this->settings = new stdClass();
1252 $this->name = $name;
1253 $this->visiblename = $visiblename;
1254 if (is_array($req_capability)) {
1255 $this->req_capability = $req_capability;
1256 } else {
1257 $this->req_capability = array($req_capability);
1259 $this->hidden = $hidden;
1260 $this->context = $context;
1264 * see admin_category
1266 * @param string $name
1267 * @param bool $findpath
1268 * @return mixed Object (this) if name == this->name, else returns null
1270 public function locate($name, $findpath=false) {
1271 if ($this->name == $name) {
1272 if ($findpath) {
1273 $this->visiblepath = array($this->visiblename);
1274 $this->path = array($this->name);
1276 return $this;
1277 } else {
1278 $return = NULL;
1279 return $return;
1284 * Search string in settings page.
1286 * @param string $query
1287 * @return array
1289 public function search($query) {
1290 $found = array();
1292 foreach ($this->settings as $setting) {
1293 if ($setting->is_related($query)) {
1294 $found[] = $setting;
1298 if ($found) {
1299 $result = new stdClass();
1300 $result->page = $this;
1301 $result->settings = $found;
1302 return array($this->name => $result);
1305 $found = false;
1306 if (strpos(strtolower($this->name), $query) !== false) {
1307 $found = true;
1308 } else if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1309 $found = true;
1311 if ($found) {
1312 $result = new stdClass();
1313 $result->page = $this;
1314 $result->settings = array();
1315 return array($this->name => $result);
1316 } else {
1317 return array();
1322 * This function always returns false, required by interface
1324 * @param string $name
1325 * @return bool Always false
1327 public function prune($name) {
1328 return false;
1332 * adds an admin_setting to this admin_settingpage
1334 * 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
1335 * n.b. each admin_setting in an admin_settingpage must have a unique internal name
1337 * @param object $setting is the admin_setting object you want to add
1338 * @return bool true if successful, false if not
1340 public function add($setting) {
1341 if (!($setting instanceof admin_setting)) {
1342 debugging('error - not a setting instance');
1343 return false;
1346 $this->settings->{$setting->name} = $setting;
1347 return true;
1351 * see admin_externalpage
1353 * @return bool Returns true for yes false for no
1355 public function check_access() {
1356 global $CFG;
1357 $context = empty($this->context) ? context_system::instance() : $this->context;
1358 foreach($this->req_capability as $cap) {
1359 if (has_capability($cap, $context)) {
1360 return true;
1363 return false;
1367 * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
1368 * @return string Returns an XHTML string
1370 public function output_html() {
1371 $adminroot = admin_get_root();
1372 $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
1373 foreach($this->settings as $setting) {
1374 $fullname = $setting->get_full_name();
1375 if (array_key_exists($fullname, $adminroot->errors)) {
1376 $data = $adminroot->errors[$fullname]->data;
1377 } else {
1378 $data = $setting->get_setting();
1379 // do not use defaults if settings not available - upgrade settings handles the defaults!
1381 $return .= $setting->output_html($data);
1383 $return .= '</fieldset>';
1384 return $return;
1388 * Is this settings page hidden in admin tree block?
1390 * @return bool True if hidden
1392 public function is_hidden() {
1393 return $this->hidden;
1397 * Show we display Save button at the page bottom?
1398 * @return bool
1400 public function show_save() {
1401 foreach($this->settings as $setting) {
1402 if (empty($setting->nosave)) {
1403 return true;
1406 return false;
1412 * Admin settings class. Only exists on setting pages.
1413 * Read & write happens at this level; no authentication.
1415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1417 abstract class admin_setting {
1418 /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
1419 public $name;
1420 /** @var string localised name */
1421 public $visiblename;
1422 /** @var string localised long description in Markdown format */
1423 public $description;
1424 /** @var mixed Can be string or array of string */
1425 public $defaultsetting;
1426 /** @var string */
1427 public $updatedcallback;
1428 /** @var mixed can be String or Null. Null means main config table */
1429 public $plugin; // null means main config table
1430 /** @var bool true indicates this setting does not actually save anything, just information */
1431 public $nosave = false;
1432 /** @var bool if set, indicates that a change to this setting requires rebuild course cache */
1433 public $affectsmodinfo = false;
1436 * Constructor
1437 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
1438 * or 'myplugin/mysetting' for ones in config_plugins.
1439 * @param string $visiblename localised name
1440 * @param string $description localised long description
1441 * @param mixed $defaultsetting string or array depending on implementation
1443 public function __construct($name, $visiblename, $description, $defaultsetting) {
1444 $this->parse_setting_name($name);
1445 $this->visiblename = $visiblename;
1446 $this->description = $description;
1447 $this->defaultsetting = $defaultsetting;
1451 * Set up $this->name and potentially $this->plugin
1453 * Set up $this->name and possibly $this->plugin based on whether $name looks
1454 * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
1455 * on the names, that is, output a developer debug warning if the name
1456 * contains anything other than [a-zA-Z0-9_]+.
1458 * @param string $name the setting name passed in to the constructor.
1460 private function parse_setting_name($name) {
1461 $bits = explode('/', $name);
1462 if (count($bits) > 2) {
1463 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1465 $this->name = array_pop($bits);
1466 if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
1467 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1469 if (!empty($bits)) {
1470 $this->plugin = array_pop($bits);
1471 if ($this->plugin === 'moodle') {
1472 $this->plugin = null;
1473 } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
1474 throw new moodle_exception('invalidadminsettingname', '', '', $name);
1480 * Returns the fullname prefixed by the plugin
1481 * @return string
1483 public function get_full_name() {
1484 return 's_'.$this->plugin.'_'.$this->name;
1488 * Returns the ID string based on plugin and name
1489 * @return string
1491 public function get_id() {
1492 return 'id_s_'.$this->plugin.'_'.$this->name;
1496 * @param bool $affectsmodinfo If true, changes to this setting will
1497 * cause the course cache to be rebuilt
1499 public function set_affects_modinfo($affectsmodinfo) {
1500 $this->affectsmodinfo = $affectsmodinfo;
1504 * Returns the config if possible
1506 * @return mixed returns config if successful else null
1508 public function config_read($name) {
1509 global $CFG;
1510 if (!empty($this->plugin)) {
1511 $value = get_config($this->plugin, $name);
1512 return $value === false ? NULL : $value;
1514 } else {
1515 if (isset($CFG->$name)) {
1516 return $CFG->$name;
1517 } else {
1518 return NULL;
1524 * Used to set a config pair and log change
1526 * @param string $name
1527 * @param mixed $value Gets converted to string if not null
1528 * @return bool Write setting to config table
1530 public function config_write($name, $value) {
1531 global $DB, $USER, $CFG;
1533 if ($this->nosave) {
1534 return true;
1537 // make sure it is a real change
1538 $oldvalue = get_config($this->plugin, $name);
1539 $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
1540 $value = is_null($value) ? null : (string)$value;
1542 if ($oldvalue === $value) {
1543 return true;
1546 // store change
1547 set_config($name, $value, $this->plugin);
1549 // Some admin settings affect course modinfo
1550 if ($this->affectsmodinfo) {
1551 // Clear course cache for all courses
1552 rebuild_course_cache(0, true);
1555 // log change
1556 $log = new stdClass();
1557 $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
1558 $log->timemodified = time();
1559 $log->plugin = $this->plugin;
1560 $log->name = $name;
1561 $log->value = $value;
1562 $log->oldvalue = $oldvalue;
1563 $DB->insert_record('config_log', $log);
1565 return true; // BC only
1569 * Returns current value of this setting
1570 * @return mixed array or string depending on instance, NULL means not set yet
1572 public abstract function get_setting();
1575 * Returns default setting if exists
1576 * @return mixed array or string depending on instance; NULL means no default, user must supply
1578 public function get_defaultsetting() {
1579 $adminroot = admin_get_root(false, false);
1580 if (!empty($adminroot->custom_defaults)) {
1581 $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
1582 if (isset($adminroot->custom_defaults[$plugin])) {
1583 if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
1584 return $adminroot->custom_defaults[$plugin][$this->name];
1588 return $this->defaultsetting;
1592 * Store new setting
1594 * @param mixed $data string or array, must not be NULL
1595 * @return string empty string if ok, string error message otherwise
1597 public abstract function write_setting($data);
1600 * Return part of form with setting
1601 * This function should always be overwritten
1603 * @param mixed $data array or string depending on setting
1604 * @param string $query
1605 * @return string
1607 public function output_html($data, $query='') {
1608 // should be overridden
1609 return;
1613 * Function called if setting updated - cleanup, cache reset, etc.
1614 * @param string $functionname Sets the function name
1615 * @return void
1617 public function set_updatedcallback($functionname) {
1618 $this->updatedcallback = $functionname;
1622 * Is setting related to query text - used when searching
1623 * @param string $query
1624 * @return bool
1626 public function is_related($query) {
1627 if (strpos(strtolower($this->name), $query) !== false) {
1628 return true;
1630 if (strpos(textlib::strtolower($this->visiblename), $query) !== false) {
1631 return true;
1633 if (strpos(textlib::strtolower($this->description), $query) !== false) {
1634 return true;
1636 $current = $this->get_setting();
1637 if (!is_null($current)) {
1638 if (is_string($current)) {
1639 if (strpos(textlib::strtolower($current), $query) !== false) {
1640 return true;
1644 $default = $this->get_defaultsetting();
1645 if (!is_null($default)) {
1646 if (is_string($default)) {
1647 if (strpos(textlib::strtolower($default), $query) !== false) {
1648 return true;
1652 return false;
1658 * No setting - just heading and text.
1660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1662 class admin_setting_heading extends admin_setting {
1665 * not a setting, just text
1666 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1667 * @param string $heading heading
1668 * @param string $information text in box
1670 public function __construct($name, $heading, $information) {
1671 $this->nosave = true;
1672 parent::__construct($name, $heading, $information, '');
1676 * Always returns true
1677 * @return bool Always returns true
1679 public function get_setting() {
1680 return true;
1684 * Always returns true
1685 * @return bool Always returns true
1687 public function get_defaultsetting() {
1688 return true;
1692 * Never write settings
1693 * @return string Always returns an empty string
1695 public function write_setting($data) {
1696 // do not write any setting
1697 return '';
1701 * Returns an HTML string
1702 * @return string Returns an HTML string
1704 public function output_html($data, $query='') {
1705 global $OUTPUT;
1706 $return = '';
1707 if ($this->visiblename != '') {
1708 $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
1710 if ($this->description != '') {
1711 $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
1713 return $return;
1719 * The most flexibly setting, user is typing text
1721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1723 class admin_setting_configtext extends admin_setting {
1725 /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
1726 public $paramtype;
1727 /** @var int default field size */
1728 public $size;
1731 * Config text constructor
1733 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1734 * @param string $visiblename localised
1735 * @param string $description long localised info
1736 * @param string $defaultsetting
1737 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
1738 * @param int $size default field size
1740 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
1741 $this->paramtype = $paramtype;
1742 if (!is_null($size)) {
1743 $this->size = $size;
1744 } else {
1745 $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
1747 parent::__construct($name, $visiblename, $description, $defaultsetting);
1751 * Return the setting
1753 * @return mixed returns config if successful else null
1755 public function get_setting() {
1756 return $this->config_read($this->name);
1759 public function write_setting($data) {
1760 if ($this->paramtype === PARAM_INT and $data === '') {
1761 // do not complain if '' used instead of 0
1762 $data = 0;
1764 // $data is a string
1765 $validated = $this->validate($data);
1766 if ($validated !== true) {
1767 return $validated;
1769 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
1773 * Validate data before storage
1774 * @param string data
1775 * @return mixed true if ok string if error found
1777 public function validate($data) {
1778 // allow paramtype to be a custom regex if it is the form of /pattern/
1779 if (preg_match('#^/.*/$#', $this->paramtype)) {
1780 if (preg_match($this->paramtype, $data)) {
1781 return true;
1782 } else {
1783 return get_string('validateerror', 'admin');
1786 } else if ($this->paramtype === PARAM_RAW) {
1787 return true;
1789 } else {
1790 $cleaned = clean_param($data, $this->paramtype);
1791 if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
1792 return true;
1793 } else {
1794 return get_string('validateerror', 'admin');
1800 * Return an XHTML string for the setting
1801 * @return string Returns an XHTML string
1803 public function output_html($data, $query='') {
1804 $default = $this->get_defaultsetting();
1806 return format_admin_setting($this, $this->visiblename,
1807 '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
1808 $this->description, true, '', $default, $query);
1814 * General text area without html editor.
1816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1818 class admin_setting_configtextarea extends admin_setting_configtext {
1819 private $rows;
1820 private $cols;
1823 * @param string $name
1824 * @param string $visiblename
1825 * @param string $description
1826 * @param mixed $defaultsetting string or array
1827 * @param mixed $paramtype
1828 * @param string $cols The number of columns to make the editor
1829 * @param string $rows The number of rows to make the editor
1831 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1832 $this->rows = $rows;
1833 $this->cols = $cols;
1834 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1838 * Returns an XHTML string for the editor
1840 * @param string $data
1841 * @param string $query
1842 * @return string XHTML string for the editor
1844 public function output_html($data, $query='') {
1845 $default = $this->get_defaultsetting();
1847 $defaultinfo = $default;
1848 if (!is_null($default) and $default !== '') {
1849 $defaultinfo = "\n".$default;
1852 return format_admin_setting($this, $this->visiblename,
1853 '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1854 $this->description, true, '', $defaultinfo, $query);
1860 * General text area with html editor.
1862 class admin_setting_confightmleditor extends admin_setting_configtext {
1863 private $rows;
1864 private $cols;
1867 * @param string $name
1868 * @param string $visiblename
1869 * @param string $description
1870 * @param mixed $defaultsetting string or array
1871 * @param mixed $paramtype
1873 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
1874 $this->rows = $rows;
1875 $this->cols = $cols;
1876 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
1877 editors_head_setup();
1881 * Returns an XHTML string for the editor
1883 * @param string $data
1884 * @param string $query
1885 * @return string XHTML string for the editor
1887 public function output_html($data, $query='') {
1888 $default = $this->get_defaultsetting();
1890 $defaultinfo = $default;
1891 if (!is_null($default) and $default !== '') {
1892 $defaultinfo = "\n".$default;
1895 $editor = editors_get_preferred_editor(FORMAT_HTML);
1896 $editor->use_editor($this->get_id(), array('noclean'=>true));
1898 return format_admin_setting($this, $this->visiblename,
1899 '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
1900 $this->description, true, '', $defaultinfo, $query);
1906 * Password field, allows unmasking of password
1908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1910 class admin_setting_configpasswordunmask extends admin_setting_configtext {
1912 * Constructor
1913 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1914 * @param string $visiblename localised
1915 * @param string $description long localised info
1916 * @param string $defaultsetting default password
1918 public function __construct($name, $visiblename, $description, $defaultsetting) {
1919 parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
1923 * Returns XHTML for the field
1924 * Writes Javascript into the HTML below right before the last div
1926 * @todo Make javascript available through newer methods if possible
1927 * @param string $data Value for the field
1928 * @param string $query Passed as final argument for format_admin_setting
1929 * @return string XHTML field
1931 public function output_html($data, $query='') {
1932 $id = $this->get_id();
1933 $unmask = get_string('unmaskpassword', 'form');
1934 $unmaskjs = '<script type="text/javascript">
1935 //<![CDATA[
1936 var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
1938 document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
1940 var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
1942 var unmaskchb = document.createElement("input");
1943 unmaskchb.setAttribute("type", "checkbox");
1944 unmaskchb.setAttribute("id", "'.$id.'unmask");
1945 unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
1946 unmaskdiv.appendChild(unmaskchb);
1948 var unmasklbl = document.createElement("label");
1949 unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
1950 if (is_ie) {
1951 unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
1952 } else {
1953 unmasklbl.setAttribute("for", "'.$id.'unmask");
1955 unmaskdiv.appendChild(unmasklbl);
1957 if (is_ie) {
1958 // ugly hack to work around the famous onchange IE bug
1959 unmaskchb.onclick = function() {this.blur();};
1960 unmaskdiv.onclick = function() {this.blur();};
1962 //]]>
1963 </script>';
1964 return format_admin_setting($this, $this->visiblename,
1965 '<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>',
1966 $this->description, true, '', NULL, $query);
1972 * Path to directory
1974 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1976 class admin_setting_configfile extends admin_setting_configtext {
1978 * Constructor
1979 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
1980 * @param string $visiblename localised
1981 * @param string $description long localised info
1982 * @param string $defaultdirectory default directory location
1984 public function __construct($name, $visiblename, $description, $defaultdirectory) {
1985 parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
1989 * Returns XHTML for the field
1991 * Returns XHTML for the field and also checks whether the file
1992 * specified in $data exists using file_exists()
1994 * @param string $data File name and path to use in value attr
1995 * @param string $query
1996 * @return string XHTML field
1998 public function output_html($data, $query='') {
1999 $default = $this->get_defaultsetting();
2001 if ($data) {
2002 if (file_exists($data)) {
2003 $executable = '<span class="pathok">&#x2714;</span>';
2004 } else {
2005 $executable = '<span class="patherror">&#x2718;</span>';
2007 } else {
2008 $executable = '';
2011 return format_admin_setting($this, $this->visiblename,
2012 '<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>',
2013 $this->description, true, '', $default, $query);
2019 * Path to executable file
2021 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2023 class admin_setting_configexecutable extends admin_setting_configfile {
2026 * Returns an XHTML field
2028 * @param string $data This is the value for the field
2029 * @param string $query
2030 * @return string XHTML field
2032 public function output_html($data, $query='') {
2033 $default = $this->get_defaultsetting();
2035 if ($data) {
2036 if (file_exists($data) and is_executable($data)) {
2037 $executable = '<span class="pathok">&#x2714;</span>';
2038 } else {
2039 $executable = '<span class="patherror">&#x2718;</span>';
2041 } else {
2042 $executable = '';
2045 return format_admin_setting($this, $this->visiblename,
2046 '<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>',
2047 $this->description, true, '', $default, $query);
2053 * Path to directory
2055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2057 class admin_setting_configdirectory extends admin_setting_configfile {
2060 * Returns an XHTML field
2062 * @param string $data This is the value for the field
2063 * @param string $query
2064 * @return string XHTML
2066 public function output_html($data, $query='') {
2067 $default = $this->get_defaultsetting();
2069 if ($data) {
2070 if (file_exists($data) and is_dir($data)) {
2071 $executable = '<span class="pathok">&#x2714;</span>';
2072 } else {
2073 $executable = '<span class="patherror">&#x2718;</span>';
2075 } else {
2076 $executable = '';
2079 return format_admin_setting($this, $this->visiblename,
2080 '<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>',
2081 $this->description, true, '', $default, $query);
2087 * Checkbox
2089 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2091 class admin_setting_configcheckbox extends admin_setting {
2092 /** @var string Value used when checked */
2093 public $yes;
2094 /** @var string Value used when not checked */
2095 public $no;
2098 * Constructor
2099 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2100 * @param string $visiblename localised
2101 * @param string $description long localised info
2102 * @param string $defaultsetting
2103 * @param string $yes value used when checked
2104 * @param string $no value used when not checked
2106 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
2107 parent::__construct($name, $visiblename, $description, $defaultsetting);
2108 $this->yes = (string)$yes;
2109 $this->no = (string)$no;
2113 * Retrieves the current setting using the objects name
2115 * @return string
2117 public function get_setting() {
2118 return $this->config_read($this->name);
2122 * Sets the value for the setting
2124 * Sets the value for the setting to either the yes or no values
2125 * of the object by comparing $data to yes
2127 * @param mixed $data Gets converted to str for comparison against yes value
2128 * @return string empty string or error
2130 public function write_setting($data) {
2131 if ((string)$data === $this->yes) { // convert to strings before comparison
2132 $data = $this->yes;
2133 } else {
2134 $data = $this->no;
2136 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2140 * Returns an XHTML checkbox field
2142 * @param string $data If $data matches yes then checkbox is checked
2143 * @param string $query
2144 * @return string XHTML field
2146 public function output_html($data, $query='') {
2147 $default = $this->get_defaultsetting();
2149 if (!is_null($default)) {
2150 if ((string)$default === $this->yes) {
2151 $defaultinfo = get_string('checkboxyes', 'admin');
2152 } else {
2153 $defaultinfo = get_string('checkboxno', 'admin');
2155 } else {
2156 $defaultinfo = NULL;
2159 if ((string)$data === $this->yes) { // convert to strings before comparison
2160 $checked = 'checked="checked"';
2161 } else {
2162 $checked = '';
2165 return format_admin_setting($this, $this->visiblename,
2166 '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
2167 .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
2168 $this->description, true, '', $defaultinfo, $query);
2174 * Multiple checkboxes, each represents different value, stored in csv format
2176 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2178 class admin_setting_configmulticheckbox extends admin_setting {
2179 /** @var array Array of choices value=>label */
2180 public $choices;
2183 * Constructor: uses parent::__construct
2185 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2186 * @param string $visiblename localised
2187 * @param string $description long localised info
2188 * @param array $defaultsetting array of selected
2189 * @param array $choices array of $value=>$label for each checkbox
2191 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2192 $this->choices = $choices;
2193 parent::__construct($name, $visiblename, $description, $defaultsetting);
2197 * This public function may be used in ancestors for lazy loading of choices
2199 * @todo Check if this function is still required content commented out only returns true
2200 * @return bool true if loaded, false if error
2202 public function load_choices() {
2204 if (is_array($this->choices)) {
2205 return true;
2207 .... load choices here
2209 return true;
2213 * Is setting related to query text - used when searching
2215 * @param string $query
2216 * @return bool true on related, false on not or failure
2218 public function is_related($query) {
2219 if (!$this->load_choices() or empty($this->choices)) {
2220 return false;
2222 if (parent::is_related($query)) {
2223 return true;
2226 foreach ($this->choices as $desc) {
2227 if (strpos(textlib::strtolower($desc), $query) !== false) {
2228 return true;
2231 return false;
2235 * Returns the current setting if it is set
2237 * @return mixed null if null, else an array
2239 public function get_setting() {
2240 $result = $this->config_read($this->name);
2242 if (is_null($result)) {
2243 return NULL;
2245 if ($result === '') {
2246 return array();
2248 $enabled = explode(',', $result);
2249 $setting = array();
2250 foreach ($enabled as $option) {
2251 $setting[$option] = 1;
2253 return $setting;
2257 * Saves the setting(s) provided in $data
2259 * @param array $data An array of data, if not array returns empty str
2260 * @return mixed empty string on useless data or bool true=success, false=failed
2262 public function write_setting($data) {
2263 if (!is_array($data)) {
2264 return ''; // ignore it
2266 if (!$this->load_choices() or empty($this->choices)) {
2267 return '';
2269 unset($data['xxxxx']);
2270 $result = array();
2271 foreach ($data as $key => $value) {
2272 if ($value and array_key_exists($key, $this->choices)) {
2273 $result[] = $key;
2276 return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
2280 * Returns XHTML field(s) as required by choices
2282 * Relies on data being an array should data ever be another valid vartype with
2283 * acceptable value this may cause a warning/error
2284 * if (!is_array($data)) would fix the problem
2286 * @todo Add vartype handling to ensure $data is an array
2288 * @param array $data An array of checked values
2289 * @param string $query
2290 * @return string XHTML field
2292 public function output_html($data, $query='') {
2293 if (!$this->load_choices() or empty($this->choices)) {
2294 return '';
2296 $default = $this->get_defaultsetting();
2297 if (is_null($default)) {
2298 $default = array();
2300 if (is_null($data)) {
2301 $data = array();
2303 $options = array();
2304 $defaults = array();
2305 foreach ($this->choices as $key=>$description) {
2306 if (!empty($data[$key])) {
2307 $checked = 'checked="checked"';
2308 } else {
2309 $checked = '';
2311 if (!empty($default[$key])) {
2312 $defaults[] = $description;
2315 $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
2316 .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
2319 if (is_null($default)) {
2320 $defaultinfo = NULL;
2321 } else if (!empty($defaults)) {
2322 $defaultinfo = implode(', ', $defaults);
2323 } else {
2324 $defaultinfo = get_string('none');
2327 $return = '<div class="form-multicheckbox">';
2328 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2329 if ($options) {
2330 $return .= '<ul>';
2331 foreach ($options as $option) {
2332 $return .= '<li>'.$option.'</li>';
2334 $return .= '</ul>';
2336 $return .= '</div>';
2338 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2345 * Multiple checkboxes 2, value stored as string 00101011
2347 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2349 class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
2352 * Returns the setting if set
2354 * @return mixed null if not set, else an array of set settings
2356 public function get_setting() {
2357 $result = $this->config_read($this->name);
2358 if (is_null($result)) {
2359 return NULL;
2361 if (!$this->load_choices()) {
2362 return NULL;
2364 $result = str_pad($result, count($this->choices), '0');
2365 $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
2366 $setting = array();
2367 foreach ($this->choices as $key=>$unused) {
2368 $value = array_shift($result);
2369 if ($value) {
2370 $setting[$key] = 1;
2373 return $setting;
2377 * Save setting(s) provided in $data param
2379 * @param array $data An array of settings to save
2380 * @return mixed empty string for bad data or bool true=>success, false=>error
2382 public function write_setting($data) {
2383 if (!is_array($data)) {
2384 return ''; // ignore it
2386 if (!$this->load_choices() or empty($this->choices)) {
2387 return '';
2389 $result = '';
2390 foreach ($this->choices as $key=>$unused) {
2391 if (!empty($data[$key])) {
2392 $result .= '1';
2393 } else {
2394 $result .= '0';
2397 return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
2403 * Select one value from list
2405 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2407 class admin_setting_configselect extends admin_setting {
2408 /** @var array Array of choices value=>label */
2409 public $choices;
2412 * Constructor
2413 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2414 * @param string $visiblename localised
2415 * @param string $description long localised info
2416 * @param string|int $defaultsetting
2417 * @param array $choices array of $value=>$label for each selection
2419 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2420 $this->choices = $choices;
2421 parent::__construct($name, $visiblename, $description, $defaultsetting);
2425 * This function may be used in ancestors for lazy loading of choices
2427 * Override this method if loading of choices is expensive, such
2428 * as when it requires multiple db requests.
2430 * @return bool true if loaded, false if error
2432 public function load_choices() {
2434 if (is_array($this->choices)) {
2435 return true;
2437 .... load choices here
2439 return true;
2443 * Check if this is $query is related to a choice
2445 * @param string $query
2446 * @return bool true if related, false if not
2448 public function is_related($query) {
2449 if (parent::is_related($query)) {
2450 return true;
2452 if (!$this->load_choices()) {
2453 return false;
2455 foreach ($this->choices as $key=>$value) {
2456 if (strpos(textlib::strtolower($key), $query) !== false) {
2457 return true;
2459 if (strpos(textlib::strtolower($value), $query) !== false) {
2460 return true;
2463 return false;
2467 * Return the setting
2469 * @return mixed returns config if successful else null
2471 public function get_setting() {
2472 return $this->config_read($this->name);
2476 * Save a setting
2478 * @param string $data
2479 * @return string empty of error string
2481 public function write_setting($data) {
2482 if (!$this->load_choices() or empty($this->choices)) {
2483 return '';
2485 if (!array_key_exists($data, $this->choices)) {
2486 return ''; // ignore it
2489 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
2493 * Returns XHTML select field
2495 * Ensure the options are loaded, and generate the XHTML for the select
2496 * element and any warning message. Separating this out from output_html
2497 * makes it easier to subclass this class.
2499 * @param string $data the option to show as selected.
2500 * @param string $current the currently selected option in the database, null if none.
2501 * @param string $default the default selected option.
2502 * @return array the HTML for the select element, and a warning message.
2504 public function output_select_html($data, $current, $default, $extraname = '') {
2505 if (!$this->load_choices() or empty($this->choices)) {
2506 return array('', '');
2509 $warning = '';
2510 if (is_null($current)) {
2511 // first run
2512 } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
2513 // no warning
2514 } else if (!array_key_exists($current, $this->choices)) {
2515 $warning = get_string('warningcurrentsetting', 'admin', s($current));
2516 if (!is_null($default) and $data == $current) {
2517 $data = $default; // use default instead of first value when showing the form
2521 $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
2522 foreach ($this->choices as $key => $value) {
2523 // the string cast is needed because key may be integer - 0 is equal to most strings!
2524 $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
2526 $selecthtml .= '</select>';
2527 return array($selecthtml, $warning);
2531 * Returns XHTML select field and wrapping div(s)
2533 * @see output_select_html()
2535 * @param string $data the option to show as selected
2536 * @param string $query
2537 * @return string XHTML field and wrapping div
2539 public function output_html($data, $query='') {
2540 $default = $this->get_defaultsetting();
2541 $current = $this->get_setting();
2543 list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
2544 if (!$selecthtml) {
2545 return '';
2548 if (!is_null($default) and array_key_exists($default, $this->choices)) {
2549 $defaultinfo = $this->choices[$default];
2550 } else {
2551 $defaultinfo = NULL;
2554 $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
2556 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
2562 * Select multiple items from list
2564 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2566 class admin_setting_configmultiselect extends admin_setting_configselect {
2568 * Constructor
2569 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
2570 * @param string $visiblename localised
2571 * @param string $description long localised info
2572 * @param array $defaultsetting array of selected items
2573 * @param array $choices array of $value=>$label for each list item
2575 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
2576 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
2580 * Returns the select setting(s)
2582 * @return mixed null or array. Null if no settings else array of setting(s)
2584 public function get_setting() {
2585 $result = $this->config_read($this->name);
2586 if (is_null($result)) {
2587 return NULL;
2589 if ($result === '') {
2590 return array();
2592 return explode(',', $result);
2596 * Saves setting(s) provided through $data
2598 * Potential bug in the works should anyone call with this function
2599 * using a vartype that is not an array
2601 * @param array $data
2603 public function write_setting($data) {
2604 if (!is_array($data)) {
2605 return ''; //ignore it
2607 if (!$this->load_choices() or empty($this->choices)) {
2608 return '';
2611 unset($data['xxxxx']);
2613 $save = array();
2614 foreach ($data as $value) {
2615 if (!array_key_exists($value, $this->choices)) {
2616 continue; // ignore it
2618 $save[] = $value;
2621 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
2625 * Is setting related to query text - used when searching
2627 * @param string $query
2628 * @return bool true if related, false if not
2630 public function is_related($query) {
2631 if (!$this->load_choices() or empty($this->choices)) {
2632 return false;
2634 if (parent::is_related($query)) {
2635 return true;
2638 foreach ($this->choices as $desc) {
2639 if (strpos(textlib::strtolower($desc), $query) !== false) {
2640 return true;
2643 return false;
2647 * Returns XHTML multi-select field
2649 * @todo Add vartype handling to ensure $data is an array
2650 * @param array $data Array of values to select by default
2651 * @param string $query
2652 * @return string XHTML multi-select field
2654 public function output_html($data, $query='') {
2655 if (!$this->load_choices() or empty($this->choices)) {
2656 return '';
2658 $choices = $this->choices;
2659 $default = $this->get_defaultsetting();
2660 if (is_null($default)) {
2661 $default = array();
2663 if (is_null($data)) {
2664 $data = array();
2667 $defaults = array();
2668 $size = min(10, count($this->choices));
2669 $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
2670 $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
2671 foreach ($this->choices as $key => $description) {
2672 if (in_array($key, $data)) {
2673 $selected = 'selected="selected"';
2674 } else {
2675 $selected = '';
2677 if (in_array($key, $default)) {
2678 $defaults[] = $description;
2681 $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
2684 if (is_null($default)) {
2685 $defaultinfo = NULL;
2686 } if (!empty($defaults)) {
2687 $defaultinfo = implode(', ', $defaults);
2688 } else {
2689 $defaultinfo = get_string('none');
2692 $return .= '</select></div>';
2693 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
2698 * Time selector
2700 * This is a liiitle bit messy. we're using two selects, but we're returning
2701 * them as an array named after $name (so we only use $name2 internally for the setting)
2703 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2705 class admin_setting_configtime extends admin_setting {
2706 /** @var string Used for setting second select (minutes) */
2707 public $name2;
2710 * Constructor
2711 * @param string $hoursname setting for hours
2712 * @param string $minutesname setting for hours
2713 * @param string $visiblename localised
2714 * @param string $description long localised info
2715 * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
2717 public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
2718 $this->name2 = $minutesname;
2719 parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
2723 * Get the selected time
2725 * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
2727 public function get_setting() {
2728 $result1 = $this->config_read($this->name);
2729 $result2 = $this->config_read($this->name2);
2730 if (is_null($result1) or is_null($result2)) {
2731 return NULL;
2734 return array('h' => $result1, 'm' => $result2);
2738 * Store the time (hours and minutes)
2740 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2741 * @return bool true if success, false if not
2743 public function write_setting($data) {
2744 if (!is_array($data)) {
2745 return '';
2748 $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
2749 return ($result ? '' : get_string('errorsetting', 'admin'));
2753 * Returns XHTML time select fields
2755 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2756 * @param string $query
2757 * @return string XHTML time select fields and wrapping div(s)
2759 public function output_html($data, $query='') {
2760 $default = $this->get_defaultsetting();
2762 if (is_array($default)) {
2763 $defaultinfo = $default['h'].':'.$default['m'];
2764 } else {
2765 $defaultinfo = NULL;
2768 $return = '<div class="form-time defaultsnext">'.
2769 '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
2770 for ($i = 0; $i < 24; $i++) {
2771 $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2773 $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
2774 for ($i = 0; $i < 60; $i += 5) {
2775 $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
2777 $return .= '</select></div>';
2778 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2785 * Seconds duration setting.
2787 * @copyright 2012 Petr Skoda (http://skodak.org)
2788 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2790 class admin_setting_configduration extends admin_setting {
2792 /** @var int default duration unit */
2793 protected $defaultunit;
2796 * Constructor
2797 * @param string $name unique ascii name, either 'mysetting' for settings that in config,
2798 * or 'myplugin/mysetting' for ones in config_plugins.
2799 * @param string $visiblename localised name
2800 * @param string $description localised long description
2801 * @param mixed $defaultsetting string or array depending on implementation
2802 * @param int $defaultunit - day, week, etc. (in seconds)
2804 public function __construct($name, $visiblename, $description, $defaultsetting, $defaultunit = 86400) {
2805 if (is_number($defaultsetting)) {
2806 $defaultsetting = self::parse_seconds($defaultsetting);
2808 $units = self::get_units();
2809 if (isset($units[$defaultunit])) {
2810 $this->defaultunit = $defaultunit;
2811 } else {
2812 $this->defaultunit = 86400;
2814 parent::__construct($name, $visiblename, $description, $defaultsetting);
2818 * Returns selectable units.
2819 * @static
2820 * @return array
2822 protected static function get_units() {
2823 return array(
2824 604800 => get_string('weeks'),
2825 86400 => get_string('days'),
2826 3600 => get_string('hours'),
2827 60 => get_string('minutes'),
2828 1 => get_string('seconds'),
2833 * Converts seconds to some more user friendly string.
2834 * @static
2835 * @param int $seconds
2836 * @return string
2838 protected static function get_duration_text($seconds) {
2839 if (empty($seconds)) {
2840 return get_string('none');
2842 $data = self::parse_seconds($seconds);
2843 switch ($data['u']) {
2844 case (60*60*24*7):
2845 return get_string('numweeks', '', $data['v']);
2846 case (60*60*24):
2847 return get_string('numdays', '', $data['v']);
2848 case (60*60):
2849 return get_string('numhours', '', $data['v']);
2850 case (60):
2851 return get_string('numminutes', '', $data['v']);
2852 default:
2853 return get_string('numseconds', '', $data['v']*$data['u']);
2858 * Finds suitable units for given duration.
2859 * @static
2860 * @param int $seconds
2861 * @return array
2863 protected static function parse_seconds($seconds) {
2864 foreach (self::get_units() as $unit => $unused) {
2865 if ($seconds % $unit === 0) {
2866 return array('v'=>(int)($seconds/$unit), 'u'=>$unit);
2869 return array('v'=>(int)$seconds, 'u'=>1);
2873 * Get the selected duration as array.
2875 * @return mixed An array containing 'v'=>xx, 'u'=>xx, or null if not set
2877 public function get_setting() {
2878 $seconds = $this->config_read($this->name);
2879 if (is_null($seconds)) {
2880 return null;
2883 return self::parse_seconds($seconds);
2887 * Store the duration as seconds.
2889 * @param array $data Must be form 'h'=>xx, 'm'=>xx
2890 * @return bool true if success, false if not
2892 public function write_setting($data) {
2893 if (!is_array($data)) {
2894 return '';
2897 $seconds = (int)($data['v']*$data['u']);
2898 if ($seconds < 0) {
2899 return get_string('errorsetting', 'admin');
2902 $result = $this->config_write($this->name, $seconds);
2903 return ($result ? '' : get_string('errorsetting', 'admin'));
2907 * Returns duration text+select fields.
2909 * @param array $data Must be form 'v'=>xx, 'u'=>xx
2910 * @param string $query
2911 * @return string duration text+select fields and wrapping div(s)
2913 public function output_html($data, $query='') {
2914 $default = $this->get_defaultsetting();
2916 if (is_number($default)) {
2917 $defaultinfo = self::get_duration_text($default);
2918 } else if (is_array($default)) {
2919 $defaultinfo = self::get_duration_text($default['v']*$default['u']);
2920 } else {
2921 $defaultinfo = null;
2924 $units = self::get_units();
2926 $return = '<div class="form-duration defaultsnext">';
2927 $return .= '<input type="text" size="5" id="'.$this->get_id().'v" name="'.$this->get_full_name().'[v]" value="'.s($data['v']).'" />';
2928 $return .= '<select id="'.$this->get_id().'u" name="'.$this->get_full_name().'[u]">';
2929 foreach ($units as $val => $text) {
2930 $selected = '';
2931 if ($data['v'] == 0) {
2932 if ($val == $this->defaultunit) {
2933 $selected = ' selected="selected"';
2935 } else if ($val == $data['u']) {
2936 $selected = ' selected="selected"';
2938 $return .= '<option value="'.$val.'"'.$selected.'>'.$text.'</option>';
2940 $return .= '</select></div>';
2941 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
2947 * Used to validate a textarea used for ip addresses
2949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2951 class admin_setting_configiplist extends admin_setting_configtextarea {
2954 * Validate the contents of the textarea as IP addresses
2956 * Used to validate a new line separated list of IP addresses collected from
2957 * a textarea control
2959 * @param string $data A list of IP Addresses separated by new lines
2960 * @return mixed bool true for success or string:error on failure
2962 public function validate($data) {
2963 if(!empty($data)) {
2964 $ips = explode("\n", $data);
2965 } else {
2966 return true;
2968 $result = true;
2969 foreach($ips as $ip) {
2970 $ip = trim($ip);
2971 if (preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
2972 preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
2973 preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
2974 $result = true;
2975 } else {
2976 $result = false;
2977 break;
2980 if($result) {
2981 return true;
2982 } else {
2983 return get_string('validateerror', 'admin');
2990 * An admin setting for selecting one or more users who have a capability
2991 * in the system context
2993 * An admin setting for selecting one or more users, who have a particular capability
2994 * in the system context. Warning, make sure the list will never be too long. There is
2995 * no paging or searching of this list.
2997 * To correctly get a list of users from this config setting, you need to call the
2998 * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
3000 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3002 class admin_setting_users_with_capability extends admin_setting_configmultiselect {
3003 /** @var string The capabilities name */
3004 protected $capability;
3005 /** @var int include admin users too */
3006 protected $includeadmins;
3009 * Constructor.
3011 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
3012 * @param string $visiblename localised name
3013 * @param string $description localised long description
3014 * @param array $defaultsetting array of usernames
3015 * @param string $capability string capability name.
3016 * @param bool $includeadmins include administrators
3018 function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
3019 $this->capability = $capability;
3020 $this->includeadmins = $includeadmins;
3021 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3025 * Load all of the uses who have the capability into choice array
3027 * @return bool Always returns true
3029 function load_choices() {
3030 if (is_array($this->choices)) {
3031 return true;
3033 list($sort, $sortparams) = users_order_by_sql('u');
3034 if (!empty($sortparams)) {
3035 throw new coding_exception('users_order_by_sql returned some query parameters. ' .
3036 'This is unexpected, and a problem because there is no way to pass these ' .
3037 'parameters to get_users_by_capability. See MDL-34657.');
3039 $users = get_users_by_capability(context_system::instance(),
3040 $this->capability, 'u.id,u.username,u.firstname,u.lastname', $sort);
3041 $this->choices = array(
3042 '$@NONE@$' => get_string('nobody'),
3043 '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
3045 if ($this->includeadmins) {
3046 $admins = get_admins();
3047 foreach ($admins as $user) {
3048 $this->choices[$user->id] = fullname($user);
3051 if (is_array($users)) {
3052 foreach ($users as $user) {
3053 $this->choices[$user->id] = fullname($user);
3056 return true;
3060 * Returns the default setting for class
3062 * @return mixed Array, or string. Empty string if no default
3064 public function get_defaultsetting() {
3065 $this->load_choices();
3066 $defaultsetting = parent::get_defaultsetting();
3067 if (empty($defaultsetting)) {
3068 return array('$@NONE@$');
3069 } else if (array_key_exists($defaultsetting, $this->choices)) {
3070 return $defaultsetting;
3071 } else {
3072 return '';
3077 * Returns the current setting
3079 * @return mixed array or string
3081 public function get_setting() {
3082 $result = parent::get_setting();
3083 if ($result === null) {
3084 // this is necessary for settings upgrade
3085 return null;
3087 if (empty($result)) {
3088 $result = array('$@NONE@$');
3090 return $result;
3094 * Save the chosen setting provided as $data
3096 * @param array $data
3097 * @return mixed string or array
3099 public function write_setting($data) {
3100 // If all is selected, remove any explicit options.
3101 if (in_array('$@ALL@$', $data)) {
3102 $data = array('$@ALL@$');
3104 // None never needs to be written to the DB.
3105 if (in_array('$@NONE@$', $data)) {
3106 unset($data[array_search('$@NONE@$', $data)]);
3108 return parent::write_setting($data);
3114 * Special checkbox for calendar - resets SESSION vars.
3116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3118 class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
3120 * Calls the parent::__construct with default values
3122 * name => calendar_adminseesall
3123 * visiblename => get_string('adminseesall', 'admin')
3124 * description => get_string('helpadminseesall', 'admin')
3125 * defaultsetting => 0
3127 public function __construct() {
3128 parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
3129 get_string('helpadminseesall', 'admin'), '0');
3133 * Stores the setting passed in $data
3135 * @param mixed gets converted to string for comparison
3136 * @return string empty string or error message
3138 public function write_setting($data) {
3139 global $SESSION;
3140 return parent::write_setting($data);
3145 * Special select for settings that are altered in setup.php and can not be altered on the fly
3147 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3149 class admin_setting_special_selectsetup extends admin_setting_configselect {
3151 * Reads the setting directly from the database
3153 * @return mixed
3155 public function get_setting() {
3156 // read directly from db!
3157 return get_config(NULL, $this->name);
3161 * Save the setting passed in $data
3163 * @param string $data The setting to save
3164 * @return string empty or error message
3166 public function write_setting($data) {
3167 global $CFG;
3168 // do not change active CFG setting!
3169 $current = $CFG->{$this->name};
3170 $result = parent::write_setting($data);
3171 $CFG->{$this->name} = $current;
3172 return $result;
3178 * Special select for frontpage - stores data in course table
3180 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3182 class admin_setting_sitesetselect extends admin_setting_configselect {
3184 * Returns the site name for the selected site
3186 * @see get_site()
3187 * @return string The site name of the selected site
3189 public function get_setting() {
3190 $site = course_get_format(get_site())->get_course();
3191 return $site->{$this->name};
3195 * Updates the database and save the setting
3197 * @param string data
3198 * @return string empty or error message
3200 public function write_setting($data) {
3201 global $DB, $SITE;
3202 if (!in_array($data, array_keys($this->choices))) {
3203 return get_string('errorsetting', 'admin');
3205 $record = new stdClass();
3206 $record->id = SITEID;
3207 $temp = $this->name;
3208 $record->$temp = $data;
3209 $record->timemodified = time();
3210 // update $SITE
3211 $SITE->{$this->name} = $data;
3212 course_get_format($SITE)->update_course_format_options($record);
3213 return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
3219 * Select for blog's bloglevel setting: if set to 0, will set blog_menu
3220 * block to hidden.
3222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3224 class admin_setting_bloglevel extends admin_setting_configselect {
3226 * Updates the database and save the setting
3228 * @param string data
3229 * @return string empty or error message
3231 public function write_setting($data) {
3232 global $DB, $CFG;
3233 if ($data == 0) {
3234 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 1");
3235 foreach ($blogblocks as $block) {
3236 $DB->set_field('block', 'visible', 0, array('id' => $block->id));
3238 } else {
3239 // reenable all blocks only when switching from disabled blogs
3240 if (isset($CFG->bloglevel) and $CFG->bloglevel == 0) {
3241 $blogblocks = $DB->get_records_select('block', "name LIKE 'blog_%' AND visible = 0");
3242 foreach ($blogblocks as $block) {
3243 $DB->set_field('block', 'visible', 1, array('id' => $block->id));
3247 return parent::write_setting($data);
3253 * Special select - lists on the frontpage - hacky
3255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3257 class admin_setting_courselist_frontpage extends admin_setting {
3258 /** @var array Array of choices value=>label */
3259 public $choices;
3262 * Construct override, requires one param
3264 * @param bool $loggedin Is the user logged in
3266 public function __construct($loggedin) {
3267 global $CFG;
3268 require_once($CFG->dirroot.'/course/lib.php');
3269 $name = 'frontpage'.($loggedin ? 'loggedin' : '');
3270 $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
3271 $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
3272 $defaults = array(FRONTPAGECOURSELIST);
3273 parent::__construct($name, $visiblename, $description, $defaults);
3277 * Loads the choices available
3279 * @return bool always returns true
3281 public function load_choices() {
3282 global $DB;
3283 if (is_array($this->choices)) {
3284 return true;
3286 $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
3287 FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
3288 FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
3289 FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
3290 'none' => get_string('none'));
3291 if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
3292 unset($this->choices[FRONTPAGECOURSELIST]);
3294 return true;
3298 * Returns the selected settings
3300 * @param mixed array or setting or null
3302 public function get_setting() {
3303 $result = $this->config_read($this->name);
3304 if (is_null($result)) {
3305 return NULL;
3307 if ($result === '') {
3308 return array();
3310 return explode(',', $result);
3314 * Save the selected options
3316 * @param array $data
3317 * @return mixed empty string (data is not an array) or bool true=success false=failure
3319 public function write_setting($data) {
3320 if (!is_array($data)) {
3321 return '';
3323 $this->load_choices();
3324 $save = array();
3325 foreach($data as $datum) {
3326 if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
3327 continue;
3329 $save[$datum] = $datum; // no duplicates
3331 return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
3335 * Return XHTML select field and wrapping div
3337 * @todo Add vartype handling to make sure $data is an array
3338 * @param array $data Array of elements to select by default
3339 * @return string XHTML select field and wrapping div
3341 public function output_html($data, $query='') {
3342 $this->load_choices();
3343 $currentsetting = array();
3344 foreach ($data as $key) {
3345 if ($key != 'none' and array_key_exists($key, $this->choices)) {
3346 $currentsetting[] = $key; // already selected first
3350 $return = '<div class="form-group">';
3351 for ($i = 0; $i < count($this->choices) - 1; $i++) {
3352 if (!array_key_exists($i, $currentsetting)) {
3353 $currentsetting[$i] = 'none'; //none
3355 $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
3356 foreach ($this->choices as $key => $value) {
3357 $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
3359 $return .= '</select>';
3360 if ($i !== count($this->choices) - 2) {
3361 $return .= '<br />';
3364 $return .= '</div>';
3366 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3372 * Special checkbox for frontpage - stores data in course table
3374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3376 class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
3378 * Returns the current sites name
3380 * @return string
3382 public function get_setting() {
3383 $site = course_get_format(get_site())->get_course();
3384 return $site->{$this->name};
3388 * Save the selected setting
3390 * @param string $data The selected site
3391 * @return string empty string or error message
3393 public function write_setting($data) {
3394 global $DB, $SITE;
3395 $record = new stdClass();
3396 $record->id = $SITE->id;
3397 $record->{$this->name} = ($data == '1' ? 1 : 0);
3398 $record->timemodified = time();
3399 // update $SITE
3400 $SITE->{$this->name} = $data;
3401 course_get_format($SITE)->update_course_format_options($record);
3402 $DB->update_record('course', $record);
3403 // There is something wrong in cache updates somewhere, let's reset everything.
3404 format_base::reset_course_cache();
3405 return '';
3410 * Special text for frontpage - stores data in course table.
3411 * Empty string means not set here. Manual setting is required.
3413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3415 class admin_setting_sitesettext extends admin_setting_configtext {
3417 * Return the current setting
3419 * @return mixed string or null
3421 public function get_setting() {
3422 $site = course_get_format(get_site())->get_course();
3423 return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
3427 * Validate the selected data
3429 * @param string $data The selected value to validate
3430 * @return mixed true or message string
3432 public function validate($data) {
3433 $cleaned = clean_param($data, PARAM_TEXT);
3434 if ($cleaned === '') {
3435 return get_string('required');
3437 if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
3438 return true;
3439 } else {
3440 return get_string('validateerror', 'admin');
3445 * Save the selected setting
3447 * @param string $data The selected value
3448 * @return string empty or error message
3450 public function write_setting($data) {
3451 global $DB, $SITE;
3452 $data = trim($data);
3453 $validated = $this->validate($data);
3454 if ($validated !== true) {
3455 return $validated;
3458 $record = new stdClass();
3459 $record->id = $SITE->id;
3460 $record->{$this->name} = $data;
3461 $record->timemodified = time();
3462 // update $SITE
3463 $SITE->{$this->name} = $data;
3464 course_get_format($SITE)->update_course_format_options($record);
3465 $DB->update_record('course', $record);
3466 // There is something wrong in cache updates somewhere, let's reset everything.
3467 format_base::reset_course_cache();
3468 return '';
3474 * Special text editor for site description.
3476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3478 class admin_setting_special_frontpagedesc extends admin_setting {
3480 * Calls parent::__construct with specific arguments
3482 public function __construct() {
3483 parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
3484 editors_head_setup();
3488 * Return the current setting
3489 * @return string The current setting
3491 public function get_setting() {
3492 $site = course_get_format(get_site())->get_course();
3493 return $site->{$this->name};
3497 * Save the new setting
3499 * @param string $data The new value to save
3500 * @return string empty or error message
3502 public function write_setting($data) {
3503 global $DB, $SITE;
3504 $record = new stdClass();
3505 $record->id = $SITE->id;
3506 $record->{$this->name} = $data;
3507 $record->timemodified = time();
3508 $SITE->{$this->name} = $data;
3509 course_get_format($SITE)->update_course_format_options($record);
3510 $DB->update_record('course', $record);
3511 // There is something wrong in cache updates somewhere, let's reset everything.
3512 format_base::reset_course_cache();
3513 return '';
3517 * Returns XHTML for the field plus wrapping div
3519 * @param string $data The current value
3520 * @param string $query
3521 * @return string The XHTML output
3523 public function output_html($data, $query='') {
3524 global $CFG;
3526 $CFG->adminusehtmleditor = can_use_html_editor();
3527 $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
3529 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
3535 * Administration interface for emoticon_manager settings.
3537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3539 class admin_setting_emoticons extends admin_setting {
3542 * Calls parent::__construct with specific args
3544 public function __construct() {
3545 global $CFG;
3547 $manager = get_emoticon_manager();
3548 $defaults = $this->prepare_form_data($manager->default_emoticons());
3549 parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
3553 * Return the current setting(s)
3555 * @return array Current settings array
3557 public function get_setting() {
3558 global $CFG;
3560 $manager = get_emoticon_manager();
3562 $config = $this->config_read($this->name);
3563 if (is_null($config)) {
3564 return null;
3567 $config = $manager->decode_stored_config($config);
3568 if (is_null($config)) {
3569 return null;
3572 return $this->prepare_form_data($config);
3576 * Save selected settings
3578 * @param array $data Array of settings to save
3579 * @return bool
3581 public function write_setting($data) {
3583 $manager = get_emoticon_manager();
3584 $emoticons = $this->process_form_data($data);
3586 if ($emoticons === false) {
3587 return false;
3590 if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
3591 return ''; // success
3592 } else {
3593 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
3598 * Return XHTML field(s) for options
3600 * @param array $data Array of options to set in HTML
3601 * @return string XHTML string for the fields and wrapping div(s)
3603 public function output_html($data, $query='') {
3604 global $OUTPUT;
3606 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
3607 $out .= html_writer::start_tag('thead');
3608 $out .= html_writer::start_tag('tr');
3609 $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
3610 $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
3611 $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
3612 $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
3613 $out .= html_writer::tag('th', '');
3614 $out .= html_writer::end_tag('tr');
3615 $out .= html_writer::end_tag('thead');
3616 $out .= html_writer::start_tag('tbody');
3617 $i = 0;
3618 foreach($data as $field => $value) {
3619 switch ($i) {
3620 case 0:
3621 $out .= html_writer::start_tag('tr');
3622 $current_text = $value;
3623 $current_filename = '';
3624 $current_imagecomponent = '';
3625 $current_altidentifier = '';
3626 $current_altcomponent = '';
3627 case 1:
3628 $current_filename = $value;
3629 case 2:
3630 $current_imagecomponent = $value;
3631 case 3:
3632 $current_altidentifier = $value;
3633 case 4:
3634 $current_altcomponent = $value;
3637 $out .= html_writer::tag('td',
3638 html_writer::empty_tag('input',
3639 array(
3640 'type' => 'text',
3641 'class' => 'form-text',
3642 'name' => $this->get_full_name().'['.$field.']',
3643 'value' => $value,
3645 ), array('class' => 'c'.$i)
3648 if ($i == 4) {
3649 if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
3650 $alt = get_string($current_altidentifier, $current_altcomponent);
3651 } else {
3652 $alt = $current_text;
3654 if ($current_filename) {
3655 $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
3656 } else {
3657 $out .= html_writer::tag('td', '');
3659 $out .= html_writer::end_tag('tr');
3660 $i = 0;
3661 } else {
3662 $i++;
3666 $out .= html_writer::end_tag('tbody');
3667 $out .= html_writer::end_tag('table');
3668 $out = html_writer::tag('div', $out, array('class' => 'form-group'));
3669 $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
3671 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
3675 * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
3677 * @see self::process_form_data()
3678 * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
3679 * @return array of form fields and their values
3681 protected function prepare_form_data(array $emoticons) {
3683 $form = array();
3684 $i = 0;
3685 foreach ($emoticons as $emoticon) {
3686 $form['text'.$i] = $emoticon->text;
3687 $form['imagename'.$i] = $emoticon->imagename;
3688 $form['imagecomponent'.$i] = $emoticon->imagecomponent;
3689 $form['altidentifier'.$i] = $emoticon->altidentifier;
3690 $form['altcomponent'.$i] = $emoticon->altcomponent;
3691 $i++;
3693 // add one more blank field set for new object
3694 $form['text'.$i] = '';
3695 $form['imagename'.$i] = '';
3696 $form['imagecomponent'.$i] = '';
3697 $form['altidentifier'.$i] = '';
3698 $form['altcomponent'.$i] = '';
3700 return $form;
3704 * Converts the data from admin settings form into an array of emoticon objects
3706 * @see self::prepare_form_data()
3707 * @param array $data array of admin form fields and values
3708 * @return false|array of emoticon objects
3710 protected function process_form_data(array $form) {
3712 $count = count($form); // number of form field values
3714 if ($count % 5) {
3715 // we must get five fields per emoticon object
3716 return false;
3719 $emoticons = array();
3720 for ($i = 0; $i < $count / 5; $i++) {
3721 $emoticon = new stdClass();
3722 $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
3723 $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
3724 $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_COMPONENT);
3725 $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
3726 $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_COMPONENT);
3728 if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
3729 // prevent from breaking http://url.addresses by accident
3730 $emoticon->text = '';
3733 if (strlen($emoticon->text) < 2) {
3734 // do not allow single character emoticons
3735 $emoticon->text = '';
3738 if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
3739 // emoticon text must contain some non-alphanumeric character to prevent
3740 // breaking HTML tags
3741 $emoticon->text = '';
3744 if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
3745 $emoticons[] = $emoticon;
3748 return $emoticons;
3754 * Special setting for limiting of the list of available languages.
3756 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3758 class admin_setting_langlist extends admin_setting_configtext {
3760 * Calls parent::__construct with specific arguments
3762 public function __construct() {
3763 parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
3767 * Save the new setting
3769 * @param string $data The new setting
3770 * @return bool
3772 public function write_setting($data) {
3773 $return = parent::write_setting($data);
3774 get_string_manager()->reset_caches();
3775 return $return;
3781 * Selection of one of the recognised countries using the list
3782 * returned by {@link get_list_of_countries()}.
3784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3786 class admin_settings_country_select extends admin_setting_configselect {
3787 protected $includeall;
3788 public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
3789 $this->includeall = $includeall;
3790 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3794 * Lazy-load the available choices for the select box
3796 public function load_choices() {
3797 global $CFG;
3798 if (is_array($this->choices)) {
3799 return true;
3801 $this->choices = array_merge(
3802 array('0' => get_string('choosedots')),
3803 get_string_manager()->get_list_of_countries($this->includeall));
3804 return true;
3810 * admin_setting_configselect for the default number of sections in a course,
3811 * simply so we can lazy-load the choices.
3813 * @copyright 2011 The Open University
3814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3816 class admin_settings_num_course_sections extends admin_setting_configselect {
3817 public function __construct($name, $visiblename, $description, $defaultsetting) {
3818 parent::__construct($name, $visiblename, $description, $defaultsetting, array());
3821 /** Lazy-load the available choices for the select box */
3822 public function load_choices() {
3823 $max = get_config('moodlecourse', 'maxsections');
3824 if (!isset($max) || !is_numeric($max)) {
3825 $max = 52;
3827 for ($i = 0; $i <= $max; $i++) {
3828 $this->choices[$i] = "$i";
3830 return true;
3836 * Course category selection
3838 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3840 class admin_settings_coursecat_select extends admin_setting_configselect {
3842 * Calls parent::__construct with specific arguments
3844 public function __construct($name, $visiblename, $description, $defaultsetting) {
3845 parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
3849 * Load the available choices for the select box
3851 * @return bool
3853 public function load_choices() {
3854 global $CFG;
3855 require_once($CFG->dirroot.'/course/lib.php');
3856 if (is_array($this->choices)) {
3857 return true;
3859 $this->choices = make_categories_options();
3860 return true;
3866 * Special control for selecting days to backup
3868 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3870 class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
3872 * Calls parent::__construct with specific arguments
3874 public function __construct() {
3875 parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
3876 $this->plugin = 'backup';
3880 * Load the available choices for the select box
3882 * @return bool Always returns true
3884 public function load_choices() {
3885 if (is_array($this->choices)) {
3886 return true;
3888 $this->choices = array();
3889 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3890 foreach ($days as $day) {
3891 $this->choices[$day] = get_string($day, 'calendar');
3893 return true;
3899 * Special debug setting
3901 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3903 class admin_setting_special_debug extends admin_setting_configselect {
3905 * Calls parent::__construct with specific arguments
3907 public function __construct() {
3908 parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
3912 * Load the available choices for the select box
3914 * @return bool
3916 public function load_choices() {
3917 if (is_array($this->choices)) {
3918 return true;
3920 $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
3921 DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
3922 DEBUG_NORMAL => get_string('debugnormal', 'admin'),
3923 DEBUG_ALL => get_string('debugall', 'admin'),
3924 DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
3925 return true;
3931 * Special admin control
3933 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3935 class admin_setting_special_calendar_weekend extends admin_setting {
3937 * Calls parent::__construct with specific arguments
3939 public function __construct() {
3940 $name = 'calendar_weekend';
3941 $visiblename = get_string('calendar_weekend', 'admin');
3942 $description = get_string('helpweekenddays', 'admin');
3943 $default = array ('0', '6'); // Saturdays and Sundays
3944 parent::__construct($name, $visiblename, $description, $default);
3948 * Gets the current settings as an array
3950 * @return mixed Null if none, else array of settings
3952 public function get_setting() {
3953 $result = $this->config_read($this->name);
3954 if (is_null($result)) {
3955 return NULL;
3957 if ($result === '') {
3958 return array();
3960 $settings = array();
3961 for ($i=0; $i<7; $i++) {
3962 if ($result & (1 << $i)) {
3963 $settings[] = $i;
3966 return $settings;
3970 * Save the new settings
3972 * @param array $data Array of new settings
3973 * @return bool
3975 public function write_setting($data) {
3976 if (!is_array($data)) {
3977 return '';
3979 unset($data['xxxxx']);
3980 $result = 0;
3981 foreach($data as $index) {
3982 $result |= 1 << $index;
3984 return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
3988 * Return XHTML to display the control
3990 * @param array $data array of selected days
3991 * @param string $query
3992 * @return string XHTML for display (field + wrapping div(s)
3994 public function output_html($data, $query='') {
3995 // The order matters very much because of the implied numeric keys
3996 $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
3997 $return = '<table><thead><tr>';
3998 $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
3999 foreach($days as $index => $day) {
4000 $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
4002 $return .= '</tr></thead><tbody><tr>';
4003 foreach($days as $index => $day) {
4004 $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>';
4006 $return .= '</tr></tbody></table>';
4008 return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
4015 * Admin setting that allows a user to pick a behaviour.
4017 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4019 class admin_setting_question_behaviour extends admin_setting_configselect {
4021 * @param string $name name of config variable
4022 * @param string $visiblename display name
4023 * @param string $description description
4024 * @param string $default default.
4026 public function __construct($name, $visiblename, $description, $default) {
4027 parent::__construct($name, $visiblename, $description, $default, NULL);
4031 * Load list of behaviours as choices
4032 * @return bool true => success, false => error.
4034 public function load_choices() {
4035 global $CFG;
4036 require_once($CFG->dirroot . '/question/engine/lib.php');
4037 $this->choices = question_engine::get_archetypal_behaviours();
4038 return true;
4044 * Admin setting that allows a user to pick appropriate roles for something.
4046 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4048 class admin_setting_pickroles extends admin_setting_configmulticheckbox {
4049 /** @var array Array of capabilities which identify roles */
4050 private $types;
4053 * @param string $name Name of config variable
4054 * @param string $visiblename Display name
4055 * @param string $description Description
4056 * @param array $types Array of archetypes which identify
4057 * roles that will be enabled by default.
4059 public function __construct($name, $visiblename, $description, $types) {
4060 parent::__construct($name, $visiblename, $description, NULL, NULL);
4061 $this->types = $types;
4065 * Load roles as choices
4067 * @return bool true=>success, false=>error
4069 public function load_choices() {
4070 global $CFG, $DB;
4071 if (during_initial_install()) {
4072 return false;
4074 if (is_array($this->choices)) {
4075 return true;
4077 if ($roles = get_all_roles()) {
4078 $this->choices = role_fix_names($roles, null, ROLENAME_ORIGINAL, true);
4079 return true;
4080 } else {
4081 return false;
4086 * Return the default setting for this control
4088 * @return array Array of default settings
4090 public function get_defaultsetting() {
4091 global $CFG;
4093 if (during_initial_install()) {
4094 return null;
4096 $result = array();
4097 foreach($this->types as $archetype) {
4098 if ($caproles = get_archetype_roles($archetype)) {
4099 foreach ($caproles as $caprole) {
4100 $result[$caprole->id] = 1;
4104 return $result;
4110 * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
4112 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4114 class admin_setting_configtext_with_advanced extends admin_setting_configtext {
4116 * Constructor
4117 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4118 * @param string $visiblename localised
4119 * @param string $description long localised info
4120 * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
4121 * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
4122 * @param int $size default field size
4124 public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
4125 parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
4129 * Loads the current setting and returns array
4131 * @return array Returns array value=>xx, __construct=>xx
4133 public function get_setting() {
4134 $value = parent::get_setting();
4135 $adv = $this->config_read($this->name.'_adv');
4136 if (is_null($value) or is_null($adv)) {
4137 return NULL;
4139 return array('value' => $value, 'adv' => $adv);
4143 * Saves the new settings passed in $data
4145 * @todo Add vartype handling to ensure $data is an array
4146 * @param array $data
4147 * @return mixed string or Array
4149 public function write_setting($data) {
4150 $error = parent::write_setting($data['value']);
4151 if (!$error) {
4152 $value = empty($data['adv']) ? 0 : 1;
4153 $this->config_write($this->name.'_adv', $value);
4155 return $error;
4159 * Return XHTML for the control
4161 * @param array $data Default data array
4162 * @param string $query
4163 * @return string XHTML to display control
4165 public function output_html($data, $query='') {
4166 $default = $this->get_defaultsetting();
4167 $defaultinfo = array();
4168 if (isset($default['value'])) {
4169 if ($default['value'] === '') {
4170 $defaultinfo[] = "''";
4171 } else {
4172 $defaultinfo[] = $default['value'];
4175 if (!empty($default['adv'])) {
4176 $defaultinfo[] = get_string('advanced');
4178 $defaultinfo = implode(', ', $defaultinfo);
4180 $adv = !empty($data['adv']);
4181 $return = '<div class="form-text defaultsnext">' .
4182 '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
4183 '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
4184 ' <input type="checkbox" class="form-checkbox" id="' .
4185 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4186 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4187 ' <label for="' . $this->get_id() . '_adv">' .
4188 get_string('advanced') . '</label></div>';
4190 return format_admin_setting($this, $this->visiblename, $return,
4191 $this->description, true, '', $defaultinfo, $query);
4197 * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
4199 * @copyright 2009 Petr Skoda (http://skodak.org)
4200 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4202 class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
4205 * Constructor
4206 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4207 * @param string $visiblename localised
4208 * @param string $description long localised info
4209 * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
4210 * @param string $yes value used when checked
4211 * @param string $no value used when not checked
4213 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4214 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4218 * Loads the current setting and returns array
4220 * @return array Returns array value=>xx, adv=>xx
4222 public function get_setting() {
4223 $value = parent::get_setting();
4224 $adv = $this->config_read($this->name.'_adv');
4225 if (is_null($value) or is_null($adv)) {
4226 return NULL;
4228 return array('value' => $value, 'adv' => $adv);
4232 * Sets the value for the setting
4234 * Sets the value for the setting to either the yes or no values
4235 * of the object by comparing $data to yes
4237 * @param mixed $data Gets converted to str for comparison against yes value
4238 * @return string empty string or error
4240 public function write_setting($data) {
4241 $error = parent::write_setting($data['value']);
4242 if (!$error) {
4243 $value = empty($data['adv']) ? 0 : 1;
4244 $this->config_write($this->name.'_adv', $value);
4246 return $error;
4250 * Returns an XHTML checkbox field and with extra advanced cehckbox
4252 * @param string $data If $data matches yes then checkbox is checked
4253 * @param string $query
4254 * @return string XHTML field
4256 public function output_html($data, $query='') {
4257 $defaults = $this->get_defaultsetting();
4258 $defaultinfo = array();
4259 if (!is_null($defaults)) {
4260 if ((string)$defaults['value'] === $this->yes) {
4261 $defaultinfo[] = get_string('checkboxyes', 'admin');
4262 } else {
4263 $defaultinfo[] = get_string('checkboxno', 'admin');
4265 if (!empty($defaults['adv'])) {
4266 $defaultinfo[] = get_string('advanced');
4269 $defaultinfo = implode(', ', $defaultinfo);
4271 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4272 $checked = 'checked="checked"';
4273 } else {
4274 $checked = '';
4276 if (!empty($data['adv'])) {
4277 $advanced = 'checked="checked"';
4278 } else {
4279 $advanced = '';
4282 $fullname = $this->get_full_name();
4283 $novalue = s($this->no);
4284 $yesvalue = s($this->yes);
4285 $id = $this->get_id();
4286 $stradvanced = get_string('advanced');
4287 $return = <<<EOT
4288 <div class="form-checkbox defaultsnext" >
4289 <input type="hidden" name="{$fullname}[value]" value="$novalue" />
4290 <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
4291 <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
4292 <label for="{$id}_adv">$stradvanced</label>
4293 </div>
4294 EOT;
4295 return format_admin_setting($this, $this->visiblename, $return, $this->description,
4296 true, '', $defaultinfo, $query);
4302 * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
4304 * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
4306 * @copyright 2010 Sam Hemelryk
4307 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4309 class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
4311 * Constructor
4312 * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
4313 * @param string $visiblename localised
4314 * @param string $description long localised info
4315 * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
4316 * @param string $yes value used when checked
4317 * @param string $no value used when not checked
4319 public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
4320 parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
4324 * Loads the current setting and returns array
4326 * @return array Returns array value=>xx, adv=>xx
4328 public function get_setting() {
4329 $value = parent::get_setting();
4330 $locked = $this->config_read($this->name.'_locked');
4331 if (is_null($value) or is_null($locked)) {
4332 return NULL;
4334 return array('value' => $value, 'locked' => $locked);
4338 * Sets the value for the setting
4340 * Sets the value for the setting to either the yes or no values
4341 * of the object by comparing $data to yes
4343 * @param mixed $data Gets converted to str for comparison against yes value
4344 * @return string empty string or error
4346 public function write_setting($data) {
4347 $error = parent::write_setting($data['value']);
4348 if (!$error) {
4349 $value = empty($data['locked']) ? 0 : 1;
4350 $this->config_write($this->name.'_locked', $value);
4352 return $error;
4356 * Returns an XHTML checkbox field and with extra locked checkbox
4358 * @param string $data If $data matches yes then checkbox is checked
4359 * @param string $query
4360 * @return string XHTML field
4362 public function output_html($data, $query='') {
4363 $defaults = $this->get_defaultsetting();
4364 $defaultinfo = array();
4365 if (!is_null($defaults)) {
4366 if ((string)$defaults['value'] === $this->yes) {
4367 $defaultinfo[] = get_string('checkboxyes', 'admin');
4368 } else {
4369 $defaultinfo[] = get_string('checkboxno', 'admin');
4371 if (!empty($defaults['locked'])) {
4372 $defaultinfo[] = get_string('locked', 'admin');
4375 $defaultinfo = implode(', ', $defaultinfo);
4377 $fullname = $this->get_full_name();
4378 $novalue = s($this->no);
4379 $yesvalue = s($this->yes);
4380 $id = $this->get_id();
4382 $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
4383 if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
4384 $checkboxparams['checked'] = 'checked';
4387 $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox locked-checkbox');
4388 if (!empty($data['locked'])) { // convert to strings before comparison
4389 $lockcheckboxparams['checked'] = 'checked';
4392 $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
4393 $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
4394 $return .= html_writer::empty_tag('input', $checkboxparams);
4395 $return .= html_writer::empty_tag('input', $lockcheckboxparams);
4396 $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
4397 $return .= html_writer::end_tag('div');
4398 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4404 * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
4406 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4408 class admin_setting_configselect_with_advanced extends admin_setting_configselect {
4410 * Calls parent::__construct with specific arguments
4412 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4413 parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
4417 * Loads the current setting and returns array
4419 * @return array Returns array value=>xx, adv=>xx
4421 public function get_setting() {
4422 $value = parent::get_setting();
4423 $adv = $this->config_read($this->name.'_adv');
4424 if (is_null($value) or is_null($adv)) {
4425 return NULL;
4427 return array('value' => $value, 'adv' => $adv);
4431 * Saves the new settings passed in $data
4433 * @todo Add vartype handling to ensure $data is an array
4434 * @param array $data
4435 * @return mixed string or Array
4437 public function write_setting($data) {
4438 $error = parent::write_setting($data['value']);
4439 if (!$error) {
4440 $value = empty($data['adv']) ? 0 : 1;
4441 $this->config_write($this->name.'_adv', $value);
4443 return $error;
4447 * Return XHTML for the control
4449 * @param array $data Default data array
4450 * @param string $query
4451 * @return string XHTML to display control
4453 public function output_html($data, $query='') {
4454 $default = $this->get_defaultsetting();
4455 $current = $this->get_setting();
4457 list($selecthtml, $warning) = $this->output_select_html($data['value'],
4458 $current['value'], $default['value'], '[value]');
4459 if (!$selecthtml) {
4460 return '';
4463 if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
4464 $defaultinfo = array();
4465 if (isset($this->choices[$default['value']])) {
4466 $defaultinfo[] = $this->choices[$default['value']];
4468 if (!empty($default['adv'])) {
4469 $defaultinfo[] = get_string('advanced');
4471 $defaultinfo = implode(', ', $defaultinfo);
4472 } else {
4473 $defaultinfo = '';
4476 $adv = !empty($data['adv']);
4477 $return = '<div class="form-select defaultsnext">' . $selecthtml .
4478 ' <input type="checkbox" class="form-checkbox" id="' .
4479 $this->get_id() . '_adv" name="' . $this->get_full_name() .
4480 '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
4481 ' <label for="' . $this->get_id() . '_adv">' .
4482 get_string('advanced') . '</label></div>';
4484 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
4490 * Graded roles in gradebook
4492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4494 class admin_setting_special_gradebookroles extends admin_setting_pickroles {
4496 * Calls parent::__construct with specific arguments
4498 public function __construct() {
4499 parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
4500 get_string('configgradebookroles', 'admin'),
4501 array('student'));
4508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4510 class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
4512 * Saves the new settings passed in $data
4514 * @param string $data
4515 * @return mixed string or Array
4517 public function write_setting($data) {
4518 global $CFG, $DB;
4520 $oldvalue = $this->config_read($this->name);
4521 $return = parent::write_setting($data);
4522 $newvalue = $this->config_read($this->name);
4524 if ($oldvalue !== $newvalue) {
4525 // force full regrading
4526 $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
4529 return $return;
4535 * Which roles to show on course description page
4537 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4539 class admin_setting_special_coursecontact extends admin_setting_pickroles {
4541 * Calls parent::__construct with specific arguments
4543 public function __construct() {
4544 parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
4545 get_string('coursecontact_desc', 'admin'),
4546 array('editingteacher'));
4553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4555 class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
4557 * Calls parent::__construct with specific arguments
4559 function admin_setting_special_gradelimiting() {
4560 parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
4561 get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
4565 * Force site regrading
4567 function regrade_all() {
4568 global $CFG;
4569 require_once("$CFG->libdir/gradelib.php");
4570 grade_force_site_regrading();
4574 * Saves the new settings
4576 * @param mixed $data
4577 * @return string empty string or error message
4579 function write_setting($data) {
4580 $previous = $this->get_setting();
4582 if ($previous === null) {
4583 if ($data) {
4584 $this->regrade_all();
4586 } else {
4587 if ($data != $previous) {
4588 $this->regrade_all();
4591 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
4598 * Primary grade export plugin - has state tracking.
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4602 class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
4604 * Calls parent::__construct with specific arguments
4606 public function __construct() {
4607 parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
4608 get_string('configgradeexport', 'admin'), array(), NULL);
4612 * Load the available choices for the multicheckbox
4614 * @return bool always returns true
4616 public function load_choices() {
4617 if (is_array($this->choices)) {
4618 return true;
4620 $this->choices = array();
4622 if ($plugins = get_plugin_list('gradeexport')) {
4623 foreach($plugins as $plugin => $unused) {
4624 $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
4627 return true;
4633 * Grade category settings
4635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4637 class admin_setting_gradecat_combo extends admin_setting {
4638 /** @var array Array of choices */
4639 public $choices;
4642 * Sets choices and calls parent::__construct with passed arguments
4643 * @param string $name
4644 * @param string $visiblename
4645 * @param string $description
4646 * @param mixed $defaultsetting string or array depending on implementation
4647 * @param array $choices An array of choices for the control
4649 public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
4650 $this->choices = $choices;
4651 parent::__construct($name, $visiblename, $description, $defaultsetting);
4655 * Return the current setting(s) array
4657 * @return array Array of value=>xx, forced=>xx, adv=>xx
4659 public function get_setting() {
4660 global $CFG;
4662 $value = $this->config_read($this->name);
4663 $flag = $this->config_read($this->name.'_flag');
4665 if (is_null($value) or is_null($flag)) {
4666 return NULL;
4669 $flag = (int)$flag;
4670 $forced = (boolean)(1 & $flag); // first bit
4671 $adv = (boolean)(2 & $flag); // second bit
4673 return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
4677 * Save the new settings passed in $data
4679 * @todo Add vartype handling to ensure $data is array
4680 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4681 * @return string empty or error message
4683 public function write_setting($data) {
4684 global $CFG;
4686 $value = $data['value'];
4687 $forced = empty($data['forced']) ? 0 : 1;
4688 $adv = empty($data['adv']) ? 0 : 2;
4689 $flag = ($forced | $adv); //bitwise or
4691 if (!in_array($value, array_keys($this->choices))) {
4692 return 'Error setting ';
4695 $oldvalue = $this->config_read($this->name);
4696 $oldflag = (int)$this->config_read($this->name.'_flag');
4697 $oldforced = (1 & $oldflag); // first bit
4699 $result1 = $this->config_write($this->name, $value);
4700 $result2 = $this->config_write($this->name.'_flag', $flag);
4702 // force regrade if needed
4703 if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
4704 require_once($CFG->libdir.'/gradelib.php');
4705 grade_category::updated_forced_settings();
4708 if ($result1 and $result2) {
4709 return '';
4710 } else {
4711 return get_string('errorsetting', 'admin');
4716 * Return XHTML to display the field and wrapping div
4718 * @todo Add vartype handling to ensure $data is array
4719 * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
4720 * @param string $query
4721 * @return string XHTML to display control
4723 public function output_html($data, $query='') {
4724 $value = $data['value'];
4725 $forced = !empty($data['forced']);
4726 $adv = !empty($data['adv']);
4728 $default = $this->get_defaultsetting();
4729 if (!is_null($default)) {
4730 $defaultinfo = array();
4731 if (isset($this->choices[$default['value']])) {
4732 $defaultinfo[] = $this->choices[$default['value']];
4734 if (!empty($default['forced'])) {
4735 $defaultinfo[] = get_string('force');
4737 if (!empty($default['adv'])) {
4738 $defaultinfo[] = get_string('advanced');
4740 $defaultinfo = implode(', ', $defaultinfo);
4742 } else {
4743 $defaultinfo = NULL;
4747 $return = '<div class="form-group">';
4748 $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
4749 foreach ($this->choices as $key => $val) {
4750 // the string cast is needed because key may be integer - 0 is equal to most strings!
4751 $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
4753 $return .= '</select>';
4754 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
4755 .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
4756 $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
4757 .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
4758 $return .= '</div>';
4760 return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
4766 * Selection of grade report in user profiles
4768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4770 class admin_setting_grade_profilereport extends admin_setting_configselect {
4772 * Calls parent::__construct with specific arguments
4774 public function __construct() {
4775 parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
4779 * Loads an array of choices for the configselect control
4781 * @return bool always return true
4783 public function load_choices() {
4784 if (is_array($this->choices)) {
4785 return true;
4787 $this->choices = array();
4789 global $CFG;
4790 require_once($CFG->libdir.'/gradelib.php');
4792 foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
4793 if (file_exists($plugindir.'/lib.php')) {
4794 require_once($plugindir.'/lib.php');
4795 $functionname = 'grade_report_'.$plugin.'_profilereport';
4796 if (function_exists($functionname)) {
4797 $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
4801 return true;
4807 * Special class for register auth selection
4809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4811 class admin_setting_special_registerauth extends admin_setting_configselect {
4813 * Calls parent::__construct with specific arguments
4815 public function __construct() {
4816 parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
4820 * Returns the default option
4822 * @return string empty or default option
4824 public function get_defaultsetting() {
4825 $this->load_choices();
4826 $defaultsetting = parent::get_defaultsetting();
4827 if (array_key_exists($defaultsetting, $this->choices)) {
4828 return $defaultsetting;
4829 } else {
4830 return '';
4835 * Loads the possible choices for the array
4837 * @return bool always returns true
4839 public function load_choices() {
4840 global $CFG;
4842 if (is_array($this->choices)) {
4843 return true;
4845 $this->choices = array();
4846 $this->choices[''] = get_string('disable');
4848 $authsenabled = get_enabled_auth_plugins(true);
4850 foreach ($authsenabled as $auth) {
4851 $authplugin = get_auth_plugin($auth);
4852 if (!$authplugin->can_signup()) {
4853 continue;
4855 // Get the auth title (from core or own auth lang files)
4856 $authtitle = $authplugin->get_title();
4857 $this->choices[$auth] = $authtitle;
4859 return true;
4865 * General plugins manager
4867 class admin_page_pluginsoverview extends admin_externalpage {
4870 * Sets basic information about the external page
4872 public function __construct() {
4873 global $CFG;
4874 parent::__construct('pluginsoverview', get_string('pluginsoverview', 'core_admin'),
4875 "$CFG->wwwroot/$CFG->admin/plugins.php");
4880 * Module manage page
4882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4884 class admin_page_managemods extends admin_externalpage {
4886 * Calls parent::__construct with specific arguments
4888 public function __construct() {
4889 global $CFG;
4890 parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
4894 * Try to find the specified module
4896 * @param string $query The module to search for
4897 * @return array
4899 public function search($query) {
4900 global $CFG, $DB;
4901 if ($result = parent::search($query)) {
4902 return $result;
4905 $found = false;
4906 if ($modules = $DB->get_records('modules')) {
4907 foreach ($modules as $module) {
4908 if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
4909 continue;
4911 if (strpos($module->name, $query) !== false) {
4912 $found = true;
4913 break;
4915 $strmodulename = get_string('modulename', $module->name);
4916 if (strpos(textlib::strtolower($strmodulename), $query) !== false) {
4917 $found = true;
4918 break;
4922 if ($found) {
4923 $result = new stdClass();
4924 $result->page = $this;
4925 $result->settings = array();
4926 return array($this->name => $result);
4927 } else {
4928 return array();
4935 * Special class for enrol plugins management.
4937 * @copyright 2010 Petr Skoda {@link http://skodak.org}
4938 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4940 class admin_setting_manageenrols extends admin_setting {
4942 * Calls parent::__construct with specific arguments
4944 public function __construct() {
4945 $this->nosave = true;
4946 parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
4950 * Always returns true, does nothing
4952 * @return true
4954 public function get_setting() {
4955 return true;
4959 * Always returns true, does nothing
4961 * @return true
4963 public function get_defaultsetting() {
4964 return true;
4968 * Always returns '', does not write anything
4970 * @return string Always returns ''
4972 public function write_setting($data) {
4973 // do not write any setting
4974 return '';
4978 * Checks if $query is one of the available enrol plugins
4980 * @param string $query The string to search for
4981 * @return bool Returns true if found, false if not
4983 public function is_related($query) {
4984 if (parent::is_related($query)) {
4985 return true;
4988 $query = textlib::strtolower($query);
4989 $enrols = enrol_get_plugins(false);
4990 foreach ($enrols as $name=>$enrol) {
4991 $localised = get_string('pluginname', 'enrol_'.$name);
4992 if (strpos(textlib::strtolower($name), $query) !== false) {
4993 return true;
4995 if (strpos(textlib::strtolower($localised), $query) !== false) {
4996 return true;
4999 return false;
5003 * Builds the XHTML to display the control
5005 * @param string $data Unused
5006 * @param string $query
5007 * @return string
5009 public function output_html($data, $query='') {
5010 global $CFG, $OUTPUT, $DB;
5012 // display strings
5013 $strup = get_string('up');
5014 $strdown = get_string('down');
5015 $strsettings = get_string('settings');
5016 $strenable = get_string('enable');
5017 $strdisable = get_string('disable');
5018 $struninstall = get_string('uninstallplugin', 'admin');
5019 $strusage = get_string('enrolusage', 'enrol');
5021 $enrols_available = enrol_get_plugins(false);
5022 $active_enrols = enrol_get_plugins(true);
5024 $allenrols = array();
5025 foreach ($active_enrols as $key=>$enrol) {
5026 $allenrols[$key] = true;
5028 foreach ($enrols_available as $key=>$enrol) {
5029 $allenrols[$key] = true;
5031 // now find all borked plugins and at least allow then to uninstall
5032 $borked = array();
5033 $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
5034 foreach ($condidates as $candidate) {
5035 if (empty($allenrols[$candidate])) {
5036 $allenrols[$candidate] = true;
5040 $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
5041 $return .= $OUTPUT->box_start('generalbox enrolsui');
5043 $table = new html_table();
5044 $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
5045 $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
5046 $table->width = '90%';
5047 $table->data = array();
5049 // iterate through enrol plugins and add to the display table
5050 $updowncount = 1;
5051 $enrolcount = count($active_enrols);
5052 $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
5053 $printed = array();
5054 foreach($allenrols as $enrol => $unused) {
5055 if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
5056 $name = get_string('pluginname', 'enrol_'.$enrol);
5057 } else {
5058 $name = $enrol;
5060 //usage
5061 $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
5062 $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
5063 $usage = "$ci / $cp";
5065 // hide/show link
5066 if (isset($active_enrols[$enrol])) {
5067 $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
5068 $hideshow = "<a href=\"$aurl\">";
5069 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
5070 $enabled = true;
5071 $displayname = "<span>$name</span>";
5072 } else if (isset($enrols_available[$enrol])) {
5073 $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
5074 $hideshow = "<a href=\"$aurl\">";
5075 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
5076 $enabled = false;
5077 $displayname = "<span class=\"dimmed_text\">$name</span>";
5078 } else {
5079 $hideshow = '';
5080 $enabled = false;
5081 $displayname = '<span class="notifyproblem">'.$name.'</span>';
5084 // up/down link (only if enrol is enabled)
5085 $updown = '';
5086 if ($enabled) {
5087 if ($updowncount > 1) {
5088 $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
5089 $updown .= "<a href=\"$aurl\">";
5090 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" class=\"iconsmall\" /></a>&nbsp;";
5091 } else {
5092 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5094 if ($updowncount < $enrolcount) {
5095 $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
5096 $updown .= "<a href=\"$aurl\">";
5097 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" class=\"iconsmall\" /></a>";
5098 } else {
5099 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5101 ++$updowncount;
5104 // settings link
5105 if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
5106 $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
5107 $settings = "<a href=\"$surl\">$strsettings</a>";
5108 } else {
5109 $settings = '';
5112 // uninstall
5113 $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
5114 $uninstall = "<a href=\"$aurl\">$struninstall</a>";
5116 // add a row to the table
5117 $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
5119 $printed[$enrol] = true;
5122 $return .= html_writer::table($table);
5123 $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
5124 $return .= $OUTPUT->box_end();
5125 return highlight($query, $return);
5131 * Blocks manage page
5133 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5135 class admin_page_manageblocks extends admin_externalpage {
5137 * Calls parent::__construct with specific arguments
5139 public function __construct() {
5140 global $CFG;
5141 parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
5145 * Search for a specific block
5147 * @param string $query The string to search for
5148 * @return array
5150 public function search($query) {
5151 global $CFG, $DB;
5152 if ($result = parent::search($query)) {
5153 return $result;
5156 $found = false;
5157 if ($blocks = $DB->get_records('block')) {
5158 foreach ($blocks as $block) {
5159 if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
5160 continue;
5162 if (strpos($block->name, $query) !== false) {
5163 $found = true;
5164 break;
5166 $strblockname = get_string('pluginname', 'block_'.$block->name);
5167 if (strpos(textlib::strtolower($strblockname), $query) !== false) {
5168 $found = true;
5169 break;
5173 if ($found) {
5174 $result = new stdClass();
5175 $result->page = $this;
5176 $result->settings = array();
5177 return array($this->name => $result);
5178 } else {
5179 return array();
5185 * Message outputs configuration
5187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5189 class admin_page_managemessageoutputs extends admin_externalpage {
5191 * Calls parent::__construct with specific arguments
5193 public function __construct() {
5194 global $CFG;
5195 parent::__construct('managemessageoutputs', get_string('managemessageoutputs', 'message'), new moodle_url('/admin/message.php'));
5199 * Search for a specific message processor
5201 * @param string $query The string to search for
5202 * @return array
5204 public function search($query) {
5205 global $CFG, $DB;
5206 if ($result = parent::search($query)) {
5207 return $result;
5210 $found = false;
5211 if ($processors = get_message_processors()) {
5212 foreach ($processors as $processor) {
5213 if (!$processor->available) {
5214 continue;
5216 if (strpos($processor->name, $query) !== false) {
5217 $found = true;
5218 break;
5220 $strprocessorname = get_string('pluginname', 'message_'.$processor->name);
5221 if (strpos(textlib::strtolower($strprocessorname), $query) !== false) {
5222 $found = true;
5223 break;
5227 if ($found) {
5228 $result = new stdClass();
5229 $result->page = $this;
5230 $result->settings = array();
5231 return array($this->name => $result);
5232 } else {
5233 return array();
5239 * Default message outputs configuration
5241 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5243 class admin_page_defaultmessageoutputs extends admin_page_managemessageoutputs {
5245 * Calls parent::__construct with specific arguments
5247 public function __construct() {
5248 global $CFG;
5249 admin_externalpage::__construct('defaultmessageoutputs', get_string('defaultmessageoutputs', 'message'), new moodle_url('/message/defaultoutputs.php'));
5255 * Manage question behaviours page
5257 * @copyright 2011 The Open University
5258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5260 class admin_page_manageqbehaviours extends admin_externalpage {
5262 * Constructor
5264 public function __construct() {
5265 global $CFG;
5266 parent::__construct('manageqbehaviours', get_string('manageqbehaviours', 'admin'),
5267 new moodle_url('/admin/qbehaviours.php'));
5271 * Search question behaviours for the specified string
5273 * @param string $query The string to search for in question behaviours
5274 * @return array
5276 public function search($query) {
5277 global $CFG;
5278 if ($result = parent::search($query)) {
5279 return $result;
5282 $found = false;
5283 require_once($CFG->dirroot . '/question/engine/lib.php');
5284 foreach (get_plugin_list('qbehaviour') as $behaviour => $notused) {
5285 if (strpos(textlib::strtolower(question_engine::get_behaviour_name($behaviour)),
5286 $query) !== false) {
5287 $found = true;
5288 break;
5291 if ($found) {
5292 $result = new stdClass();
5293 $result->page = $this;
5294 $result->settings = array();
5295 return array($this->name => $result);
5296 } else {
5297 return array();
5304 * Question type manage page
5306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5308 class admin_page_manageqtypes extends admin_externalpage {
5310 * Calls parent::__construct with specific arguments
5312 public function __construct() {
5313 global $CFG;
5314 parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'),
5315 new moodle_url('/admin/qtypes.php'));
5319 * Search question types for the specified string
5321 * @param string $query The string to search for in question types
5322 * @return array
5324 public function search($query) {
5325 global $CFG;
5326 if ($result = parent::search($query)) {
5327 return $result;
5330 $found = false;
5331 require_once($CFG->dirroot . '/question/engine/bank.php');
5332 foreach (question_bank::get_all_qtypes() as $qtype) {
5333 if (strpos(textlib::strtolower($qtype->local_name()), $query) !== false) {
5334 $found = true;
5335 break;
5338 if ($found) {
5339 $result = new stdClass();
5340 $result->page = $this;
5341 $result->settings = array();
5342 return array($this->name => $result);
5343 } else {
5344 return array();
5350 class admin_page_manageportfolios extends admin_externalpage {
5352 * Calls parent::__construct with specific arguments
5354 public function __construct() {
5355 global $CFG;
5356 parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
5357 "$CFG->wwwroot/$CFG->admin/portfolio.php");
5361 * Searches page for the specified string.
5362 * @param string $query The string to search for
5363 * @return bool True if it is found on this page
5365 public function search($query) {
5366 global $CFG;
5367 if ($result = parent::search($query)) {
5368 return $result;
5371 $found = false;
5372 $portfolios = get_plugin_list('portfolio');
5373 foreach ($portfolios as $p => $dir) {
5374 if (strpos($p, $query) !== false) {
5375 $found = true;
5376 break;
5379 if (!$found) {
5380 foreach (portfolio_instances(false, false) as $instance) {
5381 $title = $instance->get('name');
5382 if (strpos(textlib::strtolower($title), $query) !== false) {
5383 $found = true;
5384 break;
5389 if ($found) {
5390 $result = new stdClass();
5391 $result->page = $this;
5392 $result->settings = array();
5393 return array($this->name => $result);
5394 } else {
5395 return array();
5401 class admin_page_managerepositories extends admin_externalpage {
5403 * Calls parent::__construct with specific arguments
5405 public function __construct() {
5406 global $CFG;
5407 parent::__construct('managerepositories', get_string('manage',
5408 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
5412 * Searches page for the specified string.
5413 * @param string $query The string to search for
5414 * @return bool True if it is found on this page
5416 public function search($query) {
5417 global $CFG;
5418 if ($result = parent::search($query)) {
5419 return $result;
5422 $found = false;
5423 $repositories= get_plugin_list('repository');
5424 foreach ($repositories as $p => $dir) {
5425 if (strpos($p, $query) !== false) {
5426 $found = true;
5427 break;
5430 if (!$found) {
5431 foreach (repository::get_types() as $instance) {
5432 $title = $instance->get_typename();
5433 if (strpos(textlib::strtolower($title), $query) !== false) {
5434 $found = true;
5435 break;
5440 if ($found) {
5441 $result = new stdClass();
5442 $result->page = $this;
5443 $result->settings = array();
5444 return array($this->name => $result);
5445 } else {
5446 return array();
5453 * Special class for authentication administration.
5455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5457 class admin_setting_manageauths extends admin_setting {
5459 * Calls parent::__construct with specific arguments
5461 public function __construct() {
5462 $this->nosave = true;
5463 parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
5467 * Always returns true
5469 * @return true
5471 public function get_setting() {
5472 return true;
5476 * Always returns true
5478 * @return true
5480 public function get_defaultsetting() {
5481 return true;
5485 * Always returns '' and doesn't write anything
5487 * @return string Always returns ''
5489 public function write_setting($data) {
5490 // do not write any setting
5491 return '';
5495 * Search to find if Query is related to auth plugin
5497 * @param string $query The string to search for
5498 * @return bool true for related false for not
5500 public function is_related($query) {
5501 if (parent::is_related($query)) {
5502 return true;
5505 $authsavailable = get_plugin_list('auth');
5506 foreach ($authsavailable as $auth => $dir) {
5507 if (strpos($auth, $query) !== false) {
5508 return true;
5510 $authplugin = get_auth_plugin($auth);
5511 $authtitle = $authplugin->get_title();
5512 if (strpos(textlib::strtolower($authtitle), $query) !== false) {
5513 return true;
5516 return false;
5520 * Return XHTML to display control
5522 * @param mixed $data Unused
5523 * @param string $query
5524 * @return string highlight
5526 public function output_html($data, $query='') {
5527 global $CFG, $OUTPUT;
5530 // display strings
5531 $txt = get_strings(array('authenticationplugins', 'users', 'administration',
5532 'settings', 'edit', 'name', 'enable', 'disable',
5533 'up', 'down', 'none'));
5534 $txt->updown = "$txt->up/$txt->down";
5536 $authsavailable = get_plugin_list('auth');
5537 get_enabled_auth_plugins(true); // fix the list of enabled auths
5538 if (empty($CFG->auth)) {
5539 $authsenabled = array();
5540 } else {
5541 $authsenabled = explode(',', $CFG->auth);
5544 // construct the display array, with enabled auth plugins at the top, in order
5545 $displayauths = array();
5546 $registrationauths = array();
5547 $registrationauths[''] = $txt->disable;
5548 foreach ($authsenabled as $auth) {
5549 $authplugin = get_auth_plugin($auth);
5550 /// Get the auth title (from core or own auth lang files)
5551 $authtitle = $authplugin->get_title();
5552 /// Apply titles
5553 $displayauths[$auth] = $authtitle;
5554 if ($authplugin->can_signup()) {
5555 $registrationauths[$auth] = $authtitle;
5559 foreach ($authsavailable as $auth => $dir) {
5560 if (array_key_exists($auth, $displayauths)) {
5561 continue; //already in the list
5563 $authplugin = get_auth_plugin($auth);
5564 /// Get the auth title (from core or own auth lang files)
5565 $authtitle = $authplugin->get_title();
5566 /// Apply titles
5567 $displayauths[$auth] = $authtitle;
5568 if ($authplugin->can_signup()) {
5569 $registrationauths[$auth] = $authtitle;
5573 $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
5574 $return .= $OUTPUT->box_start('generalbox authsui');
5576 $table = new html_table();
5577 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
5578 $table->align = array('left', 'center', 'center', 'center');
5579 $table->data = array();
5580 $table->attributes['class'] = 'manageauthtable generaltable';
5582 //add always enabled plugins first
5583 $displayname = "<span>".$displayauths['manual']."</span>";
5584 $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
5585 //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
5586 $table->data[] = array($displayname, '', '', $settings);
5587 $displayname = "<span>".$displayauths['nologin']."</span>";
5588 $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
5589 $table->data[] = array($displayname, '', '', $settings);
5592 // iterate through auth plugins and add to the display table
5593 $updowncount = 1;
5594 $authcount = count($authsenabled);
5595 $url = "auth.php?sesskey=" . sesskey();
5596 foreach ($displayauths as $auth => $name) {
5597 if ($auth == 'manual' or $auth == 'nologin') {
5598 continue;
5600 // hide/show link
5601 if (in_array($auth, $authsenabled)) {
5602 $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
5603 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5604 // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
5605 $enabled = true;
5606 $displayname = "<span>$name</span>";
5608 else {
5609 $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
5610 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5611 // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
5612 $enabled = false;
5613 $displayname = "<span class=\"dimmed_text\">$name</span>";
5616 // up/down link (only if auth is enabled)
5617 $updown = '';
5618 if ($enabled) {
5619 if ($updowncount > 1) {
5620 $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
5621 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5623 else {
5624 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5626 if ($updowncount < $authcount) {
5627 $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
5628 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5630 else {
5631 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5633 ++ $updowncount;
5636 // settings link
5637 if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
5638 $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
5639 } else {
5640 $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
5643 // add a row to the table
5644 $table->data[] =array($displayname, $hideshow, $updown, $settings);
5646 $return .= html_writer::table($table);
5647 $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
5648 $return .= $OUTPUT->box_end();
5649 return highlight($query, $return);
5655 * Special class for authentication administration.
5657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5659 class admin_setting_manageeditors extends admin_setting {
5661 * Calls parent::__construct with specific arguments
5663 public function __construct() {
5664 $this->nosave = true;
5665 parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
5669 * Always returns true, does nothing
5671 * @return true
5673 public function get_setting() {
5674 return true;
5678 * Always returns true, does nothing
5680 * @return true
5682 public function get_defaultsetting() {
5683 return true;
5687 * Always returns '', does not write anything
5689 * @return string Always returns ''
5691 public function write_setting($data) {
5692 // do not write any setting
5693 return '';
5697 * Checks if $query is one of the available editors
5699 * @param string $query The string to search for
5700 * @return bool Returns true if found, false if not
5702 public function is_related($query) {
5703 if (parent::is_related($query)) {
5704 return true;
5707 $editors_available = editors_get_available();
5708 foreach ($editors_available as $editor=>$editorstr) {
5709 if (strpos($editor, $query) !== false) {
5710 return true;
5712 if (strpos(textlib::strtolower($editorstr), $query) !== false) {
5713 return true;
5716 return false;
5720 * Builds the XHTML to display the control
5722 * @param string $data Unused
5723 * @param string $query
5724 * @return string
5726 public function output_html($data, $query='') {
5727 global $CFG, $OUTPUT;
5729 // display strings
5730 $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
5731 'up', 'down', 'none'));
5732 $struninstall = get_string('uninstallplugin', 'admin');
5734 $txt->updown = "$txt->up/$txt->down";
5736 $editors_available = editors_get_available();
5737 $active_editors = explode(',', $CFG->texteditors);
5739 $active_editors = array_reverse($active_editors);
5740 foreach ($active_editors as $key=>$editor) {
5741 if (empty($editors_available[$editor])) {
5742 unset($active_editors[$key]);
5743 } else {
5744 $name = $editors_available[$editor];
5745 unset($editors_available[$editor]);
5746 $editors_available[$editor] = $name;
5749 if (empty($active_editors)) {
5750 //$active_editors = array('textarea');
5752 $editors_available = array_reverse($editors_available, true);
5753 $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
5754 $return .= $OUTPUT->box_start('generalbox editorsui');
5756 $table = new html_table();
5757 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings, $struninstall);
5758 $table->align = array('left', 'center', 'center', 'center', 'center');
5759 $table->width = '90%';
5760 $table->data = array();
5762 // iterate through auth plugins and add to the display table
5763 $updowncount = 1;
5764 $editorcount = count($active_editors);
5765 $url = "editors.php?sesskey=" . sesskey();
5766 foreach ($editors_available as $editor => $name) {
5767 // hide/show link
5768 if (in_array($editor, $active_editors)) {
5769 $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
5770 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>";
5771 // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
5772 $enabled = true;
5773 $displayname = "<span>$name</span>";
5775 else {
5776 $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
5777 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>";
5778 // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
5779 $enabled = false;
5780 $displayname = "<span class=\"dimmed_text\">$name</span>";
5783 // up/down link (only if auth is enabled)
5784 $updown = '';
5785 if ($enabled) {
5786 if ($updowncount > 1) {
5787 $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
5788 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
5790 else {
5791 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />&nbsp;";
5793 if ($updowncount < $editorcount) {
5794 $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
5795 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
5797 else {
5798 $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />";
5800 ++ $updowncount;
5803 // settings link
5804 if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
5805 $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettings'.$editor));
5806 $settings = "<a href='$eurl'>{$txt->settings}</a>";
5807 } else {
5808 $settings = '';
5811 if ($editor === 'textarea') {
5812 $uninstall = '';
5813 } else {
5814 $uurl = new moodle_url('/admin/editors.php', array('action'=>'uninstall', 'editor'=>$editor, 'sesskey'=>sesskey()));
5815 $uninstall = html_writer::link($uurl, $struninstall);
5818 // add a row to the table
5819 $table->data[] =array($displayname, $hideshow, $updown, $settings, $uninstall);
5821 $return .= html_writer::table($table);
5822 $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
5823 $return .= $OUTPUT->box_end();
5824 return highlight($query, $return);
5830 * Special class for license administration.
5832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5834 class admin_setting_managelicenses extends admin_setting {
5836 * Calls parent::__construct with specific arguments
5838 public function __construct() {
5839 $this->nosave = true;
5840 parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
5844 * Always returns true, does nothing
5846 * @return true
5848 public function get_setting() {
5849 return true;
5853 * Always returns true, does nothing
5855 * @return true
5857 public function get_defaultsetting() {
5858 return true;
5862 * Always returns '', does not write anything
5864 * @return string Always returns ''
5866 public function write_setting($data) {
5867 // do not write any setting
5868 return '';
5872 * Builds the XHTML to display the control
5874 * @param string $data Unused
5875 * @param string $query
5876 * @return string
5878 public function output_html($data, $query='') {
5879 global $CFG, $OUTPUT;
5880 require_once($CFG->libdir . '/licenselib.php');
5881 $url = "licenses.php?sesskey=" . sesskey();
5883 // display strings
5884 $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
5885 $licenses = license_manager::get_licenses();
5887 $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
5889 $return .= $OUTPUT->box_start('generalbox editorsui');
5891 $table = new html_table();
5892 $table->head = array($txt->name, $txt->enable);
5893 $table->align = array('left', 'center');
5894 $table->width = '100%';
5895 $table->data = array();
5897 foreach ($licenses as $value) {
5898 $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
5900 if ($value->enabled == 1) {
5901 $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
5902 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/hide'), 'class'=>'iconsmall', 'alt'=>'disable')));
5903 } else {
5904 $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
5905 html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/show'), 'class'=>'iconsmall', 'alt'=>'enable')));
5908 if ($value->shortname == $CFG->sitedefaultlicense) {
5909 $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('t/locked'), 'class'=>'iconsmall', 'alt'=>get_string('default'), 'title'=>get_string('default')));
5910 $hideshow = '';
5913 $enabled = true;
5915 $table->data[] =array($displayname, $hideshow);
5917 $return .= html_writer::table($table);
5918 $return .= $OUTPUT->box_end();
5919 return highlight($query, $return);
5924 * Course formats manager. Allows to enable/disable formats and jump to settings
5926 class admin_setting_manageformats extends admin_setting {
5929 * Calls parent::__construct with specific arguments
5931 public function __construct() {
5932 $this->nosave = true;
5933 parent::__construct('formatsui', new lang_string('manageformats', 'core_admin'), '', '');
5937 * Always returns true
5939 * @return true
5941 public function get_setting() {
5942 return true;
5946 * Always returns true
5948 * @return true
5950 public function get_defaultsetting() {
5951 return true;
5955 * Always returns '' and doesn't write anything
5957 * @param mixed $data string or array, must not be NULL
5958 * @return string Always returns ''
5960 public function write_setting($data) {
5961 // do not write any setting
5962 return '';
5966 * Search to find if Query is related to format plugin
5968 * @param string $query The string to search for
5969 * @return bool true for related false for not
5971 public function is_related($query) {
5972 if (parent::is_related($query)) {
5973 return true;
5975 $allplugins = plugin_manager::instance()->get_plugins();
5976 $formats = $allplugins['format'];
5977 foreach ($formats as $format) {
5978 if (strpos($format->component, $query) !== false ||
5979 strpos(textlib::strtolower($format->displayname), $query) !== false) {
5980 return true;
5983 return false;
5987 * Return XHTML to display control
5989 * @param mixed $data Unused
5990 * @param string $query
5991 * @return string highlight
5993 public function output_html($data, $query='') {
5994 global $CFG, $OUTPUT;
5995 $return = '';
5996 $return = $OUTPUT->heading(new lang_string('courseformats'), 3, 'main');
5997 $return .= $OUTPUT->box_start('generalbox formatsui');
5999 $allplugins = plugin_manager::instance()->get_plugins();
6000 $formats = $allplugins['format'];
6002 // display strings
6003 $txt = get_strings(array('settings', 'name', 'enable', 'disable', 'up', 'down', 'default', 'delete'));
6004 $txt->updown = "$txt->up/$txt->down";
6006 $table = new html_table();
6007 $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->delete, $txt->settings);
6008 $table->align = array('left', 'center', 'center', 'center', 'center');
6009 $table->width = '90%';
6010 $table->attributes['class'] = 'manageformattable generaltable';
6011 $table->data = array();
6013 $cnt = 0;
6014 $defaultformat = get_config('moodlecourse', 'format');
6015 $spacer = $OUTPUT->pix_icon('spacer', '', 'moodle', array('class' => 'iconsmall'));
6016 foreach ($formats as $format) {
6017 $url = new moodle_url('/admin/courseformats.php',
6018 array('sesskey' => sesskey(), 'format' => $format->name));
6019 $isdefault = '';
6020 if ($format->is_enabled()) {
6021 $strformatname = html_writer::tag('span', $format->displayname);
6022 if ($defaultformat === $format->name) {
6023 $hideshow = $txt->default;
6024 } else {
6025 $hideshow = html_writer::link($url->out(false, array('action' => 'disable')),
6026 $OUTPUT->pix_icon('t/hide', $txt->disable, 'moodle', array('class' => 'iconsmall')));
6028 } else {
6029 $strformatname = html_writer::tag('span', $format->displayname, array('class' => 'dimmed_text'));
6030 $hideshow = html_writer::link($url->out(false, array('action' => 'enable')),
6031 $OUTPUT->pix_icon('t/show', $txt->enable, 'moodle', array('class' => 'iconsmall')));
6033 $updown = '';
6034 if ($cnt) {
6035 $updown .= html_writer::link($url->out(false, array('action' => 'up')),
6036 $OUTPUT->pix_icon('t/up', $txt->up, 'moodle', array('class' => 'iconsmall'))). '';
6037 } else {
6038 $updown .= $spacer;
6040 if ($cnt < count($formats) - 1) {
6041 $updown .= '&nbsp;'.html_writer::link($url->out(false, array('action' => 'down')),
6042 $OUTPUT->pix_icon('t/down', $txt->down, 'moodle', array('class' => 'iconsmall')));
6043 } else {
6044 $updown .= $spacer;
6046 $cnt++;
6047 $settings = '';
6048 if ($format->get_settings_url()) {
6049 $settings = html_writer::link($format->get_settings_url(), $txt->settings);
6051 $uninstall = '';
6052 if ($defaultformat !== $format->name) {
6053 $uninstall = html_writer::link($format->get_uninstall_url(), $txt->delete);
6055 $table->data[] =array($strformatname, $hideshow, $updown, $uninstall, $settings);
6057 $return .= html_writer::table($table);
6058 $link = html_writer::link(new moodle_url('/admin/settings.php', array('section' => 'coursesettings')), new lang_string('coursesettings'));
6059 $return .= html_writer::tag('p', get_string('manageformatsgotosettings', 'admin', $link));
6060 $return .= $OUTPUT->box_end();
6061 return highlight($query, $return);
6066 * Special class for filter administration.
6068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6070 class admin_page_managefilters extends admin_externalpage {
6072 * Calls parent::__construct with specific arguments
6074 public function __construct() {
6075 global $CFG;
6076 parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
6080 * Searches all installed filters for specified filter
6082 * @param string $query The filter(string) to search for
6083 * @param string $query
6085 public function search($query) {
6086 global $CFG;
6087 if ($result = parent::search($query)) {
6088 return $result;
6091 $found = false;
6092 $filternames = filter_get_all_installed();
6093 foreach ($filternames as $path => $strfiltername) {
6094 if (strpos(textlib::strtolower($strfiltername), $query) !== false) {
6095 $found = true;
6096 break;
6098 list($type, $filter) = explode('/', $path);
6099 if (strpos($filter, $query) !== false) {
6100 $found = true;
6101 break;
6105 if ($found) {
6106 $result = new stdClass;
6107 $result->page = $this;
6108 $result->settings = array();
6109 return array($this->name => $result);
6110 } else {
6111 return array();
6118 * Initialise admin page - this function does require login and permission
6119 * checks specified in page definition.
6121 * This function must be called on each admin page before other code.
6123 * @global moodle_page $PAGE
6125 * @param string $section name of page
6126 * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
6127 * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
6128 * added to the turn blocks editing on/off form, so this page reloads correctly.
6129 * @param string $actualurl if the actual page being viewed is not the normal one for this
6130 * page (e.g. admin/roles/allow.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
6131 * @param array $options Additional options that can be specified for page setup.
6132 * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
6134 function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
6135 global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
6137 $PAGE->set_context(null); // hack - set context to something, by default to system context
6139 $site = get_site();
6140 require_login();
6142 if (!empty($options['pagelayout'])) {
6143 // A specific page layout has been requested.
6144 $PAGE->set_pagelayout($options['pagelayout']);
6145 } else if ($section === 'upgradesettings') {
6146 $PAGE->set_pagelayout('maintenance');
6147 } else {
6148 $PAGE->set_pagelayout('admin');
6151 $adminroot = admin_get_root(false, false); // settings not required for external pages
6152 $extpage = $adminroot->locate($section, true);
6154 if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
6155 // The requested section isn't in the admin tree
6156 // It could be because the user has inadequate capapbilities or because the section doesn't exist
6157 if (!has_capability('moodle/site:config', context_system::instance())) {
6158 // The requested section could depend on a different capability
6159 // but most likely the user has inadequate capabilities
6160 print_error('accessdenied', 'admin');
6161 } else {
6162 print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
6166 // this eliminates our need to authenticate on the actual pages
6167 if (!$extpage->check_access()) {
6168 print_error('accessdenied', 'admin');
6169 die;
6172 // $PAGE->set_extra_button($extrabutton); TODO
6174 if (!$actualurl) {
6175 $actualurl = $extpage->url;
6178 $PAGE->set_url($actualurl, $extraurlparams);
6179 if (strpos($PAGE->pagetype, 'admin-') !== 0) {
6180 $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
6183 if (empty($SITE->fullname) || empty($SITE->shortname)) {
6184 // During initial install.
6185 $strinstallation = get_string('installation', 'install');
6186 $strsettings = get_string('settings');
6187 $PAGE->navbar->add($strsettings);
6188 $PAGE->set_title($strinstallation);
6189 $PAGE->set_heading($strinstallation);
6190 $PAGE->set_cacheable(false);
6191 return;
6194 // Locate the current item on the navigation and make it active when found.
6195 $path = $extpage->path;
6196 $node = $PAGE->settingsnav;
6197 while ($node && count($path) > 0) {
6198 $node = $node->get(array_pop($path));
6200 if ($node) {
6201 $node->make_active();
6204 // Normal case.
6205 $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
6206 if ($PAGE->user_allowed_editing() && $adminediting != -1) {
6207 $USER->editing = $adminediting;
6210 $visiblepathtosection = array_reverse($extpage->visiblepath);
6212 if ($PAGE->user_allowed_editing()) {
6213 if ($PAGE->user_is_editing()) {
6214 $caption = get_string('blockseditoff');
6215 $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
6216 } else {
6217 $caption = get_string('blocksediton');
6218 $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
6220 $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
6223 $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
6224 $PAGE->set_heading($SITE->fullname);
6226 // prevent caching in nav block
6227 $PAGE->navigation->clear_cache();
6231 * Returns the reference to admin tree root
6233 * @return object admin_root object
6235 function admin_get_root($reload=false, $requirefulltree=true) {
6236 global $CFG, $DB, $OUTPUT;
6238 static $ADMIN = NULL;
6240 if (is_null($ADMIN)) {
6241 // create the admin tree!
6242 $ADMIN = new admin_root($requirefulltree);
6245 if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
6246 $ADMIN->purge_children($requirefulltree);
6249 if (!$ADMIN->loaded) {
6250 // we process this file first to create categories first and in correct order
6251 require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
6253 // now we process all other files in admin/settings to build the admin tree
6254 foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
6255 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
6256 continue;
6258 if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
6259 // plugins are loaded last - they may insert pages anywhere
6260 continue;
6262 require($file);
6264 require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
6266 $ADMIN->loaded = true;
6269 return $ADMIN;
6272 /// settings utility functions
6275 * This function applies default settings.
6277 * @param object $node, NULL means complete tree, null by default
6278 * @param bool $unconditional if true overrides all values with defaults, null buy default
6280 function admin_apply_default_settings($node=NULL, $unconditional=true) {
6281 global $CFG;
6283 if (is_null($node)) {
6284 $node = admin_get_root(true, true);
6287 if ($node instanceof admin_category) {
6288 $entries = array_keys($node->children);
6289 foreach ($entries as $entry) {
6290 admin_apply_default_settings($node->children[$entry], $unconditional);
6293 } else if ($node instanceof admin_settingpage) {
6294 foreach ($node->settings as $setting) {
6295 if (!$unconditional and !is_null($setting->get_setting())) {
6296 //do not override existing defaults
6297 continue;
6299 $defaultsetting = $setting->get_defaultsetting();
6300 if (is_null($defaultsetting)) {
6301 // no value yet - default maybe applied after admin user creation or in upgradesettings
6302 continue;
6304 $setting->write_setting($defaultsetting);
6310 * Store changed settings, this function updates the errors variable in $ADMIN
6312 * @param object $formdata from form
6313 * @return int number of changed settings
6315 function admin_write_settings($formdata) {
6316 global $CFG, $SITE, $DB;
6318 $olddbsessions = !empty($CFG->dbsessions);
6319 $formdata = (array)$formdata;
6321 $data = array();
6322 foreach ($formdata as $fullname=>$value) {
6323 if (strpos($fullname, 's_') !== 0) {
6324 continue; // not a config value
6326 $data[$fullname] = $value;
6329 $adminroot = admin_get_root();
6330 $settings = admin_find_write_settings($adminroot, $data);
6332 $count = 0;
6333 foreach ($settings as $fullname=>$setting) {
6334 $original = serialize($setting->get_setting()); // comparison must work for arrays too
6335 $error = $setting->write_setting($data[$fullname]);
6336 if ($error !== '') {
6337 $adminroot->errors[$fullname] = new stdClass();
6338 $adminroot->errors[$fullname]->data = $data[$fullname];
6339 $adminroot->errors[$fullname]->id = $setting->get_id();
6340 $adminroot->errors[$fullname]->error = $error;
6342 if ($original !== serialize($setting->get_setting())) {
6343 $count++;
6344 $callbackfunction = $setting->updatedcallback;
6345 if (function_exists($callbackfunction)) {
6346 $callbackfunction($fullname);
6351 if ($olddbsessions != !empty($CFG->dbsessions)) {
6352 require_logout();
6355 // Now update $SITE - just update the fields, in case other people have a
6356 // a reference to it (e.g. $PAGE, $COURSE).
6357 $newsite = $DB->get_record('course', array('id'=>$SITE->id));
6358 foreach (get_object_vars($newsite) as $field => $value) {
6359 $SITE->$field = $value;
6362 // now reload all settings - some of them might depend on the changed
6363 admin_get_root(true);
6364 return $count;
6368 * Internal recursive function - finds all settings from submitted form
6370 * @param object $node Instance of admin_category, or admin_settingpage
6371 * @param array $data
6372 * @return array
6374 function admin_find_write_settings($node, $data) {
6375 $return = array();
6377 if (empty($data)) {
6378 return $return;
6381 if ($node instanceof admin_category) {
6382 $entries = array_keys($node->children);
6383 foreach ($entries as $entry) {
6384 $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
6387 } else if ($node instanceof admin_settingpage) {
6388 foreach ($node->settings as $setting) {
6389 $fullname = $setting->get_full_name();
6390 if (array_key_exists($fullname, $data)) {
6391 $return[$fullname] = $setting;
6397 return $return;
6401 * Internal function - prints the search results
6403 * @param string $query String to search for
6404 * @return string empty or XHTML
6406 function admin_search_settings_html($query) {
6407 global $CFG, $OUTPUT;
6409 if (textlib::strlen($query) < 2) {
6410 return '';
6412 $query = textlib::strtolower($query);
6414 $adminroot = admin_get_root();
6415 $findings = $adminroot->search($query);
6416 $return = '';
6417 $savebutton = false;
6419 foreach ($findings as $found) {
6420 $page = $found->page;
6421 $settings = $found->settings;
6422 if ($page->is_hidden()) {
6423 // hidden pages are not displayed in search results
6424 continue;
6426 if ($page instanceof admin_externalpage) {
6427 $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
6428 } else if ($page instanceof admin_settingpage) {
6429 $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');
6430 } else {
6431 continue;
6433 if (!empty($settings)) {
6434 $return .= '<fieldset class="adminsettings">'."\n";
6435 foreach ($settings as $setting) {
6436 if (empty($setting->nosave)) {
6437 $savebutton = true;
6439 $return .= '<div class="clearer"><!-- --></div>'."\n";
6440 $fullname = $setting->get_full_name();
6441 if (array_key_exists($fullname, $adminroot->errors)) {
6442 $data = $adminroot->errors[$fullname]->data;
6443 } else {
6444 $data = $setting->get_setting();
6445 // do not use defaults if settings not available - upgradesettings handles the defaults!
6447 $return .= $setting->output_html($data, $query);
6449 $return .= '</fieldset>';
6453 if ($savebutton) {
6454 $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
6457 return $return;
6461 * Internal function - returns arrays of html pages with uninitialised settings
6463 * @param object $node Instance of admin_category or admin_settingpage
6464 * @return array
6466 function admin_output_new_settings_by_page($node) {
6467 global $OUTPUT;
6468 $return = array();
6470 if ($node instanceof admin_category) {
6471 $entries = array_keys($node->children);
6472 foreach ($entries as $entry) {
6473 $return += admin_output_new_settings_by_page($node->children[$entry]);
6476 } else if ($node instanceof admin_settingpage) {
6477 $newsettings = array();
6478 foreach ($node->settings as $setting) {
6479 if (is_null($setting->get_setting())) {
6480 $newsettings[] = $setting;
6483 if (count($newsettings) > 0) {
6484 $adminroot = admin_get_root();
6485 $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
6486 $page .= '<fieldset class="adminsettings">'."\n";
6487 foreach ($newsettings as $setting) {
6488 $fullname = $setting->get_full_name();
6489 if (array_key_exists($fullname, $adminroot->errors)) {
6490 $data = $adminroot->errors[$fullname]->data;
6491 } else {
6492 $data = $setting->get_setting();
6493 if (is_null($data)) {
6494 $data = $setting->get_defaultsetting();
6497 $page .= '<div class="clearer"><!-- --></div>'."\n";
6498 $page .= $setting->output_html($data);
6500 $page .= '</fieldset>';
6501 $return[$node->name] = $page;
6505 return $return;
6509 * Format admin settings
6511 * @param object $setting
6512 * @param string $title label element
6513 * @param string $form form fragment, html code - not highlighted automatically
6514 * @param string $description
6515 * @param bool $label link label to id, true by default
6516 * @param string $warning warning text
6517 * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
6518 * @param string $query search query to be highlighted
6519 * @return string XHTML
6521 function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
6522 global $CFG;
6524 $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
6525 $fullname = $setting->get_full_name();
6527 // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
6528 if ($label) {
6529 $labelfor = 'for = "'.$setting->get_id().'"';
6530 } else {
6531 $labelfor = '';
6534 $override = '';
6535 if (empty($setting->plugin)) {
6536 if (array_key_exists($setting->name, $CFG->config_php_settings)) {
6537 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6539 } else {
6540 if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
6541 $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
6545 if ($warning !== '') {
6546 $warning = '<div class="form-warning">'.$warning.'</div>';
6549 if (is_null($defaultinfo)) {
6550 $defaultinfo = '';
6551 } else {
6552 if ($defaultinfo === '') {
6553 $defaultinfo = get_string('emptysettingvalue', 'admin');
6555 $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
6556 $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
6560 $str = '
6561 <div class="form-item clearfix" id="admin-'.$setting->name.'">
6562 <div class="form-label">
6563 <label '.$labelfor.'>'.highlightfast($query, $title).$override.$warning.'</label>
6564 <span class="form-shortname">'.highlightfast($query, $name).'</span>
6565 </div>
6566 <div class="form-setting">'.$form.$defaultinfo.'</div>
6567 <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
6568 </div>';
6570 $adminroot = admin_get_root();
6571 if (array_key_exists($fullname, $adminroot->errors)) {
6572 $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
6575 return $str;
6579 * Based on find_new_settings{@link ()} in upgradesettings.php
6580 * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
6582 * @param object $node Instance of admin_category, or admin_settingpage
6583 * @return boolean true if any settings haven't been initialised, false if they all have
6585 function any_new_admin_settings($node) {
6587 if ($node instanceof admin_category) {
6588 $entries = array_keys($node->children);
6589 foreach ($entries as $entry) {
6590 if (any_new_admin_settings($node->children[$entry])) {
6591 return true;
6595 } else if ($node instanceof admin_settingpage) {
6596 foreach ($node->settings as $setting) {
6597 if ($setting->get_setting() === NULL) {
6598 return true;
6603 return false;
6607 * Moved from admin/replace.php so that we can use this in cron
6609 * @param string $search string to look for
6610 * @param string $replace string to replace
6611 * @return bool success or fail
6613 function db_replace($search, $replace) {
6614 global $DB, $CFG, $OUTPUT;
6616 // TODO: this is horrible hack, we should do whitelisting and each plugin should be responsible for proper replacing...
6617 $skiptables = array('config', 'config_plugins', 'config_log', 'upgrade_log',
6618 'filter_config', 'sessions', 'events_queue', 'repository_instance_config',
6619 'block_instances', '');
6621 // Turn off time limits, sometimes upgrades can be slow.
6622 @set_time_limit(0);
6624 if (!$tables = $DB->get_tables() ) { // No tables yet at all.
6625 return false;
6627 foreach ($tables as $table) {
6629 if (in_array($table, $skiptables)) { // Don't process these
6630 continue;
6633 if ($columns = $DB->get_columns($table)) {
6634 $DB->set_debug(true);
6635 foreach ($columns as $column => $data) {
6636 if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
6637 //TODO: this should be definitively moved to DML driver to do the actual replace, this is not going to work for MSSQL and Oracle...
6638 $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
6641 $DB->set_debug(false);
6645 // delete modinfo caches
6646 rebuild_course_cache(0, true);
6648 // TODO: we should ask all plugins to do the search&replace, for now let's do only blocks...
6649 $blocks = get_plugin_list('block');
6650 foreach ($blocks as $blockname=>$fullblock) {
6651 if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
6652 continue;
6655 if (!is_readable($fullblock.'/lib.php')) {
6656 continue;
6659 $function = 'block_'.$blockname.'_global_db_replace';
6660 include_once($fullblock.'/lib.php');
6661 if (!function_exists($function)) {
6662 continue;
6665 echo $OUTPUT->notification("Replacing in $blockname blocks...", 'notifysuccess');
6666 $function($search, $replace);
6667 echo $OUTPUT->notification("...finished", 'notifysuccess');
6670 return true;
6674 * Manage repository settings
6676 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6678 class admin_setting_managerepository extends admin_setting {
6679 /** @var string */
6680 private $baseurl;
6683 * calls parent::__construct with specific arguments
6685 public function __construct() {
6686 global $CFG;
6687 parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
6688 $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
6692 * Always returns true, does nothing
6694 * @return true
6696 public function get_setting() {
6697 return true;
6701 * Always returns true does nothing
6703 * @return true
6705 public function get_defaultsetting() {
6706 return true;
6710 * Always returns s_managerepository
6712 * @return string Always return 's_managerepository'
6714 public function get_full_name() {
6715 return 's_managerepository';
6719 * Always returns '' doesn't do anything
6721 public function write_setting($data) {
6722 $url = $this->baseurl . '&amp;new=' . $data;
6723 return '';
6724 // TODO
6725 // Should not use redirect and exit here
6726 // Find a better way to do this.
6727 // redirect($url);
6728 // exit;
6732 * Searches repository plugins for one that matches $query
6734 * @param string $query The string to search for
6735 * @return bool true if found, false if not
6737 public function is_related($query) {
6738 if (parent::is_related($query)) {
6739 return true;
6742 $repositories= get_plugin_list('repository');
6743 foreach ($repositories as $p => $dir) {
6744 if (strpos($p, $query) !== false) {
6745 return true;
6748 foreach (repository::get_types() as $instance) {
6749 $title = $instance->get_typename();
6750 if (strpos(textlib::strtolower($title), $query) !== false) {
6751 return true;
6754 return false;
6758 * Helper function that generates a moodle_url object
6759 * relevant to the repository
6762 function repository_action_url($repository) {
6763 return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
6767 * Builds XHTML to display the control
6769 * @param string $data Unused
6770 * @param string $query
6771 * @return string XHTML
6773 public function output_html($data, $query='') {
6774 global $CFG, $USER, $OUTPUT;
6776 // Get strings that are used
6777 $strshow = get_string('on', 'repository');
6778 $strhide = get_string('off', 'repository');
6779 $strdelete = get_string('disabled', 'repository');
6781 $actionchoicesforexisting = array(
6782 'show' => $strshow,
6783 'hide' => $strhide,
6784 'delete' => $strdelete
6787 $actionchoicesfornew = array(
6788 'newon' => $strshow,
6789 'newoff' => $strhide,
6790 'delete' => $strdelete
6793 $return = '';
6794 $return .= $OUTPUT->box_start('generalbox');
6796 // Set strings that are used multiple times
6797 $settingsstr = get_string('settings');
6798 $disablestr = get_string('disable');
6800 // Table to list plug-ins
6801 $table = new html_table();
6802 $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
6803 $table->align = array('left', 'center', 'center', 'center', 'center');
6804 $table->data = array();
6806 // Get list of used plug-ins
6807 $instances = repository::get_types();
6808 if (!empty($instances)) {
6809 // Array to store plugins being used
6810 $alreadyplugins = array();
6811 $totalinstances = count($instances);
6812 $updowncount = 1;
6813 foreach ($instances as $i) {
6814 $settings = '';
6815 $typename = $i->get_typename();
6816 // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
6817 $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
6818 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
6820 if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
6821 // Calculate number of instances in order to display them for the Moodle administrator
6822 if (!empty($instanceoptionnames)) {
6823 $params = array();
6824 $params['context'] = array(get_system_context());
6825 $params['onlyvisible'] = false;
6826 $params['type'] = $typename;
6827 $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
6828 // site instances
6829 $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
6830 $params['context'] = array();
6831 $instances = repository::static_function($typename, 'get_instances', $params);
6832 $courseinstances = array();
6833 $userinstances = array();
6835 foreach ($instances as $instance) {
6836 if ($instance->context->contextlevel == CONTEXT_COURSE) {
6837 $courseinstances[] = $instance;
6838 } else if ($instance->context->contextlevel == CONTEXT_USER) {
6839 $userinstances[] = $instance;
6842 // course instances
6843 $instancenumber = count($courseinstances);
6844 $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
6846 // user private instances
6847 $instancenumber = count($userinstances);
6848 $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
6849 } else {
6850 $admininstancenumbertext = "";
6851 $courseinstancenumbertext = "";
6852 $userinstancenumbertext = "";
6855 $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
6857 $settings .= $OUTPUT->container_start('mdl-left');
6858 $settings .= '<br/>';
6859 $settings .= $admininstancenumbertext;
6860 $settings .= '<br/>';
6861 $settings .= $courseinstancenumbertext;
6862 $settings .= '<br/>';
6863 $settings .= $userinstancenumbertext;
6864 $settings .= $OUTPUT->container_end();
6866 // Get the current visibility
6867 if ($i->get_visible()) {
6868 $currentaction = 'show';
6869 } else {
6870 $currentaction = 'hide';
6873 $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
6875 // Display up/down link
6876 $updown = '';
6877 // Should be done with CSS instead.
6878 $spacer = $OUTPUT->spacer(array('height' => 15, 'width' => 15, 'class' => 'smallicon'));
6880 if ($updowncount > 1) {
6881 $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
6882 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a>&nbsp;";
6884 else {
6885 $updown .= $spacer;
6887 if ($updowncount < $totalinstances) {
6888 $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
6889 $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>";
6891 else {
6892 $updown .= $spacer;
6895 $updowncount++;
6897 $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
6899 if (!in_array($typename, $alreadyplugins)) {
6900 $alreadyplugins[] = $typename;
6905 // Get all the plugins that exist on disk
6906 $plugins = get_plugin_list('repository');
6907 if (!empty($plugins)) {
6908 foreach ($plugins as $plugin => $dir) {
6909 // Check that it has not already been listed
6910 if (!in_array($plugin, $alreadyplugins)) {
6911 $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
6912 $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
6917 $return .= html_writer::table($table);
6918 $return .= $OUTPUT->box_end();
6919 return highlight($query, $return);
6924 * Special checkbox for enable mobile web service
6925 * If enable then we store the service id of the mobile service into config table
6926 * If disable then we unstore the service id from the config table
6928 class admin_setting_enablemobileservice extends admin_setting_configcheckbox {
6930 /** @var boolean True means that the capability 'webservice/xmlrpc:use' is set for authenticated user role */
6931 private $xmlrpcuse;
6932 /** @var boolean True means that the capability 'webservice/rest:use' is set for authenticated user role */
6933 private $restuse;
6936 * Return true if Authenticated user role has the capability 'webservice/xmlrpc:use' and 'webservice/rest:use', otherwise false.
6938 * @return boolean
6940 private function is_protocol_cap_allowed() {
6941 global $DB, $CFG;
6943 // We keep xmlrpc enabled for backward compatibility.
6944 // If the $this->xmlrpcuse variable is not set, it needs to be set.
6945 if (empty($this->xmlrpcuse) and $this->xmlrpcuse!==false) {
6946 $params = array();
6947 $params['permission'] = CAP_ALLOW;
6948 $params['roleid'] = $CFG->defaultuserroleid;
6949 $params['capability'] = 'webservice/xmlrpc:use';
6950 $this->xmlrpcuse = $DB->record_exists('role_capabilities', $params);
6953 // If the $this->restuse variable is not set, it needs to be set.
6954 if (empty($this->restuse) and $this->restuse!==false) {
6955 $params = array();
6956 $params['permission'] = CAP_ALLOW;
6957 $params['roleid'] = $CFG->defaultuserroleid;
6958 $params['capability'] = 'webservice/rest:use';
6959 $this->restuse = $DB->record_exists('role_capabilities', $params);
6962 return ($this->xmlrpcuse && $this->restuse);
6966 * Set the 'webservice/xmlrpc:use'/'webservice/rest:use' to the Authenticated user role (allow or not)
6967 * @param type $status true to allow, false to not set
6969 private function set_protocol_cap($status) {
6970 global $CFG;
6971 if ($status and !$this->is_protocol_cap_allowed()) {
6972 //need to allow the cap
6973 $permission = CAP_ALLOW;
6974 $assign = true;
6975 } else if (!$status and $this->is_protocol_cap_allowed()){
6976 //need to disallow the cap
6977 $permission = CAP_INHERIT;
6978 $assign = true;
6980 if (!empty($assign)) {
6981 $systemcontext = get_system_context();
6982 assign_capability('webservice/xmlrpc:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6983 assign_capability('webservice/rest:use', $permission, $CFG->defaultuserroleid, $systemcontext->id, true);
6988 * Builds XHTML to display the control.
6989 * The main purpose of this overloading is to display a warning when https
6990 * is not supported by the server
6991 * @param string $data Unused
6992 * @param string $query
6993 * @return string XHTML
6995 public function output_html($data, $query='') {
6996 global $CFG, $OUTPUT;
6997 $html = parent::output_html($data, $query);
6999 if ((string)$data === $this->yes) {
7000 require_once($CFG->dirroot . "/lib/filelib.php");
7001 $curl = new curl();
7002 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); //force https url
7003 $curl->head($httpswwwroot . "/login/index.php");
7004 $info = $curl->get_info();
7005 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
7006 $html .= $OUTPUT->notification(get_string('nohttpsformobilewarning', 'admin'));
7010 return $html;
7014 * Retrieves the current setting using the objects name
7016 * @return string
7018 public function get_setting() {
7019 global $CFG;
7021 // For install cli script, $CFG->defaultuserroleid is not set so return 0
7022 // Or if web services aren't enabled this can't be,
7023 if (empty($CFG->defaultuserroleid) || empty($CFG->enablewebservices)) {
7024 return 0;
7027 require_once($CFG->dirroot . '/webservice/lib.php');
7028 $webservicemanager = new webservice();
7029 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7030 if ($mobileservice->enabled and $this->is_protocol_cap_allowed()) {
7031 return $this->config_read($this->name); //same as returning 1
7032 } else {
7033 return 0;
7038 * Save the selected setting
7040 * @param string $data The selected site
7041 * @return string empty string or error message
7043 public function write_setting($data) {
7044 global $DB, $CFG;
7046 //for install cli script, $CFG->defaultuserroleid is not set so do nothing
7047 if (empty($CFG->defaultuserroleid)) {
7048 return '';
7051 $servicename = MOODLE_OFFICIAL_MOBILE_SERVICE;
7053 require_once($CFG->dirroot . '/webservice/lib.php');
7054 $webservicemanager = new webservice();
7056 $updateprotocol = false;
7057 if ((string)$data === $this->yes) {
7058 //code run when enable mobile web service
7059 //enable web service systeme if necessary
7060 set_config('enablewebservices', true);
7062 //enable mobile service
7063 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7064 $mobileservice->enabled = 1;
7065 $webservicemanager->update_external_service($mobileservice);
7067 //enable xml-rpc server
7068 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7070 if (!in_array('xmlrpc', $activeprotocols)) {
7071 $activeprotocols[] = 'xmlrpc';
7072 $updateprotocol = true;
7075 if (!in_array('rest', $activeprotocols)) {
7076 $activeprotocols[] = 'rest';
7077 $updateprotocol = true;
7080 if ($updateprotocol) {
7081 set_config('webserviceprotocols', implode(',', $activeprotocols));
7084 //allow xml-rpc:use capability for authenticated user
7085 $this->set_protocol_cap(true);
7087 } else {
7088 //disable web service system if no other services are enabled
7089 $otherenabledservices = $DB->get_records_select('external_services',
7090 'enabled = :enabled AND (shortname != :shortname OR shortname IS NULL)', array('enabled' => 1,
7091 'shortname' => MOODLE_OFFICIAL_MOBILE_SERVICE));
7092 if (empty($otherenabledservices)) {
7093 set_config('enablewebservices', false);
7095 //also disable xml-rpc server
7096 $activeprotocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7097 $protocolkey = array_search('xmlrpc', $activeprotocols);
7098 if ($protocolkey !== false) {
7099 unset($activeprotocols[$protocolkey]);
7100 $updateprotocol = true;
7103 $protocolkey = array_search('rest', $activeprotocols);
7104 if ($protocolkey !== false) {
7105 unset($activeprotocols[$protocolkey]);
7106 $updateprotocol = true;
7109 if ($updateprotocol) {
7110 set_config('webserviceprotocols', implode(',', $activeprotocols));
7113 //disallow xml-rpc:use capability for authenticated user
7114 $this->set_protocol_cap(false);
7117 //disable the mobile service
7118 $mobileservice = $webservicemanager->get_external_service_by_shortname(MOODLE_OFFICIAL_MOBILE_SERVICE);
7119 $mobileservice->enabled = 0;
7120 $webservicemanager->update_external_service($mobileservice);
7123 return (parent::write_setting($data));
7128 * Special class for management of external services
7130 * @author Petr Skoda (skodak)
7132 class admin_setting_manageexternalservices extends admin_setting {
7134 * Calls parent::__construct with specific arguments
7136 public function __construct() {
7137 $this->nosave = true;
7138 parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
7142 * Always returns true, does nothing
7144 * @return true
7146 public function get_setting() {
7147 return true;
7151 * Always returns true, does nothing
7153 * @return true
7155 public function get_defaultsetting() {
7156 return true;
7160 * Always returns '', does not write anything
7162 * @return string Always returns ''
7164 public function write_setting($data) {
7165 // do not write any setting
7166 return '';
7170 * Checks if $query is one of the available external services
7172 * @param string $query The string to search for
7173 * @return bool Returns true if found, false if not
7175 public function is_related($query) {
7176 global $DB;
7178 if (parent::is_related($query)) {
7179 return true;
7182 $services = $DB->get_records('external_services', array(), 'id, name');
7183 foreach ($services as $service) {
7184 if (strpos(textlib::strtolower($service->name), $query) !== false) {
7185 return true;
7188 return false;
7192 * Builds the XHTML to display the control
7194 * @param string $data Unused
7195 * @param string $query
7196 * @return string
7198 public function output_html($data, $query='') {
7199 global $CFG, $OUTPUT, $DB;
7201 // display strings
7202 $stradministration = get_string('administration');
7203 $stredit = get_string('edit');
7204 $strservice = get_string('externalservice', 'webservice');
7205 $strdelete = get_string('delete');
7206 $strplugin = get_string('plugin', 'admin');
7207 $stradd = get_string('add');
7208 $strfunctions = get_string('functions', 'webservice');
7209 $strusers = get_string('users');
7210 $strserviceusers = get_string('serviceusers', 'webservice');
7212 $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
7213 $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
7214 $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
7216 // built in services
7217 $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
7218 $return = "";
7219 if (!empty($services)) {
7220 $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
7224 $table = new html_table();
7225 $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
7226 $table->align = array('left', 'left', 'center', 'center', 'center');
7227 $table->size = array('30%', '20%', '20%', '20%', '10%');
7228 $table->width = '100%';
7229 $table->data = array();
7231 // iterate through auth plugins and add to the display table
7232 foreach ($services as $service) {
7233 $name = $service->name;
7235 // hide/show link
7236 if ($service->enabled) {
7237 $displayname = "<span>$name</span>";
7238 } else {
7239 $displayname = "<span class=\"dimmed_text\">$name</span>";
7242 $plugin = $service->component;
7244 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7246 if ($service->restrictedusers) {
7247 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7248 } else {
7249 $users = get_string('allusers', 'webservice');
7252 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7254 // add a row to the table
7255 $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
7257 $return .= html_writer::table($table);
7260 // Custom services
7261 $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
7262 $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
7264 $table = new html_table();
7265 $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
7266 $table->align = array('left', 'center', 'center', 'center', 'center');
7267 $table->size = array('30%', '20%', '20%', '20%', '10%');
7268 $table->width = '100%';
7269 $table->data = array();
7271 // iterate through auth plugins and add to the display table
7272 foreach ($services as $service) {
7273 $name = $service->name;
7275 // hide/show link
7276 if ($service->enabled) {
7277 $displayname = "<span>$name</span>";
7278 } else {
7279 $displayname = "<span class=\"dimmed_text\">$name</span>";
7282 // delete link
7283 $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
7285 $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
7287 if ($service->restrictedusers) {
7288 $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
7289 } else {
7290 $users = get_string('allusers', 'webservice');
7293 $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
7295 // add a row to the table
7296 $table->data[] = array($displayname, $delete, $functions, $users, $edit);
7298 // add new custom service option
7299 $return .= html_writer::table($table);
7301 $return .= '<br />';
7302 // add a token to the table
7303 $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
7305 return highlight($query, $return);
7310 * Special class for overview of external services
7312 * @author Jerome Mouneyrac
7314 class admin_setting_webservicesoverview extends admin_setting {
7317 * Calls parent::__construct with specific arguments
7319 public function __construct() {
7320 $this->nosave = true;
7321 parent::__construct('webservicesoverviewui',
7322 get_string('webservicesoverview', 'webservice'), '', '');
7326 * Always returns true, does nothing
7328 * @return true
7330 public function get_setting() {
7331 return true;
7335 * Always returns true, does nothing
7337 * @return true
7339 public function get_defaultsetting() {
7340 return true;
7344 * Always returns '', does not write anything
7346 * @return string Always returns ''
7348 public function write_setting($data) {
7349 // do not write any setting
7350 return '';
7354 * Builds the XHTML to display the control
7356 * @param string $data Unused
7357 * @param string $query
7358 * @return string
7360 public function output_html($data, $query='') {
7361 global $CFG, $OUTPUT;
7363 $return = "";
7364 $brtag = html_writer::empty_tag('br');
7366 // Enable mobile web service
7367 $enablemobile = new admin_setting_enablemobileservice('enablemobilewebservice',
7368 get_string('enablemobilewebservice', 'admin'),
7369 get_string('configenablemobilewebservice',
7370 'admin', ''), 0); //we don't want to display it but to know the ws mobile status
7371 $manageserviceurl = new moodle_url("/admin/settings.php?section=externalservices");
7372 $wsmobileparam = new stdClass();
7373 $wsmobileparam->enablemobileservice = get_string('enablemobilewebservice', 'admin');
7374 $wsmobileparam->manageservicelink = html_writer::link($manageserviceurl,
7375 get_string('externalservices', 'webservice'));
7376 $mobilestatus = $enablemobile->get_setting()?get_string('mobilewsenabled', 'webservice'):get_string('mobilewsdisabled', 'webservice');
7377 $wsmobileparam->wsmobilestatus = html_writer::tag('strong', $mobilestatus);
7378 $return .= $OUTPUT->heading(get_string('enablemobilewebservice', 'admin'), 3, 'main');
7379 $return .= $brtag . get_string('enablemobilewsoverview', 'webservice', $wsmobileparam)
7380 . $brtag . $brtag;
7382 /// One system controlling Moodle with Token
7383 $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
7384 $table = new html_table();
7385 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7386 get_string('description'));
7387 $table->size = array('30%', '10%', '60%');
7388 $table->align = array('left', 'left', 'left');
7389 $table->width = '90%';
7390 $table->data = array();
7392 $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
7393 . $brtag . $brtag;
7395 /// 1. Enable Web Services
7396 $row = array();
7397 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7398 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7399 array('href' => $url));
7400 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7401 if ($CFG->enablewebservices) {
7402 $status = get_string('yes');
7404 $row[1] = $status;
7405 $row[2] = get_string('enablewsdescription', 'webservice');
7406 $table->data[] = $row;
7408 /// 2. Enable protocols
7409 $row = array();
7410 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7411 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7412 array('href' => $url));
7413 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7414 //retrieve activated protocol
7415 $active_protocols = empty($CFG->webserviceprotocols) ?
7416 array() : explode(',', $CFG->webserviceprotocols);
7417 if (!empty($active_protocols)) {
7418 $status = "";
7419 foreach ($active_protocols as $protocol) {
7420 $status .= $protocol . $brtag;
7423 $row[1] = $status;
7424 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7425 $table->data[] = $row;
7427 /// 3. Create user account
7428 $row = array();
7429 $url = new moodle_url("/user/editadvanced.php?id=-1");
7430 $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
7431 array('href' => $url));
7432 $row[1] = "";
7433 $row[2] = get_string('createuserdescription', 'webservice');
7434 $table->data[] = $row;
7436 /// 4. Add capability to users
7437 $row = array();
7438 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7439 $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
7440 array('href' => $url));
7441 $row[1] = "";
7442 $row[2] = get_string('checkusercapabilitydescription', 'webservice');
7443 $table->data[] = $row;
7445 /// 5. Select a web service
7446 $row = array();
7447 $url = new moodle_url("/admin/settings.php?section=externalservices");
7448 $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7449 array('href' => $url));
7450 $row[1] = "";
7451 $row[2] = get_string('createservicedescription', 'webservice');
7452 $table->data[] = $row;
7454 /// 6. Add functions
7455 $row = array();
7456 $url = new moodle_url("/admin/settings.php?section=externalservices");
7457 $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7458 array('href' => $url));
7459 $row[1] = "";
7460 $row[2] = get_string('addfunctionsdescription', 'webservice');
7461 $table->data[] = $row;
7463 /// 7. Add the specific user
7464 $row = array();
7465 $url = new moodle_url("/admin/settings.php?section=externalservices");
7466 $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
7467 array('href' => $url));
7468 $row[1] = "";
7469 $row[2] = get_string('selectspecificuserdescription', 'webservice');
7470 $table->data[] = $row;
7472 /// 8. Create token for the specific user
7473 $row = array();
7474 $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
7475 $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
7476 array('href' => $url));
7477 $row[1] = "";
7478 $row[2] = get_string('createtokenforuserdescription', 'webservice');
7479 $table->data[] = $row;
7481 /// 9. Enable the documentation
7482 $row = array();
7483 $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
7484 $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
7485 array('href' => $url));
7486 $status = '<span class="warning">' . get_string('no') . '</span>';
7487 if ($CFG->enablewsdocumentation) {
7488 $status = get_string('yes');
7490 $row[1] = $status;
7491 $row[2] = get_string('enabledocumentationdescription', 'webservice');
7492 $table->data[] = $row;
7494 /// 10. Test the service
7495 $row = array();
7496 $url = new moodle_url("/admin/webservice/testclient.php");
7497 $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7498 array('href' => $url));
7499 $row[1] = "";
7500 $row[2] = get_string('testwithtestclientdescription', 'webservice');
7501 $table->data[] = $row;
7503 $return .= html_writer::table($table);
7505 /// Users as clients with token
7506 $return .= $brtag . $brtag . $brtag;
7507 $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
7508 $table = new html_table();
7509 $table->head = array(get_string('step', 'webservice'), get_string('status'),
7510 get_string('description'));
7511 $table->size = array('30%', '10%', '60%');
7512 $table->align = array('left', 'left', 'left');
7513 $table->width = '90%';
7514 $table->data = array();
7516 $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
7517 $brtag . $brtag;
7519 /// 1. Enable Web Services
7520 $row = array();
7521 $url = new moodle_url("/admin/search.php?query=enablewebservices");
7522 $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
7523 array('href' => $url));
7524 $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
7525 if ($CFG->enablewebservices) {
7526 $status = get_string('yes');
7528 $row[1] = $status;
7529 $row[2] = get_string('enablewsdescription', 'webservice');
7530 $table->data[] = $row;
7532 /// 2. Enable protocols
7533 $row = array();
7534 $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
7535 $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
7536 array('href' => $url));
7537 $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
7538 //retrieve activated protocol
7539 $active_protocols = empty($CFG->webserviceprotocols) ?
7540 array() : explode(',', $CFG->webserviceprotocols);
7541 if (!empty($active_protocols)) {
7542 $status = "";
7543 foreach ($active_protocols as $protocol) {
7544 $status .= $protocol . $brtag;
7547 $row[1] = $status;
7548 $row[2] = get_string('enableprotocolsdescription', 'webservice');
7549 $table->data[] = $row;
7552 /// 3. Select a web service
7553 $row = array();
7554 $url = new moodle_url("/admin/settings.php?section=externalservices");
7555 $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
7556 array('href' => $url));
7557 $row[1] = "";
7558 $row[2] = get_string('createserviceforusersdescription', 'webservice');
7559 $table->data[] = $row;
7561 /// 4. Add functions
7562 $row = array();
7563 $url = new moodle_url("/admin/settings.php?section=externalservices");
7564 $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
7565 array('href' => $url));
7566 $row[1] = "";
7567 $row[2] = get_string('addfunctionsdescription', 'webservice');
7568 $table->data[] = $row;
7570 /// 5. Add capability to users
7571 $row = array();
7572 $url = new moodle_url("/admin/roles/check.php?contextid=1");
7573 $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
7574 array('href' => $url));
7575 $row[1] = "";
7576 $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
7577 $table->data[] = $row;
7579 /// 6. Test the service
7580 $row = array();
7581 $url = new moodle_url("/admin/webservice/testclient.php");
7582 $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
7583 array('href' => $url));
7584 $row[1] = "";
7585 $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
7586 $table->data[] = $row;
7588 $return .= html_writer::table($table);
7590 return highlight($query, $return);
7597 * Special class for web service protocol administration.
7599 * @author Petr Skoda (skodak)
7601 class admin_setting_managewebserviceprotocols extends admin_setting {
7604 * Calls parent::__construct with specific arguments
7606 public function __construct() {
7607 $this->nosave = true;
7608 parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
7612 * Always returns true, does nothing
7614 * @return true
7616 public function get_setting() {
7617 return true;
7621 * Always returns true, does nothing
7623 * @return true
7625 public function get_defaultsetting() {
7626 return true;
7630 * Always returns '', does not write anything
7632 * @return string Always returns ''
7634 public function write_setting($data) {
7635 // do not write any setting
7636 return '';
7640 * Checks if $query is one of the available webservices
7642 * @param string $query The string to search for
7643 * @return bool Returns true if found, false if not
7645 public function is_related($query) {
7646 if (parent::is_related($query)) {
7647 return true;
7650 $protocols = get_plugin_list('webservice');
7651 foreach ($protocols as $protocol=>$location) {
7652 if (strpos($protocol, $query) !== false) {
7653 return true;
7655 $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
7656 if (strpos(textlib::strtolower($protocolstr), $query) !== false) {
7657 return true;
7660 return false;
7664 * Builds the XHTML to display the control
7666 * @param string $data Unused
7667 * @param string $query
7668 * @return string
7670 public function output_html($data, $query='') {
7671 global $CFG, $OUTPUT;
7673 // display strings
7674 $stradministration = get_string('administration');
7675 $strsettings = get_string('settings');
7676 $stredit = get_string('edit');
7677 $strprotocol = get_string('protocol', 'webservice');
7678 $strenable = get_string('enable');
7679 $strdisable = get_string('disable');
7680 $strversion = get_string('version');
7681 $struninstall = get_string('uninstallplugin', 'admin');
7683 $protocols_available = get_plugin_list('webservice');
7684 $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
7685 ksort($protocols_available);
7687 foreach ($active_protocols as $key=>$protocol) {
7688 if (empty($protocols_available[$protocol])) {
7689 unset($active_protocols[$key]);
7693 $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
7694 $return .= $OUTPUT->box_start('generalbox webservicesui');
7696 $table = new html_table();
7697 $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
7698 $table->align = array('left', 'center', 'center', 'center', 'center');
7699 $table->width = '100%';
7700 $table->data = array();
7702 // iterate through auth plugins and add to the display table
7703 $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
7704 foreach ($protocols_available as $protocol => $location) {
7705 $name = get_string('pluginname', 'webservice_'.$protocol);
7707 $plugin = new stdClass();
7708 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
7709 include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
7711 $version = isset($plugin->version) ? $plugin->version : '';
7713 // hide/show link
7714 if (in_array($protocol, $active_protocols)) {
7715 $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
7716 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"$strdisable\" /></a>";
7717 $displayname = "<span>$name</span>";
7718 } else {
7719 $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
7720 $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"$strenable\" /></a>";
7721 $displayname = "<span class=\"dimmed_text\">$name</span>";
7724 // delete link
7725 $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
7727 // settings link
7728 if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
7729 $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
7730 } else {
7731 $settings = '';
7734 // add a row to the table
7735 $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
7737 $return .= html_writer::table($table);
7738 $return .= get_string('configwebserviceplugins', 'webservice');
7739 $return .= $OUTPUT->box_end();
7741 return highlight($query, $return);
7747 * Special class for web service token administration.
7749 * @author Jerome Mouneyrac
7751 class admin_setting_managewebservicetokens extends admin_setting {
7754 * Calls parent::__construct with specific arguments
7756 public function __construct() {
7757 $this->nosave = true;
7758 parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
7762 * Always returns true, does nothing
7764 * @return true
7766 public function get_setting() {
7767 return true;
7771 * Always returns true, does nothing
7773 * @return true
7775 public function get_defaultsetting() {
7776 return true;
7780 * Always returns '', does not write anything
7782 * @return string Always returns ''
7784 public function write_setting($data) {
7785 // do not write any setting
7786 return '';
7790 * Builds the XHTML to display the control
7792 * @param string $data Unused
7793 * @param string $query
7794 * @return string
7796 public function output_html($data, $query='') {
7797 global $CFG, $OUTPUT, $DB, $USER;
7799 // display strings
7800 $stroperation = get_string('operation', 'webservice');
7801 $strtoken = get_string('token', 'webservice');
7802 $strservice = get_string('service', 'webservice');
7803 $struser = get_string('user');
7804 $strcontext = get_string('context', 'webservice');
7805 $strvaliduntil = get_string('validuntil', 'webservice');
7806 $striprestriction = get_string('iprestriction', 'webservice');
7808 $return = $OUTPUT->box_start('generalbox webservicestokenui');
7810 $table = new html_table();
7811 $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
7812 $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
7813 $table->width = '100%';
7814 $table->data = array();
7816 $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
7818 //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
7820 //here retrieve token list (including linked users firstname/lastname and linked services name)
7821 $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.iprestriction, t.validuntil, s.id AS serviceid
7822 FROM {external_tokens} t, {user} u, {external_services} s
7823 WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
7824 $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
7825 if (!empty($tokens)) {
7826 foreach ($tokens as $token) {
7827 //TODO: retrieve context
7829 $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
7830 $delete .= get_string('delete')."</a>";
7832 $validuntil = '';
7833 if (!empty($token->validuntil)) {
7834 $validuntil = userdate($token->validuntil, get_string('strftimedatetime', 'langconfig'));
7837 $iprestriction = '';
7838 if (!empty($token->iprestriction)) {
7839 $iprestriction = $token->iprestriction;
7842 $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
7843 $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
7844 $useratag .= $token->firstname." ".$token->lastname;
7845 $useratag .= html_writer::end_tag('a');
7847 //check user missing capabilities
7848 require_once($CFG->dirroot . '/webservice/lib.php');
7849 $webservicemanager = new webservice();
7850 $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
7851 array(array('id' => $token->userid)), $token->serviceid);
7853 if (!is_siteadmin($token->userid) and
7854 array_key_exists($token->userid, $usermissingcaps)) {
7855 $missingcapabilities = implode(', ',
7856 $usermissingcaps[$token->userid]);
7857 if (!empty($missingcapabilities)) {
7858 $useratag .= html_writer::tag('div',
7859 get_string('usermissingcaps', 'webservice',
7860 $missingcapabilities)
7861 . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
7862 array('class' => 'missingcaps'));
7866 $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
7869 $return .= html_writer::table($table);
7870 } else {
7871 $return .= get_string('notoken', 'webservice');
7874 $return .= $OUTPUT->box_end();
7875 // add a token to the table
7876 $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
7877 $return .= get_string('add')."</a>";
7879 return highlight($query, $return);
7885 * Colour picker
7887 * @copyright 2010 Sam Hemelryk
7888 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7890 class admin_setting_configcolourpicker extends admin_setting {
7893 * Information for previewing the colour
7895 * @var array|null
7897 protected $previewconfig = null;
7901 * @param string $name
7902 * @param string $visiblename
7903 * @param string $description
7904 * @param string $defaultsetting
7905 * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
7907 public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
7908 $this->previewconfig = $previewconfig;
7909 parent::__construct($name, $visiblename, $description, $defaultsetting);
7913 * Return the setting
7915 * @return mixed returns config if successful else null
7917 public function get_setting() {
7918 return $this->config_read($this->name);
7922 * Saves the setting
7924 * @param string $data
7925 * @return bool
7927 public function write_setting($data) {
7928 $data = $this->validate($data);
7929 if ($data === false) {
7930 return get_string('validateerror', 'admin');
7932 return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
7936 * Validates the colour that was entered by the user
7938 * @param string $data
7939 * @return string|false
7941 protected function validate($data) {
7942 if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
7943 if (strpos($data, '#')!==0) {
7944 $data = '#'.$data;
7946 return $data;
7947 } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
7948 return $data;
7949 } else if (empty($data)) {
7950 return $this->defaultsetting;
7951 } else {
7952 return false;
7957 * Generates the HTML for the setting
7959 * @global moodle_page $PAGE
7960 * @global core_renderer $OUTPUT
7961 * @param string $data
7962 * @param string $query
7964 public function output_html($data, $query = '') {
7965 global $PAGE, $OUTPUT;
7966 $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
7967 $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
7968 $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
7969 $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$data, 'size'=>'12'));
7970 if (!empty($this->previewconfig)) {
7971 $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
7973 $content .= html_writer::end_tag('div');
7974 return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
7979 * Administration interface for user specified regular expressions for device detection.
7981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7983 class admin_setting_devicedetectregex extends admin_setting {
7986 * Calls parent::__construct with specific args
7988 * @param string $name
7989 * @param string $visiblename
7990 * @param string $description
7991 * @param mixed $defaultsetting
7993 public function __construct($name, $visiblename, $description, $defaultsetting = '') {
7994 global $CFG;
7995 parent::__construct($name, $visiblename, $description, $defaultsetting);
7999 * Return the current setting(s)
8001 * @return array Current settings array
8003 public function get_setting() {
8004 global $CFG;
8006 $config = $this->config_read($this->name);
8007 if (is_null($config)) {
8008 return null;
8011 return $this->prepare_form_data($config);
8015 * Save selected settings
8017 * @param array $data Array of settings to save
8018 * @return bool
8020 public function write_setting($data) {
8021 if (empty($data)) {
8022 $data = array();
8025 if ($this->config_write($this->name, $this->process_form_data($data))) {
8026 return ''; // success
8027 } else {
8028 return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
8033 * Return XHTML field(s) for regexes
8035 * @param array $data Array of options to set in HTML
8036 * @return string XHTML string for the fields and wrapping div(s)
8038 public function output_html($data, $query='') {
8039 global $OUTPUT;
8041 $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
8042 $out .= html_writer::start_tag('thead');
8043 $out .= html_writer::start_tag('tr');
8044 $out .= html_writer::tag('th', get_string('devicedetectregexexpression', 'admin'));
8045 $out .= html_writer::tag('th', get_string('devicedetectregexvalue', 'admin'));
8046 $out .= html_writer::end_tag('tr');
8047 $out .= html_writer::end_tag('thead');
8048 $out .= html_writer::start_tag('tbody');
8050 if (empty($data)) {
8051 $looplimit = 1;
8052 } else {
8053 $looplimit = (count($data)/2)+1;
8056 for ($i=0; $i<$looplimit; $i++) {
8057 $out .= html_writer::start_tag('tr');
8059 $expressionname = 'expression'.$i;
8061 if (!empty($data[$expressionname])){
8062 $expression = $data[$expressionname];
8063 } else {
8064 $expression = '';
8067 $out .= html_writer::tag('td',
8068 html_writer::empty_tag('input',
8069 array(
8070 'type' => 'text',
8071 'class' => 'form-text',
8072 'name' => $this->get_full_name().'[expression'.$i.']',
8073 'value' => $expression,
8075 ), array('class' => 'c'.$i)
8078 $valuename = 'value'.$i;
8080 if (!empty($data[$valuename])){
8081 $value = $data[$valuename];
8082 } else {
8083 $value= '';
8086 $out .= html_writer::tag('td',
8087 html_writer::empty_tag('input',
8088 array(
8089 'type' => 'text',
8090 'class' => 'form-text',
8091 'name' => $this->get_full_name().'[value'.$i.']',
8092 'value' => $value,
8094 ), array('class' => 'c'.$i)
8097 $out .= html_writer::end_tag('tr');
8100 $out .= html_writer::end_tag('tbody');
8101 $out .= html_writer::end_tag('table');
8103 return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', null, $query);
8107 * Converts the string of regexes
8109 * @see self::process_form_data()
8110 * @param $regexes string of regexes
8111 * @return array of form fields and their values
8113 protected function prepare_form_data($regexes) {
8115 $regexes = json_decode($regexes);
8117 $form = array();
8119 $i = 0;
8121 foreach ($regexes as $value => $regex) {
8122 $expressionname = 'expression'.$i;
8123 $valuename = 'value'.$i;
8125 $form[$expressionname] = $regex;
8126 $form[$valuename] = $value;
8127 $i++;
8130 return $form;
8134 * Converts the data from admin settings form into a string of regexes
8136 * @see self::prepare_form_data()
8137 * @param array $data array of admin form fields and values
8138 * @return false|string of regexes
8140 protected function process_form_data(array $form) {
8142 $count = count($form); // number of form field values
8144 if ($count % 2) {
8145 // we must get five fields per expression
8146 return false;
8149 $regexes = array();
8150 for ($i = 0; $i < $count / 2; $i++) {
8151 $expressionname = "expression".$i;
8152 $valuename = "value".$i;
8154 $expression = trim($form['expression'.$i]);
8155 $value = trim($form['value'.$i]);
8157 if (empty($expression)){
8158 continue;
8161 $regexes[$value] = $expression;
8164 $regexes = json_encode($regexes);
8166 return $regexes;
8171 * Multiselect for current modules
8173 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8175 class admin_setting_configmultiselect_modules extends admin_setting_configmultiselect {
8176 private $excludesystem;
8179 * Calls parent::__construct - note array $choices is not required
8181 * @param string $name setting name
8182 * @param string $visiblename localised setting name
8183 * @param string $description setting description
8184 * @param array $defaultsetting a plain array of default module ids
8185 * @param bool $excludesystem If true, excludes modules with 'system' archetype
8187 public function __construct($name, $visiblename, $description, $defaultsetting = array(),
8188 $excludesystem = true) {
8189 parent::__construct($name, $visiblename, $description, $defaultsetting, null);
8190 $this->excludesystem = $excludesystem;
8194 * Loads an array of current module choices
8196 * @return bool always return true
8198 public function load_choices() {
8199 if (is_array($this->choices)) {
8200 return true;
8202 $this->choices = array();
8204 global $CFG, $DB;
8205 $records = $DB->get_records('modules', array('visible'=>1), 'name');
8206 foreach ($records as $record) {
8207 // Exclude modules if the code doesn't exist
8208 if (file_exists("$CFG->dirroot/mod/$record->name/lib.php")) {
8209 // Also exclude system modules (if specified)
8210 if (!($this->excludesystem &&
8211 plugin_supports('mod', $record->name, FEATURE_MOD_ARCHETYPE) ===
8212 MOD_ARCHETYPE_SYSTEM)) {
8213 $this->choices[$record->id] = $record->name;
8217 return true;