PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/adminlib.php

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