PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/adminlib.php

https://github.com/mylescarrick/moodle
PHP | 7357 lines | 4377 code | 731 blank | 2249 comment | 611 complexity | eb6f6701b00e817ffbf591cf5f9ffcf9 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  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.
  13. //
  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/>.
  16. /**
  17. * Functions and classes used during installation, upgrades and for admin settings.
  18. *
  19. * ADMIN SETTINGS TREE INTRODUCTION
  20. *
  21. * This file performs the following tasks:
  22. * -it defines the necessary objects and interfaces to build the Moodle
  23. * admin hierarchy
  24. * -it defines the admin_externalpage_setup()
  25. *
  26. * ADMIN_SETTING OBJECTS
  27. *
  28. * Moodle settings are represented by objects that inherit from the admin_setting
  29. * class. These objects encapsulate how to read a setting, how to write a new value
  30. * to a setting, and how to appropriately display the HTML to modify the setting.
  31. *
  32. * ADMIN_SETTINGPAGE OBJECTS
  33. *
  34. * The admin_setting objects are then grouped into admin_settingpages. The latter
  35. * appear in the Moodle admin tree block. All interaction with admin_settingpage
  36. * objects is handled by the admin/settings.php file.
  37. *
  38. * ADMIN_EXTERNALPAGE OBJECTS
  39. *
  40. * There are some settings in Moodle that are too complex to (efficiently) handle
  41. * with admin_settingpages. (Consider, for example, user management and displaying
  42. * lists of users.) In this case, we use the admin_externalpage object. This object
  43. * places a link to an external PHP file in the admin tree block.
  44. *
  45. * If you're using an admin_externalpage object for some settings, you can take
  46. * advantage of the admin_externalpage_* functions. For example, suppose you wanted
  47. * to add a foo.php file into admin. First off, you add the following line to
  48. * admin/settings/first.php (at the end of the file) or to some other file in
  49. * admin/settings:
  50. * <code>
  51. * $ADMIN->add('userinterface', new admin_externalpage('foo', get_string('foo'),
  52. * $CFG->wwwdir . '/' . '$CFG->admin . '/foo.php', 'some_role_permission'));
  53. * </code>
  54. *
  55. * Next, in foo.php, your file structure would resemble the following:
  56. * <code>
  57. * require(dirname(dirname(dirname(__FILE__))).'/config.php');
  58. * require_once($CFG->libdir.'/adminlib.php');
  59. * admin_externalpage_setup('foo');
  60. * // functionality like processing form submissions goes here
  61. * echo $OUTPUT->header();
  62. * // your HTML goes here
  63. * echo $OUTPUT->footer();
  64. * </code>
  65. *
  66. * The admin_externalpage_setup() function call ensures the user is logged in,
  67. * and makes sure that they have the proper role permission to access the page.
  68. * It also configures all $PAGE properties needed for navigation.
  69. *
  70. * ADMIN_CATEGORY OBJECTS
  71. *
  72. * Above and beyond all this, we have admin_category objects. These objects
  73. * appear as folders in the admin tree block. They contain admin_settingpage's,
  74. * admin_externalpage's, and other admin_category's.
  75. *
  76. * OTHER NOTES
  77. *
  78. * admin_settingpage's, admin_externalpage's, and admin_category's all inherit
  79. * from part_of_admin_tree (a pseudointerface). This interface insists that
  80. * a class has a check_access method for access permissions, a locate method
  81. * used to find a specific node in the admin tree and find parent path.
  82. *
  83. * admin_category's inherit from parentable_part_of_admin_tree. This pseudo-
  84. * interface ensures that the class implements a recursive add function which
  85. * accepts a part_of_admin_tree object and searches for the proper place to
  86. * put it. parentable_part_of_admin_tree implies part_of_admin_tree.
  87. *
  88. * Please note that the $this->name field of any part_of_admin_tree must be
  89. * UNIQUE throughout the ENTIRE admin tree.
  90. *
  91. * The $this->name field of an admin_setting object (which is *not* part_of_
  92. * admin_tree) must be unique on the respective admin_settingpage where it is
  93. * used.
  94. *
  95. * Original author: Vincenzo K. Marcovecchio
  96. * Maintainer: Petr Skoda
  97. *
  98. * @package core
  99. * @subpackage admin
  100. * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
  101. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  102. */
  103. defined('MOODLE_INTERNAL') || die();
  104. /// Add libraries
  105. require_once($CFG->libdir.'/ddllib.php');
  106. require_once($CFG->libdir.'/xmlize.php');
  107. define('INSECURE_DATAROOT_WARNING', 1);
  108. define('INSECURE_DATAROOT_ERROR', 2);
  109. /**
  110. * Automatically clean-up all plugin data and remove the plugin DB tables
  111. *
  112. * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
  113. * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
  114. * @uses global $OUTPUT to produce notices and other messages
  115. * @return void
  116. */
  117. function uninstall_plugin($type, $name) {
  118. global $CFG, $DB, $OUTPUT;
  119. // recursively uninstall all module subplugins first
  120. if ($type === 'mod') {
  121. if (file_exists("$CFG->dirroot/mod/$name/db/subplugins.php")) {
  122. $subplugins = array();
  123. include("$CFG->dirroot/mod/$name/db/subplugins.php");
  124. foreach ($subplugins as $subplugintype=>$dir) {
  125. $instances = get_plugin_list($subplugintype);
  126. foreach ($instances as $subpluginname => $notusedpluginpath) {
  127. uninstall_plugin($subplugintype, $subpluginname);
  128. }
  129. }
  130. }
  131. }
  132. $component = $type . '_' . $name; // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
  133. if ($type === 'mod') {
  134. $pluginname = $name; // eg. 'forum'
  135. if (get_string_manager()->string_exists('modulename', $component)) {
  136. $strpluginname = get_string('modulename', $component);
  137. } else {
  138. $strpluginname = $component;
  139. }
  140. } else {
  141. $pluginname = $component;
  142. if (get_string_manager()->string_exists('pluginname', $component)) {
  143. $strpluginname = get_string('pluginname', $component);
  144. } else {
  145. $strpluginname = $component;
  146. }
  147. }
  148. echo $OUTPUT->heading($pluginname);
  149. $plugindirectory = get_plugin_directory($type, $name);
  150. $uninstalllib = $plugindirectory . '/db/uninstall.php';
  151. if (file_exists($uninstalllib)) {
  152. require_once($uninstalllib);
  153. $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall'; // eg. 'xmldb_workshop_uninstall()'
  154. if (function_exists($uninstallfunction)) {
  155. if (!$uninstallfunction()) {
  156. echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $pluginname);
  157. }
  158. }
  159. }
  160. if ($type === 'mod') {
  161. // perform cleanup tasks specific for activity modules
  162. if (!$module = $DB->get_record('modules', array('name' => $name))) {
  163. print_error('moduledoesnotexist', 'error');
  164. }
  165. // delete all the relevant instances from all course sections
  166. if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
  167. foreach ($coursemods as $coursemod) {
  168. if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
  169. echo $OUTPUT->notification("Could not delete the $strpluginname with id = $coursemod->id from section $coursemod->section");
  170. }
  171. }
  172. }
  173. // clear course.modinfo for courses that used this module
  174. $sql = "UPDATE {course}
  175. SET modinfo=''
  176. WHERE id IN (SELECT DISTINCT course
  177. FROM {course_modules}
  178. WHERE module=?)";
  179. $DB->execute($sql, array($module->id));
  180. // delete all the course module records
  181. $DB->delete_records('course_modules', array('module' => $module->id));
  182. // delete module contexts
  183. if ($coursemods) {
  184. foreach ($coursemods as $coursemod) {
  185. if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
  186. echo $OUTPUT->notification("Could not delete the context for $strpluginname with id = $coursemod->id");
  187. }
  188. }
  189. }
  190. // delete the module entry itself
  191. $DB->delete_records('modules', array('name' => $module->name));
  192. // cleanup the gradebook
  193. require_once($CFG->libdir.'/gradelib.php');
  194. grade_uninstalled_module($module->name);
  195. // Perform any custom uninstall tasks
  196. if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
  197. require_once($CFG->dirroot . '/mod/' . $module->name . '/lib.php');
  198. $uninstallfunction = $module->name . '_uninstall';
  199. if (function_exists($uninstallfunction)) {
  200. debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
  201. if (!$uninstallfunction()) {
  202. echo $OUTPUT->notification('Encountered a problem running uninstall function for '. $module->name.'!');
  203. }
  204. }
  205. }
  206. } else if ($type === 'enrol') {
  207. // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
  208. // nuke all role assignments
  209. role_unassign_all(array('component'=>$component));
  210. // purge participants
  211. $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
  212. // purge enrol instances
  213. $DB->delete_records('enrol', array('enrol'=>$name));
  214. // tweak enrol settings
  215. if (!empty($CFG->enrol_plugins_enabled)) {
  216. $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
  217. $enabledenrols = array_unique($enabledenrols);
  218. $enabledenrols = array_flip($enabledenrols);
  219. unset($enabledenrols[$name]);
  220. $enabledenrols = array_flip($enabledenrols);
  221. if (is_array($enabledenrols)) {
  222. set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
  223. }
  224. }
  225. }
  226. // perform clean-up task common for all the plugin/subplugin types
  227. // delete calendar events
  228. $DB->delete_records('event', array('modulename' => $pluginname));
  229. // delete all the logs
  230. $DB->delete_records('log', array('module' => $pluginname));
  231. // delete log_display information
  232. $DB->delete_records('log_display', array('component' => $component));
  233. // delete the module configuration records
  234. unset_all_config_for_plugin($pluginname);
  235. // delete the plugin tables
  236. $xmldbfilepath = $plugindirectory . '/db/install.xml';
  237. drop_plugin_tables($pluginname, $xmldbfilepath, false);
  238. // delete the capabilities that were defined by this module
  239. capabilities_cleanup($component);
  240. // remove event handlers and dequeue pending events
  241. events_uninstall($component);
  242. echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
  243. }
  244. /**
  245. * Returns the version of installed component
  246. *
  247. * @param string $component component name
  248. * @param string $source either 'disk' or 'installed' - where to get the version information from
  249. * @return string|bool version number or false if the component is not found
  250. */
  251. function get_component_version($component, $source='installed') {
  252. global $CFG, $DB;
  253. list($type, $name) = normalize_component($component);
  254. // moodle core or a core subsystem
  255. if ($type === 'core') {
  256. if ($source === 'installed') {
  257. if (empty($CFG->version)) {
  258. return false;
  259. } else {
  260. return $CFG->version;
  261. }
  262. } else {
  263. if (!is_readable($CFG->dirroot.'/version.php')) {
  264. return false;
  265. } else {
  266. $version = null; //initialize variable for IDEs
  267. include($CFG->dirroot.'/version.php');
  268. return $version;
  269. }
  270. }
  271. }
  272. // activity module
  273. if ($type === 'mod') {
  274. if ($source === 'installed') {
  275. return $DB->get_field('modules', 'version', array('name'=>$name));
  276. } else {
  277. $mods = get_plugin_list('mod');
  278. if (empty($mods[$name]) or !is_readable($mods[$name].'/version.php')) {
  279. return false;
  280. } else {
  281. $module = new stdclass();
  282. include($mods[$name].'/version.php');
  283. return $module->version;
  284. }
  285. }
  286. }
  287. // block
  288. if ($type === 'block') {
  289. if ($source === 'installed') {
  290. return $DB->get_field('block', 'version', array('name'=>$name));
  291. } else {
  292. $blocks = get_plugin_list('block');
  293. if (empty($blocks[$name]) or !is_readable($blocks[$name].'/version.php')) {
  294. return false;
  295. } else {
  296. $plugin = new stdclass();
  297. include($blocks[$name].'/version.php');
  298. return $plugin->version;
  299. }
  300. }
  301. }
  302. // all other plugin types
  303. if ($source === 'installed') {
  304. return get_config($type.'_'.$name, 'version');
  305. } else {
  306. $plugins = get_plugin_list($type);
  307. if (empty($plugins[$name])) {
  308. return false;
  309. } else {
  310. $plugin = new stdclass();
  311. include($plugins[$name].'/version.php');
  312. return $plugin->version;
  313. }
  314. }
  315. }
  316. /**
  317. * Delete all plugin tables
  318. *
  319. * @param string $name Name of plugin, used as table prefix
  320. * @param string $file Path to install.xml file
  321. * @param bool $feedback defaults to true
  322. * @return bool Always returns true
  323. */
  324. function drop_plugin_tables($name, $file, $feedback=true) {
  325. global $CFG, $DB;
  326. // first try normal delete
  327. if (file_exists($file) and $DB->get_manager()->delete_tables_from_xmldb_file($file)) {
  328. return true;
  329. }
  330. // then try to find all tables that start with name and are not in any xml file
  331. $used_tables = get_used_table_names();
  332. $tables = $DB->get_tables();
  333. /// Iterate over, fixing id fields as necessary
  334. foreach ($tables as $table) {
  335. if (in_array($table, $used_tables)) {
  336. continue;
  337. }
  338. if (strpos($table, $name) !== 0) {
  339. continue;
  340. }
  341. // found orphan table --> delete it
  342. if ($DB->get_manager()->table_exists($table)) {
  343. $xmldb_table = new xmldb_table($table);
  344. $DB->get_manager()->drop_table($xmldb_table);
  345. }
  346. }
  347. return true;
  348. }
  349. /**
  350. * Returns names of all known tables == tables that moodle knows about.
  351. *
  352. * @return array Array of lowercase table names
  353. */
  354. function get_used_table_names() {
  355. $table_names = array();
  356. $dbdirs = get_db_directories();
  357. foreach ($dbdirs as $dbdir) {
  358. $file = $dbdir.'/install.xml';
  359. $xmldb_file = new xmldb_file($file);
  360. if (!$xmldb_file->fileExists()) {
  361. continue;
  362. }
  363. $loaded = $xmldb_file->loadXMLStructure();
  364. $structure = $xmldb_file->getStructure();
  365. if ($loaded and $tables = $structure->getTables()) {
  366. foreach($tables as $table) {
  367. $table_names[] = strtolower($table->name);
  368. }
  369. }
  370. }
  371. return $table_names;
  372. }
  373. /**
  374. * Returns list of all directories where we expect install.xml files
  375. * @return array Array of paths
  376. */
  377. function get_db_directories() {
  378. global $CFG;
  379. $dbdirs = array();
  380. /// First, the main one (lib/db)
  381. $dbdirs[] = $CFG->libdir.'/db';
  382. /// Then, all the ones defined by get_plugin_types()
  383. $plugintypes = get_plugin_types();
  384. foreach ($plugintypes as $plugintype => $pluginbasedir) {
  385. if ($plugins = get_plugin_list($plugintype)) {
  386. foreach ($plugins as $plugin => $plugindir) {
  387. $dbdirs[] = $plugindir.'/db';
  388. }
  389. }
  390. }
  391. return $dbdirs;
  392. }
  393. /**
  394. * Try to obtain or release the cron lock.
  395. * @param string $name name of lock
  396. * @param int $until timestamp when this lock considered stale, null means remove lock unconditionally
  397. * @param bool $ignorecurrent ignore current lock state, usually extend previous lock, defaults to false
  398. * @return bool true if lock obtained
  399. */
  400. function set_cron_lock($name, $until, $ignorecurrent=false) {
  401. global $DB;
  402. if (empty($name)) {
  403. debugging("Tried to get a cron lock for a null fieldname");
  404. return false;
  405. }
  406. // remove lock by force == remove from config table
  407. if (is_null($until)) {
  408. set_config($name, null);
  409. return true;
  410. }
  411. if (!$ignorecurrent) {
  412. // read value from db - other processes might have changed it
  413. $value = $DB->get_field('config', 'value', array('name'=>$name));
  414. if ($value and $value > time()) {
  415. //lock active
  416. return false;
  417. }
  418. }
  419. set_config($name, $until);
  420. return true;
  421. }
  422. /**
  423. * Test if and critical warnings are present
  424. * @return bool
  425. */
  426. function admin_critical_warnings_present() {
  427. global $SESSION;
  428. if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) {
  429. return 0;
  430. }
  431. if (!isset($SESSION->admin_critical_warning)) {
  432. $SESSION->admin_critical_warning = 0;
  433. if (is_dataroot_insecure(true) === INSECURE_DATAROOT_ERROR) {
  434. $SESSION->admin_critical_warning = 1;
  435. }
  436. }
  437. return $SESSION->admin_critical_warning;
  438. }
  439. /**
  440. * Detects if float supports at least 10 decimal digits
  441. *
  442. * Detects if float supports at least 10 decimal digits
  443. * and also if float-->string conversion works as expected.
  444. *
  445. * @return bool true if problem found
  446. */
  447. function is_float_problem() {
  448. $num1 = 2009010200.01;
  449. $num2 = 2009010200.02;
  450. return ((string)$num1 === (string)$num2 or $num1 === $num2 or $num2 <= (string)$num1);
  451. }
  452. /**
  453. * Try to verify that dataroot is not accessible from web.
  454. *
  455. * Try to verify that dataroot is not accessible from web.
  456. * It is not 100% correct but might help to reduce number of vulnerable sites.
  457. * Protection from httpd.conf and .htaccess is not detected properly.
  458. *
  459. * @uses INSECURE_DATAROOT_WARNING
  460. * @uses INSECURE_DATAROOT_ERROR
  461. * @param bool $fetchtest try to test public access by fetching file, default false
  462. * @return mixed empty means secure, INSECURE_DATAROOT_ERROR found a critical problem, INSECURE_DATAROOT_WARNING might be problematic
  463. */
  464. function is_dataroot_insecure($fetchtest=false) {
  465. global $CFG;
  466. $siteroot = str_replace('\\', '/', strrev($CFG->dirroot.'/')); // win32 backslash workaround
  467. $rp = preg_replace('|https?://[^/]+|i', '', $CFG->wwwroot, 1);
  468. $rp = strrev(trim($rp, '/'));
  469. $rp = explode('/', $rp);
  470. foreach($rp as $r) {
  471. if (strpos($siteroot, '/'.$r.'/') === 0) {
  472. $siteroot = substr($siteroot, strlen($r)+1); // moodle web in subdirectory
  473. } else {
  474. break; // probably alias root
  475. }
  476. }
  477. $siteroot = strrev($siteroot);
  478. $dataroot = str_replace('\\', '/', $CFG->dataroot.'/');
  479. if (strpos($dataroot, $siteroot) !== 0) {
  480. return false;
  481. }
  482. if (!$fetchtest) {
  483. return INSECURE_DATAROOT_WARNING;
  484. }
  485. // now try all methods to fetch a test file using http protocol
  486. $httpdocroot = str_replace('\\', '/', strrev($CFG->dirroot.'/'));
  487. preg_match('|(https?://[^/]+)|i', $CFG->wwwroot, $matches);
  488. $httpdocroot = $matches[1];
  489. $datarooturl = $httpdocroot.'/'. substr($dataroot, strlen($siteroot));
  490. make_upload_directory('diag');
  491. $testfile = $CFG->dataroot.'/diag/public.txt';
  492. if (!file_exists($testfile)) {
  493. file_put_contents($testfile, 'test file, do not delete');
  494. }
  495. $teststr = trim(file_get_contents($testfile));
  496. if (empty($teststr)) {
  497. // hmm, strange
  498. return INSECURE_DATAROOT_WARNING;
  499. }
  500. $testurl = $datarooturl.'/diag/public.txt';
  501. if (extension_loaded('curl') and
  502. !(stripos(ini_get('disable_functions'), 'curl_init') !== FALSE) and
  503. !(stripos(ini_get('disable_functions'), 'curl_setop') !== FALSE) and
  504. ($ch = @curl_init($testurl)) !== false) {
  505. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  506. curl_setopt($ch, CURLOPT_HEADER, false);
  507. $data = curl_exec($ch);
  508. if (!curl_errno($ch)) {
  509. $data = trim($data);
  510. if ($data === $teststr) {
  511. curl_close($ch);
  512. return INSECURE_DATAROOT_ERROR;
  513. }
  514. }
  515. curl_close($ch);
  516. }
  517. if ($data = @file_get_contents($testurl)) {
  518. $data = trim($data);
  519. if ($data === $teststr) {
  520. return INSECURE_DATAROOT_ERROR;
  521. }
  522. }
  523. preg_match('|https?://([^/]+)|i', $testurl, $matches);
  524. $sitename = $matches[1];
  525. $error = 0;
  526. if ($fp = @fsockopen($sitename, 80, $error)) {
  527. preg_match('|https?://[^/]+(.*)|i', $testurl, $matches);
  528. $localurl = $matches[1];
  529. $out = "GET $localurl HTTP/1.1\r\n";
  530. $out .= "Host: $sitename\r\n";
  531. $out .= "Connection: Close\r\n\r\n";
  532. fwrite($fp, $out);
  533. $data = '';
  534. $incoming = false;
  535. while (!feof($fp)) {
  536. if ($incoming) {
  537. $data .= fgets($fp, 1024);
  538. } else if (@fgets($fp, 1024) === "\r\n") {
  539. $incoming = true;
  540. }
  541. }
  542. fclose($fp);
  543. $data = trim($data);
  544. if ($data === $teststr) {
  545. return INSECURE_DATAROOT_ERROR;
  546. }
  547. }
  548. return INSECURE_DATAROOT_WARNING;
  549. }
  550. /// CLASS DEFINITIONS /////////////////////////////////////////////////////////
  551. /**
  552. * Interface for anything appearing in the admin tree
  553. *
  554. * The interface that is implemented by anything that appears in the admin tree
  555. * block. It forces inheriting classes to define a method for checking user permissions
  556. * and methods for finding something in the admin tree.
  557. *
  558. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  559. */
  560. interface part_of_admin_tree {
  561. /**
  562. * Finds a named part_of_admin_tree.
  563. *
  564. * Used to find a part_of_admin_tree. If a class only inherits part_of_admin_tree
  565. * and not parentable_part_of_admin_tree, then this function should only check if
  566. * $this->name matches $name. If it does, it should return a reference to $this,
  567. * otherwise, it should return a reference to NULL.
  568. *
  569. * If a class inherits parentable_part_of_admin_tree, this method should be called
  570. * recursively on all child objects (assuming, of course, the parent object's name
  571. * doesn't match the search criterion).
  572. *
  573. * @param string $name The internal name of the part_of_admin_tree we're searching for.
  574. * @return mixed An object reference or a NULL reference.
  575. */
  576. public function locate($name);
  577. /**
  578. * Removes named part_of_admin_tree.
  579. *
  580. * @param string $name The internal name of the part_of_admin_tree we want to remove.
  581. * @return bool success.
  582. */
  583. public function prune($name);
  584. /**
  585. * Search using query
  586. * @param string $query
  587. * @return mixed array-object structure of found settings and pages
  588. */
  589. public function search($query);
  590. /**
  591. * Verifies current user's access to this part_of_admin_tree.
  592. *
  593. * Used to check if the current user has access to this part of the admin tree or
  594. * not. If a class only inherits part_of_admin_tree and not parentable_part_of_admin_tree,
  595. * then this method is usually just a call to has_capability() in the site context.
  596. *
  597. * If a class inherits parentable_part_of_admin_tree, this method should return the
  598. * logical OR of the return of check_access() on all child objects.
  599. *
  600. * @return bool True if the user has access, false if she doesn't.
  601. */
  602. public function check_access();
  603. /**
  604. * Mostly useful for removing of some parts of the tree in admin tree block.
  605. *
  606. * @return True is hidden from normal list view
  607. */
  608. public function is_hidden();
  609. /**
  610. * Show we display Save button at the page bottom?
  611. * @return bool
  612. */
  613. public function show_save();
  614. }
  615. /**
  616. * Interface implemented by any part_of_admin_tree that has children.
  617. *
  618. * The interface implemented by any part_of_admin_tree that can be a parent
  619. * to other part_of_admin_tree's. (For now, this only includes admin_category.) Apart
  620. * from ensuring part_of_admin_tree compliancy, it also ensures inheriting methods
  621. * include an add method for adding other part_of_admin_tree objects as children.
  622. *
  623. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  624. */
  625. interface parentable_part_of_admin_tree extends part_of_admin_tree {
  626. /**
  627. * Adds a part_of_admin_tree object to the admin tree.
  628. *
  629. * Used to add a part_of_admin_tree object to this object or a child of this
  630. * object. $something should only be added if $destinationname matches
  631. * $this->name. If it doesn't, add should be called on child objects that are
  632. * also parentable_part_of_admin_tree's.
  633. *
  634. * @param string $destinationname The internal name of the new parent for $something.
  635. * @param part_of_admin_tree $something The object to be added.
  636. * @return bool True on success, false on failure.
  637. */
  638. public function add($destinationname, $something);
  639. }
  640. /**
  641. * The object used to represent folders (a.k.a. categories) in the admin tree block.
  642. *
  643. * Each admin_category object contains a number of part_of_admin_tree objects.
  644. *
  645. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  646. */
  647. class admin_category implements parentable_part_of_admin_tree {
  648. /** @var mixed An array of part_of_admin_tree objects that are this object's children */
  649. public $children;
  650. /** @var string An internal name for this category. Must be unique amongst ALL part_of_admin_tree objects */
  651. public $name;
  652. /** @var string The displayed name for this category. Usually obtained through get_string() */
  653. public $visiblename;
  654. /** @var bool Should this category be hidden in admin tree block? */
  655. public $hidden;
  656. /** @var mixed Either a string or an array or strings */
  657. public $path;
  658. /** @var mixed Either a string or an array or strings */
  659. public $visiblepath;
  660. /** @var array fast lookup category cache, all categories of one tree point to one cache */
  661. protected $category_cache;
  662. /**
  663. * Constructor for an empty admin category
  664. *
  665. * @param string $name The internal name for this category. Must be unique amongst ALL part_of_admin_tree objects
  666. * @param string $visiblename The displayed named for this category. Usually obtained through get_string()
  667. * @param bool $hidden hide category in admin tree block, defaults to false
  668. */
  669. public function __construct($name, $visiblename, $hidden=false) {
  670. $this->children = array();
  671. $this->name = $name;
  672. $this->visiblename = $visiblename;
  673. $this->hidden = $hidden;
  674. }
  675. /**
  676. * Returns a reference to the part_of_admin_tree object with internal name $name.
  677. *
  678. * @param string $name The internal name of the object we want.
  679. * @param bool $findpath initialize path and visiblepath arrays
  680. * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
  681. * defaults to false
  682. */
  683. public function locate($name, $findpath=false) {
  684. if (is_array($this->category_cache) and !isset($this->category_cache[$this->name])) {
  685. // somebody much have purged the cache
  686. $this->category_cache[$this->name] = $this;
  687. }
  688. if ($this->name == $name) {
  689. if ($findpath) {
  690. $this->visiblepath[] = $this->visiblename;
  691. $this->path[] = $this->name;
  692. }
  693. return $this;
  694. }
  695. // quick category lookup
  696. if (!$findpath and is_array($this->category_cache) and isset($this->category_cache[$name])) {
  697. return $this->category_cache[$name];
  698. }
  699. $return = NULL;
  700. foreach($this->children as $childid=>$unused) {
  701. if ($return = $this->children[$childid]->locate($name, $findpath)) {
  702. break;
  703. }
  704. }
  705. if (!is_null($return) and $findpath) {
  706. $return->visiblepath[] = $this->visiblename;
  707. $return->path[] = $this->name;
  708. }
  709. return $return;
  710. }
  711. /**
  712. * Search using query
  713. *
  714. * @param string query
  715. * @return mixed array-object structure of found settings and pages
  716. */
  717. public function search($query) {
  718. $result = array();
  719. foreach ($this->children as $child) {
  720. $subsearch = $child->search($query);
  721. if (!is_array($subsearch)) {
  722. debugging('Incorrect search result from '.$child->name);
  723. continue;
  724. }
  725. $result = array_merge($result, $subsearch);
  726. }
  727. return $result;
  728. }
  729. /**
  730. * Removes part_of_admin_tree object with internal name $name.
  731. *
  732. * @param string $name The internal name of the object we want to remove.
  733. * @return bool success
  734. */
  735. public function prune($name) {
  736. if ($this->name == $name) {
  737. return false; //can not remove itself
  738. }
  739. foreach($this->children as $precedence => $child) {
  740. if ($child->name == $name) {
  741. // clear cache and delete self
  742. if (is_array($this->category_cache)) {
  743. while($this->category_cache) {
  744. // delete the cache, but keep the original array address
  745. array_pop($this->category_cache);
  746. }
  747. }
  748. unset($this->children[$precedence]);
  749. return true;
  750. } else if ($this->children[$precedence]->prune($name)) {
  751. return true;
  752. }
  753. }
  754. return false;
  755. }
  756. /**
  757. * Adds a part_of_admin_tree to a child or grandchild (or great-grandchild, and so forth) of this object.
  758. *
  759. * @param string $destinationame The internal name of the immediate parent that we want for $something.
  760. * @param mixed $something A part_of_admin_tree or setting instance to be added.
  761. * @return bool True if successfully added, false if $something can not be added.
  762. */
  763. public function add($parentname, $something) {
  764. $parent = $this->locate($parentname);
  765. if (is_null($parent)) {
  766. debugging('parent does not exist!');
  767. return false;
  768. }
  769. if ($something instanceof part_of_admin_tree) {
  770. if (!($parent instanceof parentable_part_of_admin_tree)) {
  771. debugging('error - parts of tree can be inserted only into parentable parts');
  772. return false;
  773. }
  774. $parent->children[] = $something;
  775. if (is_array($this->category_cache) and ($something instanceof admin_category)) {
  776. if (isset($this->category_cache[$something->name])) {
  777. debugging('Duplicate admin catefory name: '.$something->name);
  778. } else {
  779. $this->category_cache[$something->name] = $something;
  780. $something->category_cache =& $this->category_cache;
  781. foreach ($something->children as $child) {
  782. // just in case somebody already added subcategories
  783. if ($child instanceof admin_category) {
  784. if (isset($this->category_cache[$child->name])) {
  785. debugging('Duplicate admin catefory name: '.$child->name);
  786. } else {
  787. $this->category_cache[$child->name] = $child;
  788. $child->category_cache =& $this->category_cache;
  789. }
  790. }
  791. }
  792. }
  793. }
  794. return true;
  795. } else {
  796. debugging('error - can not add this element');
  797. return false;
  798. }
  799. }
  800. /**
  801. * Checks if the user has access to anything in this category.
  802. *
  803. * @return bool True if the user has access to at least one child in this category, false otherwise.
  804. */
  805. public function check_access() {
  806. foreach ($this->children as $child) {
  807. if ($child->check_access()) {
  808. return true;
  809. }
  810. }
  811. return false;
  812. }
  813. /**
  814. * Is this category hidden in admin tree block?
  815. *
  816. * @return bool True if hidden
  817. */
  818. public function is_hidden() {
  819. return $this->hidden;
  820. }
  821. /**
  822. * Show we display Save button at the page bottom?
  823. * @return bool
  824. */
  825. public function show_save() {
  826. foreach ($this->children as $child) {
  827. if ($child->show_save()) {
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. }
  834. /**
  835. * Root of admin settings tree, does not have any parent.
  836. *
  837. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  838. */
  839. class admin_root extends admin_category {
  840. /** @var array List of errors */
  841. public $errors;
  842. /** @var string search query */
  843. public $search;
  844. /** @var bool full tree flag - true means all settings required, false only pages required */
  845. public $fulltree;
  846. /** @var bool flag indicating loaded tree */
  847. public $loaded;
  848. /** @var mixed site custom defaults overriding defaults in settings files*/
  849. public $custom_defaults;
  850. /**
  851. * @param bool $fulltree true means all settings required,
  852. * false only pages required
  853. */
  854. public function __construct($fulltree) {
  855. global $CFG;
  856. parent::__construct('root', get_string('administration'), false);
  857. $this->errors = array();
  858. $this->search = '';
  859. $this->fulltree = $fulltree;
  860. $this->loaded = false;
  861. $this->category_cache = array();
  862. // load custom defaults if found
  863. $this->custom_defaults = null;
  864. $defaultsfile = "$CFG->dirroot/local/defaults.php";
  865. if (is_readable($defaultsfile)) {
  866. $defaults = array();
  867. include($defaultsfile);
  868. if (is_array($defaults) and count($defaults)) {
  869. $this->custom_defaults = $defaults;
  870. }
  871. }
  872. }
  873. /**
  874. * Empties children array, and sets loaded to false
  875. *
  876. * @param bool $requirefulltree
  877. */
  878. public function purge_children($requirefulltree) {
  879. $this->children = array();
  880. $this->fulltree = ($requirefulltree || $this->fulltree);
  881. $this->loaded = false;
  882. //break circular dependencies - this helps PHP 5.2
  883. while($this->category_cache) {
  884. array_pop($this->category_cache);
  885. }
  886. $this->category_cache = array();
  887. }
  888. }
  889. /**
  890. * Links external PHP pages into the admin tree.
  891. *
  892. * See detailed usage example at the top of this document (adminlib.php)
  893. *
  894. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  895. */
  896. class admin_externalpage implements part_of_admin_tree {
  897. /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
  898. public $name;
  899. /** @var string The displayed name for this external page. Usually obtained through get_string(). */
  900. public $visiblename;
  901. /** @var string The external URL that we should link to when someone requests this external page. */
  902. public $url;
  903. /** @var string The role capability/permission a user must have to access this external page. */
  904. public $req_capability;
  905. /** @var object The context in which capability/permission should be checked, default is site context. */
  906. public $context;
  907. /** @var bool hidden in admin tree block. */
  908. public $hidden;
  909. /** @var mixed either string or array of string */
  910. public $path;
  911. public $visiblepath;
  912. /**
  913. * Constructor for adding an external page into the admin tree.
  914. *
  915. * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
  916. * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
  917. * @param string $url The external URL that we should link to when someone requests this external page.
  918. * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
  919. * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
  920. * @param stdClass $context The context the page relates to. Not sure what happens
  921. * if you specify something other than system or front page. Defaults to system.
  922. */
  923. public function __construct($name, $visiblename, $url, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
  924. $this->name = $name;
  925. $this->visiblename = $visiblename;
  926. $this->url = $url;
  927. if (is_array($req_capability)) {
  928. $this->req_capability = $req_capability;
  929. } else {
  930. $this->req_capability = array($req_capability);
  931. }
  932. $this->hidden = $hidden;
  933. $this->context = $context;
  934. }
  935. /**
  936. * Returns a reference to the part_of_admin_tree object with internal name $name.
  937. *
  938. * @param string $name The internal name of the object we want.
  939. * @param bool $findpath defaults to false
  940. * @return mixed A reference to the object with internal name $name if found, otherwise a reference to NULL.
  941. */
  942. public function locate($name, $findpath=false) {
  943. if ($this->name == $name) {
  944. if ($findpath) {
  945. $this->visiblepath = array($this->visiblename);
  946. $this->path = array($this->name);
  947. }
  948. return $this;
  949. } else {
  950. $return = NULL;
  951. return $return;
  952. }
  953. }
  954. /**
  955. * This function always returns false, required function by interface
  956. *
  957. * @param string $name
  958. * @return false
  959. */
  960. public function prune($name) {
  961. return false;
  962. }
  963. /**
  964. * Search using query
  965. *
  966. * @param string $query
  967. * @return mixed array-object structure of found settings and pages
  968. */
  969. public function search($query) {
  970. $textlib = textlib_get_instance();
  971. $found = false;
  972. if (strpos(strtolower($this->name), $query) !== false) {
  973. $found = true;
  974. } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
  975. $found = true;
  976. }
  977. if ($found) {
  978. $result = new stdClass();
  979. $result->page = $this;
  980. $result->settings = array();
  981. return array($this->name => $result);
  982. } else {
  983. return array();
  984. }
  985. }
  986. /**
  987. * Determines if the current user has access to this external page based on $this->req_capability.
  988. *
  989. * @return bool True if user has access, false otherwise.
  990. */
  991. public function check_access() {
  992. global $CFG;
  993. $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
  994. foreach($this->req_capability as $cap) {
  995. if (has_capability($cap, $context)) {
  996. return true;
  997. }
  998. }
  999. return false;
  1000. }
  1001. /**
  1002. * Is this external page hidden in admin tree block?
  1003. *
  1004. * @return bool True if hidden
  1005. */
  1006. public function is_hidden() {
  1007. return $this->hidden;
  1008. }
  1009. /**
  1010. * Show we display Save button at the page bottom?
  1011. * @return bool
  1012. */
  1013. public function show_save() {
  1014. return false;
  1015. }
  1016. }
  1017. /**
  1018. * Used to group a number of admin_setting objects into a page and add them to the admin tree.
  1019. *
  1020. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1021. */
  1022. class admin_settingpage implements part_of_admin_tree {
  1023. /** @var string An internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects */
  1024. public $name;
  1025. /** @var string The displayed name for this external page. Usually obtained through get_string(). */
  1026. public $visiblename;
  1027. /** @var mixed An array of admin_setting objects that are part of this setting page. */
  1028. public $settings;
  1029. /** @var string The role capability/permission a user must have to access this external page. */
  1030. public $req_capability;
  1031. /** @var object The context in which capability/permission should be checked, default is site context. */
  1032. public $context;
  1033. /** @var bool hidden in admin tree block. */
  1034. public $hidden;
  1035. /** @var mixed string of paths or array of strings of paths */
  1036. public $path;
  1037. public $visiblepath;
  1038. /**
  1039. * see admin_settingpage for details of this function
  1040. *
  1041. * @param string $name The internal name for this external page. Must be unique amongst ALL part_of_admin_tree objects.
  1042. * @param string $visiblename The displayed name for this external page. Usually obtained through get_string().
  1043. * @param mixed $req_capability The role capability/permission a user must have to access this external page. Defaults to 'moodle/site:config'.
  1044. * @param boolean $hidden Is this external page hidden in admin tree block? Default false.
  1045. * @param stdClass $context The context the page relates to. Not sure what happens
  1046. * if you specify something other than system or front page. Defaults to system.
  1047. */
  1048. public function __construct($name, $visiblename, $req_capability='moodle/site:config', $hidden=false, $context=NULL) {
  1049. $this->settings = new stdClass();
  1050. $this->name = $name;
  1051. $this->visiblename = $visiblename;
  1052. if (is_array($req_capability)) {
  1053. $this->req_capability = $req_capability;
  1054. } else {
  1055. $this->req_capability = array($req_capability);
  1056. }
  1057. $this->hidden = $hidden;
  1058. $this->context = $context;
  1059. }
  1060. /**
  1061. * see admin_category
  1062. *
  1063. * @param string $name
  1064. * @param bool $findpath
  1065. * @return mixed Object (this) if name == this->name, else returns null
  1066. */
  1067. public function locate($name, $findpath=false) {
  1068. if ($this->name == $name) {
  1069. if ($findpath) {
  1070. $this->visiblepath = array($this->visiblename);
  1071. $this->path = array($this->name);
  1072. }
  1073. return $this;
  1074. } else {
  1075. $return = NULL;
  1076. return $return;
  1077. }
  1078. }
  1079. /**
  1080. * Search string in settings page.
  1081. *
  1082. * @param string $query
  1083. * @return array
  1084. */
  1085. public function search($query) {
  1086. $found = array();
  1087. foreach ($this->settings as $setting) {
  1088. if ($setting->is_related($query)) {
  1089. $found[] = $setting;
  1090. }
  1091. }
  1092. if ($found) {
  1093. $result = new stdClass();
  1094. $result->page = $this;
  1095. $result->settings = $found;
  1096. return array($this->name => $result);
  1097. }
  1098. $textlib = textlib_get_instance();
  1099. $found = false;
  1100. if (strpos(strtolower($this->name), $query) !== false) {
  1101. $found = true;
  1102. } else if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
  1103. $found = true;
  1104. }
  1105. if ($found) {
  1106. $result = new stdClass();
  1107. $result->page = $this;
  1108. $result->settings = array();
  1109. return array($this->name => $result);
  1110. } else {
  1111. return array();
  1112. }
  1113. }
  1114. /**
  1115. * This function always returns false, required by interface
  1116. *
  1117. * @param string $name
  1118. * @return bool Always false
  1119. */
  1120. public function prune($name) {
  1121. return false;
  1122. }
  1123. /**
  1124. * adds an admin_setting to this admin_settingpage
  1125. *
  1126. * 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
  1127. * n.b. each admin_setting in an admin_settingpage must have a unique internal name
  1128. *
  1129. * @param object $setting is the admin_setting object you want to add
  1130. * @return bool true if successful, false if not
  1131. */
  1132. public function add($setting) {
  1133. if (!($setting instanceof admin_setting)) {
  1134. debugging('error - not a setting instance');
  1135. return false;
  1136. }
  1137. $this->settings->{$setting->name} = $setting;
  1138. return true;
  1139. }
  1140. /**
  1141. * see admin_externalpage
  1142. *
  1143. * @return bool Returns true for yes false for no
  1144. */
  1145. public function check_access() {
  1146. global $CFG;
  1147. $context = empty($this->context) ? get_context_instance(CONTEXT_SYSTEM) : $this->context;
  1148. foreach($this->req_capability as $cap) {
  1149. if (has_capability($cap, $context)) {
  1150. return true;
  1151. }
  1152. }
  1153. return false;
  1154. }
  1155. /**
  1156. * outputs this page as html in a table (suitable for inclusion in an admin pagetype)
  1157. * @return string Returns an XHTML string
  1158. */
  1159. public function output_html() {
  1160. $adminroot = admin_get_root();
  1161. $return = '<fieldset>'."\n".'<div class="clearer"><!-- --></div>'."\n";
  1162. foreach($this->settings as $setting) {
  1163. $fullname = $setting->get_full_name();
  1164. if (array_key_exists($fullname, $adminroot->errors)) {
  1165. $data = $adminroot->errors[$fullname]->data;
  1166. } else {
  1167. $data = $setting->get_setting();
  1168. // do not use defaults if settings not available - upgrade settings handles the defaults!
  1169. }
  1170. $return .= $setting->output_html($data);
  1171. }
  1172. $return .= '</fieldset>';
  1173. return $return;
  1174. }
  1175. /**
  1176. * Is this settings page hidden in admin tree block?
  1177. *
  1178. * @return bool True if hidden
  1179. */
  1180. public function is_hidden() {
  1181. return $this->hidden;
  1182. }
  1183. /**
  1184. * Show we display Save button at the page bottom?
  1185. * @return bool
  1186. */
  1187. public function show_save() {
  1188. foreach($this->settings as $setting) {
  1189. if (empty($setting->nosave)) {
  1190. return true;
  1191. }
  1192. }
  1193. return false;
  1194. }
  1195. }
  1196. /**
  1197. * Admin settings class. Only exists on setting pages.
  1198. * Read & write happens at this level; no authentication.
  1199. *
  1200. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1201. */
  1202. abstract class admin_setting {
  1203. /** @var string unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins. */
  1204. public $name;
  1205. /** @var string localised name */
  1206. public $visiblename;
  1207. /** @var string localised long description in Markdown format */
  1208. public $description;
  1209. /** @var mixed Can be string or array of string */
  1210. public $defaultsetting;
  1211. /** @var string */
  1212. public $updatedcallback;
  1213. /** @var mixed can be String or Null. Null means main config table */
  1214. public $plugin; // null means main config table
  1215. /** @var bool true indicates this setting does not actually save anything, just information */
  1216. public $nosave = false;
  1217. /**
  1218. * Constructor
  1219. * @param string $name unique ascii name, either 'mysetting' for settings that in config,
  1220. * or 'myplugin/mysetting' for ones in config_plugins.
  1221. * @param string $visiblename localised name
  1222. * @param string $description localised long description
  1223. * @param mixed $defaultsetting string or array depending on implementation
  1224. */
  1225. public function __construct($name, $visiblename, $description, $defaultsetting) {
  1226. $this->parse_setting_name($name);
  1227. $this->visiblename = $visiblename;
  1228. $this->description = $description;
  1229. $this->defaultsetting = $defaultsetting;
  1230. }
  1231. /**
  1232. * Set up $this->name and potentially $this->plugin
  1233. *
  1234. * Set up $this->name and possibly $this->plugin based on whether $name looks
  1235. * like 'settingname' or 'plugin/settingname'. Also, do some sanity checking
  1236. * on the names, that is, output a developer debug warning if the name
  1237. * contains anything other than [a-zA-Z0-9_]+.
  1238. *
  1239. * @param string $name the setting name passed in to the constructor.
  1240. */
  1241. private function parse_setting_name($name) {
  1242. $bits = explode('/', $name);
  1243. if (count($bits) > 2) {
  1244. throw new moodle_exception('invalidadminsettingname', '', '', $name);
  1245. }
  1246. $this->name = array_pop($bits);
  1247. if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->name)) {
  1248. throw new moodle_exception('invalidadminsettingname', '', '', $name);
  1249. }
  1250. if (!empty($bits)) {
  1251. $this->plugin = array_pop($bits);
  1252. if ($this->plugin === 'moodle') {
  1253. $this->plugin = null;
  1254. } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $this->plugin)) {
  1255. throw new moodle_exception('invalidadminsettingname', '', '', $name);
  1256. }
  1257. }
  1258. }
  1259. /**
  1260. * Returns the fullname prefixed by the plugin
  1261. * @return string
  1262. */
  1263. public function get_full_name() {
  1264. return 's_'.$this->plugin.'_'.$this->name;
  1265. }
  1266. /**
  1267. * Returns the ID string based on plugin and name
  1268. * @return string
  1269. */
  1270. public function get_id() {
  1271. return 'id_s_'.$this->plugin.'_'.$this->name;
  1272. }
  1273. /**
  1274. * Returns the config if possible
  1275. *
  1276. * @return mixed returns config if successfull else null
  1277. */
  1278. public function config_read($name) {
  1279. global $CFG;
  1280. if (!empty($this->plugin)) {
  1281. $value = get_config($this->plugin, $name);
  1282. return $value === false ? NULL : $value;
  1283. } else {
  1284. if (isset($CFG->$name)) {
  1285. return $CFG->$name;
  1286. } else {
  1287. return NULL;
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * Used to set a config pair and log change
  1293. *
  1294. * @param string $name
  1295. * @param mixed $value Gets converted to string if not null
  1296. * @return bool Write setting to config table
  1297. */
  1298. public function config_write($name, $value) {
  1299. global $DB, $USER, $CFG;
  1300. if ($this->nosave) {
  1301. return true;
  1302. }
  1303. // make sure it is a real change
  1304. $oldvalue = get_config($this->plugin, $name);
  1305. $oldvalue = ($oldvalue === false) ? null : $oldvalue; // normalise
  1306. $value = is_null($value) ? null : (string)$value;
  1307. if ($oldvalue === $value) {
  1308. return true;
  1309. }
  1310. // store change
  1311. set_config($name, $value, $this->plugin);
  1312. // log change
  1313. $log = new stdClass();
  1314. $log->userid = during_initial_install() ? 0 :$USER->id; // 0 as user id during install
  1315. $log->timemodified = time();
  1316. $log->plugin = $this->plugin;
  1317. $log->name = $name;
  1318. $log->value = $value;
  1319. $log->oldvalue = $oldvalue;
  1320. $DB->insert_record('config_log', $log);
  1321. return true; // BC only
  1322. }
  1323. /**
  1324. * Returns current value of this setting
  1325. * @return mixed array or string depending on instance, NULL means not set yet
  1326. */
  1327. public abstract function get_setting();
  1328. /**
  1329. * Returns default setting if exists
  1330. * @return mixed array or string depending on instance; NULL means no default, user must supply
  1331. */
  1332. public function get_defaultsetting() {
  1333. $adminroot = admin_get_root(false, false);
  1334. if (!empty($adminroot->custom_defaults)) {
  1335. $plugin = is_null($this->plugin) ? 'moodle' : $this->plugin;
  1336. if (isset($adminroot->custom_defaults[$plugin])) {
  1337. if (array_key_exists($this->name, $adminroot->custom_defaults[$plugin])) { // null is valid value here ;-)
  1338. return $adminroot->custom_defaults[$plugin][$this->name];
  1339. }
  1340. }
  1341. }
  1342. return $this->defaultsetting;
  1343. }
  1344. /**
  1345. * Store new setting
  1346. *
  1347. * @param mixed $data string or array, must not be NULL
  1348. * @return string empty string if ok, string error message otherwise
  1349. */
  1350. public abstract function write_setting($data);
  1351. /**
  1352. * Return part of form with setting
  1353. * This function should always be overwritten
  1354. *
  1355. * @param mixed $data array or string depending on setting
  1356. * @param string $query
  1357. * @return string
  1358. */
  1359. public function output_html($data, $query='') {
  1360. // should be overridden
  1361. return;
  1362. }
  1363. /**
  1364. * Function called if setting updated - cleanup, cache reset, etc.
  1365. * @param string $functionname Sets the function name
  1366. */
  1367. public function set_updatedcallback($functionname) {
  1368. $this->updatedcallback = $functionname;
  1369. }
  1370. /**
  1371. * Is setting related to query text - used when searching
  1372. * @param string $query
  1373. * @return bool
  1374. */
  1375. public function is_related($query) {
  1376. if (strpos(strtolower($this->name), $query) !== false) {
  1377. return true;
  1378. }
  1379. $textlib = textlib_get_instance();
  1380. if (strpos($textlib->strtolower($this->visiblename), $query) !== false) {
  1381. return true;
  1382. }
  1383. if (strpos($textlib->strtolower($this->description), $query) !== false) {
  1384. return true;
  1385. }
  1386. $current = $this->get_setting();
  1387. if (!is_null($current)) {
  1388. if (is_string($current)) {
  1389. if (strpos($textlib->strtolower($current), $query) !== false) {
  1390. return true;
  1391. }
  1392. }
  1393. }
  1394. $default = $this->get_defaultsetting();
  1395. if (!is_null($default)) {
  1396. if (is_string($default)) {
  1397. if (strpos($textlib->strtolower($default), $query) !== false) {
  1398. return true;
  1399. }
  1400. }
  1401. }
  1402. return false;
  1403. }
  1404. }
  1405. /**
  1406. * No setting - just heading and text.
  1407. *
  1408. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1409. */
  1410. class admin_setting_heading extends admin_setting {
  1411. /**
  1412. * not a setting, just text
  1413. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1414. * @param string $heading heading
  1415. * @param string $information text in box
  1416. */
  1417. public function __construct($name, $heading, $information) {
  1418. $this->nosave = true;
  1419. parent::__construct($name, $heading, $information, '');
  1420. }
  1421. /**
  1422. * Always returns true
  1423. * @return bool Always returns true
  1424. */
  1425. public function get_setting() {
  1426. return true;
  1427. }
  1428. /**
  1429. * Always returns true
  1430. * @return bool Always returns true
  1431. */
  1432. public function get_defaultsetting() {
  1433. return true;
  1434. }
  1435. /**
  1436. * Never write settings
  1437. * @return string Always returns an empty string
  1438. */
  1439. public function write_setting($data) {
  1440. // do not write any setting
  1441. return '';
  1442. }
  1443. /**
  1444. * Returns an HTML string
  1445. * @return string Returns an HTML string
  1446. */
  1447. public function output_html($data, $query='') {
  1448. global $OUTPUT;
  1449. $return = '';
  1450. if ($this->visiblename != '') {
  1451. $return .= $OUTPUT->heading($this->visiblename, 3, 'main');
  1452. }
  1453. if ($this->description != '') {
  1454. $return .= $OUTPUT->box(highlight($query, markdown_to_html($this->description)), 'generalbox formsettingheading');
  1455. }
  1456. return $return;
  1457. }
  1458. }
  1459. /**
  1460. * The most flexibly setting, user is typing text
  1461. *
  1462. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1463. */
  1464. class admin_setting_configtext extends admin_setting {
  1465. /** @var mixed int means PARAM_XXX type, string is a allowed format in regex */
  1466. public $paramtype;
  1467. /** @var int default field size */
  1468. public $size;
  1469. /**
  1470. * Config text constructor
  1471. *
  1472. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1473. * @param string $visiblename localised
  1474. * @param string $description long localised info
  1475. * @param string $defaultsetting
  1476. * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
  1477. * @param int $size default field size
  1478. */
  1479. public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
  1480. $this->paramtype = $paramtype;
  1481. if (!is_null($size)) {
  1482. $this->size = $size;
  1483. } else {
  1484. $this->size = ($paramtype === PARAM_INT) ? 5 : 30;
  1485. }
  1486. parent::__construct($name, $visiblename, $description, $defaultsetting);
  1487. }
  1488. /**
  1489. * Return the setting
  1490. *
  1491. * @return mixed returns config if successful else null
  1492. */
  1493. public function get_setting() {
  1494. return $this->config_read($this->name);
  1495. }
  1496. public function write_setting($data) {
  1497. if ($this->paramtype === PARAM_INT and $data === '') {
  1498. // do not complain if '' used instead of 0
  1499. $data = 0;
  1500. }
  1501. // $data is a string
  1502. $validated = $this->validate($data);
  1503. if ($validated !== true) {
  1504. return $validated;
  1505. }
  1506. return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
  1507. }
  1508. /**
  1509. * Validate data before storage
  1510. * @param string data
  1511. * @return mixed true if ok string if error found
  1512. */
  1513. public function validate($data) {
  1514. // allow paramtype to be a custom regex if it is the form of /pattern/
  1515. if (preg_match('#^/.*/$#', $this->paramtype)) {
  1516. if (preg_match($this->paramtype, $data)) {
  1517. return true;
  1518. } else {
  1519. return get_string('validateerror', 'admin');
  1520. }
  1521. } else if ($this->paramtype === PARAM_RAW) {
  1522. return true;
  1523. } else {
  1524. $cleaned = clean_param($data, $this->paramtype);
  1525. if ("$data" === "$cleaned") { // implicit conversion to string is needed to do exact comparison
  1526. return true;
  1527. } else {
  1528. return get_string('validateerror', 'admin');
  1529. }
  1530. }
  1531. }
  1532. /**
  1533. * Return an XHTML string for the setting
  1534. * @return string Returns an XHTML string
  1535. */
  1536. public function output_html($data, $query='') {
  1537. $default = $this->get_defaultsetting();
  1538. return format_admin_setting($this, $this->visiblename,
  1539. '<div class="form-text defaultsnext"><input type="text" size="'.$this->size.'" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($data).'" /></div>',
  1540. $this->description, true, '', $default, $query);
  1541. }
  1542. }
  1543. /**
  1544. * General text area without html editor.
  1545. *
  1546. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1547. */
  1548. class admin_setting_configtextarea extends admin_setting_configtext {
  1549. private $rows;
  1550. private $cols;
  1551. /**
  1552. * @param string $name
  1553. * @param string $visiblename
  1554. * @param string $description
  1555. * @param mixed $defaultsetting string or array
  1556. * @param mixed $paramtype
  1557. * @param string $cols The number of columns to make the editor
  1558. * @param string $rows The number of rows to make the editor
  1559. */
  1560. public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
  1561. $this->rows = $rows;
  1562. $this->cols = $cols;
  1563. parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
  1564. }
  1565. /**
  1566. * Returns an XHTML string for the editor
  1567. *
  1568. * @param string $data
  1569. * @param string $query
  1570. * @return string XHTML string for the editor
  1571. */
  1572. public function output_html($data, $query='') {
  1573. $default = $this->get_defaultsetting();
  1574. $defaultinfo = $default;
  1575. if (!is_null($default) and $default !== '') {
  1576. $defaultinfo = "\n".$default;
  1577. }
  1578. return format_admin_setting($this, $this->visiblename,
  1579. '<div class="form-textarea" ><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
  1580. $this->description, true, '', $defaultinfo, $query);
  1581. }
  1582. }
  1583. /**
  1584. * General text area with html editor.
  1585. */
  1586. class admin_setting_confightmleditor extends admin_setting_configtext {
  1587. private $rows;
  1588. private $cols;
  1589. /**
  1590. * @param string $name
  1591. * @param string $visiblename
  1592. * @param string $description
  1593. * @param mixed $defaultsetting string or array
  1594. * @param mixed $paramtype
  1595. */
  1596. public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
  1597. $this->rows = $rows;
  1598. $this->cols = $cols;
  1599. parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
  1600. editors_head_setup();
  1601. }
  1602. /**
  1603. * Returns an XHTML string for the editor
  1604. *
  1605. * @param string $data
  1606. * @param string $query
  1607. * @return string XHTML string for the editor
  1608. */
  1609. public function output_html($data, $query='') {
  1610. $default = $this->get_defaultsetting();
  1611. $defaultinfo = $default;
  1612. if (!is_null($default) and $default !== '') {
  1613. $defaultinfo = "\n".$default;
  1614. }
  1615. $editor = editors_get_preferred_editor(FORMAT_HTML);
  1616. $editor->use_editor($this->get_id(), array('noclean'=>true));
  1617. return format_admin_setting($this, $this->visiblename,
  1618. '<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'">'. s($data) .'</textarea></div>',
  1619. $this->description, true, '', $defaultinfo, $query);
  1620. }
  1621. }
  1622. /**
  1623. * Password field, allows unmasking of password
  1624. *
  1625. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1626. */
  1627. class admin_setting_configpasswordunmask extends admin_setting_configtext {
  1628. /**
  1629. * Constructor
  1630. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1631. * @param string $visiblename localised
  1632. * @param string $description long localised info
  1633. * @param string $defaultsetting default password
  1634. */
  1635. public function __construct($name, $visiblename, $description, $defaultsetting) {
  1636. parent::__construct($name, $visiblename, $description, $defaultsetting, PARAM_RAW, 30);
  1637. }
  1638. /**
  1639. * Returns XHTML for the field
  1640. * Writes Javascript into the HTML below right before the last div
  1641. *
  1642. * @todo Make javascript available through newer methods if possible
  1643. * @param string $data Value for the field
  1644. * @param string $query Passed as final argument for format_admin_setting
  1645. * @return string XHTML field
  1646. */
  1647. public function output_html($data, $query='') {
  1648. $id = $this->get_id();
  1649. $unmask = get_string('unmaskpassword', 'form');
  1650. $unmaskjs = '<script type="text/javascript">
  1651. //<![CDATA[
  1652. var is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
  1653. document.getElementById("'.$id.'").setAttribute("autocomplete", "off");
  1654. var unmaskdiv = document.getElementById("'.$id.'unmaskdiv");
  1655. var unmaskchb = document.createElement("input");
  1656. unmaskchb.setAttribute("type", "checkbox");
  1657. unmaskchb.setAttribute("id", "'.$id.'unmask");
  1658. unmaskchb.onchange = function() {unmaskPassword("'.$id.'");};
  1659. unmaskdiv.appendChild(unmaskchb);
  1660. var unmasklbl = document.createElement("label");
  1661. unmasklbl.innerHTML = "'.addslashes_js($unmask).'";
  1662. if (is_ie) {
  1663. unmasklbl.setAttribute("htmlFor", "'.$id.'unmask");
  1664. } else {
  1665. unmasklbl.setAttribute("for", "'.$id.'unmask");
  1666. }
  1667. unmaskdiv.appendChild(unmasklbl);
  1668. if (is_ie) {
  1669. // ugly hack to work around the famous onchange IE bug
  1670. unmaskchb.onclick = function() {this.blur();};
  1671. unmaskdiv.onclick = function() {this.blur();};
  1672. }
  1673. //]]>
  1674. </script>';
  1675. return format_admin_setting($this, $this->visiblename,
  1676. '<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>',
  1677. $this->description, true, '', NULL, $query);
  1678. }
  1679. }
  1680. /**
  1681. * Path to directory
  1682. *
  1683. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1684. */
  1685. class admin_setting_configfile extends admin_setting_configtext {
  1686. /**
  1687. * Constructor
  1688. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1689. * @param string $visiblename localised
  1690. * @param string $description long localised info
  1691. * @param string $defaultdirectory default directory location
  1692. */
  1693. public function __construct($name, $visiblename, $description, $defaultdirectory) {
  1694. parent::__construct($name, $visiblename, $description, $defaultdirectory, PARAM_RAW, 50);
  1695. }
  1696. /**
  1697. * Returns XHTML for the field
  1698. *
  1699. * Returns XHTML for the field and also checks whether the file
  1700. * specified in $data exists using file_exists()
  1701. *
  1702. * @param string $data File name and path to use in value attr
  1703. * @param string $query
  1704. * @return string XHTML field
  1705. */
  1706. public function output_html($data, $query='') {
  1707. $default = $this->get_defaultsetting();
  1708. if ($data) {
  1709. if (file_exists($data)) {
  1710. $executable = '<span class="pathok">&#x2714;</span>';
  1711. } else {
  1712. $executable = '<span class="patherror">&#x2718;</span>';
  1713. }
  1714. } else {
  1715. $executable = '';
  1716. }
  1717. return format_admin_setting($this, $this->visiblename,
  1718. '<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>',
  1719. $this->description, true, '', $default, $query);
  1720. }
  1721. }
  1722. /**
  1723. * Path to executable file
  1724. *
  1725. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1726. */
  1727. class admin_setting_configexecutable extends admin_setting_configfile {
  1728. /**
  1729. * Returns an XHTML field
  1730. *
  1731. * @param string $data This is the value for the field
  1732. * @param string $query
  1733. * @return string XHTML field
  1734. */
  1735. public function output_html($data, $query='') {
  1736. $default = $this->get_defaultsetting();
  1737. if ($data) {
  1738. if (file_exists($data) and is_executable($data)) {
  1739. $executable = '<span class="pathok">&#x2714;</span>';
  1740. } else {
  1741. $executable = '<span class="patherror">&#x2718;</span>';
  1742. }
  1743. } else {
  1744. $executable = '';
  1745. }
  1746. return format_admin_setting($this, $this->visiblename,
  1747. '<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>',
  1748. $this->description, true, '', $default, $query);
  1749. }
  1750. }
  1751. /**
  1752. * Path to directory
  1753. *
  1754. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1755. */
  1756. class admin_setting_configdirectory extends admin_setting_configfile {
  1757. /**
  1758. * Returns an XHTML field
  1759. *
  1760. * @param string $data This is the value for the field
  1761. * @param string $query
  1762. * @return string XHTML
  1763. */
  1764. public function output_html($data, $query='') {
  1765. $default = $this->get_defaultsetting();
  1766. if ($data) {
  1767. if (file_exists($data) and is_dir($data)) {
  1768. $executable = '<span class="pathok">&#x2714;</span>';
  1769. } else {
  1770. $executable = '<span class="patherror">&#x2718;</span>';
  1771. }
  1772. } else {
  1773. $executable = '';
  1774. }
  1775. return format_admin_setting($this, $this->visiblename,
  1776. '<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>',
  1777. $this->description, true, '', $default, $query);
  1778. }
  1779. }
  1780. /**
  1781. * Checkbox
  1782. *
  1783. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1784. */
  1785. class admin_setting_configcheckbox extends admin_setting {
  1786. /** @var string Value used when checked */
  1787. public $yes;
  1788. /** @var string Value used when not checked */
  1789. public $no;
  1790. /**
  1791. * Constructor
  1792. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1793. * @param string $visiblename localised
  1794. * @param string $description long localised info
  1795. * @param string $defaultsetting
  1796. * @param string $yes value used when checked
  1797. * @param string $no value used when not checked
  1798. */
  1799. public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
  1800. parent::__construct($name, $visiblename, $description, $defaultsetting);
  1801. $this->yes = (string)$yes;
  1802. $this->no = (string)$no;
  1803. }
  1804. /**
  1805. * Retrieves the current setting using the objects name
  1806. *
  1807. * @return string
  1808. */
  1809. public function get_setting() {
  1810. return $this->config_read($this->name);
  1811. }
  1812. /**
  1813. * Sets the value for the setting
  1814. *
  1815. * Sets the value for the setting to either the yes or no values
  1816. * of the object by comparing $data to yes
  1817. *
  1818. * @param mixed $data Gets converted to str for comparison against yes value
  1819. * @return string empty string or error
  1820. */
  1821. public function write_setting($data) {
  1822. if ((string)$data === $this->yes) { // convert to strings before comparison
  1823. $data = $this->yes;
  1824. } else {
  1825. $data = $this->no;
  1826. }
  1827. return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
  1828. }
  1829. /**
  1830. * Returns an XHTML checkbox field
  1831. *
  1832. * @param string $data If $data matches yes then checkbox is checked
  1833. * @param string $query
  1834. * @return string XHTML field
  1835. */
  1836. public function output_html($data, $query='') {
  1837. $default = $this->get_defaultsetting();
  1838. if (!is_null($default)) {
  1839. if ((string)$default === $this->yes) {
  1840. $defaultinfo = get_string('checkboxyes', 'admin');
  1841. } else {
  1842. $defaultinfo = get_string('checkboxno', 'admin');
  1843. }
  1844. } else {
  1845. $defaultinfo = NULL;
  1846. }
  1847. if ((string)$data === $this->yes) { // convert to strings before comparison
  1848. $checked = 'checked="checked"';
  1849. } else {
  1850. $checked = '';
  1851. }
  1852. return format_admin_setting($this, $this->visiblename,
  1853. '<div class="form-checkbox defaultsnext" ><input type="hidden" name="'.$this->get_full_name().'" value="'.s($this->no).'" /> '
  1854. .'<input type="checkbox" id="'.$this->get_id().'" name="'.$this->get_full_name().'" value="'.s($this->yes).'" '.$checked.' /></div>',
  1855. $this->description, true, '', $defaultinfo, $query);
  1856. }
  1857. }
  1858. /**
  1859. * Multiple checkboxes, each represents different value, stored in csv format
  1860. *
  1861. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1862. */
  1863. class admin_setting_configmulticheckbox extends admin_setting {
  1864. /** @var array Array of choices value=>label */
  1865. public $choices;
  1866. /**
  1867. * Constructor: uses parent::__construct
  1868. *
  1869. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  1870. * @param string $visiblename localised
  1871. * @param string $description long localised info
  1872. * @param array $defaultsetting array of selected
  1873. * @param array $choices array of $value=>$label for each checkbox
  1874. */
  1875. public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
  1876. $this->choices = $choices;
  1877. parent::__construct($name, $visiblename, $description, $defaultsetting);
  1878. }
  1879. /**
  1880. * This public function may be used in ancestors for lazy loading of choices
  1881. *
  1882. * @todo Check if this function is still required content commented out only returns true
  1883. * @return bool true if loaded, false if error
  1884. */
  1885. public function load_choices() {
  1886. /*
  1887. if (is_array($this->choices)) {
  1888. return true;
  1889. }
  1890. .... load choices here
  1891. */
  1892. return true;
  1893. }
  1894. /**
  1895. * Is setting related to query text - used when searching
  1896. *
  1897. * @param string $query
  1898. * @return bool true on related, false on not or failure
  1899. */
  1900. public function is_related($query) {
  1901. if (!$this->load_choices() or empty($this->choices)) {
  1902. return false;
  1903. }
  1904. if (parent::is_related($query)) {
  1905. return true;
  1906. }
  1907. $textlib = textlib_get_instance();
  1908. foreach ($this->choices as $desc) {
  1909. if (strpos($textlib->strtolower($desc), $query) !== false) {
  1910. return true;
  1911. }
  1912. }
  1913. return false;
  1914. }
  1915. /**
  1916. * Returns the current setting if it is set
  1917. *
  1918. * @return mixed null if null, else an array
  1919. */
  1920. public function get_setting() {
  1921. $result = $this->config_read($this->name);
  1922. if (is_null($result)) {
  1923. return NULL;
  1924. }
  1925. if ($result === '') {
  1926. return array();
  1927. }
  1928. $enabled = explode(',', $result);
  1929. $setting = array();
  1930. foreach ($enabled as $option) {
  1931. $setting[$option] = 1;
  1932. }
  1933. return $setting;
  1934. }
  1935. /**
  1936. * Saves the setting(s) provided in $data
  1937. *
  1938. * @param array $data An array of data, if not array returns empty str
  1939. * @return mixed empty string on useless data or bool true=success, false=failed
  1940. */
  1941. public function write_setting($data) {
  1942. if (!is_array($data)) {
  1943. return ''; // ignore it
  1944. }
  1945. if (!$this->load_choices() or empty($this->choices)) {
  1946. return '';
  1947. }
  1948. unset($data['xxxxx']);
  1949. $result = array();
  1950. foreach ($data as $key => $value) {
  1951. if ($value and array_key_exists($key, $this->choices)) {
  1952. $result[] = $key;
  1953. }
  1954. }
  1955. return $this->config_write($this->name, implode(',', $result)) ? '' : get_string('errorsetting', 'admin');
  1956. }
  1957. /**
  1958. * Returns XHTML field(s) as required by choices
  1959. *
  1960. * Relies on data being an array should data ever be another valid vartype with
  1961. * acceptable value this may cause a warning/error
  1962. * if (!is_array($data)) would fix the problem
  1963. *
  1964. * @todo Add vartype handling to ensure $data is an array
  1965. *
  1966. * @param array $data An array of checked values
  1967. * @param string $query
  1968. * @return string XHTML field
  1969. */
  1970. public function output_html($data, $query='') {
  1971. if (!$this->load_choices() or empty($this->choices)) {
  1972. return '';
  1973. }
  1974. $default = $this->get_defaultsetting();
  1975. if (is_null($default)) {
  1976. $default = array();
  1977. }
  1978. if (is_null($data)) {
  1979. $data = array();
  1980. }
  1981. $options = array();
  1982. $defaults = array();
  1983. foreach ($this->choices as $key=>$description) {
  1984. if (!empty($data[$key])) {
  1985. $checked = 'checked="checked"';
  1986. } else {
  1987. $checked = '';
  1988. }
  1989. if (!empty($default[$key])) {
  1990. $defaults[] = $description;
  1991. }
  1992. $options[] = '<input type="checkbox" id="'.$this->get_id().'_'.$key.'" name="'.$this->get_full_name().'['.$key.']" value="1" '.$checked.' />'
  1993. .'<label for="'.$this->get_id().'_'.$key.'">'.highlightfast($query, $description).'</label>';
  1994. }
  1995. if (is_null($default)) {
  1996. $defaultinfo = NULL;
  1997. } else if (!empty($defaults)) {
  1998. $defaultinfo = implode(', ', $defaults);
  1999. } else {
  2000. $defaultinfo = get_string('none');
  2001. }
  2002. $return = '<div class="form-multicheckbox">';
  2003. $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
  2004. if ($options) {
  2005. $return .= '<ul>';
  2006. foreach ($options as $option) {
  2007. $return .= '<li>'.$option.'</li>';
  2008. }
  2009. $return .= '</ul>';
  2010. }
  2011. $return .= '</div>';
  2012. return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
  2013. }
  2014. }
  2015. /**
  2016. * Multiple checkboxes 2, value stored as string 00101011
  2017. *
  2018. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2019. */
  2020. class admin_setting_configmulticheckbox2 extends admin_setting_configmulticheckbox {
  2021. /**
  2022. * Returns the setting if set
  2023. *
  2024. * @return mixed null if not set, else an array of set settings
  2025. */
  2026. public function get_setting() {
  2027. $result = $this->config_read($this->name);
  2028. if (is_null($result)) {
  2029. return NULL;
  2030. }
  2031. if (!$this->load_choices()) {
  2032. return NULL;
  2033. }
  2034. $result = str_pad($result, count($this->choices), '0');
  2035. $result = preg_split('//', $result, -1, PREG_SPLIT_NO_EMPTY);
  2036. $setting = array();
  2037. foreach ($this->choices as $key=>$unused) {
  2038. $value = array_shift($result);
  2039. if ($value) {
  2040. $setting[$key] = 1;
  2041. }
  2042. }
  2043. return $setting;
  2044. }
  2045. /**
  2046. * Save setting(s) provided in $data param
  2047. *
  2048. * @param array $data An array of settings to save
  2049. * @return mixed empty string for bad data or bool true=>success, false=>error
  2050. */
  2051. public function write_setting($data) {
  2052. if (!is_array($data)) {
  2053. return ''; // ignore it
  2054. }
  2055. if (!$this->load_choices() or empty($this->choices)) {
  2056. return '';
  2057. }
  2058. $result = '';
  2059. foreach ($this->choices as $key=>$unused) {
  2060. if (!empty($data[$key])) {
  2061. $result .= '1';
  2062. } else {
  2063. $result .= '0';
  2064. }
  2065. }
  2066. return $this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin');
  2067. }
  2068. }
  2069. /**
  2070. * Select one value from list
  2071. *
  2072. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2073. */
  2074. class admin_setting_configselect extends admin_setting {
  2075. /** @var array Array of choices value=>label */
  2076. public $choices;
  2077. /**
  2078. * Constructor
  2079. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  2080. * @param string $visiblename localised
  2081. * @param string $description long localised info
  2082. * @param string|int $defaultsetting
  2083. * @param array $choices array of $value=>$label for each selection
  2084. */
  2085. public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
  2086. $this->choices = $choices;
  2087. parent::__construct($name, $visiblename, $description, $defaultsetting);
  2088. }
  2089. /**
  2090. * This function may be used in ancestors for lazy loading of choices
  2091. *
  2092. * Override this method if loading of choices is expensive, such
  2093. * as when it requires multiple db requests.
  2094. *
  2095. * @return bool true if loaded, false if error
  2096. */
  2097. public function load_choices() {
  2098. /*
  2099. if (is_array($this->choices)) {
  2100. return true;
  2101. }
  2102. .... load choices here
  2103. */
  2104. return true;
  2105. }
  2106. /**
  2107. * Check if this is $query is related to a choice
  2108. *
  2109. * @param string $query
  2110. * @return bool true if related, false if not
  2111. */
  2112. public function is_related($query) {
  2113. if (parent::is_related($query)) {
  2114. return true;
  2115. }
  2116. if (!$this->load_choices()) {
  2117. return false;
  2118. }
  2119. $textlib = textlib_get_instance();
  2120. foreach ($this->choices as $key=>$value) {
  2121. if (strpos($textlib->strtolower($key), $query) !== false) {
  2122. return true;
  2123. }
  2124. if (strpos($textlib->strtolower($value), $query) !== false) {
  2125. return true;
  2126. }
  2127. }
  2128. return false;
  2129. }
  2130. /**
  2131. * Return the setting
  2132. *
  2133. * @return mixed returns config if successful else null
  2134. */
  2135. public function get_setting() {
  2136. return $this->config_read($this->name);
  2137. }
  2138. /**
  2139. * Save a setting
  2140. *
  2141. * @param string $data
  2142. * @return string empty of error string
  2143. */
  2144. public function write_setting($data) {
  2145. if (!$this->load_choices() or empty($this->choices)) {
  2146. return '';
  2147. }
  2148. if (!array_key_exists($data, $this->choices)) {
  2149. return ''; // ignore it
  2150. }
  2151. return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
  2152. }
  2153. /**
  2154. * Returns XHTML select field
  2155. *
  2156. * Ensure the options are loaded, and generate the XHTML for the select
  2157. * element and any warning message. Separating this out from output_html
  2158. * makes it easier to subclass this class.
  2159. *
  2160. * @param string $data the option to show as selected.
  2161. * @param string $current the currently selected option in the database, null if none.
  2162. * @param string $default the default selected option.
  2163. * @return array the HTML for the select element, and a warning message.
  2164. */
  2165. public function output_select_html($data, $current, $default, $extraname = '') {
  2166. if (!$this->load_choices() or empty($this->choices)) {
  2167. return array('', '');
  2168. }
  2169. $warning = '';
  2170. if (is_null($current)) {
  2171. // first run
  2172. } else if (empty($current) and (array_key_exists('', $this->choices) or array_key_exists(0, $this->choices))) {
  2173. // no warning
  2174. } else if (!array_key_exists($current, $this->choices)) {
  2175. $warning = get_string('warningcurrentsetting', 'admin', s($current));
  2176. if (!is_null($default) and $data == $current) {
  2177. $data = $default; // use default instead of first value when showing the form
  2178. }
  2179. }
  2180. $selecthtml = '<select id="'.$this->get_id().'" name="'.$this->get_full_name().$extraname.'">';
  2181. foreach ($this->choices as $key => $value) {
  2182. // the string cast is needed because key may be integer - 0 is equal to most strings!
  2183. $selecthtml .= '<option value="'.$key.'"'.((string)$key==$data ? ' selected="selected"' : '').'>'.$value.'</option>';
  2184. }
  2185. $selecthtml .= '</select>';
  2186. return array($selecthtml, $warning);
  2187. }
  2188. /**
  2189. * Returns XHTML select field and wrapping div(s)
  2190. *
  2191. * @see output_select_html()
  2192. *
  2193. * @param string $data the option to show as selected
  2194. * @param string $query
  2195. * @return string XHTML field and wrapping div
  2196. */
  2197. public function output_html($data, $query='') {
  2198. $default = $this->get_defaultsetting();
  2199. $current = $this->get_setting();
  2200. list($selecthtml, $warning) = $this->output_select_html($data, $current, $default);
  2201. if (!$selecthtml) {
  2202. return '';
  2203. }
  2204. if (!is_null($default) and array_key_exists($default, $this->choices)) {
  2205. $defaultinfo = $this->choices[$default];
  2206. } else {
  2207. $defaultinfo = NULL;
  2208. }
  2209. $return = '<div class="form-select defaultsnext">' . $selecthtml . '</div>';
  2210. return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
  2211. }
  2212. }
  2213. /**
  2214. * Select multiple items from list
  2215. *
  2216. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2217. */
  2218. class admin_setting_configmultiselect extends admin_setting_configselect {
  2219. /**
  2220. * Constructor
  2221. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  2222. * @param string $visiblename localised
  2223. * @param string $description long localised info
  2224. * @param array $defaultsetting array of selected items
  2225. * @param array $choices array of $value=>$label for each list item
  2226. */
  2227. public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
  2228. parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
  2229. }
  2230. /**
  2231. * Returns the select setting(s)
  2232. *
  2233. * @return mixed null or array. Null if no settings else array of setting(s)
  2234. */
  2235. public function get_setting() {
  2236. $result = $this->config_read($this->name);
  2237. if (is_null($result)) {
  2238. return NULL;
  2239. }
  2240. if ($result === '') {
  2241. return array();
  2242. }
  2243. return explode(',', $result);
  2244. }
  2245. /**
  2246. * Saves setting(s) provided through $data
  2247. *
  2248. * Potential bug in the works should anyone call with this function
  2249. * using a vartype that is not an array
  2250. *
  2251. * @todo Add vartype handling to ensure $data is an array
  2252. * @param array $data
  2253. */
  2254. public function write_setting($data) {
  2255. if (!is_array($data)) {
  2256. return ''; //ignore it
  2257. }
  2258. if (!$this->load_choices() or empty($this->choices)) {
  2259. return '';
  2260. }
  2261. unset($data['xxxxx']);
  2262. $save = array();
  2263. foreach ($data as $value) {
  2264. if (!array_key_exists($value, $this->choices)) {
  2265. continue; // ignore it
  2266. }
  2267. $save[] = $value;
  2268. }
  2269. return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
  2270. }
  2271. /**
  2272. * Is setting related to query text - used when searching
  2273. *
  2274. * @param string $query
  2275. * @return bool true if related, false if not
  2276. */
  2277. public function is_related($query) {
  2278. if (!$this->load_choices() or empty($this->choices)) {
  2279. return false;
  2280. }
  2281. if (parent::is_related($query)) {
  2282. return true;
  2283. }
  2284. $textlib = textlib_get_instance();
  2285. foreach ($this->choices as $desc) {
  2286. if (strpos($textlib->strtolower($desc), $query) !== false) {
  2287. return true;
  2288. }
  2289. }
  2290. return false;
  2291. }
  2292. /**
  2293. * Returns XHTML multi-select field
  2294. *
  2295. * @todo Add vartype handling to ensure $data is an array
  2296. * @param array $data Array of values to select by default
  2297. * @param string $query
  2298. * @return string XHTML multi-select field
  2299. */
  2300. public function output_html($data, $query='') {
  2301. if (!$this->load_choices() or empty($this->choices)) {
  2302. return '';
  2303. }
  2304. $choices = $this->choices;
  2305. $default = $this->get_defaultsetting();
  2306. if (is_null($default)) {
  2307. $default = array();
  2308. }
  2309. if (is_null($data)) {
  2310. $data = array();
  2311. }
  2312. $defaults = array();
  2313. $size = min(10, count($this->choices));
  2314. $return = '<div class="form-select"><input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
  2315. $return .= '<select id="'.$this->get_id().'" name="'.$this->get_full_name().'[]" size="'.$size.'" multiple="multiple">';
  2316. foreach ($this->choices as $key => $description) {
  2317. if (in_array($key, $data)) {
  2318. $selected = 'selected="selected"';
  2319. } else {
  2320. $selected = '';
  2321. }
  2322. if (in_array($key, $default)) {
  2323. $defaults[] = $description;
  2324. }
  2325. $return .= '<option value="'.s($key).'" '.$selected.'>'.$description.'</option>';
  2326. }
  2327. if (is_null($default)) {
  2328. $defaultinfo = NULL;
  2329. } if (!empty($defaults)) {
  2330. $defaultinfo = implode(', ', $defaults);
  2331. } else {
  2332. $defaultinfo = get_string('none');
  2333. }
  2334. $return .= '</select></div>';
  2335. return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
  2336. }
  2337. }
  2338. /**
  2339. * Time selector
  2340. *
  2341. * This is a liiitle bit messy. we're using two selects, but we're returning
  2342. * them as an array named after $name (so we only use $name2 internally for the setting)
  2343. *
  2344. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2345. */
  2346. class admin_setting_configtime extends admin_setting {
  2347. /** @var string Used for setting second select (minutes) */
  2348. public $name2;
  2349. /**
  2350. * Constructor
  2351. * @param string $hoursname setting for hours
  2352. * @param string $minutesname setting for hours
  2353. * @param string $visiblename localised
  2354. * @param string $description long localised info
  2355. * @param array $defaultsetting array representing default time 'h'=>hours, 'm'=>minutes
  2356. */
  2357. public function __construct($hoursname, $minutesname, $visiblename, $description, $defaultsetting) {
  2358. $this->name2 = $minutesname;
  2359. parent::__construct($hoursname, $visiblename, $description, $defaultsetting);
  2360. }
  2361. /**
  2362. * Get the selected time
  2363. *
  2364. * @return mixed An array containing 'h'=>xx, 'm'=>xx, or null if not set
  2365. */
  2366. public function get_setting() {
  2367. $result1 = $this->config_read($this->name);
  2368. $result2 = $this->config_read($this->name2);
  2369. if (is_null($result1) or is_null($result2)) {
  2370. return NULL;
  2371. }
  2372. return array('h' => $result1, 'm' => $result2);
  2373. }
  2374. /**
  2375. * Store the time (hours and minutes)
  2376. *
  2377. * @param array $data Must be form 'h'=>xx, 'm'=>xx
  2378. * @return bool true if success, false if not
  2379. */
  2380. public function write_setting($data) {
  2381. if (!is_array($data)) {
  2382. return '';
  2383. }
  2384. $result = $this->config_write($this->name, (int)$data['h']) && $this->config_write($this->name2, (int)$data['m']);
  2385. return ($result ? '' : get_string('errorsetting', 'admin'));
  2386. }
  2387. /**
  2388. * Returns XHTML time select fields
  2389. *
  2390. * @param array $data Must be form 'h'=>xx, 'm'=>xx
  2391. * @param string $query
  2392. * @return string XHTML time select fields and wrapping div(s)
  2393. */
  2394. public function output_html($data, $query='') {
  2395. $default = $this->get_defaultsetting();
  2396. if (is_array($default)) {
  2397. $defaultinfo = $default['h'].':'.$default['m'];
  2398. } else {
  2399. $defaultinfo = NULL;
  2400. }
  2401. $return = '<div class="form-time defaultsnext">'.
  2402. '<select id="'.$this->get_id().'h" name="'.$this->get_full_name().'[h]">';
  2403. for ($i = 0; $i < 24; $i++) {
  2404. $return .= '<option value="'.$i.'"'.($i == $data['h'] ? ' selected="selected"' : '').'>'.$i.'</option>';
  2405. }
  2406. $return .= '</select>:<select id="'.$this->get_id().'m" name="'.$this->get_full_name().'[m]">';
  2407. for ($i = 0; $i < 60; $i += 5) {
  2408. $return .= '<option value="'.$i.'"'.($i == $data['m'] ? ' selected="selected"' : '').'>'.$i.'</option>';
  2409. }
  2410. $return .= '</select></div>';
  2411. return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', $defaultinfo, $query);
  2412. }
  2413. }
  2414. /**
  2415. * Used to validate a textarea used for ip addresses
  2416. *
  2417. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2418. */
  2419. class admin_setting_configiplist extends admin_setting_configtextarea {
  2420. /**
  2421. * Validate the contents of the textarea as IP addresses
  2422. *
  2423. * Used to validate a new line separated list of IP addresses collected from
  2424. * a textarea control
  2425. *
  2426. * @param string $data A list of IP Addresses separated by new lines
  2427. * @return mixed bool true for success or string:error on failure
  2428. */
  2429. public function validate($data) {
  2430. if(!empty($data)) {
  2431. $ips = explode("\n", $data);
  2432. } else {
  2433. return true;
  2434. }
  2435. $result = true;
  2436. foreach($ips as $ip) {
  2437. $ip = trim($ip);
  2438. if(preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}$#', $ip, $match) ||
  2439. preg_match('#^(\d{1,3})(\.\d{1,3}){0,3}(\/\d{1,2})$#', $ip, $match) ||
  2440. preg_match('#^(\d{1,3})(\.\d{1,3}){3}(-\d{1,3})$#', $ip, $match)) {
  2441. $result = true;
  2442. } else {
  2443. $result = false;
  2444. break;
  2445. }
  2446. }
  2447. if($result) {
  2448. return true;
  2449. } else {
  2450. return get_string('validateerror', 'admin');
  2451. }
  2452. }
  2453. }
  2454. /**
  2455. * An admin setting for selecting one or more users who have a capability
  2456. * in the system context
  2457. *
  2458. * An admin setting for selecting one or more users, who have a particular capability
  2459. * in the system context. Warning, make sure the list will never be too long. There is
  2460. * no paging or searching of this list.
  2461. *
  2462. * To correctly get a list of users from this config setting, you need to call the
  2463. * get_users_from_config($CFG->mysetting, $capability); function in moodlelib.php.
  2464. *
  2465. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2466. */
  2467. class admin_setting_users_with_capability extends admin_setting_configmultiselect {
  2468. /** @var string The capabilities name */
  2469. protected $capability;
  2470. /** @var int include admin users too */
  2471. protected $includeadmins;
  2472. /**
  2473. * Constructor.
  2474. *
  2475. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  2476. * @param string $visiblename localised name
  2477. * @param string $description localised long description
  2478. * @param array $defaultsetting array of usernames
  2479. * @param string $capability string capability name.
  2480. * @param bool $includeadmins include administrators
  2481. */
  2482. function __construct($name, $visiblename, $description, $defaultsetting, $capability, $includeadmins = true) {
  2483. $this->capability = $capability;
  2484. $this->includeadmins = $includeadmins;
  2485. parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
  2486. }
  2487. /**
  2488. * Load all of the uses who have the capability into choice array
  2489. *
  2490. * @return bool Always returns true
  2491. */
  2492. function load_choices() {
  2493. if (is_array($this->choices)) {
  2494. return true;
  2495. }
  2496. $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM),
  2497. $this->capability, 'u.id,u.username,u.firstname,u.lastname', 'u.lastname,u.firstname');
  2498. $this->choices = array(
  2499. '$@NONE@$' => get_string('nobody'),
  2500. '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)),
  2501. );
  2502. if ($this->includeadmins) {
  2503. $admins = get_admins();
  2504. foreach ($admins as $user) {
  2505. $this->choices[$user->id] = fullname($user);
  2506. }
  2507. }
  2508. if (is_array($users)) {
  2509. foreach ($users as $user) {
  2510. $this->choices[$user->id] = fullname($user);
  2511. }
  2512. }
  2513. return true;
  2514. }
  2515. /**
  2516. * Returns the default setting for class
  2517. *
  2518. * @return mixed Array, or string. Empty string if no default
  2519. */
  2520. public function get_defaultsetting() {
  2521. $this->load_choices();
  2522. $defaultsetting = parent::get_defaultsetting();
  2523. if (empty($defaultsetting)) {
  2524. return array('$@NONE@$');
  2525. } else if (array_key_exists($defaultsetting, $this->choices)) {
  2526. return $defaultsetting;
  2527. } else {
  2528. return '';
  2529. }
  2530. }
  2531. /**
  2532. * Returns the current setting
  2533. *
  2534. * @return mixed array or string
  2535. */
  2536. public function get_setting() {
  2537. $result = parent::get_setting();
  2538. if ($result === null) {
  2539. // this is necessary for settings upgrade
  2540. return null;
  2541. }
  2542. if (empty($result)) {
  2543. $result = array('$@NONE@$');
  2544. }
  2545. return $result;
  2546. }
  2547. /**
  2548. * Save the chosen setting provided as $data
  2549. *
  2550. * @param array $data
  2551. * @return mixed string or array
  2552. */
  2553. public function write_setting($data) {
  2554. // If all is selected, remove any explicit options.
  2555. if (in_array('$@ALL@$', $data)) {
  2556. $data = array('$@ALL@$');
  2557. }
  2558. // None never needs to be written to the DB.
  2559. if (in_array('$@NONE@$', $data)) {
  2560. unset($data[array_search('$@NONE@$', $data)]);
  2561. }
  2562. return parent::write_setting($data);
  2563. }
  2564. }
  2565. /**
  2566. * Special checkbox for calendar - resets SESSION vars.
  2567. *
  2568. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2569. */
  2570. class admin_setting_special_adminseesall extends admin_setting_configcheckbox {
  2571. /**
  2572. * Calls the parent::__construct with default values
  2573. *
  2574. * name => calendar_adminseesall
  2575. * visiblename => get_string('adminseesall', 'admin')
  2576. * description => get_string('helpadminseesall', 'admin')
  2577. * defaultsetting => 0
  2578. */
  2579. public function __construct() {
  2580. parent::__construct('calendar_adminseesall', get_string('adminseesall', 'admin'),
  2581. get_string('helpadminseesall', 'admin'), '0');
  2582. }
  2583. /**
  2584. * Stores the setting passed in $data
  2585. *
  2586. * @param mixed gets converted to string for comparison
  2587. * @return string empty string or error message
  2588. */
  2589. public function write_setting($data) {
  2590. global $SESSION;
  2591. unset($SESSION->cal_courses_shown);
  2592. return parent::write_setting($data);
  2593. }
  2594. }
  2595. /**
  2596. * Special select for settings that are altered in setup.php and can not be altered on the fly
  2597. *
  2598. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2599. */
  2600. class admin_setting_special_selectsetup extends admin_setting_configselect {
  2601. /**
  2602. * Reads the setting directly from the database
  2603. *
  2604. * @return mixed
  2605. */
  2606. public function get_setting() {
  2607. // read directly from db!
  2608. return get_config(NULL, $this->name);
  2609. }
  2610. /**
  2611. * Save the setting passed in $data
  2612. *
  2613. * @param string $data The setting to save
  2614. * @return string empty or error message
  2615. */
  2616. public function write_setting($data) {
  2617. global $CFG;
  2618. // do not change active CFG setting!
  2619. $current = $CFG->{$this->name};
  2620. $result = parent::write_setting($data);
  2621. $CFG->{$this->name} = $current;
  2622. return $result;
  2623. }
  2624. }
  2625. /**
  2626. * Special select for frontpage - stores data in course table
  2627. *
  2628. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2629. */
  2630. class admin_setting_sitesetselect extends admin_setting_configselect {
  2631. /**
  2632. * Returns the site name for the selected site
  2633. *
  2634. * @see get_site()
  2635. * @return string The site name of the selected site
  2636. */
  2637. public function get_setting() {
  2638. $site = get_site();
  2639. return $site->{$this->name};
  2640. }
  2641. /**
  2642. * Updates the database and save the setting
  2643. *
  2644. * @param string data
  2645. * @return string empty or error message
  2646. */
  2647. public function write_setting($data) {
  2648. global $DB, $SITE;
  2649. if (!in_array($data, array_keys($this->choices))) {
  2650. return get_string('errorsetting', 'admin');
  2651. }
  2652. $record = new stdClass();
  2653. $record->id = SITEID;
  2654. $temp = $this->name;
  2655. $record->$temp = $data;
  2656. $record->timemodified = time();
  2657. // update $SITE
  2658. $SITE->{$this->name} = $data;
  2659. return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
  2660. }
  2661. }
  2662. /**
  2663. * Select for blog's bloglevel setting: if set to 0, will set blog_menu
  2664. * block to hidden.
  2665. *
  2666. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2667. */
  2668. class admin_setting_bloglevel extends admin_setting_configselect {
  2669. /**
  2670. * Updates the database and save the setting
  2671. *
  2672. * @param string data
  2673. * @return string empty or error message
  2674. */
  2675. public function write_setting($data) {
  2676. global $DB;
  2677. if ($data['bloglevel'] == 0) {
  2678. $DB->set_field('block', 'visible', 0, array('name' => 'blog_menu'));
  2679. } else {
  2680. $DB->set_field('block', 'visible', 1, array('name' => 'blog_menu'));
  2681. }
  2682. return parent::write_setting($data);
  2683. }
  2684. }
  2685. /**
  2686. * Special select - lists on the frontpage - hacky
  2687. *
  2688. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2689. */
  2690. class admin_setting_courselist_frontpage extends admin_setting {
  2691. /** @var array Array of choices value=>label */
  2692. public $choices;
  2693. /**
  2694. * Construct override, requires one param
  2695. *
  2696. * @param bool $loggedin Is the user logged in
  2697. */
  2698. public function __construct($loggedin) {
  2699. global $CFG;
  2700. require_once($CFG->dirroot.'/course/lib.php');
  2701. $name = 'frontpage'.($loggedin ? 'loggedin' : '');
  2702. $visiblename = get_string('frontpage'.($loggedin ? 'loggedin' : ''),'admin');
  2703. $description = get_string('configfrontpage'.($loggedin ? 'loggedin' : ''),'admin');
  2704. $defaults = array(FRONTPAGECOURSELIST);
  2705. parent::__construct($name, $visiblename, $description, $defaults);
  2706. }
  2707. /**
  2708. * Loads the choices available
  2709. *
  2710. * @return bool always returns true
  2711. */
  2712. public function load_choices() {
  2713. global $DB;
  2714. if (is_array($this->choices)) {
  2715. return true;
  2716. }
  2717. $this->choices = array(FRONTPAGENEWS => get_string('frontpagenews'),
  2718. FRONTPAGECOURSELIST => get_string('frontpagecourselist'),
  2719. FRONTPAGECATEGORYNAMES => get_string('frontpagecategorynames'),
  2720. FRONTPAGECATEGORYCOMBO => get_string('frontpagecategorycombo'),
  2721. 'none' => get_string('none'));
  2722. if ($this->name == 'frontpage' and $DB->count_records('course') > FRONTPAGECOURSELIMIT) {
  2723. unset($this->choices[FRONTPAGECOURSELIST]);
  2724. }
  2725. return true;
  2726. }
  2727. /**
  2728. * Returns the selected settings
  2729. *
  2730. * @param mixed array or setting or null
  2731. */
  2732. public function get_setting() {
  2733. $result = $this->config_read($this->name);
  2734. if (is_null($result)) {
  2735. return NULL;
  2736. }
  2737. if ($result === '') {
  2738. return array();
  2739. }
  2740. return explode(',', $result);
  2741. }
  2742. /**
  2743. * Save the selected options
  2744. *
  2745. * @param array $data
  2746. * @return mixed empty string (data is not an array) or bool true=success false=failure
  2747. */
  2748. public function write_setting($data) {
  2749. if (!is_array($data)) {
  2750. return '';
  2751. }
  2752. $this->load_choices();
  2753. $save = array();
  2754. foreach($data as $datum) {
  2755. if ($datum == 'none' or !array_key_exists($datum, $this->choices)) {
  2756. continue;
  2757. }
  2758. $save[$datum] = $datum; // no duplicates
  2759. }
  2760. return ($this->config_write($this->name, implode(',', $save)) ? '' : get_string('errorsetting', 'admin'));
  2761. }
  2762. /**
  2763. * Return XHTML select field and wrapping div
  2764. *
  2765. * @todo Add vartype handling to make sure $data is an array
  2766. * @param array $data Array of elements to select by default
  2767. * @return string XHTML select field and wrapping div
  2768. */
  2769. public function output_html($data, $query='') {
  2770. $this->load_choices();
  2771. $currentsetting = array();
  2772. foreach ($data as $key) {
  2773. if ($key != 'none' and array_key_exists($key, $this->choices)) {
  2774. $currentsetting[] = $key; // already selected first
  2775. }
  2776. }
  2777. $return = '<div class="form-group">';
  2778. for ($i = 0; $i < count($this->choices) - 1; $i++) {
  2779. if (!array_key_exists($i, $currentsetting)) {
  2780. $currentsetting[$i] = 'none'; //none
  2781. }
  2782. $return .='<select class="form-select" id="'.$this->get_id().$i.'" name="'.$this->get_full_name().'[]">';
  2783. foreach ($this->choices as $key => $value) {
  2784. $return .= '<option value="'.$key.'"'.("$key" == $currentsetting[$i] ? ' selected="selected"' : '').'>'.$value.'</option>';
  2785. }
  2786. $return .= '</select>';
  2787. if ($i !== count($this->choices) - 2) {
  2788. $return .= '<br />';
  2789. }
  2790. }
  2791. $return .= '</div>';
  2792. return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
  2793. }
  2794. }
  2795. /**
  2796. * Special checkbox for frontpage - stores data in course table
  2797. *
  2798. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2799. */
  2800. class admin_setting_sitesetcheckbox extends admin_setting_configcheckbox {
  2801. /**
  2802. * Returns the current sites name
  2803. *
  2804. * @return string
  2805. */
  2806. public function get_setting() {
  2807. $site = get_site();
  2808. return $site->{$this->name};
  2809. }
  2810. /**
  2811. * Save the selected setting
  2812. *
  2813. * @param string $data The selected site
  2814. * @return string empty string or error message
  2815. */
  2816. public function write_setting($data) {
  2817. global $DB, $SITE;
  2818. $record = new stdClass();
  2819. $record->id = SITEID;
  2820. $record->{$this->name} = ($data == '1' ? 1 : 0);
  2821. $record->timemodified = time();
  2822. // update $SITE
  2823. $SITE->{$this->name} = $data;
  2824. return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
  2825. }
  2826. }
  2827. /**
  2828. * Special text for frontpage - stores data in course table.
  2829. * Empty string means not set here. Manual setting is required.
  2830. *
  2831. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2832. */
  2833. class admin_setting_sitesettext extends admin_setting_configtext {
  2834. /**
  2835. * Return the current setting
  2836. *
  2837. * @return mixed string or null
  2838. */
  2839. public function get_setting() {
  2840. $site = get_site();
  2841. return $site->{$this->name} != '' ? $site->{$this->name} : NULL;
  2842. }
  2843. /**
  2844. * Validate the selected data
  2845. *
  2846. * @param string $data The selected value to validate
  2847. * @return mixed true or message string
  2848. */
  2849. public function validate($data) {
  2850. $cleaned = clean_param($data, PARAM_MULTILANG);
  2851. if ($cleaned === '') {
  2852. return get_string('required');
  2853. }
  2854. if ("$data" == "$cleaned") { // implicit conversion to string is needed to do exact comparison
  2855. return true;
  2856. } else {
  2857. return get_string('validateerror', 'admin');
  2858. }
  2859. }
  2860. /**
  2861. * Save the selected setting
  2862. *
  2863. * @param string $data The selected value
  2864. * @return string empty or error message
  2865. */
  2866. public function write_setting($data) {
  2867. global $DB, $SITE;
  2868. $data = trim($data);
  2869. $validated = $this->validate($data);
  2870. if ($validated !== true) {
  2871. return $validated;
  2872. }
  2873. $record = new stdClass();
  2874. $record->id = SITEID;
  2875. $record->{$this->name} = $data;
  2876. $record->timemodified = time();
  2877. // update $SITE
  2878. $SITE->{$this->name} = $data;
  2879. return ($DB->update_record('course', $record) ? '' : get_string('dbupdatefailed', 'error'));
  2880. }
  2881. }
  2882. /**
  2883. * Special text editor for site description.
  2884. *
  2885. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2886. */
  2887. class admin_setting_special_frontpagedesc extends admin_setting {
  2888. /**
  2889. * Calls parent::__construct with specific arguments
  2890. */
  2891. public function __construct() {
  2892. parent::__construct('summary', get_string('frontpagedescription'), get_string('frontpagedescriptionhelp'), NULL);
  2893. editors_head_setup();
  2894. }
  2895. /**
  2896. * Return the current setting
  2897. * @return string The current setting
  2898. */
  2899. public function get_setting() {
  2900. $site = get_site();
  2901. return $site->{$this->name};
  2902. }
  2903. /**
  2904. * Save the new setting
  2905. *
  2906. * @param string $data The new value to save
  2907. * @return string empty or error message
  2908. */
  2909. public function write_setting($data) {
  2910. global $DB, $SITE;
  2911. $record = new stdClass();
  2912. $record->id = SITEID;
  2913. $record->{$this->name} = $data;
  2914. $record->timemodified = time();
  2915. $SITE->{$this->name} = $data;
  2916. return ($DB->update_record('course', $record) ? '' : get_string('errorsetting', 'admin'));
  2917. }
  2918. /**
  2919. * Returns XHTML for the field plus wrapping div
  2920. *
  2921. * @param string $data The current value
  2922. * @param string $query
  2923. * @return string The XHTML output
  2924. */
  2925. public function output_html($data, $query='') {
  2926. global $CFG;
  2927. $CFG->adminusehtmleditor = can_use_html_editor();
  2928. $return = '<div class="form-htmlarea">'.print_textarea($CFG->adminusehtmleditor, 15, 60, 0, 0, $this->get_full_name(), $data, 0, true, 'summary') .'</div>';
  2929. return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
  2930. }
  2931. }
  2932. /**
  2933. * Administration interface for emoticon_manager settings.
  2934. *
  2935. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2936. */
  2937. class admin_setting_emoticons extends admin_setting {
  2938. /**
  2939. * Calls parent::__construct with specific args
  2940. */
  2941. public function __construct() {
  2942. global $CFG;
  2943. $manager = get_emoticon_manager();
  2944. $defaults = $this->prepare_form_data($manager->default_emoticons());
  2945. parent::__construct('emoticons', get_string('emoticons', 'admin'), get_string('emoticons_desc', 'admin'), $defaults);
  2946. }
  2947. /**
  2948. * Return the current setting(s)
  2949. *
  2950. * @return array Current settings array
  2951. */
  2952. public function get_setting() {
  2953. global $CFG;
  2954. $manager = get_emoticon_manager();
  2955. $config = $this->config_read($this->name);
  2956. if (is_null($config)) {
  2957. return null;
  2958. }
  2959. $config = $manager->decode_stored_config($config);
  2960. if (is_null($config)) {
  2961. return null;
  2962. }
  2963. return $this->prepare_form_data($config);
  2964. }
  2965. /**
  2966. * Save selected settings
  2967. *
  2968. * @param array $data Array of settings to save
  2969. * @return bool
  2970. */
  2971. public function write_setting($data) {
  2972. $manager = get_emoticon_manager();
  2973. $emoticons = $this->process_form_data($data);
  2974. if ($emoticons === false) {
  2975. return false;
  2976. }
  2977. if ($this->config_write($this->name, $manager->encode_stored_config($emoticons))) {
  2978. return ''; // success
  2979. } else {
  2980. return get_string('errorsetting', 'admin') . $this->visiblename . html_writer::empty_tag('br');
  2981. }
  2982. }
  2983. /**
  2984. * Return XHTML field(s) for options
  2985. *
  2986. * @param array $data Array of options to set in HTML
  2987. * @return string XHTML string for the fields and wrapping div(s)
  2988. */
  2989. public function output_html($data, $query='') {
  2990. global $OUTPUT;
  2991. $out = html_writer::start_tag('table', array('border' => 1, 'class' => 'generaltable'));
  2992. $out .= html_writer::start_tag('thead');
  2993. $out .= html_writer::start_tag('tr');
  2994. $out .= html_writer::tag('th', get_string('emoticontext', 'admin'));
  2995. $out .= html_writer::tag('th', get_string('emoticonimagename', 'admin'));
  2996. $out .= html_writer::tag('th', get_string('emoticoncomponent', 'admin'));
  2997. $out .= html_writer::tag('th', get_string('emoticonalt', 'admin'), array('colspan' => 2));
  2998. $out .= html_writer::tag('th', '');
  2999. $out .= html_writer::end_tag('tr');
  3000. $out .= html_writer::end_tag('thead');
  3001. $out .= html_writer::start_tag('tbody');
  3002. $i = 0;
  3003. foreach($data as $field => $value) {
  3004. switch ($i) {
  3005. case 0:
  3006. $out .= html_writer::start_tag('tr');
  3007. $current_text = $value;
  3008. $current_filename = '';
  3009. $current_imagecomponent = '';
  3010. $current_altidentifier = '';
  3011. $current_altcomponent = '';
  3012. case 1:
  3013. $current_filename = $value;
  3014. case 2:
  3015. $current_imagecomponent = $value;
  3016. case 3:
  3017. $current_altidentifier = $value;
  3018. case 4:
  3019. $current_altcomponent = $value;
  3020. }
  3021. $out .= html_writer::tag('td',
  3022. html_writer::empty_tag('input',
  3023. array(
  3024. 'type' => 'text',
  3025. 'class' => 'form-text',
  3026. 'name' => $this->get_full_name().'['.$field.']',
  3027. 'value' => $value,
  3028. )
  3029. ), array('class' => 'c'.$i)
  3030. );
  3031. if ($i == 4) {
  3032. if (get_string_manager()->string_exists($current_altidentifier, $current_altcomponent)) {
  3033. $alt = get_string($current_altidentifier, $current_altcomponent);
  3034. } else {
  3035. $alt = $current_text;
  3036. }
  3037. if ($current_filename) {
  3038. $out .= html_writer::tag('td', $OUTPUT->render(new pix_emoticon($current_filename, $alt, $current_imagecomponent)));
  3039. } else {
  3040. $out .= html_writer::tag('td', '');
  3041. }
  3042. $out .= html_writer::end_tag('tr');
  3043. $i = 0;
  3044. } else {
  3045. $i++;
  3046. }
  3047. }
  3048. $out .= html_writer::end_tag('tbody');
  3049. $out .= html_writer::end_tag('table');
  3050. $out = html_writer::tag('div', $out, array('class' => 'form-group'));
  3051. $out .= html_writer::tag('div', html_writer::link(new moodle_url('/admin/resetemoticons.php'), get_string('emoticonsreset', 'admin')));
  3052. return format_admin_setting($this, $this->visiblename, $out, $this->description, false, '', NULL, $query);
  3053. }
  3054. /**
  3055. * Converts the array of emoticon objects provided by {@see emoticon_manager} into admin settings form data
  3056. *
  3057. * @see self::process_form_data()
  3058. * @param array $emoticons array of emoticon objects as returned by {@see emoticon_manager}
  3059. * @return array of form fields and their values
  3060. */
  3061. protected function prepare_form_data(array $emoticons) {
  3062. $form = array();
  3063. $i = 0;
  3064. foreach ($emoticons as $emoticon) {
  3065. $form['text'.$i] = $emoticon->text;
  3066. $form['imagename'.$i] = $emoticon->imagename;
  3067. $form['imagecomponent'.$i] = $emoticon->imagecomponent;
  3068. $form['altidentifier'.$i] = $emoticon->altidentifier;
  3069. $form['altcomponent'.$i] = $emoticon->altcomponent;
  3070. $i++;
  3071. }
  3072. // add one more blank field set for new object
  3073. $form['text'.$i] = '';
  3074. $form['imagename'.$i] = '';
  3075. $form['imagecomponent'.$i] = '';
  3076. $form['altidentifier'.$i] = '';
  3077. $form['altcomponent'.$i] = '';
  3078. return $form;
  3079. }
  3080. /**
  3081. * Converts the data from admin settings form into an array of emoticon objects
  3082. *
  3083. * @see self::prepare_form_data()
  3084. * @param array $data array of admin form fields and values
  3085. * @return false|array of emoticon objects
  3086. */
  3087. protected function process_form_data(array $form) {
  3088. $count = count($form); // number of form field values
  3089. if ($count % 5) {
  3090. // we must get five fields per emoticon object
  3091. return false;
  3092. }
  3093. $emoticons = array();
  3094. for ($i = 0; $i < $count / 5; $i++) {
  3095. $emoticon = new stdClass();
  3096. $emoticon->text = clean_param(trim($form['text'.$i]), PARAM_NOTAGS);
  3097. $emoticon->imagename = clean_param(trim($form['imagename'.$i]), PARAM_PATH);
  3098. $emoticon->imagecomponent = clean_param(trim($form['imagecomponent'.$i]), PARAM_SAFEDIR);
  3099. $emoticon->altidentifier = clean_param(trim($form['altidentifier'.$i]), PARAM_STRINGID);
  3100. $emoticon->altcomponent = clean_param(trim($form['altcomponent'.$i]), PARAM_SAFEDIR);
  3101. if (strpos($emoticon->text, ':/') !== false or strpos($emoticon->text, '//') !== false) {
  3102. // prevent from breaking http://url.addresses by accident
  3103. $emoticon->text = '';
  3104. }
  3105. if (strlen($emoticon->text) < 2) {
  3106. // do not allow single character emoticons
  3107. $emoticon->text = '';
  3108. }
  3109. if (preg_match('/^[a-zA-Z]+[a-zA-Z0-9]*$/', $emoticon->text)) {
  3110. // emoticon text must contain some non-alphanumeric character to prevent
  3111. // breaking HTML tags
  3112. $emoticon->text = '';
  3113. }
  3114. if ($emoticon->text !== '' and $emoticon->imagename !== '' and $emoticon->imagecomponent !== '') {
  3115. $emoticons[] = $emoticon;
  3116. }
  3117. }
  3118. return $emoticons;
  3119. }
  3120. }
  3121. /**
  3122. * Special setting for limiting of the list of available languages.
  3123. *
  3124. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3125. */
  3126. class admin_setting_langlist extends admin_setting_configtext {
  3127. /**
  3128. * Calls parent::__construct with specific arguments
  3129. */
  3130. public function __construct() {
  3131. parent::__construct('langlist', get_string('langlist', 'admin'), get_string('configlanglist', 'admin'), '', PARAM_NOTAGS);
  3132. }
  3133. /**
  3134. * Save the new setting
  3135. *
  3136. * @param string $data The new setting
  3137. * @return bool
  3138. */
  3139. public function write_setting($data) {
  3140. $return = parent::write_setting($data);
  3141. get_string_manager()->reset_caches();
  3142. return $return;
  3143. }
  3144. }
  3145. /**
  3146. * Selection of one of the recognised countries using the list
  3147. * returned by {@link get_list_of_countries()}.
  3148. *
  3149. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3150. */
  3151. class admin_settings_country_select extends admin_setting_configselect {
  3152. protected $includeall;
  3153. public function __construct($name, $visiblename, $description, $defaultsetting, $includeall=false) {
  3154. $this->includeall = $includeall;
  3155. parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
  3156. }
  3157. /**
  3158. * Lazy-load the available choices for the select box
  3159. */
  3160. public function load_choices() {
  3161. global $CFG;
  3162. if (is_array($this->choices)) {
  3163. return true;
  3164. }
  3165. $this->choices = array_merge(
  3166. array('0' => get_string('choosedots')),
  3167. get_string_manager()->get_list_of_countries($this->includeall));
  3168. return true;
  3169. }
  3170. }
  3171. /**
  3172. * Course category selection
  3173. *
  3174. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3175. */
  3176. class admin_settings_coursecat_select extends admin_setting_configselect {
  3177. /**
  3178. * Calls parent::__construct with specific arguments
  3179. */
  3180. public function __construct($name, $visiblename, $description, $defaultsetting) {
  3181. parent::__construct($name, $visiblename, $description, $defaultsetting, NULL);
  3182. }
  3183. /**
  3184. * Load the available choices for the select box
  3185. *
  3186. * @return bool
  3187. */
  3188. public function load_choices() {
  3189. global $CFG;
  3190. require_once($CFG->dirroot.'/course/lib.php');
  3191. if (is_array($this->choices)) {
  3192. return true;
  3193. }
  3194. $this->choices = make_categories_options();
  3195. return true;
  3196. }
  3197. }
  3198. /**
  3199. * Special control for selecting days to backup
  3200. *
  3201. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3202. */
  3203. class admin_setting_special_backupdays extends admin_setting_configmulticheckbox2 {
  3204. /**
  3205. * Calls parent::__construct with specific arguments
  3206. */
  3207. public function __construct() {
  3208. parent::__construct('backup_auto_weekdays', get_string('automatedbackupschedule','backup'), get_string('automatedbackupschedulehelp','backup'), array(), NULL);
  3209. $this->plugin = 'backup';
  3210. }
  3211. /**
  3212. * Load the available choices for the select box
  3213. *
  3214. * @return bool Always returns true
  3215. */
  3216. public function load_choices() {
  3217. if (is_array($this->choices)) {
  3218. return true;
  3219. }
  3220. $this->choices = array();
  3221. $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
  3222. foreach ($days as $day) {
  3223. $this->choices[$day] = get_string($day, 'calendar');
  3224. }
  3225. return true;
  3226. }
  3227. }
  3228. /**
  3229. * Special debug setting
  3230. *
  3231. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3232. */
  3233. class admin_setting_special_debug extends admin_setting_configselect {
  3234. /**
  3235. * Calls parent::__construct with specific arguments
  3236. */
  3237. public function __construct() {
  3238. parent::__construct('debug', get_string('debug', 'admin'), get_string('configdebug', 'admin'), DEBUG_NONE, NULL);
  3239. }
  3240. /**
  3241. * Load the available choices for the select box
  3242. *
  3243. * @return bool
  3244. */
  3245. public function load_choices() {
  3246. if (is_array($this->choices)) {
  3247. return true;
  3248. }
  3249. $this->choices = array(DEBUG_NONE => get_string('debugnone', 'admin'),
  3250. DEBUG_MINIMAL => get_string('debugminimal', 'admin'),
  3251. DEBUG_NORMAL => get_string('debugnormal', 'admin'),
  3252. DEBUG_ALL => get_string('debugall', 'admin'),
  3253. DEBUG_DEVELOPER => get_string('debugdeveloper', 'admin'));
  3254. return true;
  3255. }
  3256. }
  3257. /**
  3258. * Special admin control
  3259. *
  3260. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3261. */
  3262. class admin_setting_special_calendar_weekend extends admin_setting {
  3263. /**
  3264. * Calls parent::__construct with specific arguments
  3265. */
  3266. public function __construct() {
  3267. $name = 'calendar_weekend';
  3268. $visiblename = get_string('calendar_weekend', 'admin');
  3269. $description = get_string('helpweekenddays', 'admin');
  3270. $default = array ('0', '6'); // Saturdays and Sundays
  3271. parent::__construct($name, $visiblename, $description, $default);
  3272. }
  3273. /**
  3274. * Gets the current settings as an array
  3275. *
  3276. * @return mixed Null if none, else array of settings
  3277. */
  3278. public function get_setting() {
  3279. $result = $this->config_read($this->name);
  3280. if (is_null($result)) {
  3281. return NULL;
  3282. }
  3283. if ($result === '') {
  3284. return array();
  3285. }
  3286. $settings = array();
  3287. for ($i=0; $i<7; $i++) {
  3288. if ($result & (1 << $i)) {
  3289. $settings[] = $i;
  3290. }
  3291. }
  3292. return $settings;
  3293. }
  3294. /**
  3295. * Save the new settings
  3296. *
  3297. * @param array $data Array of new settings
  3298. * @return bool
  3299. */
  3300. public function write_setting($data) {
  3301. if (!is_array($data)) {
  3302. return '';
  3303. }
  3304. unset($data['xxxxx']);
  3305. $result = 0;
  3306. foreach($data as $index) {
  3307. $result |= 1 << $index;
  3308. }
  3309. return ($this->config_write($this->name, $result) ? '' : get_string('errorsetting', 'admin'));
  3310. }
  3311. /**
  3312. * Return XHTML to display the control
  3313. *
  3314. * @param array $data array of selected days
  3315. * @param string $query
  3316. * @return string XHTML for display (field + wrapping div(s)
  3317. */
  3318. public function output_html($data, $query='') {
  3319. // The order matters very much because of the implied numeric keys
  3320. $days = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
  3321. $return = '<table><thead><tr>';
  3322. $return .= '<input type="hidden" name="'.$this->get_full_name().'[xxxxx]" value="1" />'; // something must be submitted even if nothing selected
  3323. foreach($days as $index => $day) {
  3324. $return .= '<td><label for="'.$this->get_id().$index.'">'.get_string($day, 'calendar').'</label></td>';
  3325. }
  3326. $return .= '</tr></thead><tbody><tr>';
  3327. foreach($days as $index => $day) {
  3328. $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>';
  3329. }
  3330. $return .= '</tr></tbody></table>';
  3331. return format_admin_setting($this, $this->visiblename, $return, $this->description, false, '', NULL, $query);
  3332. }
  3333. }
  3334. /**
  3335. * Admin setting that allows a user to pick appropriate roles for something.
  3336. *
  3337. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3338. */
  3339. class admin_setting_pickroles extends admin_setting_configmulticheckbox {
  3340. /** @var array Array of capabilities which identify roles */
  3341. private $types;
  3342. /**
  3343. * @param string $name Name of config variable
  3344. * @param string $visiblename Display name
  3345. * @param string $description Description
  3346. * @param array $types Array of archetypes which identify
  3347. * roles that will be enabled by default.
  3348. */
  3349. public function __construct($name, $visiblename, $description, $types) {
  3350. parent::__construct($name, $visiblename, $description, NULL, NULL);
  3351. $this->types = $types;
  3352. }
  3353. /**
  3354. * Load roles as choices
  3355. *
  3356. * @return bool true=>success, false=>error
  3357. */
  3358. public function load_choices() {
  3359. global $CFG, $DB;
  3360. if (during_initial_install()) {
  3361. return false;
  3362. }
  3363. if (is_array($this->choices)) {
  3364. return true;
  3365. }
  3366. if ($roles = get_all_roles()) {
  3367. $this->choices = array();
  3368. foreach($roles as $role) {
  3369. $this->choices[$role->id] = format_string($role->name);
  3370. }
  3371. return true;
  3372. } else {
  3373. return false;
  3374. }
  3375. }
  3376. /**
  3377. * Return the default setting for this control
  3378. *
  3379. * @return array Array of default settings
  3380. */
  3381. public function get_defaultsetting() {
  3382. global $CFG;
  3383. if (during_initial_install()) {
  3384. return null;
  3385. }
  3386. $result = array();
  3387. foreach($this->types as $archetype) {
  3388. if ($caproles = get_archetype_roles($archetype)) {
  3389. foreach ($caproles as $caprole) {
  3390. $result[$caprole->id] = 1;
  3391. }
  3392. }
  3393. }
  3394. return $result;
  3395. }
  3396. }
  3397. /**
  3398. * Text field with an advanced checkbox, that controls a additional $name.'_adv' setting.
  3399. *
  3400. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3401. */
  3402. class admin_setting_configtext_with_advanced extends admin_setting_configtext {
  3403. /**
  3404. * Constructor
  3405. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  3406. * @param string $visiblename localised
  3407. * @param string $description long localised info
  3408. * @param array $defaultsetting ('value'=>string, '__construct'=>bool)
  3409. * @param mixed $paramtype int means PARAM_XXX type, string is a allowed format in regex
  3410. * @param int $size default field size
  3411. */
  3412. public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $size=null) {
  3413. parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype, $size);
  3414. }
  3415. /**
  3416. * Loads the current setting and returns array
  3417. *
  3418. * @return array Returns array value=>xx, __construct=>xx
  3419. */
  3420. public function get_setting() {
  3421. $value = parent::get_setting();
  3422. $adv = $this->config_read($this->name.'_adv');
  3423. if (is_null($value) or is_null($adv)) {
  3424. return NULL;
  3425. }
  3426. return array('value' => $value, 'adv' => $adv);
  3427. }
  3428. /**
  3429. * Saves the new settings passed in $data
  3430. *
  3431. * @todo Add vartype handling to ensure $data is an array
  3432. * @param array $data
  3433. * @return mixed string or Array
  3434. */
  3435. public function write_setting($data) {
  3436. $error = parent::write_setting($data['value']);
  3437. if (!$error) {
  3438. $value = empty($data['adv']) ? 0 : 1;
  3439. $this->config_write($this->name.'_adv', $value);
  3440. }
  3441. return $error;
  3442. }
  3443. /**
  3444. * Return XHTML for the control
  3445. *
  3446. * @param array $data Default data array
  3447. * @param string $query
  3448. * @return string XHTML to display control
  3449. */
  3450. public function output_html($data, $query='') {
  3451. $default = $this->get_defaultsetting();
  3452. $defaultinfo = array();
  3453. if (isset($default['value'])) {
  3454. if ($default['value'] === '') {
  3455. $defaultinfo[] = "''";
  3456. } else {
  3457. $defaultinfo[] = $default['value'];
  3458. }
  3459. }
  3460. if (!empty($default['adv'])) {
  3461. $defaultinfo[] = get_string('advanced');
  3462. }
  3463. $defaultinfo = implode(', ', $defaultinfo);
  3464. $adv = !empty($data['adv']);
  3465. $return = '<div class="form-text defaultsnext">' .
  3466. '<input type="text" size="' . $this->size . '" id="' . $this->get_id() .
  3467. '" name="' . $this->get_full_name() . '[value]" value="' . s($data['value']) . '" />' .
  3468. ' <input type="checkbox" class="form-checkbox" id="' .
  3469. $this->get_id() . '_adv" name="' . $this->get_full_name() .
  3470. '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
  3471. ' <label for="' . $this->get_id() . '_adv">' .
  3472. get_string('advanced') . '</label></div>';
  3473. return format_admin_setting($this, $this->visiblename, $return,
  3474. $this->description, true, '', $defaultinfo, $query);
  3475. }
  3476. }
  3477. /**
  3478. * Checkbox with an advanced checkbox that controls an additional $name.'_adv' config setting.
  3479. *
  3480. * @copyright 2009 Petr Skoda (http://skodak.org)
  3481. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3482. */
  3483. class admin_setting_configcheckbox_with_advanced extends admin_setting_configcheckbox {
  3484. /**
  3485. * Constructor
  3486. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  3487. * @param string $visiblename localised
  3488. * @param string $description long localised info
  3489. * @param array $defaultsetting ('value'=>string, 'adv'=>bool)
  3490. * @param string $yes value used when checked
  3491. * @param string $no value used when not checked
  3492. */
  3493. public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
  3494. parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
  3495. }
  3496. /**
  3497. * Loads the current setting and returns array
  3498. *
  3499. * @return array Returns array value=>xx, adv=>xx
  3500. */
  3501. public function get_setting() {
  3502. $value = parent::get_setting();
  3503. $adv = $this->config_read($this->name.'_adv');
  3504. if (is_null($value) or is_null($adv)) {
  3505. return NULL;
  3506. }
  3507. return array('value' => $value, 'adv' => $adv);
  3508. }
  3509. /**
  3510. * Sets the value for the setting
  3511. *
  3512. * Sets the value for the setting to either the yes or no values
  3513. * of the object by comparing $data to yes
  3514. *
  3515. * @param mixed $data Gets converted to str for comparison against yes value
  3516. * @return string empty string or error
  3517. */
  3518. public function write_setting($data) {
  3519. $error = parent::write_setting($data['value']);
  3520. if (!$error) {
  3521. $value = empty($data['adv']) ? 0 : 1;
  3522. $this->config_write($this->name.'_adv', $value);
  3523. }
  3524. return $error;
  3525. }
  3526. /**
  3527. * Returns an XHTML checkbox field and with extra advanced cehckbox
  3528. *
  3529. * @param string $data If $data matches yes then checkbox is checked
  3530. * @param string $query
  3531. * @return string XHTML field
  3532. */
  3533. public function output_html($data, $query='') {
  3534. $defaults = $this->get_defaultsetting();
  3535. $defaultinfo = array();
  3536. if (!is_null($defaults)) {
  3537. if ((string)$defaults['value'] === $this->yes) {
  3538. $defaultinfo[] = get_string('checkboxyes', 'admin');
  3539. } else {
  3540. $defaultinfo[] = get_string('checkboxno', 'admin');
  3541. }
  3542. if (!empty($defaults['adv'])) {
  3543. $defaultinfo[] = get_string('advanced');
  3544. }
  3545. }
  3546. $defaultinfo = implode(', ', $defaultinfo);
  3547. if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
  3548. $checked = 'checked="checked"';
  3549. } else {
  3550. $checked = '';
  3551. }
  3552. if (!empty($data['adv'])) {
  3553. $advanced = 'checked="checked"';
  3554. } else {
  3555. $advanced = '';
  3556. }
  3557. $fullname = $this->get_full_name();
  3558. $novalue = s($this->no);
  3559. $yesvalue = s($this->yes);
  3560. $id = $this->get_id();
  3561. $stradvanced = get_string('advanced');
  3562. $return = <<<EOT
  3563. <div class="form-checkbox defaultsnext" >
  3564. <input type="hidden" name="{$fullname}[value]" value="$novalue" />
  3565. <input type="checkbox" id="$id" name="{$fullname}[value]" value="$yesvalue" $checked />
  3566. <input type="checkbox" class="form-checkbox" id="{$id}_adv" name="{$fullname}[adv]" value="1" $advanced />
  3567. <label for="{$id}_adv">$stradvanced</label>
  3568. </div>
  3569. EOT;
  3570. return format_admin_setting($this, $this->visiblename, $return, $this->description,
  3571. true, '', $defaultinfo, $query);
  3572. }
  3573. }
  3574. /**
  3575. * Checkbox with an advanced checkbox that controls an additional $name.'_locked' config setting.
  3576. *
  3577. * This is nearly a copy/paste of admin_setting_configcheckbox_with_adv
  3578. *
  3579. * @copyright 2010 Sam Hemelryk
  3580. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3581. */
  3582. class admin_setting_configcheckbox_with_lock extends admin_setting_configcheckbox {
  3583. /**
  3584. * Constructor
  3585. * @param string $name unique ascii name, either 'mysetting' for settings that in config, or 'myplugin/mysetting' for ones in config_plugins.
  3586. * @param string $visiblename localised
  3587. * @param string $description long localised info
  3588. * @param array $defaultsetting ('value'=>string, 'locked'=>bool)
  3589. * @param string $yes value used when checked
  3590. * @param string $no value used when not checked
  3591. */
  3592. public function __construct($name, $visiblename, $description, $defaultsetting, $yes='1', $no='0') {
  3593. parent::__construct($name, $visiblename, $description, $defaultsetting, $yes, $no);
  3594. }
  3595. /**
  3596. * Loads the current setting and returns array
  3597. *
  3598. * @return array Returns array value=>xx, adv=>xx
  3599. */
  3600. public function get_setting() {
  3601. $value = parent::get_setting();
  3602. $locked = $this->config_read($this->name.'_locked');
  3603. if (is_null($value) or is_null($locked)) {
  3604. return NULL;
  3605. }
  3606. return array('value' => $value, 'locked' => $locked);
  3607. }
  3608. /**
  3609. * Sets the value for the setting
  3610. *
  3611. * Sets the value for the setting to either the yes or no values
  3612. * of the object by comparing $data to yes
  3613. *
  3614. * @param mixed $data Gets converted to str for comparison against yes value
  3615. * @return string empty string or error
  3616. */
  3617. public function write_setting($data) {
  3618. $error = parent::write_setting($data['value']);
  3619. if (!$error) {
  3620. $value = empty($data['locked']) ? 0 : 1;
  3621. $this->config_write($this->name.'_locked', $value);
  3622. }
  3623. return $error;
  3624. }
  3625. /**
  3626. * Returns an XHTML checkbox field and with extra locked checkbox
  3627. *
  3628. * @param string $data If $data matches yes then checkbox is checked
  3629. * @param string $query
  3630. * @return string XHTML field
  3631. */
  3632. public function output_html($data, $query='') {
  3633. $defaults = $this->get_defaultsetting();
  3634. $defaultinfo = array();
  3635. if (!is_null($defaults)) {
  3636. if ((string)$defaults['value'] === $this->yes) {
  3637. $defaultinfo[] = get_string('checkboxyes', 'admin');
  3638. } else {
  3639. $defaultinfo[] = get_string('checkboxno', 'admin');
  3640. }
  3641. if (!empty($defaults['locked'])) {
  3642. $defaultinfo[] = get_string('locked', 'admin');
  3643. }
  3644. }
  3645. $defaultinfo = implode(', ', $defaultinfo);
  3646. $fullname = $this->get_full_name();
  3647. $novalue = s($this->no);
  3648. $yesvalue = s($this->yes);
  3649. $id = $this->get_id();
  3650. $checkboxparams = array('type'=>'checkbox', 'id'=>$id,'name'=>$fullname.'[value]', 'value'=>$yesvalue);
  3651. if ((string)$data['value'] === $this->yes) { // convert to strings before comparison
  3652. $checkboxparams['checked'] = 'checked';
  3653. }
  3654. $lockcheckboxparams = array('type'=>'checkbox', 'id'=>$id.'_locked','name'=>$fullname.'[locked]', 'value'=>1, 'class'=>'form-checkbox');
  3655. if (!empty($data['locked'])) { // convert to strings before comparison
  3656. $lockcheckboxparams['checked'] = 'checked';
  3657. }
  3658. $return = html_writer::start_tag('div', array('class'=>'form-checkbox defaultsnext'));
  3659. $return .= html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>$fullname.'[value]', 'value'=>$novalue));
  3660. $return .= html_writer::empty_tag('input', $checkboxparams);
  3661. $return .= html_writer::empty_tag('input', $lockcheckboxparams);
  3662. $return .= html_writer::tag('label', get_string('locked', 'admin'), array('for'=>$id.'_locked'));
  3663. $return .= html_writer::end_tag('div');
  3664. return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
  3665. }
  3666. }
  3667. /**
  3668. * Dropdown menu with an advanced checkbox, that controls a additional $name.'_adv' setting.
  3669. *
  3670. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3671. */
  3672. class admin_setting_configselect_with_advanced extends admin_setting_configselect {
  3673. /**
  3674. * Calls parent::__construct with specific arguments
  3675. */
  3676. public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
  3677. parent::__construct($name, $visiblename, $description, $defaultsetting, $choices);
  3678. }
  3679. /**
  3680. * Loads the current setting and returns array
  3681. *
  3682. * @return array Returns array value=>xx, adv=>xx
  3683. */
  3684. public function get_setting() {
  3685. $value = parent::get_setting();
  3686. $adv = $this->config_read($this->name.'_adv');
  3687. if (is_null($value) or is_null($adv)) {
  3688. return NULL;
  3689. }
  3690. return array('value' => $value, 'adv' => $adv);
  3691. }
  3692. /**
  3693. * Saves the new settings passed in $data
  3694. *
  3695. * @todo Add vartype handling to ensure $data is an array
  3696. * @param array $data
  3697. * @return mixed string or Array
  3698. */
  3699. public function write_setting($data) {
  3700. $error = parent::write_setting($data['value']);
  3701. if (!$error) {
  3702. $value = empty($data['adv']) ? 0 : 1;
  3703. $this->config_write($this->name.'_adv', $value);
  3704. }
  3705. return $error;
  3706. }
  3707. /**
  3708. * Return XHTML for the control
  3709. *
  3710. * @param array $data Default data array
  3711. * @param string $query
  3712. * @return string XHTML to display control
  3713. */
  3714. public function output_html($data, $query='') {
  3715. $default = $this->get_defaultsetting();
  3716. $current = $this->get_setting();
  3717. list($selecthtml, $warning) = $this->output_select_html($data['value'],
  3718. $current['value'], $default['value'], '[value]');
  3719. if (!$selecthtml) {
  3720. return '';
  3721. }
  3722. if (!is_null($default) and array_key_exists($default['value'], $this->choices)) {
  3723. $defaultinfo = array();
  3724. if (isset($this->choices[$default['value']])) {
  3725. $defaultinfo[] = $this->choices[$default['value']];
  3726. }
  3727. if (!empty($default['adv'])) {
  3728. $defaultinfo[] = get_string('advanced');
  3729. }
  3730. $defaultinfo = implode(', ', $defaultinfo);
  3731. } else {
  3732. $defaultinfo = '';
  3733. }
  3734. $adv = !empty($data['adv']);
  3735. $return = '<div class="form-select defaultsnext">' . $selecthtml .
  3736. ' <input type="checkbox" class="form-checkbox" id="' .
  3737. $this->get_id() . '_adv" name="' . $this->get_full_name() .
  3738. '[adv]" value="1" ' . ($adv ? 'checked="checked"' : '') . ' />' .
  3739. ' <label for="' . $this->get_id() . '_adv">' .
  3740. get_string('advanced') . '</label></div>';
  3741. return format_admin_setting($this, $this->visiblename, $return, $this->description, true, $warning, $defaultinfo, $query);
  3742. }
  3743. }
  3744. /**
  3745. * Graded roles in gradebook
  3746. *
  3747. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3748. */
  3749. class admin_setting_special_gradebookroles extends admin_setting_pickroles {
  3750. /**
  3751. * Calls parent::__construct with specific arguments
  3752. */
  3753. public function __construct() {
  3754. parent::__construct('gradebookroles', get_string('gradebookroles', 'admin'),
  3755. get_string('configgradebookroles', 'admin'),
  3756. array('student'));
  3757. }
  3758. }
  3759. /**
  3760. *
  3761. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3762. */
  3763. class admin_setting_regradingcheckbox extends admin_setting_configcheckbox {
  3764. /**
  3765. * Saves the new settings passed in $data
  3766. *
  3767. * @param string $data
  3768. * @return mixed string or Array
  3769. */
  3770. public function write_setting($data) {
  3771. global $CFG, $DB;
  3772. $oldvalue = $this->config_read($this->name);
  3773. $return = parent::write_setting($data);
  3774. $newvalue = $this->config_read($this->name);
  3775. if ($oldvalue !== $newvalue) {
  3776. // force full regrading
  3777. $DB->set_field('grade_items', 'needsupdate', 1, array('needsupdate'=>0));
  3778. }
  3779. return $return;
  3780. }
  3781. }
  3782. /**
  3783. * Which roles to show on course description page
  3784. *
  3785. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3786. */
  3787. class admin_setting_special_coursecontact extends admin_setting_pickroles {
  3788. /**
  3789. * Calls parent::__construct with specific arguments
  3790. */
  3791. public function __construct() {
  3792. parent::__construct('coursecontact', get_string('coursecontact', 'admin'),
  3793. get_string('coursecontact_desc', 'admin'),
  3794. array('editingteacher'));
  3795. }
  3796. }
  3797. /**
  3798. *
  3799. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3800. */
  3801. class admin_setting_special_gradelimiting extends admin_setting_configcheckbox {
  3802. /**
  3803. * Calls parent::__construct with specific arguments
  3804. */
  3805. function admin_setting_special_gradelimiting() {
  3806. parent::__construct('unlimitedgrades', get_string('unlimitedgrades', 'grades'),
  3807. get_string('unlimitedgrades_help', 'grades'), '0', '1', '0');
  3808. }
  3809. /**
  3810. * Force site regrading
  3811. */
  3812. function regrade_all() {
  3813. global $CFG;
  3814. require_once("$CFG->libdir/gradelib.php");
  3815. grade_force_site_regrading();
  3816. }
  3817. /**
  3818. * Saves the new settings
  3819. *
  3820. * @param mixed $data
  3821. * @return string empty string or error message
  3822. */
  3823. function write_setting($data) {
  3824. $previous = $this->get_setting();
  3825. if ($previous === null) {
  3826. if ($data) {
  3827. $this->regrade_all();
  3828. }
  3829. } else {
  3830. if ($data != $previous) {
  3831. $this->regrade_all();
  3832. }
  3833. }
  3834. return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
  3835. }
  3836. }
  3837. /**
  3838. * Primary grade export plugin - has state tracking.
  3839. *
  3840. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3841. */
  3842. class admin_setting_special_gradeexport extends admin_setting_configmulticheckbox {
  3843. /**
  3844. * Calls parent::__construct with specific arguments
  3845. */
  3846. public function __construct() {
  3847. parent::__construct('gradeexport', get_string('gradeexport', 'admin'),
  3848. get_string('configgradeexport', 'admin'), array(), NULL);
  3849. }
  3850. /**
  3851. * Load the available choices for the multicheckbox
  3852. *
  3853. * @return bool always returns true
  3854. */
  3855. public function load_choices() {
  3856. if (is_array($this->choices)) {
  3857. return true;
  3858. }
  3859. $this->choices = array();
  3860. if ($plugins = get_plugin_list('gradeexport')) {
  3861. foreach($plugins as $plugin => $unused) {
  3862. $this->choices[$plugin] = get_string('pluginname', 'gradeexport_'.$plugin);
  3863. }
  3864. }
  3865. return true;
  3866. }
  3867. }
  3868. /**
  3869. * Grade category settings
  3870. *
  3871. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3872. */
  3873. class admin_setting_gradecat_combo extends admin_setting {
  3874. /** @var array Array of choices */
  3875. public $choices;
  3876. /**
  3877. * Sets choices and calls parent::__construct with passed arguments
  3878. * @param string $name
  3879. * @param string $visiblename
  3880. * @param string $description
  3881. * @param mixed $defaultsetting string or array depending on implementation
  3882. * @param array $choices An array of choices for the control
  3883. */
  3884. public function __construct($name, $visiblename, $description, $defaultsetting, $choices) {
  3885. $this->choices = $choices;
  3886. parent::__construct($name, $visiblename, $description, $defaultsetting);
  3887. }
  3888. /**
  3889. * Return the current setting(s) array
  3890. *
  3891. * @return array Array of value=>xx, forced=>xx, adv=>xx
  3892. */
  3893. public function get_setting() {
  3894. global $CFG;
  3895. $value = $this->config_read($this->name);
  3896. $flag = $this->config_read($this->name.'_flag');
  3897. if (is_null($value) or is_null($flag)) {
  3898. return NULL;
  3899. }
  3900. $flag = (int)$flag;
  3901. $forced = (boolean)(1 & $flag); // first bit
  3902. $adv = (boolean)(2 & $flag); // second bit
  3903. return array('value' => $value, 'forced' => $forced, 'adv' => $adv);
  3904. }
  3905. /**
  3906. * Save the new settings passed in $data
  3907. *
  3908. * @todo Add vartype handling to ensure $data is array
  3909. * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
  3910. * @return string empty or error message
  3911. */
  3912. public function write_setting($data) {
  3913. global $CFG;
  3914. $value = $data['value'];
  3915. $forced = empty($data['forced']) ? 0 : 1;
  3916. $adv = empty($data['adv']) ? 0 : 2;
  3917. $flag = ($forced | $adv); //bitwise or
  3918. if (!in_array($value, array_keys($this->choices))) {
  3919. return 'Error setting ';
  3920. }
  3921. $oldvalue = $this->config_read($this->name);
  3922. $oldflag = (int)$this->config_read($this->name.'_flag');
  3923. $oldforced = (1 & $oldflag); // first bit
  3924. $result1 = $this->config_write($this->name, $value);
  3925. $result2 = $this->config_write($this->name.'_flag', $flag);
  3926. // force regrade if needed
  3927. if ($oldforced != $forced or ($forced and $value != $oldvalue)) {
  3928. require_once($CFG->libdir.'/gradelib.php');
  3929. grade_category::updated_forced_settings();
  3930. }
  3931. if ($result1 and $result2) {
  3932. return '';
  3933. } else {
  3934. return get_string('errorsetting', 'admin');
  3935. }
  3936. }
  3937. /**
  3938. * Return XHTML to display the field and wrapping div
  3939. *
  3940. * @todo Add vartype handling to ensure $data is array
  3941. * @param array $data Associative array of value=>xx, forced=>xx, adv=>xx
  3942. * @param string $query
  3943. * @return string XHTML to display control
  3944. */
  3945. public function output_html($data, $query='') {
  3946. $value = $data['value'];
  3947. $forced = !empty($data['forced']);
  3948. $adv = !empty($data['adv']);
  3949. $default = $this->get_defaultsetting();
  3950. if (!is_null($default)) {
  3951. $defaultinfo = array();
  3952. if (isset($this->choices[$default['value']])) {
  3953. $defaultinfo[] = $this->choices[$default['value']];
  3954. }
  3955. if (!empty($default['forced'])) {
  3956. $defaultinfo[] = get_string('force');
  3957. }
  3958. if (!empty($default['adv'])) {
  3959. $defaultinfo[] = get_string('advanced');
  3960. }
  3961. $defaultinfo = implode(', ', $defaultinfo);
  3962. } else {
  3963. $defaultinfo = NULL;
  3964. }
  3965. $return = '<div class="form-group">';
  3966. $return .= '<select class="form-select" id="'.$this->get_id().'" name="'.$this->get_full_name().'[value]">';
  3967. foreach ($this->choices as $key => $val) {
  3968. // the string cast is needed because key may be integer - 0 is equal to most strings!
  3969. $return .= '<option value="'.$key.'"'.((string)$key==$value ? ' selected="selected"' : '').'>'.$val.'</option>';
  3970. }
  3971. $return .= '</select>';
  3972. $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'force" name="'.$this->get_full_name().'[forced]" value="1" '.($forced ? 'checked="checked"' : '').' />'
  3973. .'<label for="'.$this->get_id().'force">'.get_string('force').'</label>';
  3974. $return .= '<input type="checkbox" class="form-checkbox" id="'.$this->get_id().'adv" name="'.$this->get_full_name().'[adv]" value="1" '.($adv ? 'checked="checked"' : '').' />'
  3975. .'<label for="'.$this->get_id().'adv">'.get_string('advanced').'</label>';
  3976. $return .= '</div>';
  3977. return format_admin_setting($this, $this->visiblename, $return, $this->description, true, '', $defaultinfo, $query);
  3978. }
  3979. }
  3980. /**
  3981. * Selection of grade report in user profiles
  3982. *
  3983. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3984. */
  3985. class admin_setting_grade_profilereport extends admin_setting_configselect {
  3986. /**
  3987. * Calls parent::__construct with specific arguments
  3988. */
  3989. public function __construct() {
  3990. parent::__construct('grade_profilereport', get_string('profilereport', 'grades'), get_string('profilereport_help', 'grades'), 'user', null);
  3991. }
  3992. /**
  3993. * Loads an array of choices for the configselect control
  3994. *
  3995. * @return bool always return true
  3996. */
  3997. public function load_choices() {
  3998. if (is_array($this->choices)) {
  3999. return true;
  4000. }
  4001. $this->choices = array();
  4002. global $CFG;
  4003. require_once($CFG->libdir.'/gradelib.php');
  4004. foreach (get_plugin_list('gradereport') as $plugin => $plugindir) {
  4005. if (file_exists($plugindir.'/lib.php')) {
  4006. require_once($plugindir.'/lib.php');
  4007. $functionname = 'grade_report_'.$plugin.'_profilereport';
  4008. if (function_exists($functionname)) {
  4009. $this->choices[$plugin] = get_string('pluginname', 'gradereport_'.$plugin);
  4010. }
  4011. }
  4012. }
  4013. return true;
  4014. }
  4015. }
  4016. /**
  4017. * Special class for register auth selection
  4018. *
  4019. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4020. */
  4021. class admin_setting_special_registerauth extends admin_setting_configselect {
  4022. /**
  4023. * Calls parent::__construct with specific arguments
  4024. */
  4025. public function __construct() {
  4026. parent::__construct('registerauth', get_string('selfregistration', 'auth'), get_string('selfregistration_help', 'auth'), '', null);
  4027. }
  4028. /**
  4029. * Returns the default option
  4030. *
  4031. * @return string empty or default option
  4032. */
  4033. public function get_defaultsetting() {
  4034. $this->load_choices();
  4035. $defaultsetting = parent::get_defaultsetting();
  4036. if (array_key_exists($defaultsetting, $this->choices)) {
  4037. return $defaultsetting;
  4038. } else {
  4039. return '';
  4040. }
  4041. }
  4042. /**
  4043. * Loads the possible choices for the array
  4044. *
  4045. * @return bool always returns true
  4046. */
  4047. public function load_choices() {
  4048. global $CFG;
  4049. if (is_array($this->choices)) {
  4050. return true;
  4051. }
  4052. $this->choices = array();
  4053. $this->choices[''] = get_string('disable');
  4054. $authsenabled = get_enabled_auth_plugins(true);
  4055. foreach ($authsenabled as $auth) {
  4056. $authplugin = get_auth_plugin($auth);
  4057. if (!$authplugin->can_signup()) {
  4058. continue;
  4059. }
  4060. // Get the auth title (from core or own auth lang files)
  4061. $authtitle = $authplugin->get_title();
  4062. $this->choices[$auth] = $authtitle;
  4063. }
  4064. return true;
  4065. }
  4066. }
  4067. /**
  4068. * Module manage page
  4069. *
  4070. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4071. */
  4072. class admin_page_managemods extends admin_externalpage {
  4073. /**
  4074. * Calls parent::__construct with specific arguments
  4075. */
  4076. public function __construct() {
  4077. global $CFG;
  4078. parent::__construct('managemodules', get_string('modsettings', 'admin'), "$CFG->wwwroot/$CFG->admin/modules.php");
  4079. }
  4080. /**
  4081. * Try to find the specified module
  4082. *
  4083. * @param string $query The module to search for
  4084. * @return array
  4085. */
  4086. public function search($query) {
  4087. global $CFG, $DB;
  4088. if ($result = parent::search($query)) {
  4089. return $result;
  4090. }
  4091. $found = false;
  4092. if ($modules = $DB->get_records('modules')) {
  4093. $textlib = textlib_get_instance();
  4094. foreach ($modules as $module) {
  4095. if (!file_exists("$CFG->dirroot/mod/$module->name/lib.php")) {
  4096. continue;
  4097. }
  4098. if (strpos($module->name, $query) !== false) {
  4099. $found = true;
  4100. break;
  4101. }
  4102. $strmodulename = get_string('modulename', $module->name);
  4103. if (strpos($textlib->strtolower($strmodulename), $query) !== false) {
  4104. $found = true;
  4105. break;
  4106. }
  4107. }
  4108. }
  4109. if ($found) {
  4110. $result = new stdClass();
  4111. $result->page = $this;
  4112. $result->settings = array();
  4113. return array($this->name => $result);
  4114. } else {
  4115. return array();
  4116. }
  4117. }
  4118. }
  4119. /**
  4120. * Special class for enrol plugins management.
  4121. *
  4122. * @copyright 2010 Petr Skoda {@link http://skodak.org}
  4123. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4124. */
  4125. class admin_setting_manageenrols extends admin_setting {
  4126. /**
  4127. * Calls parent::__construct with specific arguments
  4128. */
  4129. public function __construct() {
  4130. $this->nosave = true;
  4131. parent::__construct('enrolsui', get_string('manageenrols', 'enrol'), '', '');
  4132. }
  4133. /**
  4134. * Always returns true, does nothing
  4135. *
  4136. * @return true
  4137. */
  4138. public function get_setting() {
  4139. return true;
  4140. }
  4141. /**
  4142. * Always returns true, does nothing
  4143. *
  4144. * @return true
  4145. */
  4146. public function get_defaultsetting() {
  4147. return true;
  4148. }
  4149. /**
  4150. * Always returns '', does not write anything
  4151. *
  4152. * @return string Always returns ''
  4153. */
  4154. public function write_setting($data) {
  4155. // do not write any setting
  4156. return '';
  4157. }
  4158. /**
  4159. * Checks if $query is one of the available enrol plugins
  4160. *
  4161. * @param string $query The string to search for
  4162. * @return bool Returns true if found, false if not
  4163. */
  4164. public function is_related($query) {
  4165. if (parent::is_related($query)) {
  4166. return true;
  4167. }
  4168. $textlib = textlib_get_instance();
  4169. $query = $textlib->strtolower($query);
  4170. $enrols = enrol_get_plugins(false);
  4171. foreach ($enrols as $name=>$enrol) {
  4172. $localised = get_string('pluginname', 'enrol_'.$name);
  4173. if (strpos($textlib->strtolower($name), $query) !== false) {
  4174. return true;
  4175. }
  4176. if (strpos($textlib->strtolower($localised), $query) !== false) {
  4177. return true;
  4178. }
  4179. }
  4180. return false;
  4181. }
  4182. /**
  4183. * Builds the XHTML to display the control
  4184. *
  4185. * @param string $data Unused
  4186. * @param string $query
  4187. * @return string
  4188. */
  4189. public function output_html($data, $query='') {
  4190. global $CFG, $OUTPUT, $DB;
  4191. // display strings
  4192. $strup = get_string('up');
  4193. $strdown = get_string('down');
  4194. $strsettings = get_string('settings');
  4195. $strenable = get_string('enable');
  4196. $strdisable = get_string('disable');
  4197. $struninstall = get_string('uninstallplugin', 'admin');
  4198. $strusage = get_string('enrolusage', 'enrol');
  4199. $enrols_available = enrol_get_plugins(false);
  4200. $active_enrols = enrol_get_plugins(true);
  4201. $allenrols = array();
  4202. foreach ($active_enrols as $key=>$enrol) {
  4203. $allenrols[$key] = true;
  4204. }
  4205. foreach ($enrols_available as $key=>$enrol) {
  4206. $allenrols[$key] = true;
  4207. }
  4208. // now find all borked plugins and at least allow then to uninstall
  4209. $borked = array();
  4210. $condidates = $DB->get_fieldset_sql("SELECT DISTINCT enrol FROM {enrol}");
  4211. foreach ($condidates as $candidate) {
  4212. if (empty($allenrols[$candidate])) {
  4213. $allenrols[$candidate] = true;
  4214. }
  4215. }
  4216. $return = $OUTPUT->heading(get_string('actenrolshhdr', 'enrol'), 3, 'main', true);
  4217. $return .= $OUTPUT->box_start('generalbox enrolsui');
  4218. $table = new html_table();
  4219. $table->head = array(get_string('name'), $strusage, $strenable, $strup.'/'.$strdown, $strsettings, $struninstall);
  4220. $table->align = array('left', 'center', 'center', 'center', 'center', 'center');
  4221. $table->width = '90%';
  4222. $table->data = array();
  4223. // iterate through enrol plugins and add to the display table
  4224. $updowncount = 1;
  4225. $enrolcount = count($active_enrols);
  4226. $url = new moodle_url('/admin/enrol.php', array('sesskey'=>sesskey()));
  4227. $printed = array();
  4228. foreach($allenrols as $enrol => $unused) {
  4229. if (get_string_manager()->string_exists('pluginname', 'enrol_'.$enrol)) {
  4230. $name = get_string('pluginname', 'enrol_'.$enrol);
  4231. } else {
  4232. $name = $enrol;
  4233. }
  4234. //usage
  4235. $ci = $DB->count_records('enrol', array('enrol'=>$enrol));
  4236. $cp = $DB->count_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($enrol));
  4237. $usage = "$ci / $cp";
  4238. // hide/show link
  4239. if (isset($active_enrols[$enrol])) {
  4240. $aurl = new moodle_url($url, array('action'=>'disable', 'enrol'=>$enrol));
  4241. $hideshow = "<a href=\"$aurl\">";
  4242. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
  4243. $enabled = true;
  4244. $displayname = "<span>$name</span>";
  4245. } else if (isset($enrols_available[$enrol])) {
  4246. $aurl = new moodle_url($url, array('action'=>'enable', 'enrol'=>$enrol));
  4247. $hideshow = "<a href=\"$aurl\">";
  4248. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
  4249. $enabled = false;
  4250. $displayname = "<span class=\"dimmed_text\">$name</span>";
  4251. } else {
  4252. $hideshow = '';
  4253. $enabled = false;
  4254. $displayname = '<span class="notifyproblem">'.$name.'</span>';
  4255. }
  4256. // up/down link (only if enrol is enabled)
  4257. $updown = '';
  4258. if ($enabled) {
  4259. if ($updowncount > 1) {
  4260. $aurl = new moodle_url($url, array('action'=>'up', 'enrol'=>$enrol));
  4261. $updown .= "<a href=\"$aurl\">";
  4262. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"$strup\" /></a>&nbsp;";
  4263. } else {
  4264. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
  4265. }
  4266. if ($updowncount < $enrolcount) {
  4267. $aurl = new moodle_url($url, array('action'=>'down', 'enrol'=>$enrol));
  4268. $updown .= "<a href=\"$aurl\">";
  4269. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"$strdown\" /></a>";
  4270. } else {
  4271. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
  4272. }
  4273. ++$updowncount;
  4274. }
  4275. // settings link
  4276. if (isset($active_enrols[$enrol]) or file_exists($CFG->dirroot.'/enrol/'.$enrol.'/settings.php')) {
  4277. $surl = new moodle_url('/admin/settings.php', array('section'=>'enrolsettings'.$enrol));
  4278. $settings = "<a href=\"$surl\">$strsettings</a>";
  4279. } else {
  4280. $settings = '';
  4281. }
  4282. // uninstall
  4283. $aurl = new moodle_url($url, array('action'=>'uninstall', 'enrol'=>$enrol));
  4284. $uninstall = "<a href=\"$aurl\">$struninstall</a>";
  4285. // add a row to the table
  4286. $table->data[] = array($displayname, $usage, $hideshow, $updown, $settings, $uninstall);
  4287. $printed[$enrol] = true;
  4288. }
  4289. $return .= html_writer::table($table);
  4290. $return .= get_string('configenrolplugins', 'enrol').'<br />'.get_string('tablenosave', 'admin');
  4291. $return .= $OUTPUT->box_end();
  4292. return highlight($query, $return);
  4293. }
  4294. }
  4295. /**
  4296. * Blocks manage page
  4297. *
  4298. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4299. */
  4300. class admin_page_manageblocks extends admin_externalpage {
  4301. /**
  4302. * Calls parent::__construct with specific arguments
  4303. */
  4304. public function __construct() {
  4305. global $CFG;
  4306. parent::__construct('manageblocks', get_string('blocksettings', 'admin'), "$CFG->wwwroot/$CFG->admin/blocks.php");
  4307. }
  4308. /**
  4309. * Search for a specific block
  4310. *
  4311. * @param string $query The string to search for
  4312. * @return array
  4313. */
  4314. public function search($query) {
  4315. global $CFG, $DB;
  4316. if ($result = parent::search($query)) {
  4317. return $result;
  4318. }
  4319. $found = false;
  4320. if ($blocks = $DB->get_records('block')) {
  4321. $textlib = textlib_get_instance();
  4322. foreach ($blocks as $block) {
  4323. if (!file_exists("$CFG->dirroot/blocks/$block->name/")) {
  4324. continue;
  4325. }
  4326. if (strpos($block->name, $query) !== false) {
  4327. $found = true;
  4328. break;
  4329. }
  4330. $strblockname = get_string('pluginname', 'block_'.$block->name);
  4331. if (strpos($textlib->strtolower($strblockname), $query) !== false) {
  4332. $found = true;
  4333. break;
  4334. }
  4335. }
  4336. }
  4337. if ($found) {
  4338. $result = new stdClass();
  4339. $result->page = $this;
  4340. $result->settings = array();
  4341. return array($this->name => $result);
  4342. } else {
  4343. return array();
  4344. }
  4345. }
  4346. }
  4347. /**
  4348. * Question type manage page
  4349. *
  4350. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4351. */
  4352. class admin_page_manageqtypes extends admin_externalpage {
  4353. /**
  4354. * Calls parent::__construct with specific arguments
  4355. */
  4356. public function __construct() {
  4357. global $CFG;
  4358. parent::__construct('manageqtypes', get_string('manageqtypes', 'admin'), "$CFG->wwwroot/$CFG->admin/qtypes.php");
  4359. }
  4360. /**
  4361. * Search QTYPES for the specified string
  4362. *
  4363. * @param string $query The string to search for in QTYPES
  4364. * @return array
  4365. */
  4366. public function search($query) {
  4367. global $CFG;
  4368. if ($result = parent::search($query)) {
  4369. return $result;
  4370. }
  4371. $found = false;
  4372. $textlib = textlib_get_instance();
  4373. require_once($CFG->libdir . '/questionlib.php');
  4374. global $QTYPES;
  4375. foreach ($QTYPES as $qtype) {
  4376. if (strpos($textlib->strtolower($qtype->local_name()), $query) !== false) {
  4377. $found = true;
  4378. break;
  4379. }
  4380. }
  4381. if ($found) {
  4382. $result = new stdClass();
  4383. $result->page = $this;
  4384. $result->settings = array();
  4385. return array($this->name => $result);
  4386. } else {
  4387. return array();
  4388. }
  4389. }
  4390. }
  4391. class admin_page_manageportfolios extends admin_externalpage {
  4392. /**
  4393. * Calls parent::__construct with specific arguments
  4394. */
  4395. public function __construct() {
  4396. global $CFG;
  4397. parent::__construct('manageportfolios', get_string('manageportfolios', 'portfolio'),
  4398. "$CFG->wwwroot/$CFG->admin/portfolio.php");
  4399. }
  4400. /**
  4401. * Searches page for the specified string.
  4402. * @param string $query The string to search for
  4403. * @return bool True if it is found on this page
  4404. */
  4405. public function search($query) {
  4406. global $CFG;
  4407. if ($result = parent::search($query)) {
  4408. return $result;
  4409. }
  4410. $found = false;
  4411. $textlib = textlib_get_instance();
  4412. $portfolios = get_plugin_list('portfolio');
  4413. foreach ($portfolios as $p => $dir) {
  4414. if (strpos($p, $query) !== false) {
  4415. $found = true;
  4416. break;
  4417. }
  4418. }
  4419. if (!$found) {
  4420. foreach (portfolio_instances(false, false) as $instance) {
  4421. $title = $instance->get('name');
  4422. if (strpos($textlib->strtolower($title), $query) !== false) {
  4423. $found = true;
  4424. break;
  4425. }
  4426. }
  4427. }
  4428. if ($found) {
  4429. $result = new stdClass();
  4430. $result->page = $this;
  4431. $result->settings = array();
  4432. return array($this->name => $result);
  4433. } else {
  4434. return array();
  4435. }
  4436. }
  4437. }
  4438. class admin_page_managerepositories extends admin_externalpage {
  4439. /**
  4440. * Calls parent::__construct with specific arguments
  4441. */
  4442. public function __construct() {
  4443. global $CFG;
  4444. parent::__construct('managerepositories', get_string('manage',
  4445. 'repository'), "$CFG->wwwroot/$CFG->admin/repository.php");
  4446. }
  4447. /**
  4448. * Searches page for the specified string.
  4449. * @param string $query The string to search for
  4450. * @return bool True if it is found on this page
  4451. */
  4452. public function search($query) {
  4453. global $CFG;
  4454. if ($result = parent::search($query)) {
  4455. return $result;
  4456. }
  4457. $found = false;
  4458. $textlib = textlib_get_instance();
  4459. $repositories= get_plugin_list('repository');
  4460. foreach ($repositories as $p => $dir) {
  4461. if (strpos($p, $query) !== false) {
  4462. $found = true;
  4463. break;
  4464. }
  4465. }
  4466. if (!$found) {
  4467. foreach (repository::get_types() as $instance) {
  4468. $title = $instance->get_typename();
  4469. if (strpos($textlib->strtolower($title), $query) !== false) {
  4470. $found = true;
  4471. break;
  4472. }
  4473. }
  4474. }
  4475. if ($found) {
  4476. $result = new stdClass();
  4477. $result->page = $this;
  4478. $result->settings = array();
  4479. return array($this->name => $result);
  4480. } else {
  4481. return array();
  4482. }
  4483. }
  4484. }
  4485. /**
  4486. * Special class for authentication administration.
  4487. *
  4488. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4489. */
  4490. class admin_setting_manageauths extends admin_setting {
  4491. /**
  4492. * Calls parent::__construct with specific arguments
  4493. */
  4494. public function __construct() {
  4495. $this->nosave = true;
  4496. parent::__construct('authsui', get_string('authsettings', 'admin'), '', '');
  4497. }
  4498. /**
  4499. * Always returns true
  4500. *
  4501. * @return true
  4502. */
  4503. public function get_setting() {
  4504. return true;
  4505. }
  4506. /**
  4507. * Always returns true
  4508. *
  4509. * @return true
  4510. */
  4511. public function get_defaultsetting() {
  4512. return true;
  4513. }
  4514. /**
  4515. * Always returns '' and doesn't write anything
  4516. *
  4517. * @return string Always returns ''
  4518. */
  4519. public function write_setting($data) {
  4520. // do not write any setting
  4521. return '';
  4522. }
  4523. /**
  4524. * Search to find if Query is related to auth plugin
  4525. *
  4526. * @param string $query The string to search for
  4527. * @return bool true for related false for not
  4528. */
  4529. public function is_related($query) {
  4530. if (parent::is_related($query)) {
  4531. return true;
  4532. }
  4533. $textlib = textlib_get_instance();
  4534. $authsavailable = get_plugin_list('auth');
  4535. foreach ($authsavailable as $auth => $dir) {
  4536. if (strpos($auth, $query) !== false) {
  4537. return true;
  4538. }
  4539. $authplugin = get_auth_plugin($auth);
  4540. $authtitle = $authplugin->get_title();
  4541. if (strpos($textlib->strtolower($authtitle), $query) !== false) {
  4542. return true;
  4543. }
  4544. }
  4545. return false;
  4546. }
  4547. /**
  4548. * Return XHTML to display control
  4549. *
  4550. * @param mixed $data Unused
  4551. * @param string $query
  4552. * @return string highlight
  4553. */
  4554. public function output_html($data, $query='') {
  4555. global $CFG, $OUTPUT;
  4556. // display strings
  4557. $txt = get_strings(array('authenticationplugins', 'users', 'administration',
  4558. 'settings', 'edit', 'name', 'enable', 'disable',
  4559. 'up', 'down', 'none'));
  4560. $txt->updown = "$txt->up/$txt->down";
  4561. $authsavailable = get_plugin_list('auth');
  4562. get_enabled_auth_plugins(true); // fix the list of enabled auths
  4563. if (empty($CFG->auth)) {
  4564. $authsenabled = array();
  4565. } else {
  4566. $authsenabled = explode(',', $CFG->auth);
  4567. }
  4568. // construct the display array, with enabled auth plugins at the top, in order
  4569. $displayauths = array();
  4570. $registrationauths = array();
  4571. $registrationauths[''] = $txt->disable;
  4572. foreach ($authsenabled as $auth) {
  4573. $authplugin = get_auth_plugin($auth);
  4574. /// Get the auth title (from core or own auth lang files)
  4575. $authtitle = $authplugin->get_title();
  4576. /// Apply titles
  4577. $displayauths[$auth] = $authtitle;
  4578. if ($authplugin->can_signup()) {
  4579. $registrationauths[$auth] = $authtitle;
  4580. }
  4581. }
  4582. foreach ($authsavailable as $auth => $dir) {
  4583. if (array_key_exists($auth, $displayauths)) {
  4584. continue; //already in the list
  4585. }
  4586. $authplugin = get_auth_plugin($auth);
  4587. /// Get the auth title (from core or own auth lang files)
  4588. $authtitle = $authplugin->get_title();
  4589. /// Apply titles
  4590. $displayauths[$auth] = $authtitle;
  4591. if ($authplugin->can_signup()) {
  4592. $registrationauths[$auth] = $authtitle;
  4593. }
  4594. }
  4595. $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main');
  4596. $return .= $OUTPUT->box_start('generalbox authsui');
  4597. $table = new html_table();
  4598. $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
  4599. $table->align = array('left', 'center', 'center', 'center');
  4600. $table->data = array();
  4601. $table->attributes['class'] = 'manageauthtable generaltable';
  4602. //add always enabled plugins first
  4603. $displayname = "<span>".$displayauths['manual']."</span>";
  4604. $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>";
  4605. //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>";
  4606. $table->data[] = array($displayname, '', '', $settings);
  4607. $displayname = "<span>".$displayauths['nologin']."</span>";
  4608. $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>";
  4609. $table->data[] = array($displayname, '', '', $settings);
  4610. // iterate through auth plugins and add to the display table
  4611. $updowncount = 1;
  4612. $authcount = count($authsenabled);
  4613. $url = "auth.php?sesskey=" . sesskey();
  4614. foreach ($displayauths as $auth => $name) {
  4615. if ($auth == 'manual' or $auth == 'nologin') {
  4616. continue;
  4617. }
  4618. // hide/show link
  4619. if (in_array($auth, $authsenabled)) {
  4620. $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\">";
  4621. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
  4622. // $hideshow = "<a href=\"$url&amp;action=disable&amp;auth=$auth\"><input type=\"checkbox\" checked /></a>";
  4623. $enabled = true;
  4624. $displayname = "<span>$name</span>";
  4625. }
  4626. else {
  4627. $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\">";
  4628. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
  4629. // $hideshow = "<a href=\"$url&amp;action=enable&amp;auth=$auth\"><input type=\"checkbox\" /></a>";
  4630. $enabled = false;
  4631. $displayname = "<span class=\"dimmed_text\">$name</span>";
  4632. }
  4633. // up/down link (only if auth is enabled)
  4634. $updown = '';
  4635. if ($enabled) {
  4636. if ($updowncount > 1) {
  4637. $updown .= "<a href=\"$url&amp;action=up&amp;auth=$auth\">";
  4638. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
  4639. }
  4640. else {
  4641. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
  4642. }
  4643. if ($updowncount < $authcount) {
  4644. $updown .= "<a href=\"$url&amp;action=down&amp;auth=$auth\">";
  4645. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
  4646. }
  4647. else {
  4648. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
  4649. }
  4650. ++ $updowncount;
  4651. }
  4652. // settings link
  4653. if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) {
  4654. $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>";
  4655. } else {
  4656. $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>";
  4657. }
  4658. // add a row to the table
  4659. $table->data[] =array($displayname, $hideshow, $updown, $settings);
  4660. }
  4661. $return .= html_writer::table($table);
  4662. $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters');
  4663. $return .= $OUTPUT->box_end();
  4664. return highlight($query, $return);
  4665. }
  4666. }
  4667. /**
  4668. * Special class for authentication administration.
  4669. *
  4670. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4671. */
  4672. class admin_setting_manageeditors extends admin_setting {
  4673. /**
  4674. * Calls parent::__construct with specific arguments
  4675. */
  4676. public function __construct() {
  4677. $this->nosave = true;
  4678. parent::__construct('editorsui', get_string('editorsettings', 'editor'), '', '');
  4679. }
  4680. /**
  4681. * Always returns true, does nothing
  4682. *
  4683. * @return true
  4684. */
  4685. public function get_setting() {
  4686. return true;
  4687. }
  4688. /**
  4689. * Always returns true, does nothing
  4690. *
  4691. * @return true
  4692. */
  4693. public function get_defaultsetting() {
  4694. return true;
  4695. }
  4696. /**
  4697. * Always returns '', does not write anything
  4698. *
  4699. * @return string Always returns ''
  4700. */
  4701. public function write_setting($data) {
  4702. // do not write any setting
  4703. return '';
  4704. }
  4705. /**
  4706. * Checks if $query is one of the available editors
  4707. *
  4708. * @param string $query The string to search for
  4709. * @return bool Returns true if found, false if not
  4710. */
  4711. public function is_related($query) {
  4712. if (parent::is_related($query)) {
  4713. return true;
  4714. }
  4715. $textlib = textlib_get_instance();
  4716. $editors_available = editors_get_available();
  4717. foreach ($editors_available as $editor=>$editorstr) {
  4718. if (strpos($editor, $query) !== false) {
  4719. return true;
  4720. }
  4721. if (strpos($textlib->strtolower($editorstr), $query) !== false) {
  4722. return true;
  4723. }
  4724. }
  4725. return false;
  4726. }
  4727. /**
  4728. * Builds the XHTML to display the control
  4729. *
  4730. * @param string $data Unused
  4731. * @param string $query
  4732. * @return string
  4733. */
  4734. public function output_html($data, $query='') {
  4735. global $CFG, $OUTPUT;
  4736. // display strings
  4737. $txt = get_strings(array('administration', 'settings', 'edit', 'name', 'enable', 'disable',
  4738. 'up', 'down', 'none'));
  4739. $txt->updown = "$txt->up/$txt->down";
  4740. $editors_available = editors_get_available();
  4741. $active_editors = explode(',', $CFG->texteditors);
  4742. $active_editors = array_reverse($active_editors);
  4743. foreach ($active_editors as $key=>$editor) {
  4744. if (empty($editors_available[$editor])) {
  4745. unset($active_editors[$key]);
  4746. } else {
  4747. $name = $editors_available[$editor];
  4748. unset($editors_available[$editor]);
  4749. $editors_available[$editor] = $name;
  4750. }
  4751. }
  4752. if (empty($active_editors)) {
  4753. //$active_editors = array('textarea');
  4754. }
  4755. $editors_available = array_reverse($editors_available, true);
  4756. $return = $OUTPUT->heading(get_string('acteditorshhdr', 'editor'), 3, 'main', true);
  4757. $return .= $OUTPUT->box_start('generalbox editorsui');
  4758. $table = new html_table();
  4759. $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings);
  4760. $table->align = array('left', 'center', 'center', 'center');
  4761. $table->width = '90%';
  4762. $table->data = array();
  4763. // iterate through auth plugins and add to the display table
  4764. $updowncount = 1;
  4765. $editorcount = count($active_editors);
  4766. $url = "editors.php?sesskey=" . sesskey();
  4767. foreach ($editors_available as $editor => $name) {
  4768. // hide/show link
  4769. if (in_array($editor, $active_editors)) {
  4770. $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\">";
  4771. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>";
  4772. // $hideshow = "<a href=\"$url&amp;action=disable&amp;editor=$editor\"><input type=\"checkbox\" checked /></a>";
  4773. $enabled = true;
  4774. $displayname = "<span>$name</span>";
  4775. }
  4776. else {
  4777. $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\">";
  4778. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>";
  4779. // $hideshow = "<a href=\"$url&amp;action=enable&amp;editor=$editor\"><input type=\"checkbox\" /></a>";
  4780. $enabled = false;
  4781. $displayname = "<span class=\"dimmed_text\">$name</span>";
  4782. }
  4783. // up/down link (only if auth is enabled)
  4784. $updown = '';
  4785. if ($enabled) {
  4786. if ($updowncount > 1) {
  4787. $updown .= "<a href=\"$url&amp;action=up&amp;editor=$editor\">";
  4788. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
  4789. }
  4790. else {
  4791. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />&nbsp;";
  4792. }
  4793. if ($updowncount < $editorcount) {
  4794. $updown .= "<a href=\"$url&amp;action=down&amp;editor=$editor\">";
  4795. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
  4796. }
  4797. else {
  4798. $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />";
  4799. }
  4800. ++ $updowncount;
  4801. }
  4802. // settings link
  4803. if (file_exists($CFG->dirroot.'/lib/editor/'.$editor.'/settings.php')) {
  4804. $eurl = new moodle_url('/admin/settings.php', array('section'=>'editorsettingstinymce'));
  4805. $settings = "<a href='$eurl'>{$txt->settings}</a>";
  4806. } else {
  4807. $settings = '';
  4808. }
  4809. // add a row to the table
  4810. $table->data[] =array($displayname, $hideshow, $updown, $settings);
  4811. }
  4812. $return .= html_writer::table($table);
  4813. $return .= get_string('configeditorplugins', 'editor').'<br />'.get_string('tablenosave', 'admin');
  4814. $return .= $OUTPUT->box_end();
  4815. return highlight($query, $return);
  4816. }
  4817. }
  4818. /**
  4819. * Special class for license administration.
  4820. *
  4821. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4822. */
  4823. class admin_setting_managelicenses extends admin_setting {
  4824. /**
  4825. * Calls parent::__construct with specific arguments
  4826. */
  4827. public function __construct() {
  4828. $this->nosave = true;
  4829. parent::__construct('licensesui', get_string('licensesettings', 'admin'), '', '');
  4830. }
  4831. /**
  4832. * Always returns true, does nothing
  4833. *
  4834. * @return true
  4835. */
  4836. public function get_setting() {
  4837. return true;
  4838. }
  4839. /**
  4840. * Always returns true, does nothing
  4841. *
  4842. * @return true
  4843. */
  4844. public function get_defaultsetting() {
  4845. return true;
  4846. }
  4847. /**
  4848. * Always returns '', does not write anything
  4849. *
  4850. * @return string Always returns ''
  4851. */
  4852. public function write_setting($data) {
  4853. // do not write any setting
  4854. return '';
  4855. }
  4856. /**
  4857. * Builds the XHTML to display the control
  4858. *
  4859. * @param string $data Unused
  4860. * @param string $query
  4861. * @return string
  4862. */
  4863. public function output_html($data, $query='') {
  4864. global $CFG, $OUTPUT;
  4865. require_once($CFG->libdir . '/licenselib.php');
  4866. $url = "licenses.php?sesskey=" . sesskey();
  4867. // display strings
  4868. $txt = get_strings(array('administration', 'settings', 'name', 'enable', 'disable', 'none'));
  4869. $licenses = license_manager::get_licenses();
  4870. $return = $OUTPUT->heading(get_string('availablelicenses', 'admin'), 3, 'main', true);
  4871. $return .= $OUTPUT->box_start('generalbox editorsui');
  4872. $table = new html_table();
  4873. $table->head = array($txt->name, $txt->enable);
  4874. $table->align = array('left', 'center');
  4875. $table->width = '100%';
  4876. $table->data = array();
  4877. foreach ($licenses as $value) {
  4878. $displayname = html_writer::link($value->source, get_string($value->shortname, 'license'), array('target'=>'_blank'));
  4879. if ($value->enabled == 1) {
  4880. $hideshow = html_writer::link($url.'&action=disable&license='.$value->shortname,
  4881. html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/hide'), 'class'=>'icon', 'alt'=>'disable')));
  4882. } else {
  4883. $hideshow = html_writer::link($url.'&action=enable&license='.$value->shortname,
  4884. html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/show'), 'class'=>'icon', 'alt'=>'enable')));
  4885. }
  4886. if ($value->shortname == $CFG->sitedefaultlicense) {
  4887. $displayname .= ' '.html_writer::tag('img', '', array('src'=>$OUTPUT->pix_url('i/lock'), 'class'=>'icon', 'alt'=>get_string('default'), 'title'=>get_string('default')));
  4888. $hideshow = '';
  4889. }
  4890. $enabled = true;
  4891. $table->data[] =array($displayname, $hideshow);
  4892. }
  4893. $return .= html_writer::table($table);
  4894. $return .= $OUTPUT->box_end();
  4895. return highlight($query, $return);
  4896. }
  4897. }
  4898. /**
  4899. * Special class for filter administration.
  4900. *
  4901. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4902. */
  4903. class admin_page_managefilters extends admin_externalpage {
  4904. /**
  4905. * Calls parent::__construct with specific arguments
  4906. */
  4907. public function __construct() {
  4908. global $CFG;
  4909. parent::__construct('managefilters', get_string('filtersettings', 'admin'), "$CFG->wwwroot/$CFG->admin/filters.php");
  4910. }
  4911. /**
  4912. * Searches all installed filters for specified filter
  4913. *
  4914. * @param string $query The filter(string) to search for
  4915. * @param string $query
  4916. */
  4917. public function search($query) {
  4918. global $CFG;
  4919. if ($result = parent::search($query)) {
  4920. return $result;
  4921. }
  4922. $found = false;
  4923. $filternames = filter_get_all_installed();
  4924. $textlib = textlib_get_instance();
  4925. foreach ($filternames as $path => $strfiltername) {
  4926. if (strpos($textlib->strtolower($strfiltername), $query) !== false) {
  4927. $found = true;
  4928. break;
  4929. }
  4930. list($type, $filter) = explode('/', $path);
  4931. if (strpos($filter, $query) !== false) {
  4932. $found = true;
  4933. break;
  4934. }
  4935. }
  4936. if ($found) {
  4937. $result = new stdClass;
  4938. $result->page = $this;
  4939. $result->settings = array();
  4940. return array($this->name => $result);
  4941. } else {
  4942. return array();
  4943. }
  4944. }
  4945. }
  4946. /**
  4947. * Initialise admin page - this function does require login and permission
  4948. * checks specified in page definition.
  4949. *
  4950. * This function must be called on each admin page before other code.
  4951. *
  4952. * @global moodle_page $PAGE
  4953. *
  4954. * @param string $section name of page
  4955. * @param string $extrabutton extra HTML that is added after the blocks editing on/off button.
  4956. * @param array $extraurlparams an array paramname => paramvalue, or parameters that need to be
  4957. * added to the turn blocks editing on/off form, so this page reloads correctly.
  4958. * @param string $actualurl if the actual page being viewed is not the normal one for this
  4959. * page (e.g. admin/roles/allowassin.php, instead of admin/roles/manage.php, you can pass the alternate URL here.
  4960. * @param array $options Additional options that can be specified for page setup.
  4961. * pagelayout - This option can be used to set a specific pagelyaout, admin is default.
  4962. */
  4963. function admin_externalpage_setup($section, $extrabutton = '', array $extraurlparams = null, $actualurl = '', array $options = array()) {
  4964. global $CFG, $PAGE, $USER, $SITE, $OUTPUT;
  4965. $PAGE->set_context(null); // hack - set context to something, by default to system context
  4966. $site = get_site();
  4967. require_login();
  4968. $adminroot = admin_get_root(false, false); // settings not required for external pages
  4969. $extpage = $adminroot->locate($section, true);
  4970. if (empty($extpage) or !($extpage instanceof admin_externalpage)) {
  4971. print_error('sectionerror', 'admin', "$CFG->wwwroot/$CFG->admin/");
  4972. die;
  4973. }
  4974. // this eliminates our need to authenticate on the actual pages
  4975. if (!$extpage->check_access()) {
  4976. print_error('accessdenied', 'admin');
  4977. die;
  4978. }
  4979. if (!empty($options['pagelayout'])) {
  4980. // A specific page layout has been requested.
  4981. $PAGE->set_pagelayout($options['pagelayout']);
  4982. } else if ($section === 'upgradesettings') {
  4983. $PAGE->set_pagelayout('maintenance');
  4984. } else {
  4985. $PAGE->set_pagelayout('admin');
  4986. }
  4987. // $PAGE->set_extra_button($extrabutton); TODO
  4988. if (!$actualurl) {
  4989. $actualurl = $extpage->url;
  4990. }
  4991. $PAGE->set_url($actualurl, $extraurlparams);
  4992. if (strpos($PAGE->pagetype, 'admin-') !== 0) {
  4993. $PAGE->set_pagetype('admin-' . $PAGE->pagetype);
  4994. }
  4995. if (empty($SITE->fullname) || empty($SITE->shortname)) {
  4996. // During initial install.
  4997. $strinstallation = get_string('installation', 'install');
  4998. $strsettings = get_string('settings');
  4999. $PAGE->navbar->add($strsettings);
  5000. $PAGE->set_title($strinstallation);
  5001. $PAGE->set_heading($strinstallation);
  5002. $PAGE->set_cacheable(false);
  5003. return;
  5004. }
  5005. // Locate the current item on the navigation and make it active when found.
  5006. $path = $extpage->path;
  5007. $node = $PAGE->settingsnav;
  5008. while ($node && count($path) > 0) {
  5009. $node = $node->get(array_pop($path));
  5010. }
  5011. if ($node) {
  5012. $node->make_active();
  5013. }
  5014. // Normal case.
  5015. $adminediting = optional_param('adminedit', -1, PARAM_BOOL);
  5016. if ($PAGE->user_allowed_editing() && $adminediting != -1) {
  5017. $USER->editing = $adminediting;
  5018. }
  5019. $visiblepathtosection = array_reverse($extpage->visiblepath);
  5020. if ($PAGE->user_allowed_editing()) {
  5021. if ($PAGE->user_is_editing()) {
  5022. $caption = get_string('blockseditoff');
  5023. $url = new moodle_url($PAGE->url, array('adminedit'=>'0'));
  5024. } else {
  5025. $caption = get_string('blocksediton');
  5026. $url = new moodle_url($PAGE->url, array('adminedit'=>'1'));
  5027. }
  5028. $PAGE->set_button($OUTPUT->single_button($url, $caption, 'get'));
  5029. }
  5030. $PAGE->set_title("$SITE->shortname: " . implode(": ", $visiblepathtosection));
  5031. $PAGE->set_heading($SITE->fullname);
  5032. // prevent caching in nav block
  5033. $PAGE->navigation->clear_cache();
  5034. }
  5035. /**
  5036. * Returns the reference to admin tree root
  5037. *
  5038. * @return object admin_roow object
  5039. */
  5040. function admin_get_root($reload=false, $requirefulltree=true) {
  5041. global $CFG, $DB, $OUTPUT;
  5042. static $ADMIN = NULL;
  5043. if (is_null($ADMIN)) {
  5044. // create the admin tree!
  5045. $ADMIN = new admin_root($requirefulltree);
  5046. }
  5047. if ($reload or ($requirefulltree and !$ADMIN->fulltree)) {
  5048. $ADMIN->purge_children($requirefulltree);
  5049. }
  5050. if (!$ADMIN->loaded) {
  5051. // we process this file first to create categories first and in correct order
  5052. require($CFG->dirroot.'/'.$CFG->admin.'/settings/top.php');
  5053. // now we process all other files in admin/settings to build the admin tree
  5054. foreach (glob($CFG->dirroot.'/'.$CFG->admin.'/settings/*.php') as $file) {
  5055. if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/top.php') {
  5056. continue;
  5057. }
  5058. if ($file == $CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php') {
  5059. // plugins are loaded last - they may insert pages anywhere
  5060. continue;
  5061. }
  5062. require($file);
  5063. }
  5064. require($CFG->dirroot.'/'.$CFG->admin.'/settings/plugins.php');
  5065. $ADMIN->loaded = true;
  5066. }
  5067. return $ADMIN;
  5068. }
  5069. /// settings utility functions
  5070. /**
  5071. * This function applies default settings.
  5072. *
  5073. * @param object $node, NULL means complete tree, null by default
  5074. * @param bool $unconditional if true overrides all values with defaults, null buy default
  5075. */
  5076. function admin_apply_default_settings($node=NULL, $unconditional=true) {
  5077. global $CFG;
  5078. if (is_null($node)) {
  5079. $node = admin_get_root(true, true);
  5080. }
  5081. if ($node instanceof admin_category) {
  5082. $entries = array_keys($node->children);
  5083. foreach ($entries as $entry) {
  5084. admin_apply_default_settings($node->children[$entry], $unconditional);
  5085. }
  5086. } else if ($node instanceof admin_settingpage) {
  5087. foreach ($node->settings as $setting) {
  5088. if (!$unconditional and !is_null($setting->get_setting())) {
  5089. //do not override existing defaults
  5090. continue;
  5091. }
  5092. $defaultsetting = $setting->get_defaultsetting();
  5093. if (is_null($defaultsetting)) {
  5094. // no value yet - default maybe applied after admin user creation or in upgradesettings
  5095. continue;
  5096. }
  5097. $setting->write_setting($defaultsetting);
  5098. }
  5099. }
  5100. }
  5101. /**
  5102. * Store changed settings, this function updates the errors variable in $ADMIN
  5103. *
  5104. * @param object $formdata from form
  5105. * @return int number of changed settings
  5106. */
  5107. function admin_write_settings($formdata) {
  5108. global $CFG, $SITE, $DB;
  5109. $olddbsessions = !empty($CFG->dbsessions);
  5110. $formdata = (array)$formdata;
  5111. $data = array();
  5112. foreach ($formdata as $fullname=>$value) {
  5113. if (strpos($fullname, 's_') !== 0) {
  5114. continue; // not a config value
  5115. }
  5116. $data[$fullname] = $value;
  5117. }
  5118. $adminroot = admin_get_root();
  5119. $settings = admin_find_write_settings($adminroot, $data);
  5120. $count = 0;
  5121. foreach ($settings as $fullname=>$setting) {
  5122. $original = serialize($setting->get_setting()); // comparison must work for arrays too
  5123. $error = $setting->write_setting($data[$fullname]);
  5124. if ($error !== '') {
  5125. $adminroot->errors[$fullname] = new stdClass();
  5126. $adminroot->errors[$fullname]->data = $data[$fullname];
  5127. $adminroot->errors[$fullname]->id = $setting->get_id();
  5128. $adminroot->errors[$fullname]->error = $error;
  5129. }
  5130. if ($original !== serialize($setting->get_setting())) {
  5131. $count++;
  5132. $callbackfunction = $setting->updatedcallback;
  5133. if (function_exists($callbackfunction)) {
  5134. $callbackfunction($fullname);
  5135. }
  5136. }
  5137. }
  5138. if ($olddbsessions != !empty($CFG->dbsessions)) {
  5139. require_logout();
  5140. }
  5141. // Now update $SITE - just update the fields, in case other people have a
  5142. // a reference to it (e.g. $PAGE, $COURSE).
  5143. $newsite = $DB->get_record('course', array('id'=>$SITE->id));
  5144. foreach (get_object_vars($newsite) as $field => $value) {
  5145. $SITE->$field = $value;
  5146. }
  5147. // now reload all settings - some of them might depend on the changed
  5148. admin_get_root(true);
  5149. return $count;
  5150. }
  5151. /**
  5152. * Internal recursive function - finds all settings from submitted form
  5153. *
  5154. * @param object $node Instance of admin_category, or admin_settingpage
  5155. * @param array $data
  5156. * @return array
  5157. */
  5158. function admin_find_write_settings($node, $data) {
  5159. $return = array();
  5160. if (empty($data)) {
  5161. return $return;
  5162. }
  5163. if ($node instanceof admin_category) {
  5164. $entries = array_keys($node->children);
  5165. foreach ($entries as $entry) {
  5166. $return = array_merge($return, admin_find_write_settings($node->children[$entry], $data));
  5167. }
  5168. } else if ($node instanceof admin_settingpage) {
  5169. foreach ($node->settings as $setting) {
  5170. $fullname = $setting->get_full_name();
  5171. if (array_key_exists($fullname, $data)) {
  5172. $return[$fullname] = $setting;
  5173. }
  5174. }
  5175. }
  5176. return $return;
  5177. }
  5178. /**
  5179. * Internal function - prints the search results
  5180. *
  5181. * @param string $query String to search for
  5182. * @return string empty or XHTML
  5183. */
  5184. function admin_search_settings_html($query) {
  5185. global $CFG, $OUTPUT;
  5186. $textlib = textlib_get_instance();
  5187. if ($textlib->strlen($query) < 2) {
  5188. return '';
  5189. }
  5190. $query = $textlib->strtolower($query);
  5191. $adminroot = admin_get_root();
  5192. $findings = $adminroot->search($query);
  5193. $return = '';
  5194. $savebutton = false;
  5195. foreach ($findings as $found) {
  5196. $page = $found->page;
  5197. $settings = $found->settings;
  5198. if ($page->is_hidden()) {
  5199. // hidden pages are not displayed in search results
  5200. continue;
  5201. }
  5202. if ($page instanceof admin_externalpage) {
  5203. $return .= $OUTPUT->heading(get_string('searchresults','admin').' - <a href="'.$page->url.'">'.highlight($query, $page->visiblename).'</a>', 2, 'main');
  5204. } else if ($page instanceof admin_settingpage) {
  5205. $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');
  5206. } else {
  5207. continue;
  5208. }
  5209. if (!empty($settings)) {
  5210. $return .= '<fieldset class="adminsettings">'."\n";
  5211. foreach ($settings as $setting) {
  5212. if (empty($setting->nosave)) {
  5213. $savebutton = true;
  5214. }
  5215. $return .= '<div class="clearer"><!-- --></div>'."\n";
  5216. $fullname = $setting->get_full_name();
  5217. if (array_key_exists($fullname, $adminroot->errors)) {
  5218. $data = $adminroot->errors[$fullname]->data;
  5219. } else {
  5220. $data = $setting->get_setting();
  5221. // do not use defaults if settings not available - upgradesettings handles the defaults!
  5222. }
  5223. $return .= $setting->output_html($data, $query);
  5224. }
  5225. $return .= '</fieldset>';
  5226. }
  5227. }
  5228. if ($savebutton) {
  5229. $return .= '<div class="form-buttons"><input class="form-submit" type="submit" value="'.get_string('savechanges','admin').'" /></div>';
  5230. }
  5231. return $return;
  5232. }
  5233. /**
  5234. * Internal function - returns arrays of html pages with uninitialised settings
  5235. *
  5236. * @param object $node Instance of admin_category or admin_settingpage
  5237. * @return array
  5238. */
  5239. function admin_output_new_settings_by_page($node) {
  5240. global $OUTPUT;
  5241. $return = array();
  5242. if ($node instanceof admin_category) {
  5243. $entries = array_keys($node->children);
  5244. foreach ($entries as $entry) {
  5245. $return += admin_output_new_settings_by_page($node->children[$entry]);
  5246. }
  5247. } else if ($node instanceof admin_settingpage) {
  5248. $newsettings = array();
  5249. foreach ($node->settings as $setting) {
  5250. if (is_null($setting->get_setting())) {
  5251. $newsettings[] = $setting;
  5252. }
  5253. }
  5254. if (count($newsettings) > 0) {
  5255. $adminroot = admin_get_root();
  5256. $page = $OUTPUT->heading(get_string('upgradesettings','admin').' - '.$node->visiblename, 2, 'main');
  5257. $page .= '<fieldset class="adminsettings">'."\n";
  5258. foreach ($newsettings as $setting) {
  5259. $fullname = $setting->get_full_name();
  5260. if (array_key_exists($fullname, $adminroot->errors)) {
  5261. $data = $adminroot->errors[$fullname]->data;
  5262. } else {
  5263. $data = $setting->get_setting();
  5264. if (is_null($data)) {
  5265. $data = $setting->get_defaultsetting();
  5266. }
  5267. }
  5268. $page .= '<div class="clearer"><!-- --></div>'."\n";
  5269. $page .= $setting->output_html($data);
  5270. }
  5271. $page .= '</fieldset>';
  5272. $return[$node->name] = $page;
  5273. }
  5274. }
  5275. return $return;
  5276. }
  5277. /**
  5278. * Format admin settings
  5279. *
  5280. * @param object $setting
  5281. * @param string $title label element
  5282. * @param string $form form fragment, html code - not highlighted automatically
  5283. * @param string $description
  5284. * @param bool $label link label to id, true by default
  5285. * @param string $warning warning text
  5286. * @param sting $defaultinfo defaults info, null means nothing, '' is converted to "Empty" string, defaults to null
  5287. * @param string $query search query to be highlighted
  5288. * @return string XHTML
  5289. */
  5290. function format_admin_setting($setting, $title='', $form='', $description='', $label=true, $warning='', $defaultinfo=NULL, $query='') {
  5291. global $CFG;
  5292. $name = empty($setting->plugin) ? $setting->name : "$setting->plugin | $setting->name";
  5293. $fullname = $setting->get_full_name();
  5294. // sometimes the id is not id_s_name, but id_s_name_m or something, and this does not validate
  5295. if ($label) {
  5296. $labelfor = 'for = "'.$setting->get_id().'"';
  5297. } else {
  5298. $labelfor = '';
  5299. }
  5300. $override = '';
  5301. if (empty($setting->plugin)) {
  5302. if (array_key_exists($setting->name, $CFG->config_php_settings)) {
  5303. $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
  5304. }
  5305. } else {
  5306. if (array_key_exists($setting->plugin, $CFG->forced_plugin_settings) and array_key_exists($setting->name, $CFG->forced_plugin_settings[$setting->plugin])) {
  5307. $override = '<div class="form-overridden">'.get_string('configoverride', 'admin').'</div>';
  5308. }
  5309. }
  5310. if ($warning !== '') {
  5311. $warning = '<div class="form-warning">'.$warning.'</div>';
  5312. }
  5313. if (is_null($defaultinfo)) {
  5314. $defaultinfo = '';
  5315. } else {
  5316. if ($defaultinfo === '') {
  5317. $defaultinfo = get_string('emptysettingvalue', 'admin');
  5318. }
  5319. $defaultinfo = highlight($query, nl2br(s($defaultinfo)));
  5320. $defaultinfo = '<div class="form-defaultinfo">'.get_string('defaultsettinginfo', 'admin', $defaultinfo).'</div>';
  5321. }
  5322. $str = '
  5323. <div class="form-item clearfix" id="admin-'.$setting->name.'">
  5324. <div class="form-label">
  5325. <label '.$labelfor.'>'.highlightfast($query, $title).'<span class="form-shortname">'.highlightfast($query, $name).'</span>
  5326. '.$override.$warning.'
  5327. </label>
  5328. </div>
  5329. <div class="form-setting">'.$form.$defaultinfo.'</div>
  5330. <div class="form-description">'.highlight($query, markdown_to_html($description)).'</div>
  5331. </div>';
  5332. $adminroot = admin_get_root();
  5333. if (array_key_exists($fullname, $adminroot->errors)) {
  5334. $str = '<fieldset class="error"><legend>'.$adminroot->errors[$fullname]->error.'</legend>'.$str.'</fieldset>';
  5335. }
  5336. return $str;
  5337. }
  5338. /**
  5339. * Based on find_new_settings{@link ()} in upgradesettings.php
  5340. * Looks to find any admin settings that have not been initialized. Returns 1 if it finds any.
  5341. *
  5342. * @param object $node Instance of admin_category, or admin_settingpage
  5343. * @return boolean true if any settings haven't been initialised, false if they all have
  5344. */
  5345. function any_new_admin_settings($node) {
  5346. if ($node instanceof admin_category) {
  5347. $entries = array_keys($node->children);
  5348. foreach ($entries as $entry) {
  5349. if (any_new_admin_settings($node->children[$entry])) {
  5350. return true;
  5351. }
  5352. }
  5353. } else if ($node instanceof admin_settingpage) {
  5354. foreach ($node->settings as $setting) {
  5355. if ($setting->get_setting() === NULL) {
  5356. return true;
  5357. }
  5358. }
  5359. }
  5360. return false;
  5361. }
  5362. /**
  5363. * Moved from admin/replace.php so that we can use this in cron
  5364. *
  5365. * @param string $search string to look for
  5366. * @param string $replace string to replace
  5367. * @return bool success or fail
  5368. */
  5369. function db_replace($search, $replace) {
  5370. global $DB, $CFG;
  5371. /// Turn off time limits, sometimes upgrades can be slow.
  5372. @set_time_limit(0);
  5373. if (!$tables = $DB->get_tables() ) { // No tables yet at all.
  5374. return false;
  5375. }
  5376. foreach ($tables as $table) {
  5377. if (in_array($table, array('config'))) { // Don't process these
  5378. continue;
  5379. }
  5380. if ($columns = $DB->get_columns($table)) {
  5381. $DB->set_debug(true);
  5382. foreach ($columns as $column => $data) {
  5383. if (in_array($data->meta_type, array('C', 'X'))) { // Text stuff only
  5384. $DB->execute("UPDATE {".$table."} SET $column = REPLACE($column, ?, ?)", array($search, $replace));
  5385. }
  5386. }
  5387. $DB->set_debug(false);
  5388. }
  5389. }
  5390. return true;
  5391. }
  5392. /**
  5393. * Prints tables of detected plugins, one table per plugin type,
  5394. * and prints whether they are part of the standard Moodle
  5395. * distribution or not.
  5396. */
  5397. function print_plugin_tables() {
  5398. global $DB;
  5399. $plugins_standard = array();
  5400. $plugins_standard['mod'] = array('assignment',
  5401. 'chat',
  5402. 'choice',
  5403. 'data',
  5404. 'feedback',
  5405. 'folder',
  5406. 'forum',
  5407. 'glossary',
  5408. 'imscp',
  5409. 'label',
  5410. 'lesson',
  5411. 'page',
  5412. 'quiz',
  5413. 'resource',
  5414. 'scorm',
  5415. 'survey',
  5416. 'url',
  5417. 'wiki',
  5418. 'workshop');
  5419. $plugins_standard['blocks'] = array('activity_modules',
  5420. 'admin_bookmarks',
  5421. 'blog_menu',
  5422. 'blog_recent',
  5423. 'blog_tags',
  5424. 'calendar_month',
  5425. 'calendar_upcoming',
  5426. 'comments',
  5427. 'community',
  5428. 'completionstatus',
  5429. 'course_list',
  5430. 'course_overview',
  5431. 'course_summary',
  5432. 'feedback',
  5433. 'glossary_random',
  5434. 'html',
  5435. 'login',
  5436. 'mentees',
  5437. 'messages',
  5438. 'mnet_hosts',
  5439. 'myprofile',
  5440. 'navigation',
  5441. 'news_items',
  5442. 'online_users',
  5443. 'participants',
  5444. 'private_files',
  5445. 'quiz_results',
  5446. 'recent_activity',
  5447. 'rss_client',
  5448. 'search',
  5449. 'search_forums',
  5450. 'section_links',
  5451. 'selfcompletion',
  5452. 'settings',
  5453. 'site_main_menu',
  5454. 'social_activities',
  5455. 'tag_flickr',
  5456. 'tag_youtube',
  5457. 'tags');
  5458. $plugins_standard['filter'] = array('activitynames',
  5459. 'algebra',
  5460. 'censor',
  5461. 'emailprotect',
  5462. 'emoticon',
  5463. 'filter',
  5464. 'mediaplugin',
  5465. 'multilang',
  5466. 'tex',
  5467. 'tidy',
  5468. 'urltolink');
  5469. $plugins_installed = array();
  5470. $installed_mods = $DB->get_records('modules', null, 'name');
  5471. $installed_blocks = $DB->get_records('block', null, 'name');
  5472. foreach($installed_mods as $mod) {
  5473. $plugins_installed['mod'][] = $mod->name;
  5474. }
  5475. foreach($installed_blocks as $block) {
  5476. $plugins_installed['blocks'][] = $block->name;
  5477. }
  5478. $plugins_installed['filter'] = array();
  5479. $plugins_ondisk = array();
  5480. $plugins_ondisk['mod'] = array_keys(get_plugin_list('mod'));
  5481. $plugins_ondisk['blocks'] = array_keys(get_plugin_list('block'));
  5482. $plugins_ondisk['filter'] = array_keys(get_plugin_list('filter'));
  5483. $strstandard = get_string('standard');
  5484. $strnonstandard = get_string('nonstandard');
  5485. $strmissingfromdisk = '(' . get_string('missingfromdisk') . ')';
  5486. $strabouttobeinstalled = '(' . get_string('abouttobeinstalled') . ')';
  5487. $html = '';
  5488. $html .= '<table class="generaltable plugincheckwrapper" cellspacing="4" cellpadding="1"><tr valign="top">';
  5489. foreach ($plugins_ondisk as $cat => $list_ondisk) {
  5490. if ($cat == 'mod') {
  5491. $strcaption = get_string('activitymodule');
  5492. } elseif ($cat == 'filter') {
  5493. $strcaption = get_string('managefilters');
  5494. } else {
  5495. $strcaption = get_string($cat);
  5496. }
  5497. $html .= '<td><table class="plugincompattable generaltable boxaligncenter" cellspacing="1" cellpadding="5" '
  5498. . 'id="' . $cat . 'compattable" summary="compatibility table"><caption>' . $strcaption . '</caption>' . "\n";
  5499. $html .= '<tr class="r0"><th class="header c0">' . get_string('directory') . "</th>\n"
  5500. . '<th class="header c1">' . get_string('name') . "</th>\n"
  5501. . '<th class="header c2">' . get_string('status') . "</th>\n</tr>\n";
  5502. $row = 1;
  5503. foreach ($list_ondisk as $k => $plugin) {
  5504. $status = 'ok';
  5505. $standard = 'standard';
  5506. $note = '';
  5507. if (!in_array($plugin, $plugins_standard[$cat])) {
  5508. $standard = 'nonstandard';
  5509. $status = 'warning';
  5510. }
  5511. // Get real name and full path of plugin
  5512. $plugin_name = "[[$plugin]]";
  5513. $plugin_path = "$cat/$plugin";
  5514. $plugin_name = get_plugin_name($plugin, $cat);
  5515. // Determine if the plugin is about to be installed
  5516. if ($cat != 'filter' && !in_array($plugin, $plugins_installed[$cat])) {
  5517. $note = $strabouttobeinstalled;
  5518. $plugin_name = $plugin;
  5519. }
  5520. $html .= "<tr class=\"r$row\">\n"
  5521. . "<td class=\"cell c0\">$plugin_path</td>\n"
  5522. . "<td class=\"cell c1\">$plugin_name</td>\n"
  5523. . "<td class=\"$standard $status cell c2\">" . ${'str' . $standard} . " $note</td>\n</tr>\n";
  5524. $row++;
  5525. // If the plugin was both on disk and in the db, unset the value from the installed plugins list
  5526. if ($key = array_search($plugin, $plugins_installed[$cat])) {
  5527. unset($plugins_installed[$cat][$key]);
  5528. }
  5529. }
  5530. // If there are plugins left in the plugins_installed list, it means they are missing from disk
  5531. foreach ($plugins_installed[$cat] as $k => $missing_plugin) {
  5532. // Make sure the plugin really is missing from disk
  5533. if (!in_array($missing_plugin, $plugins_ondisk[$cat])) {
  5534. $standard = 'standard';
  5535. $status = 'warning';
  5536. if (!in_array($missing_plugin, $plugins_standard[$cat])) {
  5537. $standard = 'nonstandard';
  5538. }
  5539. $plugin_name = $missing_plugin;
  5540. $html .= "<tr class=\"r$row\">\n"
  5541. . "<td class=\"cell c0\">?</td>\n"
  5542. . "<td class=\"cell c1\">$plugin_name</td>\n"
  5543. . "<td class=\"$standard $status cell c2\">" . ${'str' . $standard} . " $strmissingfromdisk</td>\n</tr>\n";
  5544. $row++;
  5545. }
  5546. }
  5547. $html .= '</table></td>';
  5548. }
  5549. $html .= '</tr></table><br />';
  5550. echo $html;
  5551. }
  5552. /**
  5553. * Manage repository settings
  5554. *
  5555. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  5556. */
  5557. class admin_setting_managerepository extends admin_setting {
  5558. /** @var string */
  5559. private $baseurl;
  5560. /**
  5561. * calls parent::__construct with specific arguments
  5562. */
  5563. public function __construct() {
  5564. global $CFG;
  5565. parent::__construct('managerepository', get_string('manage', 'repository'), '', '');
  5566. $this->baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/repository.php?sesskey=' . sesskey();
  5567. }
  5568. /**
  5569. * Always returns true, does nothing
  5570. *
  5571. * @return true
  5572. */
  5573. public function get_setting() {
  5574. return true;
  5575. }
  5576. /**
  5577. * Always returns true does nothing
  5578. *
  5579. * @return true
  5580. */
  5581. public function get_defaultsetting() {
  5582. return true;
  5583. }
  5584. /**
  5585. * Always returns s_managerepository
  5586. *
  5587. * @return string Always return 's_managerepository'
  5588. */
  5589. public function get_full_name() {
  5590. return 's_managerepository';
  5591. }
  5592. /**
  5593. * Always returns '' doesn't do anything
  5594. */
  5595. public function write_setting($data) {
  5596. $url = $this->baseurl . '&amp;new=' . $data;
  5597. return '';
  5598. // TODO
  5599. // Should not use redirect and exit here
  5600. // Find a better way to do this.
  5601. // redirect($url);
  5602. // exit;
  5603. }
  5604. /**
  5605. * Searches repository plugins for one that matches $query
  5606. *
  5607. * @param string $query The string to search for
  5608. * @return bool true if found, false if not
  5609. */
  5610. public function is_related($query) {
  5611. if (parent::is_related($query)) {
  5612. return true;
  5613. }
  5614. $textlib = textlib_get_instance();
  5615. $repositories= get_plugin_list('repository');
  5616. foreach ($repositories as $p => $dir) {
  5617. if (strpos($p, $query) !== false) {
  5618. return true;
  5619. }
  5620. }
  5621. foreach (repository::get_types() as $instance) {
  5622. $title = $instance->get_typename();
  5623. if (strpos($textlib->strtolower($title), $query) !== false) {
  5624. return true;
  5625. }
  5626. }
  5627. return false;
  5628. }
  5629. /**
  5630. * Helper function that generates a moodle_url object
  5631. * relevant to the repository
  5632. */
  5633. function repository_action_url($repository) {
  5634. return new moodle_url($this->baseurl, array('sesskey'=>sesskey(), 'repos'=>$repository));
  5635. }
  5636. /**
  5637. * Builds XHTML to display the control
  5638. *
  5639. * @param string $data Unused
  5640. * @param string $query
  5641. * @return string XHTML
  5642. */
  5643. public function output_html($data, $query='') {
  5644. global $CFG, $USER, $OUTPUT;
  5645. // Get strings that are used
  5646. $strshow = get_string('on', 'repository');
  5647. $strhide = get_string('off', 'repository');
  5648. $strdelete = get_string('disabled', 'repository');
  5649. $actionchoicesforexisting = array(
  5650. 'show' => $strshow,
  5651. 'hide' => $strhide,
  5652. 'delete' => $strdelete
  5653. );
  5654. $actionchoicesfornew = array(
  5655. 'newon' => $strshow,
  5656. 'newoff' => $strhide,
  5657. 'delete' => $strdelete
  5658. );
  5659. $return = '';
  5660. $return .= $OUTPUT->box_start('generalbox');
  5661. // Set strings that are used multiple times
  5662. $settingsstr = get_string('settings');
  5663. $disablestr = get_string('disable');
  5664. // Table to list plug-ins
  5665. $table = new html_table();
  5666. $table->head = array(get_string('name'), get_string('isactive', 'repository'), get_string('order'), $settingsstr);
  5667. $table->align = array('left', 'center', 'center', 'center', 'center');
  5668. $table->data = array();
  5669. // Get list of used plug-ins
  5670. $instances = repository::get_types();
  5671. if (!empty($instances)) {
  5672. // Array to store plugins being used
  5673. $alreadyplugins = array();
  5674. $totalinstances = count($instances);
  5675. $updowncount = 1;
  5676. foreach ($instances as $i) {
  5677. $settings = '';
  5678. $typename = $i->get_typename();
  5679. // Display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
  5680. $typeoptionnames = repository::static_function($typename, 'get_type_option_names');
  5681. $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
  5682. if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
  5683. // Calculate number of instances in order to display them for the Moodle administrator
  5684. if (!empty($instanceoptionnames)) {
  5685. $params = array();
  5686. $params['context'] = array(get_system_context());
  5687. $params['onlyvisible'] = false;
  5688. $params['type'] = $typename;
  5689. $admininstancenumber = count(repository::static_function($typename, 'get_instances', $params));
  5690. // site instances
  5691. $admininstancenumbertext = get_string('instancesforsite', 'repository', $admininstancenumber);
  5692. $params['context'] = array();
  5693. $instances = repository::static_function($typename, 'get_instances', $params);
  5694. $courseinstances = array();
  5695. $userinstances = array();
  5696. foreach ($instances as $instance) {
  5697. if ($instance->context->contextlevel == CONTEXT_COURSE) {
  5698. $courseinstances[] = $instance;
  5699. } else if ($instance->context->contextlevel == CONTEXT_USER) {
  5700. $userinstances[] = $instance;
  5701. }
  5702. }
  5703. // course instances
  5704. $instancenumber = count($courseinstances);
  5705. $courseinstancenumbertext = get_string('instancesforcourses', 'repository', $instancenumber);
  5706. // user private instances
  5707. $instancenumber = count($userinstances);
  5708. $userinstancenumbertext = get_string('instancesforusers', 'repository', $instancenumber);
  5709. } else {
  5710. $admininstancenumbertext = "";
  5711. $courseinstancenumbertext = "";
  5712. $userinstancenumbertext = "";
  5713. }
  5714. $settings .= '<a href="' . $this->baseurl . '&amp;action=edit&amp;repos=' . $typename . '">' . $settingsstr .'</a>';
  5715. $settings .= $OUTPUT->container_start('mdl-left');
  5716. $settings .= '<br/>';
  5717. $settings .= $admininstancenumbertext;
  5718. $settings .= '<br/>';
  5719. $settings .= $courseinstancenumbertext;
  5720. $settings .= '<br/>';
  5721. $settings .= $userinstancenumbertext;
  5722. $settings .= $OUTPUT->container_end();
  5723. }
  5724. // Get the current visibility
  5725. if ($i->get_visible()) {
  5726. $currentaction = 'show';
  5727. } else {
  5728. $currentaction = 'hide';
  5729. }
  5730. $select = new single_select($this->repository_action_url($typename, 'repos'), 'action', $actionchoicesforexisting, $currentaction, null, 'applyto' . basename($typename));
  5731. // Display up/down link
  5732. $updown = '';
  5733. $spacer = $OUTPUT->spacer(array('height'=>15, 'width'=>15)); // should be done with CSS instead
  5734. if ($updowncount > 1) {
  5735. $updown .= "<a href=\"$this->baseurl&amp;action=moveup&amp;repos=".$typename."\">";
  5736. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a>&nbsp;";
  5737. }
  5738. else {
  5739. $updown .= $spacer;
  5740. }
  5741. if ($updowncount < $totalinstances) {
  5742. $updown .= "<a href=\"$this->baseurl&amp;action=movedown&amp;repos=".$typename."\">";
  5743. $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>";
  5744. }
  5745. else {
  5746. $updown .= $spacer;
  5747. }
  5748. $updowncount++;
  5749. $table->data[] = array($i->get_readablename(), $OUTPUT->render($select), $updown, $settings);
  5750. if (!in_array($typename, $alreadyplugins)) {
  5751. $alreadyplugins[] = $typename;
  5752. }
  5753. }
  5754. }
  5755. // Get all the plugins that exist on disk
  5756. $plugins = get_plugin_list('repository');
  5757. if (!empty($plugins)) {
  5758. foreach ($plugins as $plugin => $dir) {
  5759. // Check that it has not already been listed
  5760. if (!in_array($plugin, $alreadyplugins)) {
  5761. $select = new single_select($this->repository_action_url($plugin, 'repos'), 'action', $actionchoicesfornew, 'delete', null, 'applyto' . basename($plugin));
  5762. $table->data[] = array(get_string('pluginname', 'repository_'.$plugin), $OUTPUT->render($select), '', '');
  5763. }
  5764. }
  5765. }
  5766. $return .= html_writer::table($table);
  5767. $return .= $OUTPUT->box_end();
  5768. return highlight($query, $return);
  5769. }
  5770. }
  5771. /**
  5772. * Special class for management of external services
  5773. *
  5774. * @author Petr Skoda (skodak)
  5775. */
  5776. class admin_setting_manageexternalservices extends admin_setting {
  5777. /**
  5778. * Calls parent::__construct with specific arguments
  5779. */
  5780. public function __construct() {
  5781. $this->nosave = true;
  5782. parent::__construct('webservicesui', get_string('externalservices', 'webservice'), '', '');
  5783. }
  5784. /**
  5785. * Always returns true, does nothing
  5786. *
  5787. * @return true
  5788. */
  5789. public function get_setting() {
  5790. return true;
  5791. }
  5792. /**
  5793. * Always returns true, does nothing
  5794. *
  5795. * @return true
  5796. */
  5797. public function get_defaultsetting() {
  5798. return true;
  5799. }
  5800. /**
  5801. * Always returns '', does not write anything
  5802. *
  5803. * @return string Always returns ''
  5804. */
  5805. public function write_setting($data) {
  5806. // do not write any setting
  5807. return '';
  5808. }
  5809. /**
  5810. * Checks if $query is one of the available external services
  5811. *
  5812. * @param string $query The string to search for
  5813. * @return bool Returns true if found, false if not
  5814. */
  5815. public function is_related($query) {
  5816. global $DB;
  5817. if (parent::is_related($query)) {
  5818. return true;
  5819. }
  5820. $textlib = textlib_get_instance();
  5821. $services = $DB->get_records('external_services', array(), 'id, name');
  5822. foreach ($services as $service) {
  5823. if (strpos($textlib->strtolower($service->name), $query) !== false) {
  5824. return true;
  5825. }
  5826. }
  5827. return false;
  5828. }
  5829. /**
  5830. * Builds the XHTML to display the control
  5831. *
  5832. * @param string $data Unused
  5833. * @param string $query
  5834. * @return string
  5835. */
  5836. public function output_html($data, $query='') {
  5837. global $CFG, $OUTPUT, $DB;
  5838. // display strings
  5839. $stradministration = get_string('administration');
  5840. $stredit = get_string('edit');
  5841. $strservice = get_string('externalservice', 'webservice');
  5842. $strdelete = get_string('delete');
  5843. $strplugin = get_string('plugin', 'admin');
  5844. $stradd = get_string('add');
  5845. $strfunctions = get_string('functions', 'webservice');
  5846. $strusers = get_string('users');
  5847. $strserviceusers = get_string('serviceusers', 'webservice');
  5848. $esurl = "$CFG->wwwroot/$CFG->admin/webservice/service.php";
  5849. $efurl = "$CFG->wwwroot/$CFG->admin/webservice/service_functions.php";
  5850. $euurl = "$CFG->wwwroot/$CFG->admin/webservice/service_users.php";
  5851. // built in services
  5852. $services = $DB->get_records_select('external_services', 'component IS NOT NULL', null, 'name');
  5853. $return = "";
  5854. if (!empty($services)) {
  5855. $return .= $OUTPUT->heading(get_string('servicesbuiltin', 'webservice'), 3, 'main');
  5856. $table = new html_table();
  5857. $table->head = array($strservice, $strplugin, $strfunctions, $strusers, $stredit);
  5858. $table->align = array('left', 'left', 'center', 'center', 'center');
  5859. $table->size = array('30%', '20%', '20%', '20%', '10%');
  5860. $table->width = '100%';
  5861. $table->data = array();
  5862. // iterate through auth plugins and add to the display table
  5863. foreach ($services as $service) {
  5864. $name = $service->name;
  5865. // hide/show link
  5866. if ($service->enabled) {
  5867. $displayname = "<span>$name</span>";
  5868. } else {
  5869. $displayname = "<span class=\"dimmed_text\">$name</span>";
  5870. }
  5871. $plugin = $service->component;
  5872. $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
  5873. if ($service->restrictedusers) {
  5874. $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
  5875. } else {
  5876. $users = get_string('allusers', 'webservice');
  5877. }
  5878. $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
  5879. // add a row to the table
  5880. $table->data[] = array($displayname, $plugin, $functions, $users, $edit);
  5881. }
  5882. $return .= html_writer::table($table);
  5883. }
  5884. // Custom services
  5885. $return .= $OUTPUT->heading(get_string('servicescustom', 'webservice'), 3, 'main');
  5886. $services = $DB->get_records_select('external_services', 'component IS NULL', null, 'name');
  5887. $table = new html_table();
  5888. $table->head = array($strservice, $strdelete, $strfunctions, $strusers, $stredit);
  5889. $table->align = array('left', 'center', 'center', 'center', 'center');
  5890. $table->size = array('30%', '20%', '20%', '20%', '10%');
  5891. $table->width = '100%';
  5892. $table->data = array();
  5893. // iterate through auth plugins and add to the display table
  5894. foreach ($services as $service) {
  5895. $name = $service->name;
  5896. // hide/show link
  5897. if ($service->enabled) {
  5898. $displayname = "<span>$name</span>";
  5899. } else {
  5900. $displayname = "<span class=\"dimmed_text\">$name</span>";
  5901. }
  5902. // delete link
  5903. $delete = "<a href=\"$esurl?action=delete&amp;sesskey=".sesskey()."&amp;id=$service->id\">$strdelete</a>";
  5904. $functions = "<a href=\"$efurl?id=$service->id\">$strfunctions</a>";
  5905. if ($service->restrictedusers) {
  5906. $users = "<a href=\"$euurl?id=$service->id\">$strserviceusers</a>";
  5907. } else {
  5908. $users = get_string('allusers', 'webservice');
  5909. }
  5910. $edit = "<a href=\"$esurl?id=$service->id\">$stredit</a>";
  5911. // add a row to the table
  5912. $table->data[] = array($displayname, $delete, $functions, $users, $edit);
  5913. }
  5914. // add new custom service option
  5915. $return .= html_writer::table($table);
  5916. $return .= '<br />';
  5917. // add a token to the table
  5918. $return .= "<a href=\"$esurl?id=0\">$stradd</a>";
  5919. return highlight($query, $return);
  5920. }
  5921. }
  5922. /**
  5923. * Special class for plagiarism administration.
  5924. *
  5925. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  5926. */
  5927. class admin_setting_manageplagiarism extends admin_setting {
  5928. /**
  5929. * Calls parent::__construct with specific arguments
  5930. */
  5931. public function __construct() {
  5932. $this->nosave = true;
  5933. parent::__construct('plagiarismui', get_string('plagiarismsettings', 'plagiarism'), '', '');
  5934. }
  5935. /**
  5936. * Always returns true
  5937. *
  5938. * @return true
  5939. */
  5940. public function get_setting() {
  5941. return true;
  5942. }
  5943. /**
  5944. * Always returns true
  5945. *
  5946. * @return true
  5947. */
  5948. public function get_defaultsetting() {
  5949. return true;
  5950. }
  5951. /**
  5952. * Always returns '' and doesn't write anything
  5953. *
  5954. * @return string Always returns ''
  5955. */
  5956. public function write_setting($data) {
  5957. // do not write any setting
  5958. return '';
  5959. }
  5960. /**
  5961. * Return XHTML to display control
  5962. *
  5963. * @param mixed $data Unused
  5964. * @param string $query
  5965. * @return string highlight
  5966. */
  5967. public function output_html($data, $query='') {
  5968. global $CFG, $OUTPUT;
  5969. // display strings
  5970. $txt = get_strings(array('settings', 'name'));
  5971. $plagiarismplugins = get_plugin_list('plagiarism');
  5972. if (empty($plagiarismplugins)) {
  5973. return get_string('nopluginsinstalled', 'plagiarism');
  5974. }
  5975. $return = $OUTPUT->heading(get_string('availableplugins', 'plagiarism'), 3, 'main');
  5976. $return .= $OUTPUT->box_start('generalbox authsui');
  5977. $table = new html_table();
  5978. $table->head = array($txt->name, $txt->settings);
  5979. $table->align = array('left', 'center');
  5980. $table->data = array();
  5981. $table->attributes['class'] = 'manageplagiarismtable generaltable';
  5982. // iterate through auth plugins and add to the display table
  5983. $authcount = count($plagiarismplugins);
  5984. foreach ($plagiarismplugins as $plugin => $dir) {
  5985. if (file_exists($dir.'/settings.php')) {
  5986. $displayname = "<span>".get_string($plugin, 'plagiarism_'.$plugin)."</span>";
  5987. // settings link
  5988. $settings = "<a href=\"$CFG->wwwroot/plagiarism/$plugin/settings.php\">{$txt->settings}</a>";
  5989. // add a row to the table
  5990. $table->data[] =array($displayname, $settings);
  5991. }
  5992. }
  5993. $return .= html_writer::table($table);
  5994. $return .= get_string('configplagiarismplugins', 'plagiarism');
  5995. $return .= $OUTPUT->box_end();
  5996. return highlight($query, $return);
  5997. }
  5998. }
  5999. /**
  6000. * Special class for overview of external services
  6001. *
  6002. * @author Jerome Mouneyrac
  6003. */
  6004. class admin_setting_webservicesoverview extends admin_setting {
  6005. /**
  6006. * Calls parent::__construct with specific arguments
  6007. */
  6008. public function __construct() {
  6009. $this->nosave = true;
  6010. parent::__construct('webservicesoverviewui',
  6011. get_string('webservicesoverview', 'webservice'), '', '');
  6012. }
  6013. /**
  6014. * Always returns true, does nothing
  6015. *
  6016. * @return true
  6017. */
  6018. public function get_setting() {
  6019. return true;
  6020. }
  6021. /**
  6022. * Always returns true, does nothing
  6023. *
  6024. * @return true
  6025. */
  6026. public function get_defaultsetting() {
  6027. return true;
  6028. }
  6029. /**
  6030. * Always returns '', does not write anything
  6031. *
  6032. * @return string Always returns ''
  6033. */
  6034. public function write_setting($data) {
  6035. // do not write any setting
  6036. return '';
  6037. }
  6038. /**
  6039. * Builds the XHTML to display the control
  6040. *
  6041. * @param string $data Unused
  6042. * @param string $query
  6043. * @return string
  6044. */
  6045. public function output_html($data, $query='') {
  6046. global $CFG, $OUTPUT;
  6047. $return = "";
  6048. /// One system controlling Moodle with Token
  6049. $brtag = html_writer::empty_tag('br');
  6050. $return .= $OUTPUT->heading(get_string('onesystemcontrolling', 'webservice'), 3, 'main');
  6051. $table = new html_table();
  6052. $table->head = array(get_string('step', 'webservice'), get_string('status'),
  6053. get_string('description'));
  6054. $table->size = array('30%', '10%', '60%');
  6055. $table->align = array('left', 'left', 'left');
  6056. $table->width = '90%';
  6057. $table->data = array();
  6058. $return .= $brtag . get_string('onesystemcontrollingdescription', 'webservice')
  6059. . $brtag . $brtag;
  6060. /// 1. Enable Web Services
  6061. $row = array();
  6062. $url = new moodle_url("/admin/search.php?query=enablewebservices");
  6063. $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
  6064. array('href' => $url));
  6065. $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
  6066. if ($CFG->enablewebservices) {
  6067. $status = get_string('yes');
  6068. }
  6069. $row[1] = $status;
  6070. $row[2] = get_string('enablewsdescription', 'webservice');
  6071. $table->data[] = $row;
  6072. /// 2. Enable protocols
  6073. $row = array();
  6074. $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
  6075. $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
  6076. array('href' => $url));
  6077. $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
  6078. //retrieve activated protocol
  6079. $active_protocols = empty($CFG->webserviceprotocols) ?
  6080. array() : explode(',', $CFG->webserviceprotocols);
  6081. if (!empty($active_protocols)) {
  6082. $status = "";
  6083. foreach ($active_protocols as $protocol) {
  6084. $status .= $protocol . $brtag;
  6085. }
  6086. }
  6087. $row[1] = $status;
  6088. $row[2] = get_string('enableprotocolsdescription', 'webservice');
  6089. $table->data[] = $row;
  6090. /// 3. Create user account
  6091. $row = array();
  6092. $url = new moodle_url("/user/editadvanced.php?id=-1");
  6093. $row[0] = "3. " . html_writer::tag('a', get_string('createuser', 'webservice'),
  6094. array('href' => $url));
  6095. $row[1] = "";
  6096. $row[2] = get_string('createuserdescription', 'webservice');
  6097. $table->data[] = $row;
  6098. /// 4. Add capability to users
  6099. $row = array();
  6100. $url = new moodle_url("/admin/roles/check.php?contextid=1");
  6101. $row[0] = "4. " . html_writer::tag('a', get_string('checkusercapability', 'webservice'),
  6102. array('href' => $url));
  6103. $row[1] = "";
  6104. $row[2] = get_string('checkusercapabilitydescription', 'webservice');
  6105. $table->data[] = $row;
  6106. /// 5. Select a web service
  6107. $row = array();
  6108. $url = new moodle_url("/admin/settings.php?section=externalservices");
  6109. $row[0] = "5. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
  6110. array('href' => $url));
  6111. $row[1] = "";
  6112. $row[2] = get_string('createservicedescription', 'webservice');
  6113. $table->data[] = $row;
  6114. /// 6. Add functions
  6115. $row = array();
  6116. $url = new moodle_url("/admin/settings.php?section=externalservices");
  6117. $row[0] = "6. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
  6118. array('href' => $url));
  6119. $row[1] = "";
  6120. $row[2] = get_string('addfunctionsdescription', 'webservice');
  6121. $table->data[] = $row;
  6122. /// 7. Add the specific user
  6123. $row = array();
  6124. $url = new moodle_url("/admin/settings.php?section=externalservices");
  6125. $row[0] = "7. " . html_writer::tag('a', get_string('selectspecificuser', 'webservice'),
  6126. array('href' => $url));
  6127. $row[1] = "";
  6128. $row[2] = get_string('selectspecificuserdescription', 'webservice');
  6129. $table->data[] = $row;
  6130. /// 8. Create token for the specific user
  6131. $row = array();
  6132. $url = new moodle_url("/admin/webservice/tokens.php?sesskey=" . sesskey() . "&action=create");
  6133. $row[0] = "8. " . html_writer::tag('a', get_string('createtokenforuser', 'webservice'),
  6134. array('href' => $url));
  6135. $row[1] = "";
  6136. $row[2] = get_string('createtokenforuserdescription', 'webservice');
  6137. $table->data[] = $row;
  6138. /// 9. Enable the documentation
  6139. $row = array();
  6140. $url = new moodle_url("/admin/search.php?query=enablewsdocumentation");
  6141. $row[0] = "9. " . html_writer::tag('a', get_string('enabledocumentation', 'webservice'),
  6142. array('href' => $url));
  6143. $status = '<span class="warning">' . get_string('no') . '</span>';
  6144. if ($CFG->enablewsdocumentation) {
  6145. $status = get_string('yes');
  6146. }
  6147. $row[1] = $status;
  6148. $row[2] = get_string('enabledocumentationdescription', 'webservice');
  6149. $table->data[] = $row;
  6150. /// 10. Test the service
  6151. $row = array();
  6152. $url = new moodle_url("/admin/webservice/testclient.php");
  6153. $row[0] = "10. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
  6154. array('href' => $url));
  6155. $row[1] = "";
  6156. $row[2] = get_string('testwithtestclientdescription', 'webservice');
  6157. $table->data[] = $row;
  6158. $return .= html_writer::table($table);
  6159. /// Users as clients with token
  6160. $return .= $brtag . $brtag . $brtag;
  6161. $return .= $OUTPUT->heading(get_string('userasclients', 'webservice'), 3, 'main');
  6162. $table = new html_table();
  6163. $table->head = array(get_string('step', 'webservice'), get_string('status'),
  6164. get_string('description'));
  6165. $table->size = array('30%', '10%', '60%');
  6166. $table->align = array('left', 'left', 'left');
  6167. $table->width = '90%';
  6168. $table->data = array();
  6169. $return .= $brtag . get_string('userasclientsdescription', 'webservice') .
  6170. $brtag . $brtag;
  6171. /// 1. Enable Web Services
  6172. $row = array();
  6173. $url = new moodle_url("/admin/search.php?query=enablewebservices");
  6174. $row[0] = "1. " . html_writer::tag('a', get_string('enablews', 'webservice'),
  6175. array('href' => $url));
  6176. $status = html_writer::tag('span', get_string('no'), array('class' => 'statuscritical'));
  6177. if ($CFG->enablewebservices) {
  6178. $status = get_string('yes');
  6179. }
  6180. $row[1] = $status;
  6181. $row[2] = get_string('enablewsdescription', 'webservice');
  6182. $table->data[] = $row;
  6183. /// 2. Enable protocols
  6184. $row = array();
  6185. $url = new moodle_url("/admin/settings.php?section=webserviceprotocols");
  6186. $row[0] = "2. " . html_writer::tag('a', get_string('enableprotocols', 'webservice'),
  6187. array('href' => $url));
  6188. $status = html_writer::tag('span', get_string('none'), array('class' => 'statuscritical'));
  6189. //retrieve activated protocol
  6190. $active_protocols = empty($CFG->webserviceprotocols) ?
  6191. array() : explode(',', $CFG->webserviceprotocols);
  6192. if (!empty($active_protocols)) {
  6193. $status = "";
  6194. foreach ($active_protocols as $protocol) {
  6195. $status .= $protocol . $brtag;
  6196. }
  6197. }
  6198. $row[1] = $status;
  6199. $row[2] = get_string('enableprotocolsdescription', 'webservice');
  6200. $table->data[] = $row;
  6201. /// 3. Select a web service
  6202. $row = array();
  6203. $url = new moodle_url("/admin/settings.php?section=externalservices");
  6204. $row[0] = "3. " . html_writer::tag('a', get_string('selectservice', 'webservice'),
  6205. array('href' => $url));
  6206. $row[1] = "";
  6207. $row[2] = get_string('createserviceforusersdescription', 'webservice');
  6208. $table->data[] = $row;
  6209. /// 4. Add functions
  6210. $row = array();
  6211. $url = new moodle_url("/admin/settings.php?section=externalservices");
  6212. $row[0] = "4. " . html_writer::tag('a', get_string('addfunctions', 'webservice'),
  6213. array('href' => $url));
  6214. $row[1] = "";
  6215. $row[2] = get_string('addfunctionsdescription', 'webservice');
  6216. $table->data[] = $row;
  6217. /// 5. Add capability to users
  6218. $row = array();
  6219. $url = new moodle_url("/admin/roles/check.php?contextid=1");
  6220. $row[0] = "5. " . html_writer::tag('a', get_string('addcapabilitytousers', 'webservice'),
  6221. array('href' => $url));
  6222. $row[1] = "";
  6223. $row[2] = get_string('addcapabilitytousersdescription', 'webservice');
  6224. $table->data[] = $row;
  6225. /// 6. Test the service
  6226. $row = array();
  6227. $url = new moodle_url("/admin/webservice/testclient.php");
  6228. $row[0] = "6. " . html_writer::tag('a', get_string('testwithtestclient', 'webservice'),
  6229. array('href' => $url));
  6230. $row[1] = "";
  6231. $row[2] = get_string('testauserwithtestclientdescription', 'webservice');
  6232. $table->data[] = $row;
  6233. $return .= html_writer::table($table);
  6234. return highlight($query, $return);
  6235. }
  6236. }
  6237. /**
  6238. * Special class for web service protocol administration.
  6239. *
  6240. * @author Petr Skoda (skodak)
  6241. */
  6242. class admin_setting_managewebserviceprotocols extends admin_setting {
  6243. /**
  6244. * Calls parent::__construct with specific arguments
  6245. */
  6246. public function __construct() {
  6247. $this->nosave = true;
  6248. parent::__construct('webservicesui', get_string('manageprotocols', 'webservice'), '', '');
  6249. }
  6250. /**
  6251. * Always returns true, does nothing
  6252. *
  6253. * @return true
  6254. */
  6255. public function get_setting() {
  6256. return true;
  6257. }
  6258. /**
  6259. * Always returns true, does nothing
  6260. *
  6261. * @return true
  6262. */
  6263. public function get_defaultsetting() {
  6264. return true;
  6265. }
  6266. /**
  6267. * Always returns '', does not write anything
  6268. *
  6269. * @return string Always returns ''
  6270. */
  6271. public function write_setting($data) {
  6272. // do not write any setting
  6273. return '';
  6274. }
  6275. /**
  6276. * Checks if $query is one of the available webservices
  6277. *
  6278. * @param string $query The string to search for
  6279. * @return bool Returns true if found, false if not
  6280. */
  6281. public function is_related($query) {
  6282. if (parent::is_related($query)) {
  6283. return true;
  6284. }
  6285. $textlib = textlib_get_instance();
  6286. $protocols = get_plugin_list('webservice');
  6287. foreach ($protocols as $protocol=>$location) {
  6288. if (strpos($protocol, $query) !== false) {
  6289. return true;
  6290. }
  6291. $protocolstr = get_string('pluginname', 'webservice_'.$protocol);
  6292. if (strpos($textlib->strtolower($protocolstr), $query) !== false) {
  6293. return true;
  6294. }
  6295. }
  6296. return false;
  6297. }
  6298. /**
  6299. * Builds the XHTML to display the control
  6300. *
  6301. * @param string $data Unused
  6302. * @param string $query
  6303. * @return string
  6304. */
  6305. public function output_html($data, $query='') {
  6306. global $CFG, $OUTPUT;
  6307. // display strings
  6308. $stradministration = get_string('administration');
  6309. $strsettings = get_string('settings');
  6310. $stredit = get_string('edit');
  6311. $strprotocol = get_string('protocol', 'webservice');
  6312. $strenable = get_string('enable');
  6313. $strdisable = get_string('disable');
  6314. $strversion = get_string('version');
  6315. $struninstall = get_string('uninstallplugin', 'admin');
  6316. $protocols_available = get_plugin_list('webservice');
  6317. $active_protocols = empty($CFG->webserviceprotocols) ? array() : explode(',', $CFG->webserviceprotocols);
  6318. ksort($protocols_available);
  6319. foreach ($active_protocols as $key=>$protocol) {
  6320. if (empty($protocols_available[$protocol])) {
  6321. unset($active_protocols[$key]);
  6322. }
  6323. }
  6324. $return = $OUTPUT->heading(get_string('actwebserviceshhdr', 'webservice'), 3, 'main');
  6325. $return .= $OUTPUT->box_start('generalbox webservicesui');
  6326. $table = new html_table();
  6327. $table->head = array($strprotocol, $strversion, $strenable, $struninstall, $strsettings);
  6328. $table->align = array('left', 'center', 'center', 'center', 'center');
  6329. $table->width = '100%';
  6330. $table->data = array();
  6331. // iterate through auth plugins and add to the display table
  6332. $url = "$CFG->wwwroot/$CFG->admin/webservice/protocols.php?sesskey=" . sesskey();
  6333. foreach ($protocols_available as $protocol => $location) {
  6334. $name = get_string('pluginname', 'webservice_'.$protocol);
  6335. $plugin = new stdClass();
  6336. if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/version.php')) {
  6337. include($CFG->dirroot.'/webservice/'.$protocol.'/version.php');
  6338. }
  6339. $version = isset($plugin->version) ? $plugin->version : '';
  6340. // hide/show link
  6341. if (in_array($protocol, $active_protocols)) {
  6342. $hideshow = "<a href=\"$url&amp;action=disable&amp;webservice=$protocol\">";
  6343. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"$strdisable\" /></a>";
  6344. $displayname = "<span>$name</span>";
  6345. } else {
  6346. $hideshow = "<a href=\"$url&amp;action=enable&amp;webservice=$protocol\">";
  6347. $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"$strenable\" /></a>";
  6348. $displayname = "<span class=\"dimmed_text\">$name</span>";
  6349. }
  6350. // delete link
  6351. $uninstall = "<a href=\"$url&amp;action=uninstall&amp;webservice=$protocol\">$struninstall</a>";
  6352. // settings link
  6353. if (file_exists($CFG->dirroot.'/webservice/'.$protocol.'/settings.php')) {
  6354. $settings = "<a href=\"settings.php?section=webservicesetting$protocol\">$strsettings</a>";
  6355. } else {
  6356. $settings = '';
  6357. }
  6358. // add a row to the table
  6359. $table->data[] = array($displayname, $version, $hideshow, $uninstall, $settings);
  6360. }
  6361. $return .= html_writer::table($table);
  6362. $return .= get_string('configwebserviceplugins', 'webservice');
  6363. $return .= $OUTPUT->box_end();
  6364. return highlight($query, $return);
  6365. }
  6366. }
  6367. /**
  6368. * Special class for web service token administration.
  6369. *
  6370. * @author Jerome Mouneyrac
  6371. */
  6372. class admin_setting_managewebservicetokens extends admin_setting {
  6373. /**
  6374. * Calls parent::__construct with specific arguments
  6375. */
  6376. public function __construct() {
  6377. $this->nosave = true;
  6378. parent::__construct('webservicestokenui', get_string('managetokens', 'webservice'), '', '');
  6379. }
  6380. /**
  6381. * Always returns true, does nothing
  6382. *
  6383. * @return true
  6384. */
  6385. public function get_setting() {
  6386. return true;
  6387. }
  6388. /**
  6389. * Always returns true, does nothing
  6390. *
  6391. * @return true
  6392. */
  6393. public function get_defaultsetting() {
  6394. return true;
  6395. }
  6396. /**
  6397. * Always returns '', does not write anything
  6398. *
  6399. * @return string Always returns ''
  6400. */
  6401. public function write_setting($data) {
  6402. // do not write any setting
  6403. return '';
  6404. }
  6405. /**
  6406. * Builds the XHTML to display the control
  6407. *
  6408. * @param string $data Unused
  6409. * @param string $query
  6410. * @return string
  6411. */
  6412. public function output_html($data, $query='') {
  6413. global $CFG, $OUTPUT, $DB, $USER;
  6414. // display strings
  6415. $stroperation = get_string('operation', 'webservice');
  6416. $strtoken = get_string('token', 'webservice');
  6417. $strservice = get_string('service', 'webservice');
  6418. $struser = get_string('user');
  6419. $strcontext = get_string('context', 'webservice');
  6420. $strvaliduntil = get_string('validuntil', 'webservice');
  6421. $striprestriction = get_string('iprestriction', 'webservice');
  6422. $return = $OUTPUT->box_start('generalbox webservicestokenui');
  6423. $table = new html_table();
  6424. $table->head = array($strtoken, $struser, $strservice, $striprestriction, $strvaliduntil, $stroperation);
  6425. $table->align = array('left', 'left', 'left', 'center', 'center', 'center');
  6426. $table->width = '100%';
  6427. $table->data = array();
  6428. $tokenpageurl = "$CFG->wwwroot/$CFG->admin/webservice/tokens.php?sesskey=" . sesskey();
  6429. //TODO: in order to let the administrator delete obsolete token, split this request in multiple request or use LEFT JOIN
  6430. //here retrieve token list (including linked users firstname/lastname and linked services name)
  6431. $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.validuntil, s.id AS serviceid
  6432. FROM {external_tokens} t, {user} u, {external_services} s
  6433. WHERE t.creatorid=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
  6434. $tokens = $DB->get_records_sql($sql, array($USER->id, EXTERNAL_TOKEN_PERMANENT));
  6435. if (!empty($tokens)) {
  6436. foreach ($tokens as $token) {
  6437. //TODO: retrieve context
  6438. $delete = "<a href=\"".$tokenpageurl."&amp;action=delete&amp;tokenid=".$token->id."\">";
  6439. $delete .= get_string('delete')."</a>";
  6440. $validuntil = '';
  6441. if (!empty($token->validuntil)) {
  6442. $validuntil = date("F j, Y"); //TODO: language support (look for moodle function)
  6443. }
  6444. $iprestriction = '';
  6445. if (!empty($token->iprestriction)) {
  6446. $iprestriction = $token->iprestriction;
  6447. }
  6448. $userprofilurl = new moodle_url('/user/profile.php?id='.$token->userid);
  6449. $useratag = html_writer::start_tag('a', array('href' => $userprofilurl));
  6450. $useratag .= $token->firstname." ".$token->lastname;
  6451. $useratag .= html_writer::end_tag('a');
  6452. //check user missing capabilities
  6453. require_once($CFG->dirroot . '/webservice/lib.php');
  6454. $webservicemanager = new webservice();
  6455. $usermissingcaps = $webservicemanager->get_missing_capabilities_by_users(
  6456. array(array('id' => $token->userid)), $token->serviceid);
  6457. if (!is_siteadmin($token->userid) and
  6458. key_exists($token->userid, $usermissingcaps)) {
  6459. $missingcapabilities = implode(',',
  6460. $usermissingcaps[$token->userid]);
  6461. if (!empty($missingcapabilities)) {
  6462. $useratag .= html_writer::tag('div',
  6463. get_string('usermissingcaps', 'webservice',
  6464. $missingcapabilities)
  6465. . '&nbsp;' . $OUTPUT->help_icon('missingcaps', 'webservice'),
  6466. array('class' => 'missingcaps'));
  6467. }
  6468. }
  6469. $table->data[] = array($token->token, $useratag, $token->name, $iprestriction, $validuntil, $delete);
  6470. }
  6471. $return .= html_writer::table($table);
  6472. } else {
  6473. $return .= get_string('notoken', 'webservice');
  6474. }
  6475. $return .= $OUTPUT->box_end();
  6476. // add a token to the table
  6477. $return .= "<a href=\"".$tokenpageurl."&amp;action=create\">";
  6478. $return .= get_string('add')."</a>";
  6479. return highlight($query, $return);
  6480. }
  6481. }
  6482. /**
  6483. * Colour picker
  6484. *
  6485. * @copyright 2010 Sam Hemelryk
  6486. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  6487. */
  6488. class admin_setting_configcolourpicker extends admin_setting {
  6489. /**
  6490. * Information for previewing the colour
  6491. *
  6492. * @var array|null
  6493. */
  6494. protected $previewconfig = null;
  6495. /**
  6496. *
  6497. * @param string $name
  6498. * @param string $visiblename
  6499. * @param string $description
  6500. * @param string $defaultsetting
  6501. * @param array $previewconfig Array('selector'=>'.some .css .selector','style'=>'backgroundColor');
  6502. */
  6503. public function __construct($name, $visiblename, $description, $defaultsetting, array $previewconfig=null) {
  6504. $this->previewconfig = $previewconfig;
  6505. parent::__construct($name, $visiblename, $description, $defaultsetting);
  6506. }
  6507. /**
  6508. * Return the setting
  6509. *
  6510. * @return mixed returns config if successful else null
  6511. */
  6512. public function get_setting() {
  6513. return $this->config_read($this->name);
  6514. }
  6515. /**
  6516. * Saves the setting
  6517. *
  6518. * @param string $data
  6519. * @return bool
  6520. */
  6521. public function write_setting($data) {
  6522. $data = $this->validate($data);
  6523. if ($data === false) {
  6524. return get_string('validateerror', 'admin');
  6525. }
  6526. return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
  6527. }
  6528. /**
  6529. * Validates the colour that was entered by the user
  6530. *
  6531. * @param string $data
  6532. * @return string|false
  6533. */
  6534. protected function validate($data) {
  6535. if (preg_match('/^#?([a-fA-F0-9]{3}){1,2}$/', $data)) {
  6536. if (strpos($data, '#')!==0) {
  6537. $data = '#'.$data;
  6538. }
  6539. return $data;
  6540. } else if (preg_match('/^[a-zA-Z]{3, 25}$/', $data)) {
  6541. return $data;
  6542. } else if (empty($data)) {
  6543. return $this->defaultsetting;
  6544. } else {
  6545. return false;
  6546. }
  6547. }
  6548. /**
  6549. * Generates the HTML for the setting
  6550. *
  6551. * @global moodle_page $PAGE
  6552. * @global core_renderer $OUTPUT
  6553. * @param string $data
  6554. * @param string $query
  6555. */
  6556. public function output_html($data, $query = '') {
  6557. global $PAGE, $OUTPUT;
  6558. $PAGE->requires->js_init_call('M.util.init_colour_picker', array($this->get_id(), $this->previewconfig));
  6559. $content = html_writer::start_tag('div', array('class'=>'form-colourpicker defaultsnext'));
  6560. $content .= html_writer::tag('div', $OUTPUT->pix_icon('i/loading', get_string('loading', 'admin'), 'moodle', array('class'=>'loadingicon')), array('class'=>'admin_colourpicker clearfix'));
  6561. $content .= html_writer::empty_tag('input', array('type'=>'text','id'=>$this->get_id(), 'name'=>$this->get_full_name(), 'value'=>$this->get_setting(), 'size'=>'12'));
  6562. if (!empty($this->previewconfig)) {
  6563. $content .= html_writer::empty_tag('input', array('type'=>'button','id'=>$this->get_id().'_preview', 'value'=>get_string('preview'), 'class'=>'admin_colourpicker_preview'));
  6564. }
  6565. $content .= html_writer::end_tag('div');
  6566. return format_admin_setting($this, $this->visiblename, $content, $this->description, false, '', $this->get_defaultsetting(), $query);
  6567. }
  6568. }